@cuadra-ai/uikit 0.4.6 → 0.4.7

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,36 +1,36 @@
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))})(this,(function($,p,y,fe){"use strict";var mv=Object.defineProperty,gv=Object.defineProperties;var yv=Object.getOwnPropertyDescriptors;var xr=Object.getOwnPropertySymbols;var _u=Object.prototype.hasOwnProperty,Tu=Object.prototype.propertyIsEnumerable;var ns=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),Iu=$=>{throw TypeError($)},Cu=Math.pow,rs=($,p,y)=>p in $?mv($,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):$[p]=y,g=($,p)=>{for(var y in p||(p={}))_u.call(p,y)&&rs($,y,p[y]);if(xr)for(var y of xr(p))Tu.call(p,y)&&rs($,y,p[y]);return $},E=($,p)=>gv($,yv(p));var V=($,p)=>{var y={};for(var fe in $)_u.call($,fe)&&p.indexOf(fe)<0&&(y[fe]=$[fe]);if($!=null&&xr)for(var fe of xr($))p.indexOf(fe)<0&&Tu.call($,fe)&&(y[fe]=$[fe]);return y};var T=($,p,y)=>rs($,typeof p!="symbol"?p+"":p,y),Eu=($,p,y)=>p.has($)||Iu("Cannot "+y);var We=($,p,y)=>(Eu($,p,"read from private field"),y?y.call($):p.get($)),Xt=($,p,y)=>p.has($)?Iu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,y),Qt=($,p,y,fe)=>(Eu($,p,"write to private field"),fe?fe.call($,y):p.set($,y),y);var M=($,p,y)=>new Promise((fe,je)=>{var Ue=Te=>{try{Ne(y.next(Te))}catch(Be){je(Be)}},Q=Te=>{try{Ne(y.throw(Te))}catch(Be){je(Be)}},Ne=Te=>Te.done?fe(Te.value):Promise.resolve(Te.value).then(Ue,Q);Ne((y=y.apply($,p)).next())}),Ee=function($,p){this[0]=$,this[1]=p},Mn=($,p,y)=>{var fe=(Q,Ne,Te,Be)=>{try{var Zt=y[Q](Ne),Pn=(Ne=Zt.value)instanceof Ee,kr=Zt.done;Promise.resolve(Pn?Ne[0]:Ne).then(it=>Pn?fe(Q==="return"?Q:"next",Ne[1]?{done:it.done,value:it.value}:it,Te,Be):Te({value:it,done:kr})).catch(it=>fe("throw",it,Te,Be))}catch(it){Be(it)}},je=Q=>Ue[Q]=Ne=>new Promise((Te,Be)=>fe(Q,Ne,Te,Be)),Ue={};return y=y.apply($,p),Ue[ns("asyncIterator")]=()=>Ue,je("next"),je("throw"),je("return"),Ue};var Lt=($,p,y)=>(p=$[ns("asyncIterator")])?p.call($):($=$[ns("iterator")](),p={},y=(fe,je)=>(je=$[fe])&&(p[fe]=Ue=>new Promise((Q,Ne,Te)=>(Ue=je.call($,Ue),Te=Ue.done,Promise.resolve(Ue.value).then(Be=>Q({value:Be,done:Te}),Ne)))),y("next"),y("return"),p);var nt,Pt,Ke,xu,_n,vu,Tn,In,Cn,Su,ku;var je=typeof document!="undefined"?document.currentScript:null;function Ue(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Q=Ue(y);const Ne=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Te=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),Be=e=>{const t=Te(e);return t.charAt(0).toUpperCase()+t.slice(1)},Zt=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Pn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var kr={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 it=y.forwardRef((u,l)=>{var c=u,{color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i="",children:s,iconNode:a}=c,o=V(c,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",g(g(E(g({ref:l},kr),{width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Zt("lucide",i)}),!s&&!Pn(o)&&{"aria-hidden":"true"}),o),[...a.map(([d,h])=>y.createElement(d,h)),...Array.isArray(s)?s:[s]])});const $e=(e,t)=>{const n=y.forwardRef((a,s)=>{var o=a,{className:r}=o,i=V(o,["className"]);return y.createElement(it,g({ref:s,iconNode:t,className:Zt(`lucide-${Ne(Be(e))}`,`lucide-${e}`,r)},i))});return n.displayName=Be(e),n};const Mu=$e("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const ss=$e("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const _r=$e("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Pu=$e("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 Nu=$e("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 as=$e("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 Lu=$e("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 os=$e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const ls=$e("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 Du=$e("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const us=$e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const Ou=$e("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]);const Fu=$e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Bu=e=>Array.from(e).map(n=>n.getModelContext()).sort((n,r)=>{var i,s;return((i=r.priority)!=null?i:0)-((s=n.priority)!=null?s:0)}).reduce((n,r)=>{var i;if(r.system&&(n.system?n.system+=`
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))})(this,(function($,p,y,pe){"use strict";var xv=Object.defineProperty,vv=Object.defineProperties;var Sv=Object.getOwnPropertyDescriptors;var Sr=Object.getOwnPropertySymbols;var Au=Object.prototype.hasOwnProperty,Mu=Object.prototype.propertyIsEnumerable;var ss=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),Pu=$=>{throw TypeError($)},Nu=Math.pow,as=($,p,y)=>p in $?xv($,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):$[p]=y,m=($,p)=>{for(var y in p||(p={}))Au.call(p,y)&&as($,y,p[y]);if(Sr)for(var y of Sr(p))Mu.call(p,y)&&as($,y,p[y]);return $},I=($,p)=>vv($,Sv(p));var q=($,p)=>{var y={};for(var pe in $)Au.call($,pe)&&p.indexOf(pe)<0&&(y[pe]=$[pe]);if($!=null&&Sr)for(var pe of Sr($))p.indexOf(pe)<0&&Mu.call($,pe)&&(y[pe]=$[pe]);return y};var T=($,p,y)=>as($,typeof p!="symbol"?p+"":p,y),Lu=($,p,y)=>p.has($)||Pu("Cannot "+y);var We=($,p,y)=>(Lu($,p,"read from private field"),y?y.call($):p.get($)),Zt=($,p,y)=>p.has($)?Pu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,y),en=($,p,y,pe)=>(Lu($,p,"write to private field"),pe?pe.call($,y):p.set($,y),y);var M=($,p,y)=>new Promise((pe,Ue)=>{var $e=Te=>{try{Ne(y.next(Te))}catch(ze){Ue(ze)}},Q=Te=>{try{Ne(y.throw(Te))}catch(ze){Ue(ze)}},Ne=Te=>Te.done?pe(Te.value):Promise.resolve(Te.value).then($e,Q);Ne((y=y.apply($,p)).next())}),Ee=function($,p){this[0]=$,this[1]=p},Pn=($,p,y)=>{var pe=(Q,Ne,Te,ze)=>{try{var tn=y[Q](Ne),Nn=(Ne=tn.value)instanceof Ee,Tr=tn.done;Promise.resolve(Nn?Ne[0]:Ne).then(it=>Nn?pe(Q==="return"?Q:"next",Ne[1]?{done:it.done,value:it.value}:it,Te,ze):Te({value:it,done:Tr})).catch(it=>pe("throw",it,Te,ze))}catch(it){ze(it)}},Ue=Q=>$e[Q]=Ne=>new Promise((Te,ze)=>pe(Q,Ne,Te,ze)),$e={};return y=y.apply($,p),$e[ss("asyncIterator")]=()=>$e,Ue("next"),Ue("throw"),Ue("return"),$e};var Lt=($,p,y)=>(p=$[ss("asyncIterator")])?p.call($):($=$[ss("iterator")](),p={},y=(pe,Ue)=>(Ue=$[pe])&&(p[pe]=$e=>new Promise((Q,Ne,Te)=>($e=Ue.call($,$e),Te=$e.done,Promise.resolve($e.value).then(ze=>Q({value:ze,done:Te}),Ne)))),y("next"),y("return"),p);var nt,Pt,Ke,Tu,Tn,Cu,Cn,In,En,Iu,Eu;var Ue=typeof document!="undefined"?document.currentScript:null;function $e(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Q=$e(y);const Ne=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Te=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),ze=e=>{const t=Te(e);return t.charAt(0).toUpperCase()+t.slice(1)},tn=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Nn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Tr={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 it=y.forwardRef((u,l)=>{var c=u,{color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i="",children:s,iconNode:a}=c,o=q(c,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(I(m({ref:l},Tr),{width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:tn("lucide",i)}),!s&&!Nn(o)&&{"aria-hidden":"true"}),o),[...a.map(([d,h])=>y.createElement(d,h)),...Array.isArray(s)?s:[s]])});const Be=(e,t)=>{const n=y.forwardRef((a,s)=>{var o=a,{className:r}=o,i=q(o,["className"]);return y.createElement(it,m({ref:s,iconNode:t,className:tn(`lucide-${Ne(ze(e))}`,`lucide-${e}`,r)},i))});return n.displayName=ze(e),n};const Ou=Be("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const ls=Be("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const Cr=Be("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Fu=Be("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 zu=Be("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 us=Be("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 Bu=Be("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 cs=Be("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const ds=Be("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 Ru=Be("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);const hs=Be("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const ju=Be("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]);const Uu=Be("upload",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]);const $u=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Hu=e=>Array.from(e).map(n=>n.getModelContext()).sort((n,r)=>{var i,s;return((i=r.priority)!=null?i:0)-((s=n.priority)!=null?s:0)}).reduce((n,r)=>{var i;if(r.system&&(n.system?n.system+=`
2
2
 
3
- ${r.system}`:n.system=r.system),r.tools)for(const[s,a]of Object.entries(r.tools)){const o=(i=n.tools)==null?void 0:i[s];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${s}, but it already exists.`);n.tools||(n.tools={}),n.tools[s]=a}return r.config&&(n.config=g(g({},n.config),r.config)),r.callSettings&&(n.callSettings=g(g({},n.callSettings),r.callSettings)),n},{}),Tr=class{constructor(){T(this,"_providers",new Set);T(this,"_subscribers",new Set)}getModelContext(){return Bu(this._providers)}registerModelContextProvider(e){var n;this._providers.add(e);const t=(n=e.subscribe)==null?void 0:n.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)}},Ir=class{constructor(){T(this,"_contextProvider",new Tr)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},en=class{constructor(){T(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(n){e.push(n)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},zu=e=>e.status.type==="complete",cs=class extends en{constructor(){super(...arguments);T(this,"isEditing",!0);T(this,"_attachments",[]);T(this,"_text","");T(this,"_role","user");T(this,"_runConfig",{});T(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,n;return(n=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?n:"*"}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 M(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(n=>t.remove(n))))})}reset(){return M(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 M(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return M(this,null,function*(){const t=this.getAttachmentAdapter(),n=t&&this.attachments.length>0?Promise.all(this.attachments.map(s=>M(this,null,function*(){return zu(s)?s:yield t.send(s)}))):[],r=this.text;this._emptyTextAndAttachments();const i={createdAt:new Date,role:this.role,content:r?[{type:"text",text:r}]:[],attachments:yield n,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(i),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return M(this,null,function*(){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const r=u=>{const c=this._attachments.findIndex(d=>d.id===u.id);c!==-1?this._attachments=[...this._attachments.slice(0,c),u,...this._attachments.slice(c+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},i=n.add({file:t});if(Symbol.asyncIterator in i)try{for(var s=Lt(i),a,o,l;a=!(o=yield s.next()).done;a=!1){const u=o.value;r(u)}}catch(o){l=[o]}finally{try{a&&(o=s.return)&&(yield o.call(s))}finally{if(l)throw l[0]}}else r(yield i);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return M(this,null,function*(){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(s=>s.id===t);if(r===-1)throw new Error("Attachment not found");const i=this._attachments[r];yield n.remove(i),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const r of n)r()}unstable_on(t,n){const r=this._eventSubscribers.get(t);return r?r.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{const i=this._eventSubscribers.get(t);i&&i.delete(n)}}},ds=class extends cs{constructor(t){super();T(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 M(this,null,function*(){var n,r;this.runtime.append(E(g({},t),{parentId:(r=(n=this.runtime.messages.at(-1))==null?void 0:n.id)!=null?r:null,sourceId:null}))})}handleCancel(){return M(this,null,function*(){this.runtime.cancelRun()})}};let hs=(e,t=21)=>(n=t)=>{let r="",i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r};var St=hs("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Ru="__optimistic__",ju=()=>`${Ru}${St()}`,tn=Symbol("autoStatus"),Uu=Object.freeze(Object.assign({type:"running"},{[tn]:!0})),$u=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[tn]:!0})),Hu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[tn]:!0})),qu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[tn]:!0})),fs=(e,t,n,r,i)=>e&&i?Object.assign({type:"incomplete",reason:"error",error:i},{[tn]:!0}):e&&t?Uu:n?qu:r?Hu:$u;function Nn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var kt={exports:{}},ps;function Vu(){if(ps)return kt.exports;ps=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*:/,n=/"(?: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 r(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 c=JSON.parse(o,l);if(c===null||typeof c!="object")return c;const d=u&&u.protoAction||"error",h=u&&u.constructorAction||"error";if(d==="ignore"&&h==="ignore")return c;if(d!=="ignore"&&h!=="ignore"){if(t.test(o)===!1&&n.test(o)===!1)return c}else if(d!=="ignore"&&h==="ignore"){if(t.test(o)===!1)return c}else if(n.test(o)===!1)return c;return i(c,{protoAction:d,constructorAction:h,safe:u&&u.safe})}function i(o,{protoAction:l="error",constructorAction:u="error",safe:c}={}){let d=[o];for(;d.length;){const h=d;d=[];for(const f of h){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"__proto__")){if(c===!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(c===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete f.constructor}for(const m in f){const v=f[m];v&&typeof v=="object"&&d.push(v)}}}return o}function s(o,l,u){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return r(o,l,u)}finally{Error.stackTraceLimit=c}}function a(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return r(o,l,{safe:!0})}catch(c){return}finally{Error.stackTraceLimit=u}}return kt.exports=s,kt.exports.default=s,kt.exports.parse=s,kt.exports.safeParse=a,kt.exports.scan=i,kt.exports}var Wu=Vu();const Cr=Nn(Wu);function Ju(e){const t=["ROOT"];let n=-1,r=null;const i=[];let s;function a(){s!==void 0&&(i.push(JSON.parse(`"${s}"`)),s=void 0)}function o(d,h,f){switch(d){case'"':{n=h,t.pop(),t.push(f),t.push("INSIDE_STRING"),a();break}case"f":case"t":case"n":{n=h,r=h,t.pop(),t.push(f),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(f),t.push("INSIDE_NUMBER"),a();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=h,t.pop(),t.push(f),t.push("INSIDE_NUMBER"),a();break}case"{":{n=h,t.pop(),t.push(f),t.push("INSIDE_OBJECT_START"),a();break}case"[":{n=h,t.pop(),t.push(f),t.push("INSIDE_ARRAY_START"),a();break}}}function l(d,h){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=h,t.pop(),s=i.pop();break}}}function u(d,h){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{n=h,t.pop(),s=i.pop();break}}}for(let d=0;d<e.length;d++){const h=e[d];switch(t[t.length-1]){case"ROOT":o(h,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}case"}":{n=d,t.pop(),s=i.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),s+=h;break}default:{s+=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,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(h,d);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),n=d,s=i.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=d}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{n=d,t.pop(),s=i.pop();break}default:{n=d,s="0",o(h,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{n=d,t.pop(),s=i.pop();break}default:{n=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(h,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?n=d:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(s+=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":{n=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,d);break}case"}":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,d);break}case"]":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d);break}default:{t.pop(),s=i.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(r,d+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d)):n=d;break}}}let c=e.slice(0,n+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{c+='"';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":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const f=e.substring(r,e.length);"true".startsWith(f)?c+="true".slice(f.length):"false".startsWith(f)?c+="false".slice(f.length):"null".startsWith(f)&&(c+="null".slice(f.length))}}return[c,i]}var Ln=Symbol("aui.parse-partial-json-object.meta"),Ku=e=>e==null?void 0:e[Ln],Dn=e=>{if(e.length===0)return{[Ln]:{state:"partial",partialPath:[]}};try{const t=Cr.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Ln]={state:"complete",partialPath:[]},t}catch(t){try{const[n,r]=Ju(e),i=Cr.parse(n);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[Ln]={state:"partial",partialPath:r},i}catch(n){return}}},ms=(e,t,n)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(n.length===0)return t.state;const[r,...i]=n;if(!Object.prototype.hasOwnProperty.call(e,r))return"partial";const[s,...a]=t.partialPath;if(r!==s)return"complete";const o=e[r];return ms(o,{state:"partial",partialPath:a},i)},Dt=(e,t)=>{const n=Ku(e);if(!n)throw new Error("unable to determine object state");return ms(e,n,t.map(String))};function Yu(){return Mn(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:n}=yield new Ee(e.read());if(t)break;yield n}}finally{e.releaseLock()}})}function Er(e){var t,n;return(n=e[t=Symbol.asyncIterator])!=null||(e[t]=Yu),e}var Ar={toResponse(e,t){var n;return new Response(Ar.toByteStream(e,t),{headers:(n=t.headers)!=null?n:{}})},fromResponse(e,t){return Ar.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Mr=function(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});if(!e||!t)throw new Error("Failed to create promise");return{promise:n,resolve:e,reject:t}},Gu=()=>{const e=[];let t=!1,n,r;const i=a=>{a.promise||(a.promise=a.reader.read().then(({done:o,value:l})=>{a.promise=void 0,o?(e.splice(e.indexOf(a),1),t&&e.length===0&&n.close()):n.enqueue(l),r==null||r.resolve(),r=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,n.error(o),r==null||r.reject(o),r=void 0}))};return{readable:new ReadableStream({start(a){n=a},pull(){return r=Mr(),e.forEach(a=>{i(a)}),r.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(a){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:a.getReader()};e.push(o),i(o)},enqueue(a){this.addStream(new ReadableStream({start(o){o.enqueue(a),o.close()}}))}}},gs=class{constructor(e){T(this,"_controller");T(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())}},ys=e=>new ReadableStream({start(t){var n;return(n=e.start)==null?void 0:n.call(e,new gs(t))},pull(t){var n;return(n=e.pull)==null?void 0:n.call(e,new gs(t))},cancel(t){var n;return(n=e.cancel)==null?void 0:n.call(e,t)}}),bs=()=>{let e;return[ys({start(n){e=n}}),e]},ws=class{constructor(e){T(this,"_isClosed",!1);T(this,"_mergeTask");T(this,"_argsTextController");this._controller=e;const t=ys({start:r=>{this._argsTextController=r}});let n=!1;this._mergeTask=t.pipeTo(new WritableStream({write:r=>{switch(r.type){case"text-delta":n=!0,this._controller.enqueue(r);break;case"part-finish":n||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: ${r.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return M(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(g({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return M(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},Xu=e=>new ReadableStream({start(t){var n;return(n=e.start)==null?void 0:n.call(e,new ws(t))},pull(t){var n;return(n=e.pull)==null?void 0:n.call(e,new ws(t))},cancel(t){var n;return(n=e.cancel)==null?void 0:n.call(e,t)}}),Qu=()=>{let e;return[Xu({start(n){e=n}}),e]},xs=class{constructor(){T(this,"value",-1)}up(){return++this.value}},Zu=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue(E(g({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,n){const{path:[r,...i]}=t;if(e!==r)throw new Error(`Path mismatch: expected ${e}, got ${r}`);n.enqueue(E(g({},t),{path:i}))}})}});var ec=class extends TransformStream{constructor(e){const t=new xs,n=new Map;super({transform(r,i){r.type==="part-start"&&r.path.length===0&&n.set(t.up(),e.up());const[s,...a]=r.path;if(s===void 0){i.enqueue(r);return}const o=n.get(s);if(o===void 0)throw new Error("Path not found");i.enqueue(E(g({},r),{path:[o,...a]}))}})}},vs=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},Ss=class extends TransformStream{constructor(){const e=[];super({transform(t,n){if(t.type==="part-start"){if(t.path.length!==0){n.error(new Error("Nested parts are not supported"));return}e.push(t.part),n.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){n.error(new Error(`${t.type} chunks must have a path of length 1`));return}const r=t.path[0];if(r<0||r>=e.length){n.error(new Error(`Invalid path index: ${r}`));return}const i=e[r];n.enqueue(E(g({},t),{meta:i}));return}n.enqueue(t)}})}},ks=hs("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),tc=class Au{constructor(t){T(this,"_state");T(this,"_parentId");this._state=t||{merger:Gu(),contentCounter:new xs}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,n){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(n.pipeThrough(new Zu(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new ec(this._state.contentCounter)))}appendText(t){var n;((n=this._state.append)==null?void 0:n.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var n;((n=this._state.append)==null?void 0:n.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,n]=bs();return this._addPart({type:"text"},t),n}addReasoningPart(){const[t,n]=bs();return this._addPart({type:"reasoning"},t),n}addToolCallPart(t){var o;const n=typeof t=="string"?{toolName:t}:t,r=n.toolName,i=(o=n.toolCallId)!=null?o:ks(),[s,a]=Qu();return this._addPart(g({type:"tool-call",toolName:r,toolCallId:i},this._parentId&&{parentId:this._parentId}),s),n.argsText!==void 0&&(a.argsText.append(n.argsText),a.argsText.close()),n.args!==void 0&&(a.argsText.append(JSON.stringify(n.args)),a.argsText.close()),n.response!==void 0&&a.setResponse(n.response),a}appendSource(t){this._addPart(g(g({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const n=new Au(this._state);return n._parentId=t,n}close(){var t,n,r,i;(n=(t=this._state.append)==null?void 0:t.controller)==null||n.close(),this._state.merger.seal(),(i=(r=this._state).closeSubscriber)==null||i.call(r)}};function nc(e){const t=new tc;return M(null,null,function*(){try{yield e(t)}catch(r){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(r)}),r}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function _s(){const{resolve:e,promise:t}=Mr();let n;return[nc(i=>(n=i,n.__internal_subscribeToClose(e),t)),n]}var rc=class extends TransformStream{constructor(e,t,n){const[r,i]=_s();let s;super({start(o){var l;return s=r.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,i)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,i)},flush(){return M(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,i),i.close(),yield s})}},t,n)}},nn=(e,t,n)=>{var h,f,m,v,b,x,C;const{role:r,id:i,createdAt:s,attachments:a,status:o,metadata:l}=e,u={id:i!=null?i:t,createdAt:s!=null?s:new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,d=z=>{var I=z,{image:_}=I,F=V(I,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(g({},F),{image:_}):(console.warn("Invalid image data format detected"),null)};if(r!=="user"&&(a!=null&&a.length))throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return E(g({},u),{role:r,content:c.map(_=>{var I,H,q,j,k;const F=_.type;switch(F){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return d(_);case"data":return _;case"tool-call":{const z=_,{parentId:O,messages:P}=z,R=V(z,["parentId","messages"]),L=g(g(E(g({},R),{toolCallId:(I=_.toolCallId)!=null?I:`tool-${St()}`}),O!==void 0&&{parentId:O}),P!==void 0&&{messages:P});return _.args?E(g({},L),{args:_.args,argsText:(H=_.argsText)!=null?H:JSON.stringify(_.args)}):E(g({},L),{args:(j=Dn((q=_.argsText)!=null?q:""))!=null?j:{},argsText:(k=_.argsText)!=null?k:""})}default:{const O=F;throw new Error(`Unsupported assistant message part type: ${O}`)}}}).filter(_=>!!_),status:o!=null?o:n,metadata:g({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:(m=l==null?void 0:l.unstable_data)!=null?m:[],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(g({},u),{role:r,content:c.map(_=>{const F=_.type;switch(F){case"text":case"image":case"audio":case"file":return _;default:{const z=F;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:a!=null?a:[],metadata:{custom:(x=l==null?void 0:l.custom)!=null?x:{}}});case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(g({},u),{role:r,content:c,metadata:{custom:(C=l==null?void 0:l.custom)!=null?C:{}}});default:{const _=r;throw new Error(`Unknown message role: ${_}`)}}},Pr={fromArray:e=>{const t=e.map(n=>nn(n,St(),fs(!1,!1,!1,!1,void 0)));return{messages:t.map((n,r)=>({parentId:r>0?t[r-1].id:null,message:n}))}}},On=e=>e.next?On(e.next):"current"in e?e:null,ic=class{constructor(e){T(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Ts=class{constructor(){T(this,"messages",new Map);T(this,"head",null);T(this,"root",{children:[],next:null});T(this,"_messages",new ic(()=>{var t,n;const e=new Array(((n=(t=this.head)==null?void 0:t.level)!=null?n:-1)+1);for(let r=this.head;r;r=r.prev)e[r.level]=r.current;return e}))}updateLevels(e,t){e.level=t;for(const n of e.children){const r=this.messages.get(n);r&&this.updateLevels(r,t+1)}}performOp(e,t,n){var s;const r=(s=t.prev)!=null?s:this.root,i=e!=null?e:this.root;if(!(n==="relink"&&r===i)){if(n!=="link"&&(r.children=r.children.filter(a=>a!==t.current.id),r.next===t)){const a=r.children.at(-1),o=a?this.messages.get(a):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.");r.next=o}if(n!=="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.");i.children=[...i.children,t.current.id],(On(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;const a=e?e.level+1:0;this.updateLevels(t,a)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var r;if(e===void 0||e===((r=this.head)==null?void 0:r.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 n=new Array(t.level+1);for(let i=t;i;i=i.prev)n[i.level]=i.current;return n}addOrUpdateMessage(e,t){const n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(n){n.current=t,this.performOp(r,n,"relink"),this._messages.dirty();return}const i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,"link"),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){var n,r;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:(r=(n=t.prev)==null?void 0:n.current.id)!=null?r:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let n;do n=ju();while(this.messages.has(n));return this.addOrUpdateMessage(e,nn(t,n,{type:"running"})),n}deleteMessage(e,t){const n=this.messages.get(e);if(!n)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const i of n.children){const s=this.messages.get(i);if(!s)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,s,"relink")}this.performOp(null,n,"cut"),this.messages.delete(e),this.head===n&&(this.head=On(r!=null?r:this.root)),this._messages.dirty()}getBranches(e){var r;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:n}=(r=t.prev)!=null?r:this.root;return n}switchToBranch(e){var r;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 n=(r=t.prev)!=null?r:this.root;n.next=t,this.head=On(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 n=r=>{for(const i of r.children){const s=this.messages.get(i);s&&(n(s),this.messages.delete(i))}};n(t),t.children=[],t.next=null}this.head=t;for(let n=t;n;n=n.prev)n.prev&&(n.prev.next=n);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,n,r,i;const e=[];for(const[,s]of this.messages)e.push({message:s.current,parentId:(n=(t=s.prev)==null?void 0:t.current.id)!=null?n:null});return{headId:(i=(r=this.head)==null?void 0:r.current.id)!=null?i:null,messages:e}}import({headId:e,messages:t}){var n,r;for(const{message:i,parentId:s}of t)this.addOrUpdateMessage(s,i);this.resetHead((r=e!=null?e:(n=t.at(-1))==null?void 0:n.message.id)!=null?r:null)}},Fn=class{constructor(){T(this,"_subscriptions",new Set);T(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()}}},Xe=Symbol("skip-update"),Nr=class extends Fn{constructor(t){super();T(this,"_previousStateDirty",!0);T(this,"_previousState");T(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Xe&&(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)}},Bn=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 n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const i=this._core.getState(),s=i.isMain,a=i.id;n===s&&r===a||(n=s,r=a,!(e==="switched-to"&&!s)&&(e==="switched-away"&&s||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function sc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const n of Object.keys(e)){const r=e[n],i=t[n];if(!Object.is(r,i))return!1}return!0}var Qe=class extends Fn{constructor(t){super();T(this,"_previousState");T(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const n=t.getState();if(n===Xe)throw new Error("Entry not available in the store");this._previousState=n}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Xe||sc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},zn=Symbol("innerMessage"),Rn=e=>e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
3
+ ${r.system}`:n.system=r.system),r.tools)for(const[s,a]of Object.entries(r.tools)){const o=(i=n.tools)==null?void 0:i[s];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${s}, but it already exists.`);n.tools||(n.tools={}),n.tools[s]=a}return r.config&&(n.config=m(m({},n.config),r.config)),r.callSettings&&(n.callSettings=m(m({},n.callSettings),r.callSettings)),n},{}),Ir=class{constructor(){T(this,"_providers",new Set);T(this,"_subscribers",new Set)}getModelContext(){return Hu(this._providers)}registerModelContextProvider(e){var n;this._providers.add(e);const t=(n=e.subscribe)==null?void 0:n.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)}},Er=class{constructor(){T(this,"_contextProvider",new Ir)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},nn=class{constructor(){T(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(n){e.push(n)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},qu=e=>e.status.type==="complete",fs=class extends nn{constructor(){super(...arguments);T(this,"isEditing",!0);T(this,"_attachments",[]);T(this,"_text","");T(this,"_role","user");T(this,"_runConfig",{});T(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,n;return(n=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?n:"*"}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 M(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(n=>t.remove(n))))})}reset(){return M(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 M(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return M(this,null,function*(){const t=this.getAttachmentAdapter(),n=t&&this.attachments.length>0?Promise.all(this.attachments.map(s=>M(this,null,function*(){return qu(s)?s:yield t.send(s)}))):[],r=this.text;this._emptyTextAndAttachments();const i={createdAt:new Date,role:this.role,content:r?[{type:"text",text:r}]:[],attachments:yield n,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(i),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return M(this,null,function*(){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const r=u=>{const c=this._attachments.findIndex(d=>d.id===u.id);c!==-1?this._attachments=[...this._attachments.slice(0,c),u,...this._attachments.slice(c+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},i=n.add({file:t});if(Symbol.asyncIterator in i)try{for(var s=Lt(i),a,o,l;a=!(o=yield s.next()).done;a=!1){const u=o.value;r(u)}}catch(o){l=[o]}finally{try{a&&(o=s.return)&&(yield o.call(s))}finally{if(l)throw l[0]}}else r(yield i);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return M(this,null,function*(){const n=this.getAttachmentAdapter();if(!n)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(s=>s.id===t);if(r===-1)throw new Error("Attachment not found");const i=this._attachments[r];yield n.remove(i),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const n=this._eventSubscribers.get(t);if(n)for(const r of n)r()}unstable_on(t,n){const r=this._eventSubscribers.get(t);return r?r.add(n):this._eventSubscribers.set(t,new Set([n])),()=>{const i=this._eventSubscribers.get(t);i&&i.delete(n)}}},ps=class extends fs{constructor(t){super();T(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 M(this,null,function*(){var n,r;this.runtime.append(I(m({},t),{parentId:(r=(n=this.runtime.messages.at(-1))==null?void 0:n.id)!=null?r:null,sourceId:null}))})}handleCancel(){return M(this,null,function*(){this.runtime.cancelRun()})}};let ms=(e,t=21)=>(n=t)=>{let r="",i=n|0;for(;i--;)r+=e[Math.random()*e.length|0];return r};var St=ms("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Vu="__optimistic__",Wu=()=>`${Vu}${St()}`,rn=Symbol("autoStatus"),Ju=Object.freeze(Object.assign({type:"running"},{[rn]:!0})),Ku=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[rn]:!0})),Yu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[rn]:!0})),Gu=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[rn]:!0})),gs=(e,t,n,r,i)=>e&&i?Object.assign({type:"incomplete",reason:"error",error:i},{[rn]:!0}):e&&t?Ju:n?Gu:r?Yu:Ku;function Ln(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var kt={exports:{}},ys;function Xu(){if(ys)return kt.exports;ys=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*:/,n=/"(?: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 r(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 c=JSON.parse(o,l);if(c===null||typeof c!="object")return c;const d=u&&u.protoAction||"error",h=u&&u.constructorAction||"error";if(d==="ignore"&&h==="ignore")return c;if(d!=="ignore"&&h!=="ignore"){if(t.test(o)===!1&&n.test(o)===!1)return c}else if(d!=="ignore"&&h==="ignore"){if(t.test(o)===!1)return c}else if(n.test(o)===!1)return c;return i(c,{protoAction:d,constructorAction:h,safe:u&&u.safe})}function i(o,{protoAction:l="error",constructorAction:u="error",safe:c}={}){let d=[o];for(;d.length;){const h=d;d=[];for(const f of h){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"__proto__")){if(c===!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(c===!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"&&d.push(v)}}}return o}function s(o,l,u){const{stackTraceLimit:c}=Error;Error.stackTraceLimit=0;try{return r(o,l,u)}finally{Error.stackTraceLimit=c}}function a(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return r(o,l,{safe:!0})}catch(c){return}finally{Error.stackTraceLimit=u}}return kt.exports=s,kt.exports.default=s,kt.exports.parse=s,kt.exports.safeParse=a,kt.exports.scan=i,kt.exports}var Qu=Xu();const Ar=Ln(Qu);function Zu(e){const t=["ROOT"];let n=-1,r=null;const i=[];let s;function a(){s!==void 0&&(i.push(JSON.parse(`"${s}"`)),s=void 0)}function o(d,h,f){switch(d){case'"':{n=h,t.pop(),t.push(f),t.push("INSIDE_STRING"),a();break}case"f":case"t":case"n":{n=h,r=h,t.pop(),t.push(f),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(f),t.push("INSIDE_NUMBER"),a();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=h,t.pop(),t.push(f),t.push("INSIDE_NUMBER"),a();break}case"{":{n=h,t.pop(),t.push(f),t.push("INSIDE_OBJECT_START"),a();break}case"[":{n=h,t.pop(),t.push(f),t.push("INSIDE_ARRAY_START"),a();break}}}function l(d,h){switch(d){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=h,t.pop(),s=i.pop();break}}}function u(d,h){switch(d){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{n=h,t.pop(),s=i.pop();break}}}for(let d=0;d<e.length;d++){const h=e[d];switch(t[t.length-1]){case"ROOT":o(h,d,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}case"}":{n=d,t.pop(),s=i.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),s="";break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),s+=h;break}default:{s+=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,d,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(h,d);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),n=d,s=i.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=d}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{n=d,t.pop(),s=i.pop();break}default:{n=d,s="0",o(h,d,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),s=(Number(s)+1).toString();break}case"]":{n=d,t.pop(),s=i.pop();break}default:{n=d;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(h,d,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?n=d:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(s+=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":{n=d;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,d);break}case"}":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,d);break}case"]":{t.pop(),s=i.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d);break}default:{t.pop(),s=i.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(r,d+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,d):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,d)):n=d;break}}}let c=e.slice(0,n+1);for(let d=t.length-1;d>=0;d--)switch(t[d]){case"INSIDE_STRING":{c+='"';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":{c+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{c+="]";break}case"INSIDE_LITERAL":{const f=e.substring(r,e.length);"true".startsWith(f)?c+="true".slice(f.length):"false".startsWith(f)?c+="false".slice(f.length):"null".startsWith(f)&&(c+="null".slice(f.length))}}return[c,i]}var Dn=Symbol("aui.parse-partial-json-object.meta"),ec=e=>e==null?void 0:e[Dn],On=e=>{if(e.length===0)return{[Dn]:{state:"partial",partialPath:[]}};try{const t=Ar.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Dn]={state:"complete",partialPath:[]},t}catch(t){try{const[n,r]=Zu(e),i=Ar.parse(n);if(typeof i!="object"||i===null)throw new Error("argsText is expected to be an object");return i[Dn]={state:"partial",partialPath:r},i}catch(n){return}}},bs=(e,t,n)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(n.length===0)return t.state;const[r,...i]=n;if(!Object.prototype.hasOwnProperty.call(e,r))return"partial";const[s,...a]=t.partialPath;if(r!==s)return"complete";const o=e[r];return bs(o,{state:"partial",partialPath:a},i)},Dt=(e,t)=>{const n=ec(e);if(!n)throw new Error("unable to determine object state");return bs(e,n,t.map(String))};function tc(){return Pn(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:n}=yield new Ee(e.read());if(t)break;yield n}}finally{e.releaseLock()}})}function Mr(e){var t,n;return(n=e[t=Symbol.asyncIterator])!=null||(e[t]=tc),e}var Pr={toResponse(e,t){var n;return new Response(Pr.toByteStream(e,t),{headers:(n=t.headers)!=null?n:{}})},fromResponse(e,t){return Pr.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Nr=function(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});if(!e||!t)throw new Error("Failed to create promise");return{promise:n,resolve:e,reject:t}},nc=()=>{const e=[];let t=!1,n,r;const i=a=>{a.promise||(a.promise=a.reader.read().then(({done:o,value:l})=>{a.promise=void 0,o?(e.splice(e.indexOf(a),1),t&&e.length===0&&n.close()):n.enqueue(l),r==null||r.resolve(),r=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,n.error(o),r==null||r.reject(o),r=void 0}))};return{readable:new ReadableStream({start(a){n=a},pull(){return r=Nr(),e.forEach(a=>{i(a)}),r.promise},cancel(){e.forEach(a=>{a.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&n.close()},addStream(a){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:a.getReader()};e.push(o),i(o)},enqueue(a){this.addStream(new ReadableStream({start(o){o.enqueue(a),o.close()}}))}}},ws=class{constructor(e){T(this,"_controller");T(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())}},xs=e=>new ReadableStream({start(t){var n;return(n=e.start)==null?void 0:n.call(e,new ws(t))},pull(t){var n;return(n=e.pull)==null?void 0:n.call(e,new ws(t))},cancel(t){var n;return(n=e.cancel)==null?void 0:n.call(e,t)}}),vs=()=>{let e;return[xs({start(n){e=n}}),e]},Ss=class{constructor(e){T(this,"_isClosed",!1);T(this,"_mergeTask");T(this,"_argsTextController");this._controller=e;const t=xs({start:r=>{this._argsTextController=r}});let n=!1;this._mergeTask=t.pipeTo(new WritableStream({write:r=>{switch(r.type){case"text-delta":n=!0,this._controller.enqueue(r);break;case"part-finish":n||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: ${r.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return M(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(I(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return M(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},rc=e=>new ReadableStream({start(t){var n;return(n=e.start)==null?void 0:n.call(e,new Ss(t))},pull(t){var n;return(n=e.pull)==null?void 0:n.call(e,new Ss(t))},cancel(t){var n;return(n=e.cancel)==null?void 0:n.call(e,t)}}),ic=()=>{let e;return[rc({start(n){e=n}}),e]},ks=class{constructor(){T(this,"value",-1)}up(){return++this.value}},sc=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue(I(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,n){const{path:[r,...i]}=t;if(e!==r)throw new Error(`Path mismatch: expected ${e}, got ${r}`);n.enqueue(I(m({},t),{path:i}))}})}});var ac=class extends TransformStream{constructor(e){const t=new ks,n=new Map;super({transform(r,i){r.type==="part-start"&&r.path.length===0&&n.set(t.up(),e.up());const[s,...a]=r.path;if(s===void 0){i.enqueue(r);return}const o=n.get(s);if(o===void 0)throw new Error("Path not found");i.enqueue(I(m({},r),{path:[o,...a]}))}})}},_s=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},Ts=class extends TransformStream{constructor(){const e=[];super({transform(t,n){if(t.type==="part-start"){if(t.path.length!==0){n.error(new Error("Nested parts are not supported"));return}e.push(t.part),n.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){n.error(new Error(`${t.type} chunks must have a path of length 1`));return}const r=t.path[0];if(r<0||r>=e.length){n.error(new Error(`Invalid path index: ${r}`));return}const i=e[r];n.enqueue(I(m({},t),{meta:i}));return}n.enqueue(t)}})}},Cs=ms("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),oc=class Du{constructor(t){T(this,"_state");T(this,"_parentId");this._state=t||{merger:nc(),contentCounter:new ks}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,n){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(n.pipeThrough(new sc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new ac(this._state.contentCounter)))}appendText(t){var n;((n=this._state.append)==null?void 0:n.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var n;((n=this._state.append)==null?void 0:n.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,n]=vs();return this._addPart({type:"text"},t),n}addReasoningPart(){const[t,n]=vs();return this._addPart({type:"reasoning"},t),n}addToolCallPart(t){var o;const n=typeof t=="string"?{toolName:t}:t,r=n.toolName,i=(o=n.toolCallId)!=null?o:Cs(),[s,a]=ic();return this._addPart(m({type:"tool-call",toolName:r,toolCallId:i},this._parentId&&{parentId:this._parentId}),s),n.argsText!==void 0&&(a.argsText.append(n.argsText),a.argsText.close()),n.args!==void 0&&(a.argsText.append(JSON.stringify(n.args)),a.argsText.close()),n.response!==void 0&&a.setResponse(n.response),a}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(n){n.enqueue({type:"part-finish",path:[]}),n.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const n=new Du(this._state);return n._parentId=t,n}close(){var t,n,r,i;(n=(t=this._state.append)==null?void 0:t.controller)==null||n.close(),this._state.merger.seal(),(i=(r=this._state).closeSubscriber)==null||i.call(r)}};function Is(e){const t=new oc;return M(null,null,function*(){try{yield e(t)}catch(r){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(r)}),r}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function Es(){const{resolve:e,promise:t}=Nr();let n;return[Is(i=>(n=i,n.__internal_subscribeToClose(e),t)),n]}var lc=class extends TransformStream{constructor(e,t,n){const[r,i]=Es();let s;super({start(o){var l;return s=r.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,i)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,i)},flush(){return M(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,i),i.close(),yield s})}},t,n)}},sn=(e,t,n)=>{var h,f,g,v,b,x,E;const{role:r,id:i,createdAt:s,attachments:a,status:o,metadata:l}=e,u={id:i!=null?i:t,createdAt:s!=null?s:new Date},c=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,d=B=>{var C=B,{image:_}=C,F=q(C,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?I(m({},F),{image:_}):(console.warn("Invalid image data format detected"),null)};if(r!=="user"&&(a!=null&&a.length))throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return I(m({},u),{role:r,content:c.map(_=>{var C,H,V,j,k;const F=_.type;switch(F){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return d(_);case"data":return _;case"tool-call":{const B=_,{parentId:O,messages:P}=B,R=q(B,["parentId","messages"]),L=m(m(I(m({},R),{toolCallId:(C=_.toolCallId)!=null?C:`tool-${St()}`}),O!==void 0&&{parentId:O}),P!==void 0&&{messages:P});return _.args?I(m({},L),{args:_.args,argsText:(H=_.argsText)!=null?H:JSON.stringify(_.args)}):I(m({},L),{args:(j=On((V=_.argsText)!=null?V:""))!=null?j:{},argsText:(k=_.argsText)!=null?k:""})}default:{const O=F;throw new Error(`Unsupported assistant message part type: ${O}`)}}}).filter(_=>!!_),status:o!=null?o:n,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 I(m({},u),{role:r,content:c.map(_=>{const F=_.type;switch(F){case"text":case"image":case"audio":case"file":return _;default:{const B=F;throw new Error(`Unsupported user message part type: ${B}`)}}}),attachments:a!=null?a:[],metadata:{custom:(x=l==null?void 0:l.custom)!=null?x:{}}});case"system":if(c.length!==1||c[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return I(m({},u),{role:r,content:c,metadata:{custom:(E=l==null?void 0:l.custom)!=null?E:{}}});default:{const _=r;throw new Error(`Unknown message role: ${_}`)}}},Lr={fromArray:e=>{const t=e.map(n=>sn(n,St(),gs(!1,!1,!1,!1,void 0)));return{messages:t.map((n,r)=>({parentId:r>0?t[r-1].id:null,message:n}))}}},Fn=e=>e.next?Fn(e.next):"current"in e?e:null,uc=class{constructor(e){T(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},As=class{constructor(){T(this,"messages",new Map);T(this,"head",null);T(this,"root",{children:[],next:null});T(this,"_messages",new uc(()=>{var t,n;const e=new Array(((n=(t=this.head)==null?void 0:t.level)!=null?n:-1)+1);for(let r=this.head;r;r=r.prev)e[r.level]=r.current;return e}))}updateLevels(e,t){e.level=t;for(const n of e.children){const r=this.messages.get(n);r&&this.updateLevels(r,t+1)}}performOp(e,t,n){var s;const r=(s=t.prev)!=null?s:this.root,i=e!=null?e:this.root;if(!(n==="relink"&&r===i)){if(n!=="link"&&(r.children=r.children.filter(a=>a!==t.current.id),r.next===t)){const a=r.children.at(-1),o=a?this.messages.get(a):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.");r.next=o}if(n!=="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.");i.children=[...i.children,t.current.id],(Fn(t)===this.head||i.next===null)&&(i.next=t),t.prev=e;const a=e?e.level+1:0;this.updateLevels(t,a)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var r;if(e===void 0||e===((r=this.head)==null?void 0:r.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 n=new Array(t.level+1);for(let i=t;i;i=i.prev)n[i.level]=i.current;return n}addOrUpdateMessage(e,t){const n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(n){n.current=t,this.performOp(r,n,"relink"),this._messages.dirty();return}const i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,"link"),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){var n,r;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:(r=(n=t.prev)==null?void 0:n.current.id)!=null?r:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let n;do n=Wu();while(this.messages.has(n));return this.addOrUpdateMessage(e,sn(t,n,{type:"running"})),n}deleteMessage(e,t){const n=this.messages.get(e);if(!n)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const i of n.children){const s=this.messages.get(i);if(!s)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,s,"relink")}this.performOp(null,n,"cut"),this.messages.delete(e),this.head===n&&(this.head=Fn(r!=null?r:this.root)),this._messages.dirty()}getBranches(e){var r;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:n}=(r=t.prev)!=null?r:this.root;return n}switchToBranch(e){var r;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 n=(r=t.prev)!=null?r:this.root;n.next=t,this.head=Fn(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 n=r=>{for(const i of r.children){const s=this.messages.get(i);s&&(n(s),this.messages.delete(i))}};n(t),t.children=[],t.next=null}this.head=t;for(let n=t;n;n=n.prev)n.prev&&(n.prev.next=n);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,n,r,i;const e=[];for(const[,s]of this.messages)e.push({message:s.current,parentId:(n=(t=s.prev)==null?void 0:t.current.id)!=null?n:null});return{headId:(i=(r=this.head)==null?void 0:r.current.id)!=null?i:null,messages:e}}import({headId:e,messages:t}){var n,r;for(const{message:i,parentId:s}of t)this.addOrUpdateMessage(s,i);this.resetHead((r=e!=null?e:(n=t.at(-1))==null?void 0:n.message.id)!=null?r:null)}},zn=class{constructor(){T(this,"_subscriptions",new Set);T(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()}}},Xe=Symbol("skip-update"),Dr=class extends zn{constructor(t){super();T(this,"_previousStateDirty",!0);T(this,"_previousState");T(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==Xe&&(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)}},Bn=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 n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{const i=this._core.getState(),s=i.isMain,a=i.id;n===s&&r===a||(n=s,r=a,!(e==="switched-to"&&!s)&&(e==="switched-away"&&s||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function cc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const n of Object.keys(e)){const r=e[n],i=t[n];if(!Object.is(r,i))return!1}return!0}var Qe=class extends zn{constructor(t){super();T(this,"_previousState");T(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const n=t.getState();if(n===Xe)throw new Error("Entry not available in the store");this._previousState=n}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===Xe||cc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Rn=Symbol("innerMessage"),jn=e=>e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
4
4
 
5
- `),Is=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)}},Cs=class extends Is{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)}},ac=class extends Cs{get source(){return"thread-composer"}},oc=class extends Cs{get source(){return"edit-composer"}},lc=class extends Is{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Es=class extends Fn{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(),n=t==null?void 0:t.unstable_on(this.config.event,e);const r=()=>{var a;const s=this.config.binding.getState();s!==t&&(t=s,n==null||n(),n=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,e))},i=this.outerSubscribe(r);return()=>{i==null||i(),n==null||n()}}},As=Object.freeze([]),Ms=Object.freeze({}),uc=e=>{var t,n,r,i,s,a,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,attachments:(i=e==null?void 0:e.attachments)!=null?i:As,text:(s=e==null?void 0:e.text)!=null?s:"",role:(a=e==null?void 0:e.role)!=null?a:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ms,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},cc=e=>{var t,n,r,i,s,a,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",attachments:(a=e==null?void 0:e.attachments)!=null?a:As,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ms,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Ps=class{constructor(e){T(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 n=this._eventSubscriptionSubjects.get(e);return n||(n=new Es({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},dc=class extends Ps{constructor(t){const n=new Nr({path:t.path,getState:()=>uc(t.getState()),subscribe:r=>t.subscribe(r)});super({path:t.path,getState:()=>t.getState(),subscribe:r=>n.subscribe(r)});T(this,"_getState");this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new ac(new Qe({path:E(g({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const r=this.getState().attachments[t];return r?E(g({},r),{source:"thread-composer"}):Xe},subscribe:n=>this._core.subscribe(n)}),this._core)}},hc=class extends Ps{constructor(t,n){const r=new Nr({path:t.path,getState:()=>cc(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>r.subscribe(i)});T(this,"_getState");this._beginEdit=n,this._getState=r.getState.bind(r),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 oc(new Qe({path:E(g({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const r=this.getState().attachments[t];return r?E(g({},r),{source:"edit-composer"}):Xe},subscribe:n=>this._core.subscribe(n)}),this._core)}},fc=class vr{constructor(t=null){T(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,r)=>vr.apply(n,r),this._state)}static apply(t,n){const r=n.type;switch(r){case"set":return vr.updatePath(t,n.path,()=>n.value);case"append-text":return vr.updatePath(t,n.path,i=>{if(typeof i!="string")throw new Error(`Expected string at path [${n.path.join(", ")}]`);return i+n.value});default:{const i=r;throw new Error(`Invalid operation type: ${i}`)}}}static updatePath(t,n,r){if(n.length===0)return r(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${n.join(", ")}]`);const[i,...s]=n;if(Array.isArray(t)){const o=Number(i);if(Number.isNaN(o))throw new Error(`Expected array index at [${n.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],s,r),l}const a=g({},t);return a[i]=this.updatePath(a[i],s,r),a}},pc=({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:{}}}),jn=(e,t,n)=>{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 r=t.path[0],i=n(e.parts[r]);return E(g({},e),{parts:[...e.parts.slice(0,r),i,...e.parts.slice(r+1)],get content(){return this.parts}})},mc=(e,t)=>{const n=t.part;if(n.type==="text"||n.type==="reasoning"){const r=g({type:n.type,text:"",status:{type:"running"}},n.parentId&&{parentId:n.parentId});return E(g({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="tool-call"){const r=g({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:"",args:{}},n.parentId&&{parentId:n.parentId});return E(g({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="source"){const r=g(g({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0),n.parentId&&{parentId:n.parentId});return E(g({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="file"){const r={type:"file",mimeType:n.mimeType,data:n.data};return E(g({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${n.type}`)},gc=(e,t)=>jn(e,t,n=>{if(n.type!=="tool-call")throw new Error("Last is not a tool call");return n.state!=="partial-call"?n:E(g({},n),{state:"call"})}),yc=(e,t)=>jn(e,t,n=>E(g({},n),{status:{type:"complete",reason:"unknown"}})),bc=(e,t)=>jn(e,t,n=>{var r;if(n.type==="text"||n.type==="reasoning")return E(g({},n),{text:n.text+t.textDelta});if(n.type==="tool-call"){const i=n.argsText+t.textDelta,s=(r=Dn(i))!=null?r:n.args;return E(g({},n),{argsText:i,args:s})}else throw new Error("text-delta received but part is neither text nor tool-call")}),wc=(e,t)=>jn(e,t,n=>{var r;if(n.type==="tool-call")return E(g(E(g({},n),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(r=t.isError)!=null?r:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Ns=(e,t)=>{var r,i;if(((r=e.status)==null?void 0:r.type)==="incomplete"&&((i=e.status)==null?void 0:i.reason)==="error")return e;const n=xc(t);return E(g({},e),{status:n})},xc=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},vc=(e,t)=>E(g({},e),{metadata:E(g({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Sc=(e,t)=>E(g({},e),{metadata:E(g({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),kc=(e,t)=>E(g({},e),{metadata:E(g({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),_c=(e,t)=>{var i;const n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&((i=n[r])==null?void 0:i.state)==="started"?n[r]=E(g({},n[r]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):n.push({state:"finished",messageId:ks(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(g({},e),{metadata:E(g({},e.metadata),{steps:n})})},Tc=(e,t)=>E(g({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Ic=(e,t)=>{const n=new fc(e.metadata.unstable_state);return n.append(t.operations),E(g({},e),{metadata:E(g({},e.metadata),{unstable_state:n.state})})},Cc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Ec=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n}={}){let r=e!=null?e:pc(),i;const s=t?Cc(()=>{i==null||i.enqueue(r)}):()=>{i==null||i.enqueue(r)};super({start(a){i=a},transform(a){const o=a.type;switch(o){case"part-start":r=mc(r,a);break;case"tool-call-args-text-finish":r=gc(r,a);break;case"part-finish":r=yc(r,a);break;case"text-delta":r=bc(r,a);break;case"result":r=wc(r,a);break;case"message-finish":r=Ns(r,a);break;case"annotations":r=vc(r,a);break;case"data":r=Sc(r,a);break;case"step-start":r=kc(r,a);break;case"step-finish":r=_c(r,a);break;case"error":r=Tc(r,a),n==null||n(a.error);break;case"update-state":r=Ic(r,a);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}s()},flush(a){var o,l,u;if(((o=r.status)==null?void 0:o.type)==="running"){const c=(u=(l=r.parts)==null?void 0:l.some(d=>d.type==="tool-call"&&(d.state==="call"||d.state==="partial-call")&&d.result===void 0))!=null?u:!1;r=Ns(r,{finishReason:c?"tool-calls":"unknown"}),a.enqueue(r)}}})}},Ac=class extends vs{constructor(){super(e=>{const t=new rc({transform(n,r){r.appendText(n)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Mc=class Sr{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new Sr(t.pipeThrough(new Ec))}unstable_result(){return M(this,null,function*(){let t;try{for(var n=Lt(this),r,i,s;r=!(i=yield n.next()).done;r=!1){const a=i.value;t=a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield i.call(n))}finally{if(s)throw s[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 M(this,null,function*(){const{done:r,value:i}=yield t.read();return r?{done:!0,value:void 0}:{done:!1,value:i}})}}}tee(){const[t,n]=this.readable.tee();return[new Sr(t),new Sr(n)]}},Ls=Symbol.for("aui.tool-response"),pt=class is{constructor(t){T(this,"artifact");T(this,"result");T(this,"isError");var n;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(n=t.isError)!=null?n:!1}get[Ls](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Ls in t}static toResponse(t){return t instanceof is?t:new is({result:t===void 0?"<no result>":t})}};function Pc(e,t,n){try{const r=e();if(typeof r=="object"&&r!==null&&"then"in r)return r.then(t,n);t(r)}catch(r){n(r)}}function rn(e,t){let n=e;for(const r of t){if(n==null)return;n=n[r]}return n}var Nc=class{constructor(e,t,n){T(this,"resolve");T(this,"reject");T(this,"disposed",!1);T(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=n}update(e){if(!this.disposed)try{if(Dt(e,this.fieldPath)==="complete"){const t=rn(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Ds=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=rn(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Os=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const n=rn(e,this.fieldPath);if(n!==void 0&&typeof n=="string"){const r=n.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=n,this.controller.enqueue(r)}Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}},Fs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=rn(e,this.fieldPath);if(!Array.isArray(t))return;for(let n=0;n<t.length;n++)if(!this.processedIndexes.has(n)){const r=[...this.fieldPath,n];Dt(e,r)==="complete"&&(this.controller.enqueue(t[n]),this.processedIndexes.add(n))}Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Lc=class{constructor(e){T(this,"argTextDeltas");T(this,"handles",new Set);T(this,"args",Dn(""));this.argTextDeltas=e,this.processStream()}processStream(){return M(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:n,done:r}=yield t.read();if(r)break;e+=n;const i=Dn(e);if(i!==void 0){this.args=i;for(const s of this.handles)s.update(i)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,n)=>{const r=new Nc(t,n,e);if(this.args&&Dt(this.args,e)==="complete"){const i=rn(this.args,e);if(i!==void 0){t(i);return}}this.handles.add(r),r.update(this.args)})}streamValues(...e){const t=e,n=new ReadableStream({start:r=>{const i=new Ds(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Ds){r.dispose(),this.handles.delete(r);break}}});return Er(n)}streamText(...e){const t=e,n=new ReadableStream({start:r=>{const i=new Os(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Os){r.dispose(),this.handles.delete(r);break}}});return Er(n)}forEach(...e){const t=e,n=new ReadableStream({start:r=>{const i=new Fs(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Fs){r.dispose(),this.handles.delete(r);break}}});return Er(n)}},Dc=class{constructor(e){this.promise=e}get(){return this.promise}},Oc=class{constructor(){T(this,"args");T(this,"response");T(this,"writable");T(this,"resolve");T(this,"argsText","");T(this,"result",{get:()=>M(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Lc(e.readable);const{promise:t,resolve:n}=Mr();this.resolve=n,this.response=new Dc(t)}appendArgsTextDelta(e){return M(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(n){console.warn(n)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Fc=class extends vs{constructor(e){const t=new Map,n=new Map;super(r=>{const i=new TransformStream({transform(a,o){switch((a.type!=="part-finish"||a.meta.type!=="tool-call")&&o.enqueue(a),a.type){case"part-start":if(a.part.type==="tool-call"){const u=new Oc;n.set(a.part.toolCallId,u),e.streamCall({reader:u,toolCallId:a.part.toolCallId,toolName:a.part.toolName})}break;case"text-delta":{if(a.meta.type==="tool-call"){const u=a.meta.toolCallId,c=n.get(u);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(a.textDelta)}break}case"result":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,c=n.get(u);if(!c)throw new Error("No controller found for tool call");c.setResponse(new pt({result:a.result,artifact:a.artifact,isError:a.isError}));break}case"tool-call-args-text-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u,toolName:c}=a.meta,d=n.get(u);if(!d)throw new Error("No controller found for tool call");let h=!1;const f=Pc(()=>{var b;let m;try{m=Cr.parse(d.argsText)}catch(x){throw new Error(`Function parameter parsing failed. ${JSON.stringify(x.message)}`)}const v=e.execute({toolCallId:u,toolName:c,args:m});return v!==void 0&&(h=!0,(b=e.onExecutionStart)==null||b.call(e,u,c)),v},m=>{var b;if(h&&((b=e.onExecutionEnd)==null||b.call(e,u,c)),m===void 0)return;const v=new pt({artifact:m.artifact,result:m.result,isError:m.isError});d.setResponse(v),o.enqueue(g({type:"result",path:a.path},v))},m=>{var b;h&&((b=e.onExecutionEnd)==null||b.call(e,u,c));const v=new pt({result:String(m),isError:!0});d.setResponse(v),o.enqueue(g({type:"result",path:a.path},v))});f&&t.set(u,f);break}case"part-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,c=t.get(u);c?c.then(()=>{t.delete(u),n.delete(u),o.enqueue(a)}):o.enqueue(a)}}},flush(){return M(this,null,function*(){yield Promise.all(t.values())})}});return r.pipeThrough(new Ss).pipeThrough(i)})}},Bc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function zc(e,t,n,r){const i=e==null?void 0:e[n.toolName];return!i||!i.execute?void 0:(a=>M(null,null,function*(){var c;if(t.aborted)return new pt({result:"Tool execution was cancelled.",isError:!0});let o=a;if(Bc(i.parameters)){let d=i.parameters["~standard"].validate(n.args);d instanceof Promise&&(d=yield d),d.issues&&(o=(c=i.experimental_onSchemaValidationError)!=null?c:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(d.issues)}`)}))}const l=new Promise(d=>{const h=()=>{queueMicrotask(()=>{queueMicrotask(()=>{d(new pt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?h():t.addEventListener("abort",h,{once:!0})}),u=M(null,null,function*(){const d=yield o(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:h=>r(n.toolCallId,h)});return pt.toResponse(d)});return Promise.race([u,l])}))(i.execute)}function Rc(e,t,n,r,i){var s,a;(a=(s=e==null?void 0:e[r.toolName])==null?void 0:s.streamCall)==null||a.call(s,n,{toolCallId:r.toolCallId,abortSignal:t,human:o=>i(r.toolCallId,o)})}function jc(e,t,n,r){const i=typeof e=="function"?e:()=>e,s=typeof t=="function"?t:()=>t;return new Fc({execute:a=>zc(i(),s(),a,n),streamCall:l=>{var u=l,{reader:a}=u,o=V(u,["reader"]);return Rc(i(),s(),a,o,n)},onExecutionStart:r==null?void 0:r.onExecutionStart,onExecutionEnd:r==null?void 0:r.onExecutionEnd})}var Bs=class{constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,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 n=this.messageApi.getState();if(!n)throw new Error("Message is not available");const r=t.toolName,i=t.toolCallId,s=pt.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:s.result,artifact:s.artifact,isError:s.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 n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Un=class extends Fn{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(),n=t==null?void 0:t.subscribe(e);const r=()=>{var a;const s=this.binding.getState();s!==t&&(t=s,n==null||n(),n=(a=this.binding.getState())==null?void 0:a.subscribe(e),e())},i=this.outerSubscribe(r);return()=>{i==null||i(),n==null||n()}}},$n=Object.freeze({type:"complete"}),Uc=(e,t,n)=>{if(e.role!=="assistant")return $n;if(n.type==="tool-call")return n.result?$n:e.status;const r=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?$n:r?e.status:$n},zs=(e,t)=>{const n=e.content[t];if(!n)return Xe;const r=Uc(e,t,n);return Object.freeze(E(g({},n),{[zn]:n[zn],status:r}))},$c=class{constructor(e,t){T(this,"composer");T(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new hc(new Un({path:E(g({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:n=>this._threadBinding.subscribe(n)}),()=>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(),n=t!=null?t:this._threadBinding.getState().composer,r=t!=null?t:n,{runConfig:i=r.runConfig}=e,s=this._core.getState();if(s.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:s.parentId,sourceId:s.id,runConfig:i})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var n;const e=this._core.getState();if(((n=this._threadBinding.getState().speech)==null?void 0:n.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 n=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 i=this._threadBinding.getState().getBranches(n.id);let s=t;if(e==="previous"?s=i[n.branchNumber-2]:e==="next"&&(s=i[n.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return Rn(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 Bs(new Qe({path:E(g({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>zs(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Bs(new Qe({path:E(g({},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(),n=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===e);return n===-1?Xe:zs(t,n)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new lc(new Qe({path:E(g({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,n=t==null?void 0:t[e];return n?E(g({},n),{source:"message"}):Xe},subscribe:t=>this._core.subscribe(t)}))}},Hc=e=>{var t,n,r;return g({parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}},e.stream?{stream:e.stream}:{})},qc=e=>{var t,n,r;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}}},Vc=(e,t)=>{var n,r,i,s,a,o,l,u,c,d,h;return typeof t=="string"?{createdAt:new Date,parentId:(r=(n=e.at(-1))==null?void 0:n.id)!=null?r:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(i=t.createdAt)!=null?i:new Date,parentId:(o=(a=t.parentId)!=null?a:(s=e.at(-1))==null?void 0:s.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(c=t.attachments)!=null?c:[],metadata:(d=t.metadata)!=null?d:{custom:{}},runConfig:(h=t.runConfig)!=null?h:{},startRun:t.startRun}},Wc=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(n==null?void 0:n.role)!=="assistant"?!1:n.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},Rs=class{constructor(e,t){T(this,"_threadBinding");T(this,"composer");T(this,"_eventSubscriptionSubjects",new Map);const n=new Qe({path:e.path,getState:()=>Wc(e.getState(),t.getState()),subscribe:r=>{const i=e.subscribe(r),s=t.subscribe(r);return()=>{i(),s()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:r=>e.outerSubscribe(r),subscribe:r=>e.subscribe(r)},this.composer=new dc(new Un({path:E(g({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),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(Vc(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(qc(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Hc(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(g({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var r,i;const t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:(i=(r=t[e-1])==null?void 0:r.id)!=null?i:null,index:e}})}getMessageById(e){return this._getMessageRuntime(E(g({},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 $c(new Qe({path:e,getState:()=>{var c,d;const{message:n,parentId:r,index:i}=(c=t())!=null?c:{},{messages:s,speech:a}=this._threadBinding.getState();if(!n||r===void 0||i===void 0)return Xe;const l=this._threadBinding.getState().getBranches(n.id),u=n.metadata.submittedFeedback;return E(g({},n),{[zn]:n[zn],index:i,isLast:((d=s.at(-1))==null?void 0:d.id)===n.id,parentId:r,branchNumber:l.indexOf(n.id)+1,branchCount:l.length,speech:(a==null?void 0:a.messageId)===n.id?a:void 0,submittedFeedback:u})},subscribe:n=>this._threadBinding.subscribe(n)}),this._threadBinding)}unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new Es({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Jc=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Hn=(e,t)=>{if(t===void 0)return Xe;const n=e.getItemById(t);return n?{id:n.id,threadId:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:Xe},Kc=class{constructor(e,t=Rs){T(this,"_getState");T(this,"_mainThreadListItemRuntime");T(this,"main");this._core=e,this._runtimeFactory=t;const n=new Nr({path:{},getState:()=>Jc(e),subscribe:r=>e.subscribe(r)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new Bn(new Qe({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Hn(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new t(new Un({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:r=>e.subscribe(r)}),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 Un({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 Bn(new Qe({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Hn(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Bn(new Qe({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Hn(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Bn(new Qe({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Hn(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},Yc=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",Gc=class{constructor(e){T(this,"accept","*");T(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Mn(this,arguments,function*({file:e}){const n=crypto.randomUUID(),r=Yc(e.type);let i={id:n,type:r,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield i;try{const{signedUrl:s,publicUrl:a}=yield new Ee(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ee(fetch(s,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(n,a),i=E(g({},i),{status:{type:"requires-action",reason:"composer-send"}}),yield i}catch(s){i=E(g({},i),{status:{type:"incomplete",reason:"error"}}),yield i}})}remove(e){return M(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return M(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let n;return e.type==="image"?n=[{type:"image",image:t,filename:e.name}]:n=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],E(g({},e),{status:{type:"complete"},content:n})})}},Lr=y.createContext(null),Dr=({adapters:e,children:t})=>{const n=y.useContext(Lr);return p.jsx(Lr.Provider,{value:g(g({},n),e),children:t})},Xc=()=>y.useContext(Lr),Qc=class extends cs{constructor(t,n,{parentId:r,message:i}){var s;super();T(this,"_nonTextParts");T(this,"_previousText");T(this,"_parentId");T(this,"_sourceId");this.runtime=t,this.endEditCallback=n,this._parentId=r,this._sourceId=i.id,this._previousText=Rn(i),this.setText(this._previousText),this.setRole(i.role),this.setAttachments((s=i.attachments)!=null?s:[]),this._nonTextParts=i.content.filter(a=>a.type!=="text"),this.setRunConfig(g({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return M(this,null,function*(){Rn(t)!==this._previousText&&this.runtime.append(E(g({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},Zc=class{constructor(e){T(this,"_subscriptions",new Set);T(this,"_isInitialized",!1);T(this,"repository",new Ts);T(this,"composer",new ds(this));T(this,"_editComposers",new Map);T(this,"_stopSpeaking");T(this,"speech");T(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const n of this.messages)if(n.role==="assistant"){e=n;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 Qc(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 n of t)n()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var s;const n=(s=this.adapters)==null?void 0:s.feedback;if(!n)throw new Error("Feedback adapter not configured");const{message:r,parentId:i}=this.repository.getMessage(e);if(n.submit({message:r,type:t}),r.role==="assistant"){const a=E(g({},r),{metadata:E(g({},r.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(i,a)}this._notifySubscribers()}speak(e){var s,a;const t=(s=this.adapters)==null?void 0:s.speech;if(!t)throw new Error("Speech adapter not configured");const{message:n}=this.repository.getMessage(e);(a=this._stopSpeaking)==null||a.call(this);const r=t.speak(Rn(n)),i=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:r.status},this._notifySubscribers()});this.speech={messageId:e,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),i(),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(Pr.fromArray(e!=null?e:[]))}unstable_on(e,t){var r,i,s;if(e==="model-context-update")return(s=(i=(r=this._contextProvider).subscribe)==null?void 0:i.call(r,t))!=null?s:(()=>{});const n=this._eventSubscribers.get(e);return n?n.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},ed=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function td({state:e,getTools:t,onResult:n,setToolStatuses:r}){const i=y.useRef({}),s=y.useRef(new Map),a=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[f,m]=_s(),v=jc(t,()=>{var b,x;return(x=(b=a.current)==null?void 0:b.signal)!=null?x:new AbortController().signal},(b,x)=>new Promise((C,_)=>{const F=s.current.get(b);F&&F.reject(new Error("Human input request was superseded by a new request")),s.current.set(b,{resolve:C,reject:_}),r(z=>E(g({},z),{[b]:{type:"interrupt",payload:{type:"human",payload:x}}}))}),{onExecutionStart:b=>{o.current++,r(x=>E(g({},x),{[b]:{type:"executing"}}))},onExecutionEnd:b=>{o.current--,r(x=>{const C=g({},x);return delete C[b],C}),o.current===0&&(l.current.forEach(x=>x()),l.current=[])}});return f.pipeThrough(v).pipeThrough(new Ss).pipeTo(new WritableStream({write(b){var x;if(b.type==="result"){if((x=i.current[b.meta.toolCallId])!=null&&x.hasResult)return;n(g({type:"add-tool-result",toolCallId:b.meta.toolCallId,toolName:b.meta.toolName,result:b.result,isError:b.isError},b.artifact&&{artifact:b.artifact}))}}})),m}),c=y.useRef(new Set),d=y.useRef(!0);y.useEffect(()=>{const f=m=>{m.forEach(v=>{v.content.forEach(b=>{if(b.type==="tool-call"){if(d.current)c.current.add(b.toolCallId);else{if(c.current.has(b.toolCallId))return;let x=i.current[b.toolCallId];if(x||(x={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:b.toolName,toolCallId:b.toolCallId})},i.current[b.toolCallId]=x),b.argsText!==x.argsText)if(x.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:x.argsText,next:b.argsText});else{if(!b.argsText.startsWith(x.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${b.argsText} does not start with ${x.argsText}`);const C=b.argsText.slice(x.argsText.length);x.controller.argsText.append(C);const _=ed(b.argsText);_&&x.controller.argsText.close(),i.current[b.toolCallId]={argsText:b.argsText,hasResult:x.hasResult,argsComplete:_,controller:x.controller}}b.result!==void 0&&!x.hasResult&&(x.controller.setResponse(new pt({result:b.result,artifact:b.artifact,isError:b.isError})),x.controller.close(),i.current[b.toolCallId]={hasResult:!0,argsComplete:!0,argsText:x.argsText,controller:x.controller})}b.messages&&f(b.messages)}})})};f(e.messages),d.current&&(d.current=!1)},[e,u,n]);const h=()=>(s.current.forEach(({reject:f})=>{f(new Error("Tool execution aborted"))}),s.current.clear(),a.current.abort(),a.current=new AbortController,o.current===0?Promise.resolve():new Promise(f=>{l.current.push(f)}));return{reset:()=>{h(),d.current=!0},abort:h,resume:(f,m)=>{const v=s.current.get(f);if(v)s.current.delete(f),r(b=>E(g({},b),{[f]:{type:"executing"}})),v.resolve(m);else throw new Error(`Tool call ${f} is not waiting for human input`)}}}var nd=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 rd(e,t){e.commitTasks.forEach(n=>{const r=n.cellIndex,i=t.cells[r];if(i.type!=="effect")throw new Error("Cannot find effect cell");let s=!0;if(i.deps!==void 0&&n.deps!==void 0&&(s=i.deps.length!==n.deps.length||i.deps.some((a,o)=>!Object.is(a,n.deps[o]))),s){if(i.mounted){if(typeof i.deps!=typeof n.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{i.mounted&&i.cleanup&&i.cleanup()}finally{i.mounted=!1}}try{const a=n.effect();if(a!==void 0&&typeof a!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof a}`);i.mounted=!0,i.cleanup=typeof a=="function"?a:void 0,i.deps=n.deps}catch(a){throw a}}})}function id(e){let t=null;for(let n=e.cells.length-1;n>=0;n--){const r=e.cells[n];if((r==null?void 0:r.type)==="effect"&&r.mounted&&r.cleanup)try{r.cleanup()}catch(i){t==null&&(t=i)}finally{r.mounted=!1}}if(t!=null)throw t}var sn=null;function sd(e,t){e.currentIndex=0;const n=sn;sn=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{sn=n}}function Or(){if(!sn)throw new Error("No resource fiber available");return sn}function js(e,t){const n=e[Us];if(!n)throw new Error("ResourceElement.type is not a valid Resource");return n(t)}var Us=Symbol("fnSymbol");function qn(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Ot(e){e.isMounted=!1,id(e)}function an(e,t){const n={commitTasks:[],props:t,state:void 0};return sd(e,()=>{e.renderContext=n;try{n.state=js(e.resource,t)}finally{e.renderContext=void 0}}),n}function Ft(e,t){e.isMounted=!0,e.isNeverMounted=!1,rd(t,e)}var ad=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,$s=ad?y.useEffect:y.useLayoutEffect;function Fr(e){const[,t]=y.useState({}),n=y.useMemo(()=>qn(e.type,()=>t({})),[e.type,t]),r=an(n,e.props);return $s(()=>()=>Ot(n),[]),$s(()=>{Ft(n,r)}),r.state}var Bt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},_t=(e,t,n)=>t===e,zt,Br=()=>{if(zt)return zt;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return zt=e(),zt;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return zt=t,t;const n=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=n,zt=n,n},od=(nt=class{static register(t){var o,l;const n=Br();for(const u of n.apis.values())if(u.api===t)return()=>{};const r=n.nextId++,i={api:t,logs:[]},s=(o=t.on)==null?void 0:o.call(t,"*",u=>{const c=n.apis.get(r);c&&(c.logs.push({time:new Date,event:u.event,data:u.payload}),c.logs.length>nt.MAX_EVENT_LOGS_PER_API&&(c.logs=c.logs.slice(-200)),nt.notifyListeners(r))}),a=(l=t.subscribe)==null?void 0:l.call(t,()=>{nt.notifyListeners(r)});return n.apis.set(r,i),nt.notifyListeners(r),()=>{const u=Br();u.apis.get(r)&&(s==null||s(),a==null||a(),u.apis.delete(r),nt.notifyListeners(r))}}static notifyListeners(t){Br().listeners.forEach(r=>r(t))}},T(nt,"MAX_EVENT_LOGS_PER_API",200),nt);function pe(e){const t=(n,r)=>g({type:t,props:n},(r==null?void 0:r.key)!==void 0&&{key:r.key});return t[Us]=e,t}var ld=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 ud(e){const t=Or(),n=t.currentIndex++;if(!t.isFirstRender&&n>=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[n]){const s={type:"state",value:typeof e=="function"?e():e,set:a=>{const o=s.value,l=typeof a=="function"?a(o):a;Object.is(o,l)||(s.value=l,ld(t))}};t.cells[n]=s}const r=t.cells[n];if(r.type!=="state")throw new Error("Hook order changed between renders");return r}function st(e){const t=ud(e);return[t.value,t.set]}function cd(){const e=Or(),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 r={type:"effect",mounted:!1};e.cells[t]=r}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function Le(e,t){const n=Or(),r=cd();n.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:r})}function Rt(e){const[t]=st(()=>({current:e}));return t}var dd=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},oe=(e,t)=>{const n=Rt();return n.current||(n.current={value:e(),deps:t}),dd(n.current.deps,t)||(n.current.value=e(),n.current.deps=t),n.current.value};function Vn(e,t){const[n,r]=st({}),i=oe(()=>qn(e.type,()=>r({})),[e.type]),s=t?oe(()=>e.props,t):e.props,a=oe(()=>an(i,s),[i,s,n]);return Le(()=>()=>Ot(i),[i]),Le(()=>{Ft(i,a)},[i,a]),a.state}function Ze(e){return js(e.type,e.props)}function Hs(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[n,r]=st({}),i=oe(()=>new Map(e.map(o=>[o.key,o])),[e]),[s]=st(()=>new Map),a=oe(()=>{const o=new Map,l=new Set;return i.forEach((u,c)=>{l.add(c);let d=s.get(c);(!d||d.resource!==u.type)&&(d&&Ot(d),d=qn(u.type,()=>r({})),s.set(c,d));const h=an(d,u.props);o.set(c,h)}),s.forEach((u,c)=>{l.has(c)||(Ot(u),s.delete(c))}),o},[i,n]);return Le(()=>{a.forEach((o,l)=>{const u=s.get(l);u&&Ft(u,o)})},[a,s]),Le(()=>()=>{s.forEach(o=>{Ot(o)}),s.clear()},[s]),oe(()=>e.map(o=>{var l;return(l=a.get(o.key))==null?void 0:l.state}),[e,a])}var zr=[],Rr=!1;function hd(){Rr=!1;const e=zr;zr=[];for(const t of e)try{t()}catch(n){console.error("Error in scheduled task:",n)}}function fd(e){zr.push(e),Rr||(Rr=!0,queueMicrotask(hd))}var pd=(Pt=class{constructor(t){T(this,"_isDirty",!1);T(this,"_hasScheduledTask",!1);T(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,fd(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Pt.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}}},T(Pt,"MAX_FLUSH_DEPTH",50),Pt),md=pe(({element:e,onUpdateInput:t,onFlushSync:n,onDispose:r})=>{const[i,s]=st(e.props),a=Ze({type:e.type,props:i}),o=Rt(new Set).current,l=Rt(a);return Le(()=>{a!==l.current&&(l.current=a,o.forEach(c=>c()))}),oe(()=>({getState:()=>l.current,subscribe:c=>(o.add(c),()=>o.delete(c)),updateInput:c=>{t(),s(()=>c)},flushSync:n,dispose:r}),[])}),gd=(e,t=!1)=>{let n=!t;const r={element:e,onUpdateInput:()=>{n||(n=!0,Ft(s,a))},onFlushSync:()=>{i.flushSync()},onDispose:()=>Ot(s)},i=new pd(()=>{a=an(s,r),n&&Ft(s,a)}),s=qn(md,()=>i.markDirty());let a=an(s,r);return n&&Ft(s,a),a.state},on=Symbol("tap.Context"),qs=e=>({[on]:e}),Vs=(e,t,n)=>{const r=e[on];e[on]=t;try{return n()}finally{e[on]=r}},Ws=e=>e[on];const Js=e=>{let t;const n=new Set,r=(u,c)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const h=t;t=(c!=null?c:typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(f=>f(t,h))}},i=()=>t,o={setState:r,getState:i,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,i,o);return o},yd=(e=>e?Js(e):Js),bd=e=>e;function wd(e,t=bd){const n=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(n),n}const Ks=e=>{const t=yd(e),n=r=>wd(t,r);return Object.assign(n,t),n},jt=(e=>e?Ks(e):Ks);function Ys(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Gs(...e){return t=>{let n=!1;const r=e.map(i=>{const s=Ys(i,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():Ys(e[i],null)}}}}function Wn(...e){return Q.useCallback(Gs(...e),e)}var Xs=pe(e=>{const t=oe(()=>gd(e,!0),[e.type]);return Le(()=>{t.updateInput(e.props)}),t}),xd=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}},et=(e,t)=>{const n=Rt(e);Le(()=>{n.current=e});const r=oe(()=>new Proxy({},new xd(()=>n.current)),[]),i=t==null?void 0:t.key,s=e.getState();return oe(()=>({key:i,state:s,api:r}),[s,i])},mt=pe(e=>{const t=Rt(e.get);return Le(()=>{t.current=e.get}),oe(()=>Ae({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),vd=pe(e=>{const t=Vn(e.scopeElement);return oe(()=>[e.fieldName,t],[e.fieldName,t])}),Sd=pe(e=>{const o=e,{on:t,subscribe:n,flushSync:r}=o,i=V(o,["on","subscribe","flushSync"]),s=Rt({on:t,subscribe:n,flushSync:r});Le(()=>{s.current={on:t,subscribe:n,flushSync:r}});const a=Hs(Object.entries(i).map(([l,u])=>vd({fieldName:l,scopeElement:u},{key:l})));return oe(()=>{const l=Object.fromEntries(a),{on:u,subscribe:c,flushSync:d}=s.current;return u&&(l.on=(h,f)=>u(h,f)),c&&(l.subscribe=h=>c(h)),d&&(l.flushSync=()=>d()),l},[...a])}),Qs=qs(null),kd=(e,t)=>Vs(Qs,e,t),Zs=()=>{const e=Ws(Qs);if(!e)throw new Error("Model context is not available in this context");return e},_d=pe(({toolkit:e})=>{const[t,n]=st(()=>({tools:{}})),r=Zs();Le(()=>{if(!e)return;const s=[];for(const[l,u]of Object.entries(e))u.render&&s.push(i(l,u.render));const a=Object.entries(e).reduce((l,[u,c])=>{const f=c,{render:d}=f,h=V(f,["render"]);return l[u]=h,l},{}),o={getModelContext:()=>({tools:a})};return s.push(r.register(o)),()=>{s.forEach(l=>l())}},[e,r]);const i=(s,a)=>(n(o=>{var l;return E(g({},o),{tools:E(g({},o.tools),{[s]:[...(l=o.tools[s])!=null?l:[],a]})})}),()=>{n(o=>{var l,u;return E(g({},o),{tools:E(g({},o.tools),{[s]:(u=(l=o.tools[s])==null?void 0:l.filter(c=>c!==a))!=null?u:[]})})})});return et({getState:()=>t,setToolUI:i})}),Td=pe(()=>oe(()=>{const t=new Map;return{on:(n,r)=>{t.has(n)||t.set(n,new Set);const i=t.get(n);return i.add(r),()=>{i.delete(r),i.size===0&&t.delete(n)}},emit:(n,r)=>{const i=t.get(n),s=t.get("*");!i&&!s||queueMicrotask(()=>{if(i)for(const a of i)a(r);if(s)for(const a of s)a({event:n,payload:r})})}}},[])),ea=qs(null),Id=(e,t)=>Vs(ea,e,t),jr=()=>{const e=Ws(ea);if(!e)throw new Error("Events context is not available");return e},Cd=pe(()=>{const[e]=st(()=>({})),t=new Tr;return et({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:n=>t.subscribe(n),register:n=>t.registerModelContextProvider(n)})}),Ed=pe(({threads:e,modelContext:t,tools:n})=>{const r=Ze(Td()),{threads:i,tools:s,modelContext:a}=Id(r,()=>{const l=Vn(t!=null?t:Cd(),[t]);return kd(l.api,()=>({modelContext:l,tools:Vn(n!=null?n:_d({}),[n]),threads:Vn(e,[e])}))}),o=oe(()=>({threads:i.state,tools:s.state,modelContext:a.state}),[i.state,s.state,a.state]);return et({getState:()=>o,threads:i.api,tools:s.api,modelContext:a.api,on:r.on})}),Ad=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(n,r){const{event:i,scope:s}=Bt(n);if(s==="*")return e.getState().api.on(i,r);if(_t("thread",s)||_t("thread-list-item",s)||_t("composer",s))return e.getState().api.on(i,a=>{a.threadId===t().getState().id&&r(a)});throw new Error(`Event scope is not available in this component: ${s}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Md=e=>{const t=Jn(),n=Fr(Xs(Ed(e))),r=y.useMemo(()=>Ad(n),[n]);return y.useMemo(()=>na(t,r),[t,r])},Ae=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},gt=()=>()=>{},ta=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:gt,flushSync:gt,on:e=>{const{scope:t}=Bt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Jn=()=>y.useContext(ta),Tt=e=>{const t=Jn(),n=Fr(Sd(e));return y.useMemo(()=>na(t,n),[t,n])},Pd=e=>Md(e);function me(e){return e?Pd(e):Jn()}var Nd=(e,t)=>e===gt?t:t===gt?e:(...n)=>{e(...n),t(...n)},Ld=(e,t)=>e===gt?t:t===gt?e:(...n)=>{const r=e(...n),i=t(...n);return()=>{r(),i()}},na=(e,t)=>{const n=t.subscribe,r=t.flushSync;return E(g(g({},e),t),{subscribe:Ld(e.subscribe,n!=null?n:gt),flushSync:Nd(e.flushSync,r!=null?r:gt)})},yt=({api:e,children:t,devToolsVisible:n=!0})=>(y.useEffect(()=>{if(!(!n||!e.subscribe))return od.register(e)},[e,n]),p.jsx(ta.Provider,{value:e,children:t})),ra=(xu=class{constructor(e){Xt(this,Ke);Qt(this,Ke,e)}get threads(){return We(this,Ke).threads().getState()}get tools(){return We(this,Ke).tools().getState()}get threadListItem(){return We(this,Ke).threadListItem().getState()}get thread(){return We(this,Ke).thread().getState()}get composer(){return We(this,Ke).composer().getState()}get message(){return We(this,Ke).message().getState()}get part(){return We(this,Ke).part().getState()}get attachment(){return We(this,Ke).attachment().getState()}},Ke=new WeakMap,xu),ne=e=>{const t=me(),n=y.useMemo(()=>new ra(t),[t]),r=y.useSyncExternalStore(t.subscribe,()=>e(n),()=>e(n));if(y.useDebugValue(r),r instanceof ra)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return r},Ur=(e,t)=>{const n=me(),r=y.useRef(t);y.useEffect(()=>{r.current=t});const{scope:i,event:s}=Bt(e);y.useEffect(()=>n.on({scope:i,event:s},a=>r.current(a)),[n,i,s])};function Dd(e,t){function n(r){const i=y.useContext(e);if(!(r!=null&&r.optional)&&!i)throw new Error(`This component must be used within ${t}.`);return i}return n}function ia(e,t){function n(i){const s=e(i);return s?s[t]:null}function r(i){let s=!1,a;typeof i=="function"?a=i:i&&typeof i=="object"&&(s=!!i.optional,a=i.selector);const o=n({optional:s});return o?a?o(a):o():null}return{[t]:r,[`${t}Store`]:n}}var sa=y.createContext(null),Od=Dd(sa,"ThreadPrimitive.Viewport"),{useThreadViewport:Kn,useThreadViewportStore:$r}=ia(Od,"useThreadViewport"),Fd=e=>{var n;const t=e;t.__isBound||((n=t.__internal_bindMethods)==null||n.call(t),t.__isBound=!0)};function Bd(e,t=zd){Fd(e);const n=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(n),n}var zd=e=>e;function aa(e){function t(n){let r=!1,i;typeof n=="function"?i=n:n&&(r=!!n.optional,i=n.selector);const s=e({optional:r});return s?Bd(s,i):null}return t}function oa(e){const t=me(),n=ne(()=>{var r,i,s;return t.thread.source&&(s=(i=(r=t.thread()).__internal_getRuntime)==null?void 0:i.call(r))!=null?s:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return n}var la=aa(oa);function Rd(e){const t=me(),n=ne(()=>{var r,i,s;return t.threadListItem.source&&(s=(i=(r=t.threadListItem()).__internal_getRuntime)==null?void 0:i.call(r))!=null?s:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return n}var ua=aa(Rd),It=e=>{const[,t]=st(e.getState);return Le(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},jd=pe(({runtime:e})=>{const t=It(e),n=jr();return Le(()=>{const r=[],i=["switched-to","switched-away"];for(const s of i){const a=e.unstable_on(s,()=>{n.emit(`thread-list-item.${s}`,{threadId:e.getState().id})});r.push(a)}return()=>{for(const s of r)s()}},[e,n]),et({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})}),ln=e=>{const t=Hs(e);return{state:t.map(n=>n.state),api:n=>{var i,s;const r="index"in n?(i=t[n.index])==null?void 0:i.api:(s=t.find(a=>a.key===n.key))==null?void 0:s.api;if(!r)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(n)}`);return r}}},ca=pe(({runtime:e})=>{const t=It(e);return et({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Ud=pe(({runtime:e,index:t})=>{const n=oe(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ca({runtime:n}))}),da=pe(({threadIdRef:e,messageIdRef:t,runtime:n})=>{var o;const r=It(n),i=jr();Le(()=>{const l=[],u=["send","attachment-add"];for(const c of u){const d=n.unstable_on(c,()=>{i.emit(`composer.${c}`,g({threadId:e.current},t&&{messageId:t.current}))});l.push(d)}return()=>{for(const c of l)c()}},[n,i,e,t]);const s=ln(r.attachments.map((l,u)=>Ud({runtime:n,index:u},{key:u}))),a=oe(()=>{var l;return{text:r.text,role:r.role,attachments:s.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:(l=r.type)!=null?l:"thread"}},[r,s.state]);return et({getState:()=>a,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:(o=n.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?s.api({key:l.id}):s.api(l),__internal_getRuntime:()=>n})}),$d=pe(({runtime:e})=>{const t=It(e);return et({getState:()=>t,addToolResult:r=>e.addToolResult(r),resumeToolCall:r=>e.resumeToolCall(r),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),Hd=pe(({runtime:e,index:t})=>{const n=oe(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ca({runtime:n}))}),qd=pe(({runtime:e,index:t})=>{const n=oe(()=>e.getMessagePartByIndex(t),[e,t]);return Ze($d({runtime:n}))}),Vd=pe(({runtime:e,threadIdRef:t})=>{var h,f;const n=It(e),[r,i]=st(!1),[s,a]=st(!1),o=oe(()=>({get current(){return e.getState().id}}),[e]),l=Ze(da({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=ln(n.content.map((m,v)=>qd({runtime:e,index:v},{key:v}))),c=ln((f=(h=n.attachments)==null?void 0:h.map((m,v)=>Hd({runtime:e,index:v},{key:v})))!=null?f:[]),d=oe(()=>E(g({},n),{parts:u.state,composer:l.state,isCopied:r,isHovering:s}),[n,u.state,l.state,r,s]);return et({getState:()=>d,composer:l.api,reload:m=>e.reload(m),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:m=>e.submitFeedback(m),switchToBranch:m=>e.switchToBranch(m),getCopyText:()=>e.unstable_getCopyText(),part:m=>"index"in m?u.api({index:m.index}):u.api({key:`toolCallId-${m.toolCallId}`}),attachment:m=>"id"in m?c.api({key:m.id}):c.api(m),setIsCopied:i,setIsHovering:a,__internal_getRuntime:()=>e},{key:n.id})}),Wd=pe(({runtime:e,id:t,threadIdRef:n})=>{const r=oe(()=>e.getMessageById(t),[e,t]);return Ze(Vd({runtime:r,threadIdRef:n}))}),Jd=pe(({runtime:e})=>{const t=It(e),n=jr();Le(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const c=e.unstable_on(u,()=>{var h;const d=((h=e.getState())==null?void 0:h.threadId)||"unknown";n.emit(`thread.${u}`,{threadId:d})});o.push(c)}return()=>{for(const u of o)u()}},[e]);const r=oe(()=>({get current(){return e.getState().threadId}}),[e]),i=Ze(da({runtime:e.composer,threadIdRef:r})),s=ln(t.messages.map(o=>Wd({runtime:e,id:o.id,threadIdRef:r},{key:o.id}))),a=oe(()=>({isEmpty:s.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:i.state,messages:s.state}),[t,s,i.state]);return et({getState:()=>a,composer:i.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:()=>M(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>M(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?s.api({key:o.id}):s.api(o),__internal_getRuntime:()=>e})}),Kd=pe(({runtime:e,id:t})=>{const n=oe(()=>e.getItemById(t),[e,t]);return Ze(jd({runtime:n}))}),Yd=pe(({runtime:e,__internal_assistantRuntime:t})=>{const n=It(e),r=Ze(Jd({runtime:e.main})),i=ln(Object.keys(n.threadItems).map(a=>Kd({runtime:e,id:a},{key:a}))),s=oe(()=>{var a;return{mainThreadId:n.mainThreadId,newThreadId:(a=n.newThread)!=null?a:null,isLoading:n.isLoading,threadIds:n.threads,archivedThreadIds:n.archivedThreads,threadItems:i.state,main:r.state}},[n,i.state,r.state]);return et({getState:()=>s,thread:()=>r.api,item:a=>{if(a==="main")return i.api({key:s.mainThreadId});if("id"in a)return i.api({key:a.id});const{index:o,archived:l=!1}=a,u=l?s.archivedThreadIds[o]:s.threadIds[o];return i.api({key:u})},switchToThread:a=>{e.switchToThread(a)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),Gd=pe(e=>{const t=Zs();return Le(()=>e.registerModelContextProvider(t),[e,t]),Ze(Yd({runtime:e.threads,__internal_assistantRuntime:e}))}),Hr=e=>{const t=new Map,n=()=>{let r=0;for(const i of t.values())r+=i;e(r)};return{register:()=>{const r=Symbol();return t.set(r,0),{setHeight:i=>{t.get(r)!==i&&(t.set(r,i),n())},unregister:()=>{t.delete(r),n()}}}}},Xd=(e={})=>{const t=new Set,n=Hr(a=>{s.setState({height:E(g({},s.getState().height),{viewport:a})})}),r=Hr(a=>{s.setState({height:E(g({},s.getState().height),{inset:a})})}),i=Hr(a=>{s.setState({height:E(g({},s.getState().height),{userMessage:a})})}),s=jt(()=>{var a;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(a=e.turnAnchor)!=null?a:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:r.register,registerUserMessageHeight:i.register}});return s},un=e=>e,Qd=e=>{const t=$r({optional:!0}),[n]=y.useState(()=>Xd(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),y.useEffect(()=>{if(t)return n.subscribe(r=>{t.getState().isAtBottom!==r.isAtBottom&&un(t).setState({isAtBottom:r.isAtBottom})})},[n,t]),y.useEffect(()=>{var s;const r={turnAnchor:(s=e.turnAnchor)!=null?s:"bottom"};n.getState().turnAnchor!==r.turnAnchor&&un(n).setState(r)},[n,e.turnAnchor]),n},ha=({children:e,options:t={}})=>{const n=Qd(t),[r]=y.useState(()=>({useThreadViewport:n}));return p.jsx(sa.Provider,{value:r,children:e})},Zd=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},eh=({children:e,runtime:t})=>{const n=me({threads:Gd(t)}),r=Zd(t);return p.jsxs(yt,{api:n,children:[r&&p.jsx(r,{}),p.jsx(ha,{children:e})]})},fa=y.memo(eh),th=({index:e,archived:t,children:n})=>{const r=me(),i=Tt({threadListItem:mt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>r.threads().item({index:e,archived:t})}),on(s,a){const o=()=>r.threads().item({index:e,archived:t}),{event:l,scope:u}=Bt(s);return _t("thread-list-item",u)?r.on({scope:"*",event:l},c=>{c.threadId===o().getState().id&&a(c)}):r.on(s,a)}});return p.jsx(yt,{api:i,children:n})},nh=({id:e,children:t})=>{const n=me(),r=Tt({threadListItem:mt({source:"threads",query:{type:"id",id:e},get:()=>n.threads().item({id:e})}),on(i,s){const a=()=>n.threads().item({id:e}),{event:o,scope:l}=Bt(i);return _t("thread-list-item",l)?n.on({scope:"*",event:o},u=>{u.threadId===a().getState().id&&s(u)}):n.on(i,s)}});return p.jsx(yt,{api:r,children:t})},rh=({index:e,children:t})=>{const n=me(),r=Tt({message:mt({source:"thread",query:{type:"index",index:e},get:()=>n.thread().message({index:e})}),composer:mt({source:"message",query:{},get:()=>n.thread().message({index:e}).composer}),on(i,s){const a=()=>n.thread().message({index:e}),{event:o,scope:l}=Bt(i);return!_t("composer",l)&&!_t("message",l)?n.on(i,s):n.on({scope:"thread",event:o},u=>{u.messageId===a().getState().id&&s(u)})}});return p.jsx(yt,{api:r,children:t})},ih=({index:e,children:t})=>{const n=me(),r=Tt({part:mt({source:"message",query:{type:"index",index:e},get:()=>n.message().part({index:e})})});return p.jsx(yt,{api:r,children:t})},sh=({index:e,children:t})=>{const n=me(),r=Tt({attachment:mt({source:"message",query:{type:"index",index:e},get:()=>n.message().attachment({index:e})})});return p.jsx(yt,{api:r,children:t})},ah=({index:e,children:t})=>{const n=me(),r=Tt({attachment:mt({source:"composer",query:{type:"index",index:e},get:()=>n.composer().attachment({index:e})})});return p.jsx(yt,{api:r,children:t})},oh=pe(({text:e,isRunning:t})=>{const n=oe(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return et({getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),lh=({text:e,isRunning:t=!1,children:n})=>{const r=Fr(Xs(oh({text:e,isRunning:t}))),i=Tt({part:mt({source:"root",query:{},get:()=>r.getState().api}),subscribe:r.subscribe,flushSync:r.flushSync});return p.jsx(yt,{api:i,children:n})},pa=(e,t)=>{var n,r;return t===void 0?((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result):((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result||!t.includes(i.toolName))},qr=class extends Error{constructor(t,n){super(n);T(this,"name","AbortError");T(this,"detach");this.detach=t}},uh=class extends Zc{constructor(t,n){super(t);T(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});T(this,"abortController",null);T(this,"isDisabled",!1);T(this,"_isLoading",!1);T(this,"_suggestions",[]);T(this,"_suggestionsController",null);T(this,"_options");T(this,"_lastRunConfig",{});T(this,"_loadPromise");this.__internal_setOptions(n)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var a,o,l;if(this._options===t)return;this._options=t;let n=!1;const r=((a=t.adapters)==null?void 0:a.speech)!==void 0;this.capabilities.speech!==r&&(this.capabilities.speech=r,n=!0);const i=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==i&&(this.capabilities.attachments=i,n=!0);const s=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==s&&(this.capabilities.feedback=s,n=!0),n&&this._notifySubscribers()}__internal_load(){var n,r;if(this._loadPromise)return this._loadPromise;const t=(r=(n=this.adapters.history)==null?void 0:n.load())!=null?r:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(i=>{var a,o;if(!i)return;this.repository.import(i),this._notifySubscribers();const s=(o=(a=this.adapters.history)==null?void 0:a.resume)==null?void 0:o.bind(this.adapters.history);i.unstable_resume&&s&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},s)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return M(this,null,function*(){var i,s,a;this.ensureInitialized();const n=nn(t,St(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,n),(i=this._options.adapters.history)==null||i.append(g({parentId:t.parentId,message:n},t.runConfig!==void 0&&{runConfig:t.runConfig})),((s=t.startRun)!=null?s:t.role==="user")?yield this.startRun({parentId:n.id,sourceId:t.sourceId,runConfig:(a=t.runConfig)!=null?a:{}}):(this.repository.resetHead(n.id),this._notifySubscribers())})}resumeRun(r){var i=r,{stream:t}=i,n=V(i,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(n,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(i,s){return M(this,arguments,function*({parentId:t,runConfig:n},r){var u,c,d;this.ensureInitialized();let o={id:St(),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,n,r),r=void 0;while(pa(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((c=o.status)==null?void 0:c.type)!=="requires-action"){const b=(d=this.adapters.suggestion)==null?void 0:d.generate({messages:this.messages});if(Symbol.asyncIterator in b)try{for(var h=Lt(b),f,m,v;f=!(m=yield h.next()).done;f=!1){const x=m.value;if(l.aborted)break;this._suggestions=x,this._notifySubscribers()}}catch(m){v=[m]}finally{try{f&&(m=h.return)&&(yield m.call(h))}finally{if(v)throw v[0]}}else{const x=yield b;if(l.aborted)return;this._suggestions=x,this._notifySubscribers()}}})}performRoundtrip(t,n,r,i){return M(this,null,function*(){var m,v,b,x,C,_,F,z,I,O;const s=t?this.repository.getMessages(t):[];(m=this.abortController)==null||m.abort(),this.abortController=new AbortController;const a=n.content,o=(v=n.metadata)==null?void 0:v.unstable_annotations,l=(b=n.metadata)==null?void 0:b.unstable_data,u=(x=n.metadata)==null?void 0:x.steps,c=(C=n.metadata)==null?void 0:C.custom,d=P=>{var de,w,ge,ye,S,Ie;const R=(de=P.metadata)==null?void 0:de.steps,L=R?[...u!=null?u:[],...R]:void 0,N=(w=P.metadata)==null?void 0:w.unstable_annotations,G=(ge=P.metadata)==null?void 0:ge.unstable_data,J=N?[...o!=null?o:[],...N]:void 0,Z=G?[...l!=null?l:[],...G]:void 0;n=g(E(g(g({},n),P.content?{content:[...a,...(ye=P.content)!=null?ye:[]]}:void 0),{status:(S=P.status)!=null?S:n.status}),P.metadata?{metadata:g(g(g(g(g(g({},n.metadata),P.metadata.unstable_state?{unstable_state:P.metadata.unstable_state}:void 0),J?{unstable_annotations:J}:void 0),Z?{unstable_data:Z}:void 0),L?{steps:L}:void 0),(Ie=P.metadata)!=null&&Ie.custom?{custom:g(g({},c!=null?c:{}),P.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,n),this._notifySubscribers()},h=(_=this._options.maxSteps)!=null?_:2;if(((I=(z=(F=n.metadata)==null?void 0:F.steps)==null?void 0:z.length)!=null?I:0)>=h)return d({status:{type:"incomplete",reason:"tool-calls"}}),n;d({status:{type:"running"}}),this.repository.resetHead(n.id),this._notifySubscribers();try{this._lastRunConfig=r!=null?r:{};const P=this.getModelContext();i=i!=null?i:this.adapters.chatModel.run.bind(this.adapters.chatModel);const R=this.abortController.signal,L=i({messages:s,runConfig:this._lastRunConfig,abortSignal:R,context:P,config:P,unstable_assistantMessageId:n.id,unstable_getMessage(){return n}});if(Symbol.asyncIterator in L)try{for(var H=Lt(L),q,j,k;q=!(j=yield H.next()).done;q=!1){const N=j.value;if(R.aborted){d({status:{type:"incomplete",reason:"cancelled"}});break}d(N)}}catch(j){k=[j]}finally{try{q&&(j=H.return)&&(yield j.call(H))}finally{if(k)throw k[0]}}else d(yield L);n.status.type==="running"&&d({status:{type:"complete",reason:"unknown"}})}catch(P){if(P instanceof qr)d({status:{type:"incomplete",reason:"cancelled"}});else throw d({status:{type:"incomplete",reason:"error",error:P instanceof Error?P.message:`[${typeof P}] ${new String(P).toString()}`}}),P}finally{this.abortController=null,(n.status.type==="complete"||n.status.type==="incomplete")&&(yield(O=this._options.adapters.history)==null?void 0:O.append({parentId:t,message:n,runConfig:this._lastRunConfig}))}return n})}detach(){var n;const t=new qr(!0);(n=this.abortController)==null||n.abort(t),this.abortController=null}cancelRun(){var n;const t=new qr(!1);(n=this.abortController)==null||n.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:n,result:r,isError:i,artifact:s}){const a=this.repository.getMessage(t),{parentId:o}=a;let{message:l}=a;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,c=!1;const d=l.content.map(h=>h.type!=="tool-call"||h.toolCallId!==n?h:(c=!0,h.result||(u=!0),E(g({},h),{result:r,artifact:s,isError:i})));if(!c)throw new Error("Tried to add tool result to non-existing tool call");l=E(g({},l),{content:d}),this.repository.addOrUpdateMessage(o,l),u&&pa(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},ma=Object.freeze([]),Vr="__DEFAULT_ID__",ch=Object.freeze({[Vr]:{id:Vr,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),dh=class extends en{constructor(t){super();T(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw ma}get archivedThreadIds(){throw ma}get mainThreadId(){return Vr}get threadData(){return ch}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 M(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.")}},hh=class extends Ir{constructor(t,n){super();T(this,"threads");T(this,"Provider");T(this,"_options");this._options=t,this.threads=new dh(()=>new uh(this._contextProvider,this._options)),n&&this.threads.getMainThreadRuntimeCore().import(Pr.fromArray(n))}},ga=e=>{try{const n=e.split(".")[1];if(!n)throw new Error("Invalid JWT format");let r=n.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4!==0;)r+="=";const i=atob(r),a=JSON.parse(i).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},ya=(vu=class{constructor(e){T(this,"strategy","jwt");T(this,"cachedToken",null);T(this,"tokenExpiry",null);Xt(this,_n);Qt(this,_n,e)}getAuthHeaders(){return M(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 We(this,_n).call(this);return t?(this.cachedToken=t,this.tokenExpiry=ga(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[n,r]=t.split(" ");if(n!=="Bearer"||!r)throw new Error("Invalid auth header received");this.cachedToken=r,this.tokenExpiry=ga(r)}},_n=new WeakMap,vu),fh=(Su=class{constructor(e,t,n){T(this,"strategy","api-key");Xt(this,Tn);Xt(this,In);Xt(this,Cn);Qt(this,Tn,e),Qt(this,In,t),Qt(this,Cn,n)}getAuthHeaders(){return M(this,null,function*(){return{Authorization:`Bearer ${We(this,Tn)}`,"Aui-User-Id":We(this,In),"Aui-Workspace-Id":We(this,Cn)}})}readAuthHeaders(){}},Tn=new WeakMap,In=new WeakMap,Cn=new WeakMap,Su),Yn="aui:refresh_token",ph=class{constructor(e){T(this,"strategy","anon");T(this,"baseUrl");T(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new ya(()=>M(this,null,function*(){const t=Date.now(),n=localStorage.getItem(Yn),r=n?JSON.parse(n):void 0;if(r)if(new Date(r.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:r.token})});if(u.ok){const c=yield u.json(),{access_token:d,refresh_token:h}=c;return h&&localStorage.setItem(Yn,JSON.stringify(h)),d}}else localStorage.removeItem(Yn);const i=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!i.ok)return null;const s=yield i.json(),{access_token:a,refresh_token:o}=s;return!a||!o?null:(localStorage.setItem(Yn,JSON.stringify(o)),a)}))}getAuthHeaders(){return M(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},mh=class extends Error{constructor(e){super(e),this.name="APIError"}},gh=class{constructor(e){T(this,"_auth");T(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new ya(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new fh(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new ph(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return M(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(n){return M(this,arguments,function*(e,t={}){var l;const r=yield this._auth.getAuthHeaders();if(!r)throw new Error("Authorization failed");const i=E(g(g({},r),t.headers),{"Content-Type":"application/json"}),s=new URLSearchParams;if(t.query)for(const[u,c]of Object.entries(t.query))c!==!1&&(c===!0?s.set(u,"true"):s.set(u,c.toString()));const a=new URL(`${this._baseUrl}/v1${e}`);a.search=s.toString();const o=yield fetch(a,{method:(l=t.method)!=null?l:"GET",headers:i,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const c=JSON.parse(u);throw new mh(c.message)}catch(c){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(n){return M(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},yh=class{constructor(e){this.cloud=e}create(){return M(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},bh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>M(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(g({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return M(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Ar.fromResponse(t,new Ac)})}},wh=class{constructor(e){this.cloud=e}list(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},xh=class{constructor(e){T(this,"messages");this.cloud=e,this.messages=new wh(e)}list(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},vh=class{constructor(e){this.cloud=e}pdfToImages(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Sh=class{constructor(e){T(this,"threads");T(this,"auth");T(this,"runs");T(this,"files");const t=new gh(e);this.threads=new xh(t),this.auth={tokens:new yh(t)},this.runs=new bh(t),this.files=new vh(t)}};function Wr(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(n=>Wr(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,r])=>typeof n=="string"&&Wr(r,t+1)):!1}var kh=e=>{var t;return g({role:e.role,content:e.content.map(n=>{const r=n.type;switch(r){case"text":return{type:"text",text:n.text};case"reasoning":return{type:"reasoning",text:n.text};case"source":return g({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0);case"tool-call":return Wr(n.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(n)}`),g(g(g({type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName},JSON.stringify(n.args)===n.argsText?{args:n.args}:{argsText:n.argsText}),n.result?{result:n.result}:{}),n.isError?{isError:!0}:{});default:{const i=r;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},_h=e=>{const t=e.content,n=nn(g({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},Jr=new WeakMap,Th=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return M(this,null,function*(){const t=this.formatAdapter.encode(e),n=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,n,this.formatAdapter.format,t)})}load(){return M(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Ih=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Jr.has(this.store.threadListItem())||Jr.set(this.store.threadListItem(),{}),Jr.get(this.store.threadListItem())}withFormat(e){return new Th(this,e)}append(n){return M(this,arguments,function*({parentId:e,message:t}){var s;const{remoteId:r}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(r,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:"aui/v0",content:kh(t)}).then(({message_id:a})=>(this._getIdForLocalId[t.id]=a,a));return this._getIdForLocalId[t.id]=i,i.then(()=>{})})}load(){return M(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(r=>r.format==="aui/v0").map(_h).reverse()}})}_appendWithFormat(e,t,n,r){return M(this,null,function*(){var a;const{remoteId:i}=yield this.store.threadListItem().initialize(),s=this.cloudRef.current.threads.messages.create(i,{parent_id:e?(a=yield this._getIdForLocalId[e])!=null?a:e:null,format:n,content:r}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=s,s.then(()=>{})})}_loadWithFormat(e,t){return M(this,null,function*(){const n=this.store.threadListItem().getState().remoteId;if(!n)return{messages:[]};const{messages:r}=yield this.cloudRef.current.threads.messages.list(n,{format:e});return{messages:r.filter(i=>i.format===e).map(i=>t({id:i.id,parent_id:i.parent_id,format:i.format,content:i.content})).reverse()}})}},Ch=e=>{const t=me(),[n]=y.useState(()=>new Ih(e,t));return n},ba=typeof process!="undefined"&&((ku=process==null?void 0:process.env)==null?void 0:ku.NEXT_PUBLIC_ASSISTANT_BASE_URL),Kr=ba?new Sh({baseUrl:ba,anonymous:!0}):void 0,Eh=e=>{var i;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const n=y.useCallback(function({children:a}){var d;const o=Ch({get current(){var h;return(h=t.current.cloud)!=null?h:Kr}}),l=(d=t.current.cloud)!=null?d:Kr,u=y.useMemo(()=>new Gc(l),[l]),c=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Dr,{adapters:c,children:a})},[]),r=(i=e.cloud)!=null?i:Kr;return r?{list:()=>M(null,null,function*(){const{threads:s}=yield r.threads.list();return{threads:s.map(a=>{var o;return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}})}}),initialize:()=>M(null,null,function*(){var u,c;const a=yield(c=(u=e.create)==null?void 0:u.call(e))!=null?c:Promise.resolve(),o=a?a.externalId:void 0,{thread_id:l}=yield r.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(s,a)=>M(null,null,function*(){return r.threads.update(s,{title:a})}),archive:s=>M(null,null,function*(){return r.threads.update(s,{is_archived:!0})}),unarchive:s=>M(null,null,function*(){return r.threads.update(s,{is_archived:!1})}),delete:s=>M(null,null,function*(){var a;return yield(a=e.delete)==null?void 0:a.call(e,s),r.threads.delete(s)}),generateTitle:(s,a)=>M(null,null,function*(){return r.runs.stream({thread_id:s,assistant_id:"system/thread_title",messages:a})}),fetch:s=>M(null,null,function*(){var o;const a=yield r.threads.get(s);return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}}),unstable_Provider:n}:new nd},Ah=(e,r)=>{var i=r,{initialMessages:t}=i,n=V(i,["initialMessages"]);var u;const c=(u=Xc())!=null?u:{},{modelContext:s}=c,a=V(c,["modelContext"]),o=y.useMemo(()=>E(g({},n),{adapters:E(g(g({},a),n.adapters),{chatModel:e})}),[e,n,a]),[l]=y.useState(()=>new hh(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(s)return l.registerModelContextProvider(s)},[s,l]),y.useMemo(()=>new Yr(l),[l])},wa=(e,r={})=>{var i=r,{cloud:t}=i,n=V(i,["cloud"]);const s=Eh({cloud:t});return _a({runtimeHook:function(){return Ah(e,n)},adapter:s,allowNesting:!0})},Yr=class{constructor(e){T(this,"threads");T(this,"_thread");this._core=e,this.threads=new Kc(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(Pr.fromArray(e!=null?e:[]))}},Mh=e=>{const o=e,{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:s}=o,a=V(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:s},otherOptions:a}};function Ct(e){const t=Q.useRef(e);return Q.useEffect(()=>{t.current=e}),Q.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}var xa=y.createContext(null),Ph=e=>({useSmoothStatus:jt(()=>e)}),Nh=({children:e})=>{const t=va({optional:!0}),n=me(),[r]=y.useState(()=>Ph(n.part().getState().status));return t?e:p.jsx(xa.Provider,{value:r,children:e})},Lh=e=>{const t=y.forwardRef((n,r)=>p.jsx(Nh,{children:p.jsx(e,E(g({},n),{ref:r}))}));return t.displayName=e.displayName,t};function va(e){const t=y.useContext(xa);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Dh,useSmoothStatusStore:Oh}=ia(va,"useSmoothStatus"),Fh=class{constructor(e,t){T(this,"animationFrameId",null);T(this,"lastUpdateTime",Date.now());T(this,"targetText","");T(this,"animate",()=>{const e=Date.now();let n=e-this.lastUpdateTime;const r=this.targetText.length-this.currentText.length,i=Math.min(5,250/r);let s=0;for(;n>=i&&s<r;)s++,n-=i;s!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-n,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)}},Gr=Object.freeze({type:"running"}),Sa=(e,t=!1)=>{const{text:n}=e,r=ne(({message:c})=>c.id),i=y.useRef(r),[s,a]=y.useState(n),o=Oh({optional:!0}),l=Ct(c=>{if(a(c),o){const d=s!==c||e.status.type==="running"?Gr:e.status;un(o).setState(d,!0)}});y.useEffect(()=>{if(o){const c=t&&(s!==n||e.status.type==="running")?Gr:e.status;un(o).setState(c,!0)}},[o,t,n,s,e.status]);const[u]=y.useState(new Fh(n,l));return y.useEffect(()=>{if(!t){u.stop();return}if(i.current!==r||!n.startsWith(u.targetText)){i.current=r,l(n),u.currentText=n,u.targetText=n,u.stop();return}u.targetText=n,u.start()},[l,u,r,t,n]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:s,status:n===s?e.status:Gr}:e,[t,s,e,n])};const Bh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Yr,BaseAssistantRuntimeCore:Ir,CompositeContextProvider:Tr,DefaultThreadComposerRuntimeCore:ds,MessageRepository:Ts,ThreadRuntimeImpl:Rs,fromThreadMessageLike:nn,generateId:St,getAutoStatus:fs,splitLocalRuntimeOptions:Mh,useSmooth:Sa,useSmoothStatus:Dh,useToolInvocations:td,withSmoothContextProvider:Lh},Symbol.toStringTag,{value:"Module"}));var zh=class extends en{constructor(t){super();T(this,"useRuntimeHook");T(this,"instances",new Map);T(this,"useAliveThreadsKeysChanged",jt(()=>({})));T(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:n}=this.useRuntimeHook(),r=n(),i=r.thread.__internal_threadBinding,s=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=i.getState(),this._notifySubscribers()},[t,i]),a=y.useRef(!1);a.current||s(),y.useEffect(()=>(a.current=!0,s(),i.outerSubscribe(s)),[i,s]);const o=me();return y.useEffect(()=>r.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=r.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[r,o]),null});T(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:n})=>p.jsx(nh,{id:t,children:p.jsx(n,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));T(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(n=>p.jsx(this._OuterActiveThreadProvider,{threadId:n,provider:t},n))));this.useRuntimeHook=jt(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((n,r)=>{const i=()=>{const a=this.instances.get(t);if(!a)s(),r(new Error("Thread was deleted before runtime was started"));else if(a.runtime)s(),n(a.runtime);else return},s=this.subscribe(i);i()})}getThreadRuntimeCore(t){const n=this.instances.get(t);if(n)return n.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},ve=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."),Rh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw ve},append(){throw ve},startRun(){throw ve},resumeRun(){throw ve},cancelRun(){throw ve},addToolResult(){throw ve},resumeToolCall(){throw ve},speak(){throw ve},stopSpeaking(){throw ve},submitFeedback(){throw ve},getModelContext(){return{}},unstable_loadExternalState(){throw ve},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return M(this,null,function*(){throw ve})},removeAttachment(){return M(this,null,function*(){throw ve})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw ve},role:"user",setRole(){throw ve},runConfig:{},setRunConfig(){throw ve},reset(){return M(this,null,function*(){})},clearAttachments(){return M(this,null,function*(){})},send(){throw ve},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw ve},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 ve},export(){return{messages:[]}},reset(){throw ve},unstable_on(){return()=>{}}},ka=(e,t,n)=>n.reduce((r,i)=>{var s;return(s=i==null?void 0:i(r,t))!=null?s:r},e),jh=class extends en{constructor(t){super();T(this,"_pendingTransforms",[]);T(this,"_baseValue");T(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,n)=>ka(t,n.task,[n.loading,n.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 M(this,null,function*(){const n=t.execute(),r=E(g({},t),{task:n});try{this._pendingTransforms.push(r),this._updateState();const i=yield n;return this._baseValue=ka(this._baseValue,i,[t.optimistic,t.then]),i}finally{const i=this._pendingTransforms.indexOf(r);i>-1&&this._pendingTransforms.splice(i,1),this._updateState()}})}};function Pv(e){return e}var Gn=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},Xn=(e,t,n)=>{const r=Gn(e,t);if(!r)return e;const{id:i,remoteId:s,status:a}=r;if(a===n)return e;const o=g({},e);switch(a){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==i);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==i);break;default:{const l=a;throw new Error(`Unsupported state: ${l}`)}}switch(n){case"regular":o.threadIds=[i,...o.threadIds];break;case"archived":o.archivedThreadIds=[i,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==i)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==i&&l!==s));break;default:{const l=n;throw new Error(`Unsupported state: ${l}`)}}return n!=="deleted"&&(o.threadData=E(g({},o.threadData),{[i]:E(g({},r),{status:n})})),o},Uh=class extends en{constructor(t,n){super();T(this,"_options");T(this,"_hookManager");T(this,"_loadThreadsPromise");T(this,"_mainThreadId");T(this,"_state",new jh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));T(this,"useProvider");T(this,"initialize",t=>M(this,null,function*(){if(this._state.value.newThreadId!==t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Unexpected new state");return n.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:n=>Xn(n,t,"regular"),loading:(n,r)=>{const i=t;return E(g({},n),{threadData:E(g({},n.threadData),{[i]:E(g({},n.threadData[i]),{initializeTask:r})})})},then:(n,{remoteId:r,externalId:i})=>{const s=Gn(n,t);if(!s)return n;const a=t;return E(g({},n),{threadIdMap:E(g({},n.threadIdMap),{[r]:a}),threadData:E(g({},n.threadData),{[a]:E(g({},s),{initializeTask:Promise.resolve({remoteId:r,externalId:i}),remoteId:r,externalId:i})})})}})}));T(this,"generateTitle",t=>M(this,null,function*(){var l;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");const{remoteId:r}=yield n.initializeTask,i=this._hookManager.getThreadRuntimeCore(n.id);if(!i)return;const s=i.messages,a=yield this._options.adapter.generateTitle(r,s),o=Mc.fromAssistantStream(a);try{for(var u=Lt(o),c,d,h;c=!(d=yield u.next()).done;c=!1){const f=d.value;const m=(l=f.parts.filter(b=>b.type==="text")[0])==null?void 0:l.text,v=this._state.baseValue;this._state.update(E(g({},v),{threadData:E(g({},v.threadData),{[n.id]:E(g({},n),{title:m})})}))}}catch(d){h=[d]}finally{try{c&&(d=u.return)&&(yield d.call(u))}finally{if(h)throw h[0]}}}));T(this,"useBoundIds",jt(()=>[]));T(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(s=>[...s,t],!0),()=>{this.useBoundIds.setState(s=>s.filter(a=>a!==t),!0)}),[t]);const n=this.useBoundIds(),{Provider:r}=this.useProvider(),i={modelContext:this.contextProvider};return(n.length===0||n[0]===t)&&p.jsx(Dr,{adapters:i,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:r})})});this.contextProvider=n,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new zh(t.runtimeHook),this.useProvider=jt(()=>{var r;return{Provider:(r=t.adapter.unstable_Provider)!=null?r: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(g({},t),{isLoading:!0}),then:(t,n)=>{const r=[],i=[],s={},a={};for(const o of n.threads){switch(o.status){case"regular":r.push(o.remoteId);break;case"archived":i.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;s[o.remoteId]=l,a[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(g({},t),{threadIds:r,archivedThreadIds:i,threadIdMap:g(g({},t.threadIdMap),s),threadData:g(g({},t.threadData),a)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var r;if(this._options===t)return;this._options=t;const n=(r=t.adapter.unstable_Provider)!=null?r:y.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!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||Rh}getThreadRuntimeCore(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");const r=this._hookManager.getThreadRuntimeCore(n.id);if(!r)throw new Error("Thread not found");return r}getItemById(t){return Gn(this._state.value,t)}switchToThread(t){return M(this,null,function*(){let n=this.getItemById(t);if(!n){const i=yield this._options.adapter.fetch(t),s=this._state.value,a=i.remoteId,o=E(g({},s.threadData),{[a]:{id:a,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title}}),l=E(g({},s.threadIdMap),{[i.remoteId]:a}),u=i.status==="regular"?[...s.threadIds,i.remoteId]:s.threadIds,c=i.status==="archived"?[...s.archivedThreadIds,i.remoteId]:s.archivedThreadIds;this._state.update(E(g({},s),{threadIds:u,archivedThreadIds:c,threadIdMap:l,threadData:o})),n=this.getItemById(t)}if(!n)throw new Error("Thread not found");if(this._mainThreadId===n.id)return;const r=this._hookManager.startThreadRuntime(n.id);this.mainThreadId!==void 0?yield r:r.then(()=>this._notifySubscribers()),n.status==="archived"&&(yield this.unarchive(n.id)),this._mainThreadId=n.id,this._notifySubscribers()})}switchToNewThread(){return M(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 n=this._state.value.newThreadId;if(n===void 0){do n=`__LOCALID_${St()}`;while(t.threadIdMap[n]);const r=n;this._state.update(E(g({},t),{newThreadId:n,threadIdMap:E(g({},t.threadIdMap),{[n]:r}),threadData:E(g({},t.threadData),{[r]:{status:"new",id:n,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(n)})}rename(t,n){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");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){const{remoteId:i}=yield r.initializeTask;return this._options.adapter.rename(i,n)}),optimistic:i=>{const s=Gn(i,t);return s?E(g({},i),{threadData:E(g({},i.threadData),{[s.id]:E(g({},s),{title:n})})}):i}})}_ensureThreadIsNotMain(t){return M(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 M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(n.id);const{remoteId:r}=yield n.initializeTask;return this._options.adapter.archive(r)}),optimistic:r=>Xn(r,n.id,"archived")})})}unarchive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){try{const{remoteId:r}=yield n.initializeTask;return yield this._options.adapter.unarchive(r)}catch(r){throw yield this._ensureThreadIsNotMain(n.id),r}}),optimistic:r=>Xn(r,n.id,"regular")})}delete(t){return M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(n.id);const{remoteId:r}=yield n.initializeTask;return yield this._options.adapter.delete(r)}),optimistic:r=>Xn(r,n.id,"deleted")})})}detach(t){return M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(n.id),this._hookManager.stopThreadRuntime(n.id)})}},$h=class extends Ir{constructor(t){super();T(this,"threads");this.threads=new Uh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Hh=e=>{const[t]=y.useState(()=>new $h(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Yr(t),[t])},_a=e=>{if(Jn().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 Hh(e)},qh=Symbol.for("react.lazy"),Qn=Q[" use ".trim().toString()];function Vh(e){return typeof e=="object"&&e!==null&&"then"in e}function Ta(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===qh&&"_payload"in e&&Vh(e._payload)}function Ia(e){const t=Wh(e),n=Q.forwardRef((r,i)=>{let u=r,{children:s}=u,a=V(u,["children"]);Ta(s)&&typeof Qn=="function"&&(s=Qn(s._payload));const o=Q.Children.toArray(s),l=o.find(Kh);if(l){const c=l.props.children,d=o.map(h=>h===l?Q.Children.count(c)>1?Q.Children.only(null):Q.isValidElement(c)?c.props.children:null:h);return p.jsx(t,E(g({},a),{ref:i,children:Q.isValidElement(c)?Q.cloneElement(c,void 0,d):null}))}return p.jsx(t,E(g({},a),{ref:i,children:s}))});return n.displayName=`${e}.Slot`,n}var Ca=Ia("Slot");function Wh(e){const t=Q.forwardRef((n,r)=>{let a=n,{children:i}=a,s=V(a,["children"]);if(Ta(i)&&typeof Qn=="function"&&(i=Qn(i._payload)),Q.isValidElement(i)){const o=Gh(i),l=Yh(s,i.props);return i.type!==Q.Fragment&&(l.ref=r?Gs(r,o):o),Q.cloneElement(i,l)}return Q.Children.count(i)>1?Q.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Jh=Symbol("radix.slottable");function Kh(e){return Q.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Jh}function Yh(e,t){const n=g({},t);for(const r in t){const i=e[r],s=t[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(n[r]=i):r==="style"?n[r]=g(g({},i),s):r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return g(g({},e),n)}function Gh(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Xh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ut=Xh.reduce((e,t)=>{const n=Ia(`Primitive.${t}`),r=Q.forwardRef((i,s)=>{const u=i,{asChild:a}=u,o=V(u,["asChild"]),l=a?n:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(g({},o),{ref:s}))});return r.displayName=`Primitive.${t}`,E(g({},e),{[t]:r})},{});function Ut(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}var Zn=(e,t,n=[])=>{const r=y.forwardRef((i,s)=>{var u;const a={},o={};Object.keys(i).forEach(c=>{n.includes(c)?a[c]=i[c]:o[c]=i[c]});const l=(u=t(a))!=null?u:void 0;return p.jsx(ut.button,E(g({type:"button"},o),{ref:s,disabled:o.disabled||!l,onClick:Ut(o.onClick,l)}))});return r.displayName=e,r};function Qh(e,t=globalThis==null?void 0:globalThis.document){const n=Ct(e);Q.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Zh=()=>{const e=me();return y.useCallback(()=>{e.attachment().remove()},[e])},ef=Zn("AttachmentPrimitive.Remove",Zh),cn=e=>{const t=y.useRef(void 0);return y.useCallback(r=>{t.current&&t.current(),r&&(t.current=e(r))},[e])},Ea=(e,t)=>{const n=y.useCallback(r=>{if(!e)return;const i=e(),s=()=>{const o=t?t(r):r.offsetHeight;i.setHeight(o)},a=new ResizeObserver(s);return a.observe(r),s(),()=>{a.disconnect(),i.unregister()}},[e,t]);return cn(n)},Aa=y.createContext(!1),Ma=(e,t)=>{const n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;const r=parseFloat(n[1]),i=n[2];if(i==="px")return r;if(i==="em"){const s=parseFloat(getComputedStyle(t).fontSize)||16;return r*s}if(i==="rem"){const s=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return r*s}return 0},Pa=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const r=ne(({message:l})=>l.isLast&&l.index>=2),i=$r({optional:!0}),s=y.useContext(Aa),a=y.useCallback(l=>{if(!i||s)return;const u=()=>{const c=i.getState();if(c.turnAnchor==="top"&&r){const{viewport:d,inset:h,userMessage:f}=c.height,m=Ma(t,l),v=Ma(n,l),b=f<=m?f:v,x=Math.max(0,d-h-b);l.style.minHeight=`${x}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),i.subscribe(u)},[i,r,s,t,n]),o=cn(a);return p.jsx(Aa.Provider,{value:!0,children:p.jsx(Ca,{ref:o,children:e})})};Pa.displayName="ThreadPrimitive.ViewportSlack";var tf=()=>{const e=me(),t=ne(()=>e.message()),n=y.useCallback(r=>{const i=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return r.addEventListener("mouseenter",i),r.addEventListener("mouseleave",s),r.matches(":hover")&&t.setIsHovering(!0),()=>{r.removeEventListener("mouseenter",i),r.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]);return cn(n)},nf=()=>{const e=Kn(i=>i.turnAnchor),t=Kn(i=>i.registerUserMessageHeight),n=ne(({thread:i,message:s})=>{var a;return e==="top"&&s.role==="user"&&s.index===i.messages.length-2&&((a=i.messages.at(-1))==null?void 0:a.role)==="assistant"}),r=y.useCallback(i=>i.offsetHeight,[]);return Ea(n?t:null,r)},Xr=y.forwardRef((e,t)=>{const n=tf(),r=nf(),i=Wn(t,n,r);return p.jsx(Pa,{children:p.jsx(ut.div,E(g({},e),{ref:i}))})});Xr.displayName="MessagePrimitive.Root";var Na=()=>ne(({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}),La=y.forwardRef((i,r)=>{var s=i,{smooth:e=!0,component:t="span"}=s,n=V(s,["smooth","component"]);const{text:a,status:o}=Sa(Na(),e);return p.jsx(t,E(g({"data-status":o.type},n),{ref:r,children:a}))});La.displayName="MessagePartPrimitive.Text";var rf=()=>ne(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Da=y.forwardRef((e,t)=>{const{image:n}=rf();return p.jsx(ut.img,E(g({src:n},e),{ref:t}))});Da.displayName="MessagePartPrimitive.Image";var Oa=({children:e})=>ne(({part:n})=>n.status.type==="running")?e:null;Oa.displayName="MessagePartPrimitive.InProgress";const Fa=e=>Symbol.iterator in e,Ba=e=>"entries"in e,za=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},sf=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function af(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:Fa(e)&&Fa(t)?Ba(e)&&Ba(t)?za(e,t):sf(e,t):za({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function of(e){const t=y.useRef(void 0);return n=>{const r=e(n);return af(t.current,r)?t.current:t.current=r}}var Ra=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},lf=e=>{const t=[],n=Ra("toolGroup"),r=Ra("reasoningGroup");for(let i=0;i<e.length;i++){const s=e[i];s==="tool-call"?(r.endGroup(i-1,t),n.startGroup(i)):s==="reasoning"?(n.endGroup(i-1,t),r.startGroup(i)):(n.endGroup(i-1,t),r.endGroup(i-1,t),t.push({type:"single",index:i}))}return n.finalize(e.length-1,t),r.finalize(e.length-1,t),t},uf=()=>{const e=ne(of(t=>t.message.parts.map(n=>n.type)));return y.useMemo(()=>e.length===0?[]:lf(e),[e])},cf=n=>{var r=n,{Fallback:e}=r,t=V(r,["Fallback"]);const i=ne(({tools:s})=>{var o,l;const a=(o=s.tools[t.toolName])!=null?o:e;return Array.isArray(a)?(l=a[0])!=null?l:e:a});return i?p.jsx(i,g({},t)):null},ct={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(La,{}),p.jsx(Oa,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Da,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},df=({components:{Text:e=ct.Text,Reasoning:t=ct.Reasoning,Image:n=ct.Image,Source:r=ct.Source,File:i=ct.File,Unstable_Audio:s=ct.Unstable_Audio,tools:a={}}={}})=>{var c,d,h;const o=me(),l=ne(({part:f})=>f),u=l.type;if(u==="tool-call"){const f=o.part().addToolResult,m=o.part().resumeToolCall;if("Override"in a)return p.jsx(a.Override,E(g({},l),{addResult:f,resume:m}));const v=(d=(c=a.by_name)==null?void 0:c[l.toolName])!=null?d:a.Fallback;return p.jsx(cf,E(g({},l),{Fallback:v,addResult:f,resume:m}))}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,g({},l));case"reasoning":return p.jsx(t,g({},l));case"source":return p.jsx(r,g({},l));case"image":return p.jsx(n,g({},l));case"file":return p.jsx(i,g({},l));case"audio":return p.jsx(s,g({},l));case"data":return null;default:const f=u;throw new Error(`Unknown message part type: ${f}`)}},er=y.memo(({index:e,components:t})=>p.jsx(ih,{index:e,children:p.jsx(df,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u,c,d,h,f,m,v,b,x,C,_;return e.index===t.index&&((n=e.components)==null?void 0:n.Text)===((r=t.components)==null?void 0:r.Text)&&((i=e.components)==null?void 0:i.Reasoning)===((s=t.components)==null?void 0:s.Reasoning)&&((a=e.components)==null?void 0:a.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)&&((c=e.components)==null?void 0:c.File)===((d=t.components)==null?void 0:d.File)&&((h=e.components)==null?void 0:h.Unstable_Audio)===((f=t.components)==null?void 0:f.Unstable_Audio)&&((m=e.components)==null?void 0:m.tools)===((v=t.components)==null?void 0:v.tools)&&((b=e.components)==null?void 0:b.ToolGroup)===((x=t.components)==null?void 0:x.ToolGroup)&&((C=e.components)==null?void 0:C.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});er.displayName="MessagePrimitive.PartByIndex";var hf=({status:e,component:t})=>p.jsx(lh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),ff=Object.freeze({type:"complete"}),pf=({components:e})=>{var n;const t=ne(r=>{var i;return(i=r.message.status)!=null?i:ff});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(hf,{status:t,component:(n=e==null?void 0:e.Text)!=null?n:ct.Text})},mf=y.memo(pf,(e,t)=>{var n,r,i,s;return((n=e.components)==null?void 0:n.Empty)===((r=t.components)==null?void 0:r.Empty)&&((i=e.components)==null?void 0:i.Text)===((s=t.components)==null?void 0:s.Text)}),Qr=({components:e})=>{const t=ne(({message:i})=>i.parts.length),n=uf(),r=y.useMemo(()=>t===0?p.jsx(mf,{components:e}):n.map(i=>{var s,a;if(i.type==="single")return p.jsx(er,{index:i.index,components:e},i.index);if(i.type==="toolGroup"){const o=(s=e==null?void 0:e.ToolGroup)!=null?s:ct.ToolGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(er,{index:i.startIndex+u,components:e},u))},`tool-${i.startIndex}`)}else{const o=(a=e==null?void 0:e.ReasoningGroup)!=null?a:ct.ReasoningGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(er,{index:i.startIndex+u,components:e},u))},`reasoning-${i.startIndex}`)}}),[n,e,t]);return p.jsx(p.Fragment,{children:r})};Qr.displayName="MessagePrimitive.Parts";var gf=(e,t)=>{var r,i,s;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},yf=({components:e})=>{const t=ne(({attachment:r})=>r);if(!t)return null;const n=gf(e,t);return n?p.jsx(n,{}):null},ja=y.memo(({index:e,components:t})=>p.jsx(sh,{index:e,children:p.jsx(yf,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((i=e.components)==null?void 0:i.Document)===((s=t.components)==null?void 0:s.Document)&&((a=e.components)==null?void 0:a.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)});ja.displayName="MessagePrimitive.AttachmentByIndex";var Ua=({components:e})=>{const t=ne(({message:r})=>r.role!=="user"?0:r.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,i)=>p.jsx(ja,{index:i,components:e},i)),[t,e])};Ua.displayName="MessagePrimitive.Attachments";var $a=()=>{const e=me(),t=ne(r=>r.thread.isRunning||!r.composer.isEditing||r.composer.isEmpty),n=y.useCallback(()=>{e.composer().send()},[e]);return t?null:n},bf=Zn("ComposerPrimitive.Send",$a),Ha=y.forwardRef((r,n)=>{var i=r,{onSubmit:e}=i,t=V(i,["onSubmit"]);const s=$a(),a=o=>{o.preventDefault(),s&&s()};return p.jsx(ut.form,E(g({},t),{ref:n,onSubmit:Ut(e,a)}))});Ha.displayName="ComposerPrimitive.Root";function Zr(){return Zr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Zr.apply(null,arguments)}function wf(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var xf=y.useLayoutEffect,vf=function(t){var n=y.useRef(t);return xf(function(){n.current=t}),n},qa=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},Sf=function(t,n){var r=y.useRef();return y.useCallback(function(i){t.current=i,r.current&&qa(r.current,null),r.current=n,n&&qa(n,i)},[n])},Va={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},kf=function(t){Object.keys(Va).forEach(function(n){t.style.setProperty(n,Va[n],"important")})},Wa=kf,De=null,Ja=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function _f(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),De||(De=document.createElement("textarea"),De.setAttribute("tabindex","-1"),De.setAttribute("aria-hidden","true"),Wa(De)),De.parentNode===null&&document.body.appendChild(De);var i=e.paddingSize,s=e.borderSize,a=e.sizingStyle,o=a.boxSizing;Object.keys(a).forEach(function(h){var f=h;De.style[f]=a[f]}),Wa(De),De.value=t;var l=Ja(De,e);De.value=t,l=Ja(De,e),De.value="x";var u=De.scrollHeight-i,c=u*n;o==="border-box"&&(c=c+i+s),l=Math.max(c,l);var d=u*r;return o==="border-box"&&(d=d+i+s),l=Math.min(d,l),[l,u]}var Ka=function(){},Tf=function(t,n){return t.reduce(function(r,i){return r[i]=n[i],r},{})},If=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Cf=!!document.documentElement.currentStyle,Ef=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=Tf(If,n),i=r.boxSizing;if(i==="")return null;Cf&&i==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var s=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),a=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:s,borderSize:a}},Af=Ef;function ei(e,t,n){var r=vf(n);Q.useLayoutEffect(function(){var i=function(a){return r.current(a)};if(e)return e.addEventListener(t,i),function(){return e.removeEventListener(t,i)}},[])}var Mf=function(t,n){ei(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},Pf=function(t){ei(window,"resize",t)},Nf=function(t){ei(document.fonts,"loadingdone",t)},Lf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Df=function(t,n){var r=t.cacheMeasurements,i=t.maxRows,s=t.minRows,a=t.onChange,o=a===void 0?Ka:a,l=t.onHeightChange,u=l===void 0?Ka:l,c=wf(t,Lf),d=c.value!==void 0,h=Q.useRef(null),f=Sf(h,n),m=Q.useRef(0),v=Q.useRef(),b=function(){var _=h.current,F=r&&v.current?v.current:Af(_);if(F){v.current=F;var z=_f(F,_.value||_.placeholder||"x",s,i),I=z[0],H=z[1];m.current!==I&&(m.current=I,_.style.setProperty("height",I+"px","important"),u(I,{rowHeight:H}))}},x=function(_){d||b(),o(_)};return Q.useLayoutEffect(b),Mf(h,function(){if(!d){var C=h.current.value;requestAnimationFrame(function(){var _=h.current;_&&C!==_.value&&b()})}}),Pf(b),Nf(b),Q.createElement("textarea",Zr({},c,{onChange:x,ref:f}))},Of=Q.forwardRef(Df),Ya=e=>{const t=Ct(e),n=Kn(r=>r.onScrollToBottom);y.useEffect(()=>n(t),[n,t])},Ga=y.forwardRef((m,f)=>{var v=m,{autoFocus:e=!1,asChild:t,disabled:n,onChange:r,onKeyDown:i,onPaste:s,submitOnEnter:a=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0}=v,h=V(v,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const b=me(),x=ne(({composer:k})=>k.isEditing?k.text:""),C=t?Ca:Of,_=ne(({thread:k})=>k.isDisabled)||n,F=y.useRef(null),z=Wn(f,F);Qh(k=>{var P;if(!o||!((P=F.current)!=null&&P.contains(k.target)))return;const O=b.composer();O.getState().canCancel&&(O.cancel(),k.preventDefault())});const I=k=>{var O,P;_||!a||k.nativeEvent.isComposing||k.key==="Enter"&&k.shiftKey===!1&&(b.thread().getState().isRunning||(k.preventDefault(),(P=(O=F.current)==null?void 0:O.closest("form"))==null||P.requestSubmit()))},H=k=>M(null,null,function*(){var R;if(!d)return;const O=b.thread().getState().capabilities,P=Array.from(((R=k.clipboardData)==null?void 0:R.files)||[]);if(O.attachments&&P.length>0)try{k.preventDefault(),yield Promise.all(P.map(L=>b.composer().addAttachment(L)))}catch(L){console.error("Error adding attachment:",L)}}),q=e&&!_,j=y.useCallback(()=>{const k=F.current;!k||!q||(k.focus({preventScroll:!0}),k.setSelectionRange(k.value.length,k.value.length))},[q]);return y.useEffect(()=>j(),[j]),Ya(()=>{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"||!c))return b.on("thread-list-item.switched-to",j)},[c,j,b]),p.jsx(C,E(g({name:"input",value:x},h),{ref:z,disabled:_,onChange:Ut(r,k=>{b.composer().getState().isEditing&&(b.composer().setText(k.target.value),b.flushSync())}),onKeyDown:Ut(i,I),onPaste:Ut(s,H)}))});Ga.displayName="ComposerPrimitive.Input";var Ff=({multiple:e=!0}={})=>{const t=ne(({composer:i})=>!i.isEditing),n=me(),r=y.useCallback(()=>{const i=document.createElement("input");i.type="file",i.multiple=e,i.hidden=!0;const s=n.composer().getState().attachmentAccept;s!=="*"&&(i.accept=s),document.body.appendChild(i),i.onchange=a=>{const o=a.target.files;if(o){for(const l of o)n.composer().addAttachment(l);document.body.removeChild(i)}},i.oncancel=()=>{(!i.files||i.files.length===0)&&document.body.removeChild(i)},i.click()},[n,e]);return t?null:r},Bf=Zn("ComposerPrimitive.AddAttachment",Ff,["multiple"]),zf=(e,t)=>{var r,i,s;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},Rf=({components:e})=>{const t=ne(({attachment:r})=>r);if(!t)return null;const n=zf(e,t);return n?p.jsx(n,{}):null},Xa=y.memo(({index:e,components:t})=>p.jsx(ah,{index:e,children:p.jsx(Rf,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((i=e.components)==null?void 0:i.Document)===((s=t.components)==null?void 0:s.Document)&&((a=e.components)==null?void 0:a.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)});Xa.displayName="ComposerPrimitive.AttachmentByIndex";var Qa=({components:e})=>{const t=ne(r=>r.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,i)=>p.jsx(Xa,{index:i,components:e},i)),[t,e])};Qa.displayName="ComposerPrimitive.Attachments";var Za=y.forwardRef((e,t)=>p.jsx(ut.div,E(g({},e),{ref:t})));Za.displayName="ThreadPrimitive.Root";var eo=({children:e})=>ne(({thread:n})=>n.messages.length===0&&!n.isLoading)?e:null;eo.displayName="ThreadPrimitive.Empty";var jf=e=>{const t=Ct(e),n=y.useCallback(r=>{const i=new ResizeObserver(()=>{t()}),s=new MutationObserver(()=>{t()});return i.observe(r),s.observe(r,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{i.disconnect(),s.disconnect()}},[t]);return cn(n)},Uf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{const i=y.useRef(null),s=$r();e===void 0&&(e=s.getState().turnAnchor!=="top");const a=y.useRef(0),o=y.useRef(null),l=y.useCallback(f=>{const m=i.current;m&&(o.current=f,m.scrollTo({top:m.scrollHeight,behavior:f}))},[]),u=()=>{const f=i.current;if(!f)return;const m=s.getState().isAtBottom,v=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<1||f.scrollHeight<=f.clientHeight;!v&&a.current<f.scrollTop||(v&&(o.current=null),(v||o.current===null)&&v!==m&&un(s).setState({isAtBottom:v})),a.current=f.scrollTop},c=jf(()=>{const f=o.current;f?l(f):e&&s.getState().isAtBottom&&l("instant"),u()}),d=cn(f=>(f.addEventListener("scroll",u),()=>{f.removeEventListener("scroll",u)}));return Ya(({behavior:f})=>{l(f)}),Ur("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Ur("thread.initialize",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Ur("thread-list-item.switched-to",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Wn(c,d,i)},$f=()=>{const e=Kn(n=>n.registerViewport),t=y.useCallback(n=>n.clientHeight,[]);return Ea(e,t)},to=y.forwardRef((o,a)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:i}=l,s=V(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Uf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),c=$f(),d=Wn(a,u,c);return p.jsx(ut.div,E(g({},s),{ref:d,children:i}))});to.displayName="ThreadPrimitive.ViewportScrollable";var no=y.forwardRef((r,n)=>{var i=r,{turnAnchor:e}=i,t=V(i,["turnAnchor"]);return p.jsx(ha,{options:{turnAnchor:e},children:p.jsx(to,E(g({},t),{ref:n}))})});no.displayName="ThreadPrimitive.Viewport";var ro=(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,Hf=()=>null,qf=(e,t,n)=>{var r,i,s,a,o,l,u,c,d,h,f,m;switch(t){case"user":return n?(s=(i=(r=e.UserEditComposer)!=null?r:e.EditComposer)!=null?i:e.UserMessage)!=null?s:e.Message:(a=e.UserMessage)!=null?a:e.Message;case"assistant":return n?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(c=e.AssistantMessage)!=null?c:e.Message;case"system":return n?(f=(h=(d=e.SystemEditComposer)!=null?d:e.EditComposer)!=null?h:e.SystemMessage)!=null?f:e.Message:(m=e.SystemMessage)!=null?m:Hf;default:const v=t;throw new Error(`Unknown message role: ${v}`)}},Vf=({components:e})=>{const t=ne(({message:i})=>i.role),n=ne(({message:i})=>i.composer.isEditing),r=qf(e,t,n);return p.jsx(r,{})},io=y.memo(({index:e,components:t})=>p.jsx(rh,{index:e,children:p.jsx(Vf,{components:t})}),(e,t)=>e.index===t.index&&ro(e.components,t.components));io.displayName="ThreadPrimitive.MessageByIndex";var so=({components:e})=>{const t=ne(({thread:r})=>r.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(r,i)=>p.jsx(io,{index:i,components:e},i)),[t,e])};so.displayName="ThreadPrimitive.Messages";var Wf=y.memo(so,(e,t)=>ro(e.components,t.components)),ao=y.forwardRef((i,r)=>{var s=i,{onClick:e,disabled:t}=s,n=V(s,["onClick","disabled"]);const a=ne(({threads:l})=>l.newThreadId===l.mainThreadId),o=me();return p.jsx(ut.button,E(g(g({type:"button"},a?{"data-active":"true","aria-current":"true"}:null),n),{ref:r,disabled:t,onClick:Ut(e,()=>{o.threads().switchToNewThread()})}))});ao.displayName="ThreadListPrimitive.New";var oo=y.memo(({index:e,archived:t=!1,components:n})=>{const r=n.ThreadListItem;return p.jsx(th,{index:e,archived:t,children:p.jsx(r,{})})},(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 n=ne(({threads:i})=>e?i.archivedThreadIds.length:i.threadIds.length);return y.useMemo(()=>Array.from({length:n},(i,s)=>p.jsx(oo,{index:s,archived:e,components:t},s)),[n,e,t])};lo.displayName="ThreadListPrimitive.Items";var uo=y.forwardRef((e,t)=>p.jsx(ut.div,E(g({},e),{ref:t})));uo.displayName="ThreadListPrimitive.Root";var co=y.forwardRef((e,t)=>{const n=ne(({threads:r,threadListItem:i})=>r.mainThreadId===i.id);return p.jsx(ut.div,E(g(g({},n?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});co.displayName="ThreadListItemPrimitive.Root";var Jf=()=>{const e=me();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},Kf=Zn("ThreadListItemPrimitive.Trigger",Jf);function Yf(){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,n=>n.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,n,r=!1){T(this,"baseUrl");T(this,"sessionToken",null);T(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=r,n&&(this.sessionToken=n)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const n=`${this.baseUrl}${t.replace("/v1","")}`;return n.startsWith("/")||n.startsWith("./"),n}return`${this.baseUrl}${t}`}createOrContinueChat(t,n){return M(this,null,function*(){const r=this.getUrl("/v1/chats"),s={"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&&(s.Authorization=`Bearer ${this.sessionToken}`);const a=E(g({},t),{stream:!0}),o=yield fetch(r,{method:"POST",headers:s,body:JSON.stringify(a),signal:n,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 M(this,null,function*(){const n=this.getUrl(`/v1/chats/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n,{method:"GET",headers:r});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()})}listChats(t){return M(this,null,function*(){const n=this.getUrl("/v1/chats"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(r.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}generateIdempotencyKey(){return Yf()}updateChat(t,n){return M(this,null,function*(){const r=`/v1/chats/${t}`,i=this.getUrl(r),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"PATCH",headers:o,body:JSON.stringify(n)});if(!l.ok){const c=yield l.text();let d={};try{d=JSON.parse(c)}catch(h){d={detail:c}}throw new Error(d.detail||d.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(c){return{}}})}deleteChat(t){return M(this,null,function*(){const n=`/v1/chats/${t}`,r=this.getUrl(n),i=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"DELETE",headers:a});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 M(this,null,function*(){const n=this.getUrl("/v1/models"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(r.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}getModel(t){return M(this,null,function*(){const n=this.getUrl(`/v1/models/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n,{method:"GET",headers:r});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()})}uploadFile(t,n,r){return M(this,null,function*(){const i=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),a=new FormData;a.append("file",t),n&&a.append("resource_type",n),r&&a.append("resource_id",r);const o={"Idempotency-Key":s};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i,{method:"POST",headers:o,body:a});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 Gf(e,t){return Mn(this,null,function*(){const n=e.getReader(),r=new TextDecoder;let i="";try{for(;;){if(t!=null&&t.aborted){n.cancel();break}const{done:s,value:a}=yield new Ee(n.read());if(s)break;i+=r.decode(a,{stream:!0});const o=i.split(`
5
+ `),Ms=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)}},Ps=class extends Ms{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)}},dc=class extends Ps{get source(){return"thread-composer"}},hc=class extends Ps{get source(){return"edit-composer"}},fc=class extends Ms{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Ns=class extends zn{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(),n=t==null?void 0:t.unstable_on(this.config.event,e);const r=()=>{var a;const s=this.config.binding.getState();s!==t&&(t=s,n==null||n(),n=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,e))},i=this.outerSubscribe(r);return()=>{i==null||i(),n==null||n()}}},Ls=Object.freeze([]),Ds=Object.freeze({}),pc=e=>{var t,n,r,i,s,a,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,attachments:(i=e==null?void 0:e.attachments)!=null?i:Ls,text:(s=e==null?void 0:e.text)!=null?s:"",role:(a=e==null?void 0:e.role)!=null?a:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ds,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},mc=e=>{var t,n,r,i,s,a,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(n=e==null?void 0:e.canCancel)!=null?n:!1,isEmpty:(r=e==null?void 0:e.isEmpty)!=null?r:!0,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",attachments:(a=e==null?void 0:e.attachments)!=null?a:Ls,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ds,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Os=class{constructor(e){T(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 n=this._eventSubscriptionSubjects.get(e);return n||(n=new Ns({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},gc=class extends Os{constructor(t){const n=new Dr({path:t.path,getState:()=>pc(t.getState()),subscribe:r=>t.subscribe(r)});super({path:t.path,getState:()=>t.getState(),subscribe:r=>n.subscribe(r)});T(this,"_getState");this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new dc(new Qe({path:I(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const r=this.getState().attachments[t];return r?I(m({},r),{source:"thread-composer"}):Xe},subscribe:n=>this._core.subscribe(n)}),this._core)}},yc=class extends Os{constructor(t,n){const r=new Dr({path:t.path,getState:()=>mc(t.getState()),subscribe:i=>t.subscribe(i)});super({path:t.path,getState:()=>t.getState(),subscribe:i=>r.subscribe(i)});T(this,"_getState");this._beginEdit=n,this._getState=r.getState.bind(r),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 hc(new Qe({path:I(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const r=this.getState().attachments[t];return r?I(m({},r),{source:"edit-composer"}):Xe},subscribe:n=>this._core.subscribe(n)}),this._core)}},bc=class kr{constructor(t=null){T(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((n,r)=>kr.apply(n,r),this._state)}static apply(t,n){const r=n.type;switch(r){case"set":return kr.updatePath(t,n.path,()=>n.value);case"append-text":return kr.updatePath(t,n.path,i=>{if(typeof i!="string")throw new Error(`Expected string at path [${n.path.join(", ")}]`);return i+n.value});default:{const i=r;throw new Error(`Invalid operation type: ${i}`)}}}static updatePath(t,n,r){if(n.length===0)return r(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${n.join(", ")}]`);const[i,...s]=n;if(Array.isArray(t)){const o=Number(i);if(Number.isNaN(o))throw new Error(`Expected array index at [${n.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],s,r),l}const a=m({},t);return a[i]=this.updatePath(a[i],s,r),a}},wc=({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:{}}}),Un=(e,t,n)=>{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 r=t.path[0],i=n(e.parts[r]);return I(m({},e),{parts:[...e.parts.slice(0,r),i,...e.parts.slice(r+1)],get content(){return this.parts}})},xc=(e,t)=>{const n=t.part;if(n.type==="text"||n.type==="reasoning"){const r=m({type:n.type,text:"",status:{type:"running"}},n.parentId&&{parentId:n.parentId});return I(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="tool-call"){const r=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:n.toolCallId,toolName:n.toolName,argsText:"",args:{}},n.parentId&&{parentId:n.parentId});return I(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="source"){const r=m(m({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0),n.parentId&&{parentId:n.parentId});return I(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else if(n.type==="file"){const r={type:"file",mimeType:n.mimeType,data:n.data};return I(m({},e),{parts:[...e.parts,r],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${n.type}`)},vc=(e,t)=>Un(e,t,n=>{if(n.type!=="tool-call")throw new Error("Last is not a tool call");return n.state!=="partial-call"?n:I(m({},n),{state:"call"})}),Sc=(e,t)=>Un(e,t,n=>I(m({},n),{status:{type:"complete",reason:"unknown"}})),kc=(e,t)=>Un(e,t,n=>{var r;if(n.type==="text"||n.type==="reasoning")return I(m({},n),{text:n.text+t.textDelta});if(n.type==="tool-call"){const i=n.argsText+t.textDelta,s=(r=On(i))!=null?r:n.args;return I(m({},n),{argsText:i,args:s})}else throw new Error("text-delta received but part is neither text nor tool-call")}),_c=(e,t)=>Un(e,t,n=>{var r;if(n.type==="tool-call")return I(m(I(m({},n),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(r=t.isError)!=null?r:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Fs=(e,t)=>{var r,i;if(((r=e.status)==null?void 0:r.type)==="incomplete"&&((i=e.status)==null?void 0:i.reason)==="error")return e;const n=Tc(t);return I(m({},e),{status:n})},Tc=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},Cc=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Ic=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Ec=(e,t)=>I(m({},e),{metadata:I(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Ac=(e,t)=>{var i;const n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&((i=n[r])==null?void 0:i.state)==="started"?n[r]=I(m({},n[r]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):n.push({state:"finished",messageId:Cs(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),I(m({},e),{metadata:I(m({},e.metadata),{steps:n})})},Mc=(e,t)=>I(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Pc=(e,t)=>{const n=new bc(e.metadata.unstable_state);return n.append(t.operations),I(m({},e),{metadata:I(m({},e.metadata),{unstable_state:n.state})})},Nc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Lc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n}={}){let r=e!=null?e:wc(),i;const s=t?Nc(()=>{i==null||i.enqueue(r)}):()=>{i==null||i.enqueue(r)};super({start(a){i=a},transform(a){const o=a.type;switch(o){case"part-start":r=xc(r,a);break;case"tool-call-args-text-finish":r=vc(r,a);break;case"part-finish":r=Sc(r,a);break;case"text-delta":r=kc(r,a);break;case"result":r=_c(r,a);break;case"message-finish":r=Fs(r,a);break;case"annotations":r=Cc(r,a);break;case"data":r=Ic(r,a);break;case"step-start":r=Ec(r,a);break;case"step-finish":r=Ac(r,a);break;case"error":r=Mc(r,a),n==null||n(a.error);break;case"update-state":r=Pc(r,a);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}s()},flush(a){var o,l,u;if(((o=r.status)==null?void 0:o.type)==="running"){const c=(u=(l=r.parts)==null?void 0:l.some(d=>d.type==="tool-call"&&(d.state==="call"||d.state==="partial-call")&&d.result===void 0))!=null?u:!1;r=Fs(r,{finishReason:c?"tool-calls":"unknown"}),a.enqueue(r)}}})}},Dc=class extends _s{constructor(){super(e=>{const t=new lc({transform(n,r){r.appendText(n)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},Oc=class _r{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new _r(t.pipeThrough(new Lc))}unstable_result(){return M(this,null,function*(){let t;try{for(var n=Lt(this),r,i,s;r=!(i=yield n.next()).done;r=!1){const a=i.value;t=a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield i.call(n))}finally{if(s)throw s[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 M(this,null,function*(){const{done:r,value:i}=yield t.read();return r?{done:!0,value:void 0}:{done:!1,value:i}})}}}tee(){const[t,n]=this.readable.tee();return[new _r(t),new _r(n)]}},zs=Symbol.for("aui.tool-response"),pt=class os{constructor(t){T(this,"artifact");T(this,"result");T(this,"isError");var n;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(n=t.isError)!=null?n:!1}get[zs](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&zs in t}static toResponse(t){return t instanceof os?t:new os({result:t===void 0?"<no result>":t})}};function Fc(e,t,n){try{const r=e();if(typeof r=="object"&&r!==null&&"then"in r)return r.then(t,n);t(r)}catch(r){n(r)}}function an(e,t){let n=e;for(const r of t){if(n==null)return;n=n[r]}return n}var zc=class{constructor(e,t,n){T(this,"resolve");T(this,"reject");T(this,"disposed",!1);T(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=n}update(e){if(!this.disposed)try{if(Dt(e,this.fieldPath)==="complete"){const t=an(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Bs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=an(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Rs=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const n=an(e,this.fieldPath);if(n!==void 0&&typeof n=="string"){const r=n.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=n,this.controller.enqueue(r)}Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(n){this.controller.error(n),this.dispose()}}dispose(){this.disposed=!0}},js=class{constructor(e,t){T(this,"controller");T(this,"disposed",!1);T(this,"fieldPath");T(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=an(e,this.fieldPath);if(!Array.isArray(t))return;for(let n=0;n<t.length;n++)if(!this.processedIndexes.has(n)){const r=[...this.fieldPath,n];Dt(e,r)==="complete"&&(this.controller.enqueue(t[n]),this.processedIndexes.add(n))}Dt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Bc=class{constructor(e){T(this,"argTextDeltas");T(this,"handles",new Set);T(this,"args",On(""));this.argTextDeltas=e,this.processStream()}processStream(){return M(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:n,done:r}=yield t.read();if(r)break;e+=n;const i=On(e);if(i!==void 0){this.args=i;for(const s of this.handles)s.update(i)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,n)=>{const r=new zc(t,n,e);if(this.args&&Dt(this.args,e)==="complete"){const i=an(this.args,e);if(i!==void 0){t(i);return}}this.handles.add(r),r.update(this.args)})}streamValues(...e){const t=e,n=new ReadableStream({start:r=>{const i=new Bs(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Bs){r.dispose(),this.handles.delete(r);break}}});return Mr(n)}streamText(...e){const t=e,n=new ReadableStream({start:r=>{const i=new Rs(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof Rs){r.dispose(),this.handles.delete(r);break}}});return Mr(n)}forEach(...e){const t=e,n=new ReadableStream({start:r=>{const i=new js(r,t);this.handles.add(i),i.update(this.args)},cancel:()=>{for(const r of this.handles)if(r instanceof js){r.dispose(),this.handles.delete(r);break}}});return Mr(n)}},Rc=class{constructor(e){this.promise=e}get(){return this.promise}},jc=class{constructor(){T(this,"args");T(this,"response");T(this,"writable");T(this,"resolve");T(this,"argsText","");T(this,"result",{get:()=>M(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Bc(e.readable);const{promise:t,resolve:n}=Nr();this.resolve=n,this.response=new Rc(t)}appendArgsTextDelta(e){return M(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(n){console.warn(n)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Uc=class extends _s{constructor(e){const t=new Map,n=new Map;super(r=>{const i=new TransformStream({transform(a,o){switch((a.type!=="part-finish"||a.meta.type!=="tool-call")&&o.enqueue(a),a.type){case"part-start":if(a.part.type==="tool-call"){const u=new jc;n.set(a.part.toolCallId,u),e.streamCall({reader:u,toolCallId:a.part.toolCallId,toolName:a.part.toolName})}break;case"text-delta":{if(a.meta.type==="tool-call"){const u=a.meta.toolCallId,c=n.get(u);if(!c)throw new Error("No controller found for tool call");c.appendArgsTextDelta(a.textDelta)}break}case"result":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,c=n.get(u);if(!c)throw new Error("No controller found for tool call");c.setResponse(new pt({result:a.result,artifact:a.artifact,isError:a.isError}));break}case"tool-call-args-text-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u,toolName:c}=a.meta,d=n.get(u);if(!d)throw new Error("No controller found for tool call");let h=!1;const f=Fc(()=>{var b;let g;try{g=Ar.parse(d.argsText)}catch(x){throw new Error(`Function parameter parsing failed. ${JSON.stringify(x.message)}`)}const v=e.execute({toolCallId:u,toolName:c,args:g});return v!==void 0&&(h=!0,(b=e.onExecutionStart)==null||b.call(e,u,c)),v},g=>{var b;if(h&&((b=e.onExecutionEnd)==null||b.call(e,u,c)),g===void 0)return;const v=new pt({artifact:g.artifact,result:g.result,isError:g.isError});d.setResponse(v),o.enqueue(m({type:"result",path:a.path},v))},g=>{var b;h&&((b=e.onExecutionEnd)==null||b.call(e,u,c));const v=new pt({result:String(g),isError:!0});d.setResponse(v),o.enqueue(m({type:"result",path:a.path},v))});f&&t.set(u,f);break}case"part-finish":{if(a.meta.type!=="tool-call")break;const{toolCallId:u}=a.meta,c=t.get(u);c?c.then(()=>{t.delete(u),n.delete(u),o.enqueue(a)}):o.enqueue(a)}}},flush(){return M(this,null,function*(){yield Promise.all(t.values())})}});return r.pipeThrough(new Ts).pipeThrough(i)})}},$c=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function Hc(e,t,n,r){const i=e==null?void 0:e[n.toolName];return!i||!i.execute?void 0:(a=>M(null,null,function*(){var c;if(t.aborted)return new pt({result:"Tool execution was cancelled.",isError:!0});let o=a;if($c(i.parameters)){let d=i.parameters["~standard"].validate(n.args);d instanceof Promise&&(d=yield d),d.issues&&(o=(c=i.experimental_onSchemaValidationError)!=null?c:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(d.issues)}`)}))}const l=new Promise(d=>{const h=()=>{queueMicrotask(()=>{queueMicrotask(()=>{d(new pt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?h():t.addEventListener("abort",h,{once:!0})}),u=M(null,null,function*(){const d=yield o(n.args,{toolCallId:n.toolCallId,abortSignal:t,human:h=>r(n.toolCallId,h)});return pt.toResponse(d)});return Promise.race([u,l])}))(i.execute)}function qc(e,t,n,r,i){var s,a;(a=(s=e==null?void 0:e[r.toolName])==null?void 0:s.streamCall)==null||a.call(s,n,{toolCallId:r.toolCallId,abortSignal:t,human:o=>i(r.toolCallId,o)})}function Vc(e,t,n,r){const i=typeof e=="function"?e:()=>e,s=typeof t=="function"?t:()=>t;return new Uc({execute:a=>Hc(i(),s(),a,n),streamCall:l=>{var u=l,{reader:a}=u,o=q(u,["reader"]);return qc(i(),s(),a,o,n)},onExecutionStart:r==null?void 0:r.onExecutionStart,onExecutionEnd:r==null?void 0:r.onExecutionEnd})}var Us=class{constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,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 n=this.messageApi.getState();if(!n)throw new Error("Message is not available");const r=t.toolName,i=t.toolCallId,s=pt.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:s.result,artifact:s.artifact,isError:s.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 n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},$n=class extends zn{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(),n=t==null?void 0:t.subscribe(e);const r=()=>{var a;const s=this.binding.getState();s!==t&&(t=s,n==null||n(),n=(a=this.binding.getState())==null?void 0:a.subscribe(e),e())},i=this.outerSubscribe(r);return()=>{i==null||i(),n==null||n()}}},Hn=Object.freeze({type:"complete"}),Wc=(e,t,n)=>{if(e.role!=="assistant")return Hn;if(n.type==="tool-call")return n.result?Hn:e.status;const r=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Hn:r?e.status:Hn},$s=(e,t)=>{const n=e.content[t];if(!n)return Xe;const r=Wc(e,t,n);return Object.freeze(I(m({},n),{[Rn]:n[Rn],status:r}))},Jc=class{constructor(e,t){T(this,"composer");T(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new yc(new $n({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:n=>this._threadBinding.subscribe(n)}),()=>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(),n=t!=null?t:this._threadBinding.getState().composer,r=t!=null?t:n,{runConfig:i=r.runConfig}=e,s=this._core.getState();if(s.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:s.parentId,sourceId:s.id,runConfig:i})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var n;const e=this._core.getState();if(((n=this._threadBinding.getState().speech)==null?void 0:n.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 n=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 i=this._threadBinding.getState().getBranches(n.id);let s=t;if(e==="previous"?s=i[n.branchNumber-2]:e==="next"&&(s=i[n.branchNumber]),!s)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(s)}unstable_getCopyText(){return jn(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 Us(new Qe({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>$s(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Us(new Qe({path:I(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(),n=t.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===e);return n===-1?Xe:$s(t,n)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new fc(new Qe({path:I(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,n=t==null?void 0:t[e];return n?I(m({},n),{source:"message"}):Xe},subscribe:t=>this._core.subscribe(t)}))}},Kc=e=>{var t,n,r;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}},e.stream?{stream:e.stream}:{})},Yc=e=>{var t,n,r;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(n=e.sourceId)!=null?n:null,runConfig:(r=e.runConfig)!=null?r:{}}},Gc=(e,t)=>{var n,r,i,s,a,o,l,u,c,d,h;return typeof t=="string"?{createdAt:new Date,parentId:(r=(n=e.at(-1))==null?void 0:n.id)!=null?r:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(i=t.createdAt)!=null?i:new Date,parentId:(o=(a=t.parentId)!=null?a:(s=e.at(-1))==null?void 0:s.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(c=t.attachments)!=null?c:[],metadata:(d=t.metadata)!=null?d:{custom:{}},runConfig:(h=t.runConfig)!=null?h:{},startRun:t.startRun}},Xc=(e,t)=>{const n=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(n==null?void 0:n.role)!=="assistant"?!1:n.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},Hs=class{constructor(e,t){T(this,"_threadBinding");T(this,"composer");T(this,"_eventSubscriptionSubjects",new Map);const n=new Qe({path:e.path,getState:()=>Xc(e.getState(),t.getState()),subscribe:r=>{const i=e.subscribe(r),s=t.subscribe(r);return()=>{i(),s()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:r=>e.outerSubscribe(r),subscribe:r=>e.subscribe(r)},this.composer=new gc(new $n({path:I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)})),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(Gc(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(Yc(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Kc(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(I(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var r,i;const t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:(i=(r=t[e-1])==null?void 0:r.id)!=null?i:null,index:e}})}getMessageById(e){return this._getMessageRuntime(I(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 Jc(new Qe({path:e,getState:()=>{var c,d;const{message:n,parentId:r,index:i}=(c=t())!=null?c:{},{messages:s,speech:a}=this._threadBinding.getState();if(!n||r===void 0||i===void 0)return Xe;const l=this._threadBinding.getState().getBranches(n.id),u=n.metadata.submittedFeedback;return I(m({},n),{[Rn]:n[Rn],index:i,isLast:((d=s.at(-1))==null?void 0:d.id)===n.id,parentId:r,branchNumber:l.indexOf(n.id)+1,branchCount:l.length,speech:(a==null?void 0:a.messageId)===n.id?a:void 0,submittedFeedback:u})},subscribe:n=>this._threadBinding.subscribe(n)}),this._threadBinding)}unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new Ns({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Qc=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),qn=(e,t)=>{if(t===void 0)return Xe;const n=e.getItemById(t);return n?{id:n.id,threadId:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,isMain:n.id===e.mainThreadId}:Xe},Zc=class{constructor(e,t=Hs){T(this,"_getState");T(this,"_mainThreadListItemRuntime");T(this,"main");this._core=e,this._runtimeFactory=t;const n=new Dr({path:{},getState:()=>Qc(e),subscribe:r=>e.subscribe(r)});this._getState=n.getState.bind(n),this._mainThreadListItemRuntime=new Bn(new Qe({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>qn(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new t(new $n({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:r=>e.subscribe(r)}),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 $n({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 Bn(new Qe({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>qn(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Bn(new Qe({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>qn(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Bn(new Qe({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>qn(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},ed=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",td=class{constructor(e){T(this,"accept","*");T(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Pn(this,arguments,function*({file:e}){const n=crypto.randomUUID(),r=ed(e.type);let i={id:n,type:r,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield i;try{const{signedUrl:s,publicUrl:a}=yield new Ee(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ee(fetch(s,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(n,a),i=I(m({},i),{status:{type:"requires-action",reason:"composer-send"}}),yield i}catch(s){i=I(m({},i),{status:{type:"incomplete",reason:"error"}}),yield i}})}remove(e){return M(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return M(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let n;return e.type==="image"?n=[{type:"image",image:t,filename:e.name}]:n=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],I(m({},e),{status:{type:"complete"},content:n})})}},Or=y.createContext(null),Fr=({adapters:e,children:t})=>{const n=y.useContext(Or);return p.jsx(Or.Provider,{value:m(m({},n),e),children:t})},nd=()=>y.useContext(Or),rd=class extends fs{constructor(t,n,{parentId:r,message:i}){var s;super();T(this,"_nonTextParts");T(this,"_previousText");T(this,"_parentId");T(this,"_sourceId");this.runtime=t,this.endEditCallback=n,this._parentId=r,this._sourceId=i.id,this._previousText=jn(i),this.setText(this._previousText),this.setRole(i.role),this.setAttachments((s=i.attachments)!=null?s:[]),this._nonTextParts=i.content.filter(a=>a.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 M(this,null,function*(){jn(t)!==this._previousText&&this.runtime.append(I(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},id=class{constructor(e){T(this,"_subscriptions",new Set);T(this,"_isInitialized",!1);T(this,"repository",new As);T(this,"composer",new ps(this));T(this,"_editComposers",new Map);T(this,"_stopSpeaking");T(this,"speech");T(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const n of this.messages)if(n.role==="assistant"){e=n;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 rd(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 n of t)n()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var s;const n=(s=this.adapters)==null?void 0:s.feedback;if(!n)throw new Error("Feedback adapter not configured");const{message:r,parentId:i}=this.repository.getMessage(e);if(n.submit({message:r,type:t}),r.role==="assistant"){const a=I(m({},r),{metadata:I(m({},r.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(i,a)}this._notifySubscribers()}speak(e){var s,a;const t=(s=this.adapters)==null?void 0:s.speech;if(!t)throw new Error("Speech adapter not configured");const{message:n}=this.repository.getMessage(e);(a=this._stopSpeaking)==null||a.call(this);const r=t.speak(jn(n)),i=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:r.status},this._notifySubscribers()});this.speech={messageId:e,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),i(),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(Lr.fromArray(e!=null?e:[]))}unstable_on(e,t){var r,i,s;if(e==="model-context-update")return(s=(i=(r=this._contextProvider).subscribe)==null?void 0:i.call(r,t))!=null?s:(()=>{});const n=this._eventSubscribers.get(e);return n?n.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},sd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function ad({state:e,getTools:t,onResult:n,setToolStatuses:r}){const i=y.useRef({}),s=y.useRef(new Map),a=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[f,g]=Es(),v=Vc(t,()=>{var b,x;return(x=(b=a.current)==null?void 0:b.signal)!=null?x:new AbortController().signal},(b,x)=>new Promise((E,_)=>{const F=s.current.get(b);F&&F.reject(new Error("Human input request was superseded by a new request")),s.current.set(b,{resolve:E,reject:_}),r(B=>I(m({},B),{[b]:{type:"interrupt",payload:{type:"human",payload:x}}}))}),{onExecutionStart:b=>{o.current++,r(x=>I(m({},x),{[b]:{type:"executing"}}))},onExecutionEnd:b=>{o.current--,r(x=>{const E=m({},x);return delete E[b],E}),o.current===0&&(l.current.forEach(x=>x()),l.current=[])}});return f.pipeThrough(v).pipeThrough(new Ts).pipeTo(new WritableStream({write(b){var x;if(b.type==="result"){if((x=i.current[b.meta.toolCallId])!=null&&x.hasResult)return;n(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}),c=y.useRef(new Set),d=y.useRef(!0);y.useEffect(()=>{const f=g=>{g.forEach(v=>{v.content.forEach(b=>{if(b.type==="tool-call"){if(d.current)c.current.add(b.toolCallId);else{if(c.current.has(b.toolCallId))return;let x=i.current[b.toolCallId];if(x||(x={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:b.toolName,toolCallId:b.toolCallId})},i.current[b.toolCallId]=x),b.argsText!==x.argsText)if(x.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:x.argsText,next:b.argsText});else{if(!b.argsText.startsWith(x.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${b.argsText} does not start with ${x.argsText}`);const E=b.argsText.slice(x.argsText.length);x.controller.argsText.append(E);const _=sd(b.argsText);_&&x.controller.argsText.close(),i.current[b.toolCallId]={argsText:b.argsText,hasResult:x.hasResult,argsComplete:_,controller:x.controller}}b.result!==void 0&&!x.hasResult&&(x.controller.setResponse(new pt({result:b.result,artifact:b.artifact,isError:b.isError})),x.controller.close(),i.current[b.toolCallId]={hasResult:!0,argsComplete:!0,argsText:x.argsText,controller:x.controller})}b.messages&&f(b.messages)}})})};f(e.messages),d.current&&(d.current=!1)},[e,u,n]);const h=()=>(s.current.forEach(({reject:f})=>{f(new Error("Tool execution aborted"))}),s.current.clear(),a.current.abort(),a.current=new AbortController,o.current===0?Promise.resolve():new Promise(f=>{l.current.push(f)}));return{reset:()=>{h(),d.current=!0},abort:h,resume:(f,g)=>{const v=s.current.get(f);if(v)s.current.delete(f),r(b=>I(m({},b),{[f]:{type:"executing"}})),v.resolve(g);else throw new Error(`Tool call ${f} is not waiting for human input`)}}}var od=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 ld(e,t){e.commitTasks.forEach(n=>{const r=n.cellIndex,i=t.cells[r];if(i.type!=="effect")throw new Error("Cannot find effect cell");let s=!0;if(i.deps!==void 0&&n.deps!==void 0&&(s=i.deps.length!==n.deps.length||i.deps.some((a,o)=>!Object.is(a,n.deps[o]))),s){if(i.mounted){if(typeof i.deps!=typeof n.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{i.mounted&&i.cleanup&&i.cleanup()}finally{i.mounted=!1}}try{const a=n.effect();if(a!==void 0&&typeof a!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof a}`);i.mounted=!0,i.cleanup=typeof a=="function"?a:void 0,i.deps=n.deps}catch(a){throw a}}})}function ud(e){let t=null;for(let n=e.cells.length-1;n>=0;n--){const r=e.cells[n];if((r==null?void 0:r.type)==="effect"&&r.mounted&&r.cleanup)try{r.cleanup()}catch(i){t==null&&(t=i)}finally{r.mounted=!1}}if(t!=null)throw t}var on=null;function cd(e,t){e.currentIndex=0;const n=on;on=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{on=n}}function zr(){if(!on)throw new Error("No resource fiber available");return on}function qs(e,t){const n=e[Vs];if(!n)throw new Error("ResourceElement.type is not a valid Resource");return n(t)}var Vs=Symbol("fnSymbol");function Vn(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function Ot(e){e.isMounted=!1,ud(e)}function ln(e,t){const n={commitTasks:[],props:t,state:void 0};return cd(e,()=>{e.renderContext=n;try{n.state=qs(e.resource,t)}finally{e.renderContext=void 0}}),n}function Ft(e,t){e.isMounted=!0,e.isNeverMounted=!1,ld(t,e)}var dd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,Ws=dd?y.useEffect:y.useLayoutEffect;function Br(e){const[,t]=y.useState({}),n=y.useMemo(()=>Vn(e.type,()=>t({})),[e.type,t]),r=ln(n,e.props);return Ws(()=>()=>Ot(n),[]),Ws(()=>{Ft(n,r)}),r.state}var zt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},_t=(e,t,n)=>t===e,Bt,Rr=()=>{if(Bt)return Bt;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return Bt=e(),Bt;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return Bt=t,t;const n=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=n,Bt=n,n},hd=(nt=class{static register(t){var o,l;const n=Rr();for(const u of n.apis.values())if(u.api===t)return()=>{};const r=n.nextId++,i={api:t,logs:[]},s=(o=t.on)==null?void 0:o.call(t,"*",u=>{const c=n.apis.get(r);c&&(c.logs.push({time:new Date,event:u.event,data:u.payload}),c.logs.length>nt.MAX_EVENT_LOGS_PER_API&&(c.logs=c.logs.slice(-200)),nt.notifyListeners(r))}),a=(l=t.subscribe)==null?void 0:l.call(t,()=>{nt.notifyListeners(r)});return n.apis.set(r,i),nt.notifyListeners(r),()=>{const u=Rr();u.apis.get(r)&&(s==null||s(),a==null||a(),u.apis.delete(r),nt.notifyListeners(r))}}static notifyListeners(t){Rr().listeners.forEach(r=>r(t))}},T(nt,"MAX_EVENT_LOGS_PER_API",200),nt);function me(e){const t=(n,r)=>m({type:t,props:n},(r==null?void 0:r.key)!==void 0&&{key:r.key});return t[Vs]=e,t}var fd=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 pd(e){const t=zr(),n=t.currentIndex++;if(!t.isFirstRender&&n>=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[n]){const s={type:"state",value:typeof e=="function"?e():e,set:a=>{const o=s.value,l=typeof a=="function"?a(o):a;Object.is(o,l)||(s.value=l,fd(t))}};t.cells[n]=s}const r=t.cells[n];if(r.type!=="state")throw new Error("Hook order changed between renders");return r}function st(e){const t=pd(e);return[t.value,t.set]}function md(){const e=zr(),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 r={type:"effect",mounted:!1};e.cells[t]=r}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function Le(e,t){const n=zr(),r=md();n.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:r})}function Rt(e){const[t]=st(()=>({current:e}));return t}var gd=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},oe=(e,t)=>{const n=Rt();return n.current||(n.current={value:e(),deps:t}),gd(n.current.deps,t)||(n.current.value=e(),n.current.deps=t),n.current.value};function Wn(e,t){const[n,r]=st({}),i=oe(()=>Vn(e.type,()=>r({})),[e.type]),s=t?oe(()=>e.props,t):e.props,a=oe(()=>ln(i,s),[i,s,n]);return Le(()=>()=>Ot(i),[i]),Le(()=>{Ft(i,a)},[i,a]),a.state}function Ze(e){return qs(e.type,e.props)}function Js(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[n,r]=st({}),i=oe(()=>new Map(e.map(o=>[o.key,o])),[e]),[s]=st(()=>new Map),a=oe(()=>{const o=new Map,l=new Set;return i.forEach((u,c)=>{l.add(c);let d=s.get(c);(!d||d.resource!==u.type)&&(d&&Ot(d),d=Vn(u.type,()=>r({})),s.set(c,d));const h=ln(d,u.props);o.set(c,h)}),s.forEach((u,c)=>{l.has(c)||(Ot(u),s.delete(c))}),o},[i,n]);return Le(()=>{a.forEach((o,l)=>{const u=s.get(l);u&&Ft(u,o)})},[a,s]),Le(()=>()=>{s.forEach(o=>{Ot(o)}),s.clear()},[s]),oe(()=>e.map(o=>{var l;return(l=a.get(o.key))==null?void 0:l.state}),[e,a])}var jr=[],Ur=!1;function yd(){Ur=!1;const e=jr;jr=[];for(const t of e)try{t()}catch(n){console.error("Error in scheduled task:",n)}}function bd(e){jr.push(e),Ur||(Ur=!0,queueMicrotask(yd))}var wd=(Pt=class{constructor(t){T(this,"_isDirty",!1);T(this,"_hasScheduledTask",!1);T(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,bd(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Pt.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}}},T(Pt,"MAX_FLUSH_DEPTH",50),Pt),xd=me(({element:e,onUpdateInput:t,onFlushSync:n,onDispose:r})=>{const[i,s]=st(e.props),a=Ze({type:e.type,props:i}),o=Rt(new Set).current,l=Rt(a);return Le(()=>{a!==l.current&&(l.current=a,o.forEach(c=>c()))}),oe(()=>({getState:()=>l.current,subscribe:c=>(o.add(c),()=>o.delete(c)),updateInput:c=>{t(),s(()=>c)},flushSync:n,dispose:r}),[])}),vd=(e,t=!1)=>{let n=!t;const r={element:e,onUpdateInput:()=>{n||(n=!0,Ft(s,a))},onFlushSync:()=>{i.flushSync()},onDispose:()=>Ot(s)},i=new wd(()=>{a=ln(s,r),n&&Ft(s,a)}),s=Vn(xd,()=>i.markDirty());let a=ln(s,r);return n&&Ft(s,a),a.state},un=Symbol("tap.Context"),Ks=e=>({[un]:e}),Ys=(e,t,n)=>{const r=e[un];e[un]=t;try{return n()}finally{e[un]=r}},Gs=e=>e[un];const Xs=e=>{let t;const n=new Set,r=(u,c)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const h=t;t=(c!=null?c:typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(f=>f(t,h))}},i=()=>t,o={setState:r,getState:i,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,i,o);return o},Sd=(e=>e?Xs(e):Xs),kd=e=>e;function _d(e,t=kd){const n=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(n),n}const Qs=e=>{const t=Sd(e),n=r=>_d(t,r);return Object.assign(n,t),n},jt=(e=>e?Qs(e):Qs);function Zs(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ea(...e){return t=>{let n=!1;const r=e.map(i=>{const s=Zs(i,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():Zs(e[i],null)}}}}function Jn(...e){return Q.useCallback(ea(...e),e)}var ta=me(e=>{const t=oe(()=>vd(e,!0),[e.type]);return Le(()=>{t.updateInput(e.props)}),t}),Td=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}},et=(e,t)=>{const n=Rt(e);Le(()=>{n.current=e});const r=oe(()=>new Proxy({},new Td(()=>n.current)),[]),i=t==null?void 0:t.key,s=e.getState();return oe(()=>({key:i,state:s,api:r}),[s,i])},mt=me(e=>{const t=Rt(e.get);return Le(()=>{t.current=e.get}),oe(()=>Ae({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),Cd=me(e=>{const t=Wn(e.scopeElement);return oe(()=>[e.fieldName,t],[e.fieldName,t])}),Id=me(e=>{const o=e,{on:t,subscribe:n,flushSync:r}=o,i=q(o,["on","subscribe","flushSync"]),s=Rt({on:t,subscribe:n,flushSync:r});Le(()=>{s.current={on:t,subscribe:n,flushSync:r}});const a=Js(Object.entries(i).map(([l,u])=>Cd({fieldName:l,scopeElement:u},{key:l})));return oe(()=>{const l=Object.fromEntries(a),{on:u,subscribe:c,flushSync:d}=s.current;return u&&(l.on=(h,f)=>u(h,f)),c&&(l.subscribe=h=>c(h)),d&&(l.flushSync=()=>d()),l},[...a])}),na=Ks(null),Ed=(e,t)=>Ys(na,e,t),ra=()=>{const e=Gs(na);if(!e)throw new Error("Model context is not available in this context");return e},Ad=me(({toolkit:e})=>{const[t,n]=st(()=>({tools:{}})),r=ra();Le(()=>{if(!e)return;const s=[];for(const[l,u]of Object.entries(e))u.render&&s.push(i(l,u.render));const a=Object.entries(e).reduce((l,[u,c])=>{const f=c,{render:d}=f,h=q(f,["render"]);return l[u]=h,l},{}),o={getModelContext:()=>({tools:a})};return s.push(r.register(o)),()=>{s.forEach(l=>l())}},[e,r]);const i=(s,a)=>(n(o=>{var l;return I(m({},o),{tools:I(m({},o.tools),{[s]:[...(l=o.tools[s])!=null?l:[],a]})})}),()=>{n(o=>{var l,u;return I(m({},o),{tools:I(m({},o.tools),{[s]:(u=(l=o.tools[s])==null?void 0:l.filter(c=>c!==a))!=null?u:[]})})})});return et({getState:()=>t,setToolUI:i})}),Md=me(()=>oe(()=>{const t=new Map;return{on:(n,r)=>{t.has(n)||t.set(n,new Set);const i=t.get(n);return i.add(r),()=>{i.delete(r),i.size===0&&t.delete(n)}},emit:(n,r)=>{const i=t.get(n),s=t.get("*");!i&&!s||queueMicrotask(()=>{if(i)for(const a of i)a(r);if(s)for(const a of s)a({event:n,payload:r})})}}},[])),ia=Ks(null),Pd=(e,t)=>Ys(ia,e,t),$r=()=>{const e=Gs(ia);if(!e)throw new Error("Events context is not available");return e},Nd=me(()=>{const[e]=st(()=>({})),t=new Ir;return et({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:n=>t.subscribe(n),register:n=>t.registerModelContextProvider(n)})}),Ld=me(({threads:e,modelContext:t,tools:n})=>{const r=Ze(Md()),{threads:i,tools:s,modelContext:a}=Pd(r,()=>{const l=Wn(t!=null?t:Nd(),[t]);return Ed(l.api,()=>({modelContext:l,tools:Wn(n!=null?n:Ad({}),[n]),threads:Wn(e,[e])}))}),o=oe(()=>({threads:i.state,tools:s.state,modelContext:a.state}),[i.state,s.state,a.state]);return et({getState:()=>o,threads:i.api,tools:s.api,modelContext:a.api,on:r.on})}),Dd=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(n,r){const{event:i,scope:s}=zt(n);if(s==="*")return e.getState().api.on(i,r);if(_t("thread",s)||_t("thread-list-item",s)||_t("composer",s))return e.getState().api.on(i,a=>{a.threadId===t().getState().id&&r(a)});throw new Error(`Event scope is not available in this component: ${s}`)},subscribe:e.subscribe,flushSync:e.flushSync}},Od=e=>{const t=Kn(),n=Br(ta(Ld(e))),r=y.useMemo(()=>Dd(n),[n]);return y.useMemo(()=>aa(t,r),[t,r])},Ae=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},gt=()=>()=>{},sa=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:gt,flushSync:gt,on:e=>{const{scope:t}=zt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Kn=()=>y.useContext(sa),Tt=e=>{const t=Kn(),n=Br(Id(e));return y.useMemo(()=>aa(t,n),[t,n])},Fd=e=>Od(e);function he(e){return e?Fd(e):Kn()}var zd=(e,t)=>e===gt?t:t===gt?e:(...n)=>{e(...n),t(...n)},Bd=(e,t)=>e===gt?t:t===gt?e:(...n)=>{const r=e(...n),i=t(...n);return()=>{r(),i()}},aa=(e,t)=>{const n=t.subscribe,r=t.flushSync;return I(m(m({},e),t),{subscribe:Bd(e.subscribe,n!=null?n:gt),flushSync:zd(e.flushSync,r!=null?r:gt)})},yt=({api:e,children:t,devToolsVisible:n=!0})=>(y.useEffect(()=>{if(!(!n||!e.subscribe))return hd.register(e)},[e,n]),p.jsx(sa.Provider,{value:e,children:t})),oa=(Tu=class{constructor(e){Zt(this,Ke);en(this,Ke,e)}get threads(){return We(this,Ke).threads().getState()}get tools(){return We(this,Ke).tools().getState()}get threadListItem(){return We(this,Ke).threadListItem().getState()}get thread(){return We(this,Ke).thread().getState()}get composer(){return We(this,Ke).composer().getState()}get message(){return We(this,Ke).message().getState()}get part(){return We(this,Ke).part().getState()}get attachment(){return We(this,Ke).attachment().getState()}},Ke=new WeakMap,Tu),te=e=>{const t=he(),n=y.useMemo(()=>new oa(t),[t]),r=y.useSyncExternalStore(t.subscribe,()=>e(n),()=>e(n));if(y.useDebugValue(r),r instanceof oa)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return r},Hr=(e,t)=>{const n=he(),r=y.useRef(t);y.useEffect(()=>{r.current=t});const{scope:i,event:s}=zt(e);y.useEffect(()=>n.on({scope:i,event:s},a=>r.current(a)),[n,i,s])};function Rd(e,t){function n(r){const i=y.useContext(e);if(!(r!=null&&r.optional)&&!i)throw new Error(`This component must be used within ${t}.`);return i}return n}function la(e,t){function n(i){const s=e(i);return s?s[t]:null}function r(i){let s=!1,a;typeof i=="function"?a=i:i&&typeof i=="object"&&(s=!!i.optional,a=i.selector);const o=n({optional:s});return o?a?o(a):o():null}return{[t]:r,[`${t}Store`]:n}}var ua=y.createContext(null),jd=Rd(ua,"ThreadPrimitive.Viewport"),{useThreadViewport:Yn,useThreadViewportStore:qr}=la(jd,"useThreadViewport"),Ud=e=>{var n;const t=e;t.__isBound||((n=t.__internal_bindMethods)==null||n.call(t),t.__isBound=!0)};function $d(e,t=Hd){Ud(e);const n=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(n),n}var Hd=e=>e;function ca(e){function t(n){let r=!1,i;typeof n=="function"?i=n:n&&(r=!!n.optional,i=n.selector);const s=e({optional:r});return s?$d(s,i):null}return t}function qd(e){var r,i,s;const n=(s=(i=(r=he().threads()).__internal_getAssistantRuntime)==null?void 0:i.call(r))!=null?s:null;if(!n)throw new Error("AssistantRuntime is not available");return n}function da(e){const t=he(),n=te(()=>{var r,i,s;return t.thread.source&&(s=(i=(r=t.thread()).__internal_getRuntime)==null?void 0:i.call(r))!=null?s:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return n}var ha=ca(da);function fa(e){const t=he(),n=te(()=>{var r,i,s;return t.threadListItem.source&&(s=(i=(r=t.threadListItem()).__internal_getRuntime)==null?void 0:i.call(r))!=null?s:null});if(!n&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return n}var pa=ca(fa),Ct=e=>{const[,t]=st(e.getState);return Le(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Vd=me(({runtime:e})=>{const t=Ct(e),n=$r();return Le(()=>{const r=[],i=["switched-to","switched-away"];for(const s of i){const a=e.unstable_on(s,()=>{n.emit(`thread-list-item.${s}`,{threadId:e.getState().id})});r.push(a)}return()=>{for(const s of r)s()}},[e,n]),et({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})}),cn=e=>{const t=Js(e);return{state:t.map(n=>n.state),api:n=>{var i,s;const r="index"in n?(i=t[n.index])==null?void 0:i.api:(s=t.find(a=>a.key===n.key))==null?void 0:s.api;if(!r)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(n)}`);return r}}},ma=me(({runtime:e})=>{const t=Ct(e);return et({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Wd=me(({runtime:e,index:t})=>{const n=oe(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ma({runtime:n}))}),ga=me(({threadIdRef:e,messageIdRef:t,runtime:n})=>{var o;const r=Ct(n),i=$r();Le(()=>{const l=[],u=["send","attachment-add"];for(const c of u){const d=n.unstable_on(c,()=>{i.emit(`composer.${c}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(d)}return()=>{for(const c of l)c()}},[n,i,e,t]);const s=cn(r.attachments.map((l,u)=>Wd({runtime:n,index:u},{key:u}))),a=oe(()=>{var l;return{text:r.text,role:r.role,attachments:s.state,runConfig:r.runConfig,isEditing:r.isEditing,canCancel:r.canCancel,attachmentAccept:r.attachmentAccept,isEmpty:r.isEmpty,type:(l=r.type)!=null?l:"thread"}},[r,s.state]);return et({getState:()=>a,setText:n.setText,setRole:n.setRole,setRunConfig:n.setRunConfig,addAttachment:n.addAttachment,reset:n.reset,clearAttachments:n.clearAttachments,send:n.send,cancel:n.cancel,beginEdit:(o=n.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?s.api({key:l.id}):s.api(l),__internal_getRuntime:()=>n})}),Jd=me(({runtime:e})=>{const t=Ct(e);return et({getState:()=>t,addToolResult:r=>e.addToolResult(r),resumeToolCall:r=>e.resumeToolCall(r),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),Kd=me(({runtime:e,index:t})=>{const n=oe(()=>e.getAttachmentByIndex(t),[e,t]);return Ze(ma({runtime:n}))}),Yd=me(({runtime:e,index:t})=>{const n=oe(()=>e.getMessagePartByIndex(t),[e,t]);return Ze(Jd({runtime:n}))}),Gd=me(({runtime:e,threadIdRef:t})=>{var h,f;const n=Ct(e),[r,i]=st(!1),[s,a]=st(!1),o=oe(()=>({get current(){return e.getState().id}}),[e]),l=Ze(ga({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=cn(n.content.map((g,v)=>Yd({runtime:e,index:v},{key:v}))),c=cn((f=(h=n.attachments)==null?void 0:h.map((g,v)=>Kd({runtime:e,index:v},{key:v})))!=null?f:[]),d=oe(()=>I(m({},n),{parts:u.state,composer:l.state,isCopied:r,isHovering:s}),[n,u.state,l.state,r,s]);return et({getState:()=>d,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?c.api({key:g.id}):c.api(g),setIsCopied:i,setIsHovering:a,__internal_getRuntime:()=>e},{key:n.id})}),Xd=me(({runtime:e,id:t,threadIdRef:n})=>{const r=oe(()=>e.getMessageById(t),[e,t]);return Ze(Gd({runtime:r,threadIdRef:n}))}),Qd=me(({runtime:e})=>{const t=Ct(e),n=$r();Le(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const c=e.unstable_on(u,()=>{var h;const d=((h=e.getState())==null?void 0:h.threadId)||"unknown";n.emit(`thread.${u}`,{threadId:d})});o.push(c)}return()=>{for(const u of o)u()}},[e]);const r=oe(()=>({get current(){return e.getState().threadId}}),[e]),i=Ze(ga({runtime:e.composer,threadIdRef:r})),s=cn(t.messages.map(o=>Xd({runtime:e,id:o.id,threadIdRef:r},{key:o.id}))),a=oe(()=>({isEmpty:s.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:i.state,messages:s.state}),[t,s,i.state]);return et({getState:()=>a,composer:i.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:()=>M(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>M(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?s.api({key:o.id}):s.api(o),__internal_getRuntime:()=>e})}),Zd=me(({runtime:e,id:t})=>{const n=oe(()=>e.getItemById(t),[e,t]);return Ze(Vd({runtime:n}))}),eh=me(({runtime:e,__internal_assistantRuntime:t})=>{const n=Ct(e),r=Ze(Qd({runtime:e.main})),i=cn(Object.keys(n.threadItems).map(a=>Zd({runtime:e,id:a},{key:a}))),s=oe(()=>{var a;return{mainThreadId:n.mainThreadId,newThreadId:(a=n.newThread)!=null?a:null,isLoading:n.isLoading,threadIds:n.threads,archivedThreadIds:n.archivedThreads,threadItems:i.state,main:r.state}},[n,i.state,r.state]);return et({getState:()=>s,thread:()=>r.api,item:a=>{if(a==="main")return i.api({key:s.mainThreadId});if("id"in a)return i.api({key:a.id});const{index:o,archived:l=!1}=a,u=l?s.archivedThreadIds[o]:s.threadIds[o];return i.api({key:u})},switchToThread:a=>{e.switchToThread(a)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),th=me(e=>{const t=ra();return Le(()=>e.registerModelContextProvider(t),[e,t]),Ze(eh({runtime:e.threads,__internal_assistantRuntime:e}))}),Vr=e=>{const t=new Map,n=()=>{let r=0;for(const i of t.values())r+=i;e(r)};return{register:()=>{const r=Symbol();return t.set(r,0),{setHeight:i=>{t.get(r)!==i&&(t.set(r,i),n())},unregister:()=>{t.delete(r),n()}}}}},nh=(e={})=>{const t=new Set,n=Vr(a=>{s.setState({height:I(m({},s.getState().height),{viewport:a})})}),r=Vr(a=>{s.setState({height:I(m({},s.getState().height),{inset:a})})}),i=Vr(a=>{s.setState({height:I(m({},s.getState().height),{userMessage:a})})}),s=jt(()=>{var a;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(a=e.turnAnchor)!=null?a:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:n.register,registerContentInset:r.register,registerUserMessageHeight:i.register}});return s},dn=e=>e,rh=e=>{const t=qr({optional:!0}),[n]=y.useState(()=>nh(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{n.getState().scrollToBottom()}),[t,n]),y.useEffect(()=>{if(t)return n.subscribe(r=>{t.getState().isAtBottom!==r.isAtBottom&&dn(t).setState({isAtBottom:r.isAtBottom})})},[n,t]),y.useEffect(()=>{var s;const r={turnAnchor:(s=e.turnAnchor)!=null?s:"bottom"};n.getState().turnAnchor!==r.turnAnchor&&dn(n).setState(r)},[n,e.turnAnchor]),n},ya=({children:e,options:t={}})=>{const n=rh(t),[r]=y.useState(()=>({useThreadViewport:n}));return p.jsx(ua.Provider,{value:r,children:e})},ih=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},sh=({children:e,runtime:t})=>{const n=he({threads:th(t)}),r=ih(t);return p.jsxs(yt,{api:n,children:[r&&p.jsx(r,{}),p.jsx(ya,{children:e})]})},ba=y.memo(sh),ah=({index:e,archived:t,children:n})=>{const r=he(),i=Tt({threadListItem:mt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>r.threads().item({index:e,archived:t})}),on(s,a){const o=()=>r.threads().item({index:e,archived:t}),{event:l,scope:u}=zt(s);return _t("thread-list-item",u)?r.on({scope:"*",event:l},c=>{c.threadId===o().getState().id&&a(c)}):r.on(s,a)}});return p.jsx(yt,{api:i,children:n})},oh=({id:e,children:t})=>{const n=he(),r=Tt({threadListItem:mt({source:"threads",query:{type:"id",id:e},get:()=>n.threads().item({id:e})}),on(i,s){const a=()=>n.threads().item({id:e}),{event:o,scope:l}=zt(i);return _t("thread-list-item",l)?n.on({scope:"*",event:o},u=>{u.threadId===a().getState().id&&s(u)}):n.on(i,s)}});return p.jsx(yt,{api:r,children:t})},lh=({index:e,children:t})=>{const n=he(),r=Tt({message:mt({source:"thread",query:{type:"index",index:e},get:()=>n.thread().message({index:e})}),composer:mt({source:"message",query:{},get:()=>n.thread().message({index:e}).composer}),on(i,s){const a=()=>n.thread().message({index:e}),{event:o,scope:l}=zt(i);return!_t("composer",l)&&!_t("message",l)?n.on(i,s):n.on({scope:"thread",event:o},u=>{u.messageId===a().getState().id&&s(u)})}});return p.jsx(yt,{api:r,children:t})},uh=({index:e,children:t})=>{const n=he(),r=Tt({part:mt({source:"message",query:{type:"index",index:e},get:()=>n.message().part({index:e})})});return p.jsx(yt,{api:r,children:t})},ch=({index:e,children:t})=>{const n=he(),r=Tt({attachment:mt({source:"message",query:{type:"index",index:e},get:()=>n.message().attachment({index:e})})});return p.jsx(yt,{api:r,children:t})},dh=({index:e,children:t})=>{const n=he(),r=Tt({attachment:mt({source:"composer",query:{type:"index",index:e},get:()=>n.composer().attachment({index:e})})});return p.jsx(yt,{api:r,children:t})},hh=me(({text:e,isRunning:t})=>{const n=oe(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return et({getState:()=>n,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),fh=({text:e,isRunning:t=!1,children:n})=>{const r=Br(ta(hh({text:e,isRunning:t}))),i=Tt({part:mt({source:"root",query:{},get:()=>r.getState().api}),subscribe:r.subscribe,flushSync:r.flushSync});return p.jsx(yt,{api:i,children:n})},wa=(e,t)=>{var n,r;return t===void 0?((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result):((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(i=>i.type!=="tool-call"||!!i.result||!t.includes(i.toolName))},Wr=class extends Error{constructor(t,n){super(n);T(this,"name","AbortError");T(this,"detach");this.detach=t}},ph=class extends id{constructor(t,n){super(t);T(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});T(this,"abortController",null);T(this,"isDisabled",!1);T(this,"_isLoading",!1);T(this,"_suggestions",[]);T(this,"_suggestionsController",null);T(this,"_options");T(this,"_lastRunConfig",{});T(this,"_loadPromise");this.__internal_setOptions(n)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var a,o,l;if(this._options===t)return;this._options=t;let n=!1;const r=((a=t.adapters)==null?void 0:a.speech)!==void 0;this.capabilities.speech!==r&&(this.capabilities.speech=r,n=!0);const i=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==i&&(this.capabilities.attachments=i,n=!0);const s=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==s&&(this.capabilities.feedback=s,n=!0),n&&this._notifySubscribers()}__internal_load(){var n,r;if(this._loadPromise)return this._loadPromise;const t=(r=(n=this.adapters.history)==null?void 0:n.load())!=null?r:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(i=>{var a,o;if(!i)return;this.repository.import(i),this._notifySubscribers();const s=(o=(a=this.adapters.history)==null?void 0:a.resume)==null?void 0:o.bind(this.adapters.history);i.unstable_resume&&s&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},s)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return M(this,null,function*(){var i,s,a;this.ensureInitialized();const n=sn(t,St(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,n),(i=this._options.adapters.history)==null||i.append(m({parentId:t.parentId,message:n},t.runConfig!==void 0&&{runConfig:t.runConfig})),((s=t.startRun)!=null?s:t.role==="user")?yield this.startRun({parentId:n.id,sourceId:t.sourceId,runConfig:(a=t.runConfig)!=null?a:{}}):(this.repository.resetHead(n.id),this._notifySubscribers())})}resumeRun(r){var i=r,{stream:t}=i,n=q(i,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(n,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(i,s){return M(this,arguments,function*({parentId:t,runConfig:n},r){var u,c,d;this.ensureInitialized();let o={id:St(),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,n,r),r=void 0;while(wa(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((c=o.status)==null?void 0:c.type)!=="requires-action"){const b=(d=this.adapters.suggestion)==null?void 0:d.generate({messages:this.messages});if(Symbol.asyncIterator in b)try{for(var h=Lt(b),f,g,v;f=!(g=yield h.next()).done;f=!1){const x=g.value;if(l.aborted)break;this._suggestions=x,this._notifySubscribers()}}catch(g){v=[g]}finally{try{f&&(g=h.return)&&(yield g.call(h))}finally{if(v)throw v[0]}}else{const x=yield b;if(l.aborted)return;this._suggestions=x,this._notifySubscribers()}}})}performRoundtrip(t,n,r,i){return M(this,null,function*(){var g,v,b,x,E,_,F,B,C,O;const s=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const a=n.content,o=(v=n.metadata)==null?void 0:v.unstable_annotations,l=(b=n.metadata)==null?void 0:b.unstable_data,u=(x=n.metadata)==null?void 0:x.steps,c=(E=n.metadata)==null?void 0:E.custom,d=P=>{var de,w,ge,ye,S,Ce;const R=(de=P.metadata)==null?void 0:de.steps,L=R?[...u!=null?u:[],...R]:void 0,N=(w=P.metadata)==null?void 0:w.unstable_annotations,G=(ge=P.metadata)==null?void 0:ge.unstable_data,J=N?[...o!=null?o:[],...N]:void 0,Z=G?[...l!=null?l:[],...G]:void 0;n=m(I(m(m({},n),P.content?{content:[...a,...(ye=P.content)!=null?ye:[]]}:void 0),{status:(S=P.status)!=null?S:n.status}),P.metadata?{metadata:m(m(m(m(m(m({},n.metadata),P.metadata.unstable_state?{unstable_state:P.metadata.unstable_state}:void 0),J?{unstable_annotations:J}:void 0),Z?{unstable_data:Z}:void 0),L?{steps:L}:void 0),(Ce=P.metadata)!=null&&Ce.custom?{custom:m(m({},c!=null?c:{}),P.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,n),this._notifySubscribers()},h=(_=this._options.maxSteps)!=null?_:2;if(((C=(B=(F=n.metadata)==null?void 0:F.steps)==null?void 0:B.length)!=null?C:0)>=h)return d({status:{type:"incomplete",reason:"tool-calls"}}),n;d({status:{type:"running"}}),this.repository.resetHead(n.id),this._notifySubscribers();try{this._lastRunConfig=r!=null?r:{};const P=this.getModelContext();i=i!=null?i:this.adapters.chatModel.run.bind(this.adapters.chatModel);const R=this.abortController.signal,L=i({messages:s,runConfig:this._lastRunConfig,abortSignal:R,context:P,config:P,unstable_assistantMessageId:n.id,unstable_getMessage(){return n}});if(Symbol.asyncIterator in L)try{for(var H=Lt(L),V,j,k;V=!(j=yield H.next()).done;V=!1){const N=j.value;if(R.aborted){d({status:{type:"incomplete",reason:"cancelled"}});break}d(N)}}catch(j){k=[j]}finally{try{V&&(j=H.return)&&(yield j.call(H))}finally{if(k)throw k[0]}}else d(yield L);n.status.type==="running"&&d({status:{type:"complete",reason:"unknown"}})}catch(P){if(P instanceof Wr)d({status:{type:"incomplete",reason:"cancelled"}});else throw d({status:{type:"incomplete",reason:"error",error:P instanceof Error?P.message:`[${typeof P}] ${new String(P).toString()}`}}),P}finally{this.abortController=null,(n.status.type==="complete"||n.status.type==="incomplete")&&(yield(O=this._options.adapters.history)==null?void 0:O.append({parentId:t,message:n,runConfig:this._lastRunConfig}))}return n})}detach(){var n;const t=new Wr(!0);(n=this.abortController)==null||n.abort(t),this.abortController=null}cancelRun(){var n;const t=new Wr(!1);(n=this.abortController)==null||n.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:n,result:r,isError:i,artifact:s}){const a=this.repository.getMessage(t),{parentId:o}=a;let{message:l}=a;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,c=!1;const d=l.content.map(h=>h.type!=="tool-call"||h.toolCallId!==n?h:(c=!0,h.result||(u=!0),I(m({},h),{result:r,artifact:s,isError:i})));if(!c)throw new Error("Tried to add tool result to non-existing tool call");l=I(m({},l),{content:d}),this.repository.addOrUpdateMessage(o,l),u&&wa(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},xa=Object.freeze([]),Jr="__DEFAULT_ID__",mh=Object.freeze({[Jr]:{id:Jr,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),gh=class extends nn{constructor(t){super();T(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw xa}get archivedThreadIds(){throw xa}get mainThreadId(){return Jr}get threadData(){return mh}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 M(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.")}},yh=class extends Er{constructor(t,n){super();T(this,"threads");T(this,"Provider");T(this,"_options");this._options=t,this.threads=new gh(()=>new ph(this._contextProvider,this._options)),n&&this.threads.getMainThreadRuntimeCore().import(Lr.fromArray(n))}},va=e=>{try{const n=e.split(".")[1];if(!n)throw new Error("Invalid JWT format");let r=n.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4!==0;)r+="=";const i=atob(r),a=JSON.parse(i).exp;if(!a||typeof a!="number")throw new Error('JWT does not contain a valid "exp" field');return a*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},Sa=(Cu=class{constructor(e){T(this,"strategy","jwt");T(this,"cachedToken",null);T(this,"tokenExpiry",null);Zt(this,Tn);en(this,Tn,e)}getAuthHeaders(){return M(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 We(this,Tn).call(this);return t?(this.cachedToken=t,this.tokenExpiry=va(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[n,r]=t.split(" ");if(n!=="Bearer"||!r)throw new Error("Invalid auth header received");this.cachedToken=r,this.tokenExpiry=va(r)}},Tn=new WeakMap,Cu),bh=(Iu=class{constructor(e,t,n){T(this,"strategy","api-key");Zt(this,Cn);Zt(this,In);Zt(this,En);en(this,Cn,e),en(this,In,t),en(this,En,n)}getAuthHeaders(){return M(this,null,function*(){return{Authorization:`Bearer ${We(this,Cn)}`,"Aui-User-Id":We(this,In),"Aui-Workspace-Id":We(this,En)}})}readAuthHeaders(){}},Cn=new WeakMap,In=new WeakMap,En=new WeakMap,Iu),Gn="aui:refresh_token",wh=class{constructor(e){T(this,"strategy","anon");T(this,"baseUrl");T(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new Sa(()=>M(this,null,function*(){const t=Date.now(),n=localStorage.getItem(Gn),r=n?JSON.parse(n):void 0;if(r)if(new Date(r.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:r.token})});if(u.ok){const c=yield u.json(),{access_token:d,refresh_token:h}=c;return h&&localStorage.setItem(Gn,JSON.stringify(h)),d}}else localStorage.removeItem(Gn);const i=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!i.ok)return null;const s=yield i.json(),{access_token:a,refresh_token:o}=s;return!a||!o?null:(localStorage.setItem(Gn,JSON.stringify(o)),a)}))}getAuthHeaders(){return M(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},xh=class extends Error{constructor(e){super(e),this.name="APIError"}},vh=class{constructor(e){T(this,"_auth");T(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new Sa(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new bh(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new wh(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return M(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(n){return M(this,arguments,function*(e,t={}){var l;const r=yield this._auth.getAuthHeaders();if(!r)throw new Error("Authorization failed");const i=I(m(m({},r),t.headers),{"Content-Type":"application/json"}),s=new URLSearchParams;if(t.query)for(const[u,c]of Object.entries(t.query))c!==!1&&(c===!0?s.set(u,"true"):s.set(u,c.toString()));const a=new URL(`${this._baseUrl}/v1${e}`);a.search=s.toString();const o=yield fetch(a,{method:(l=t.method)!=null?l:"GET",headers:i,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const c=JSON.parse(u);throw new xh(c.message)}catch(c){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(n){return M(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Sh=class{constructor(e){this.cloud=e}create(){return M(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},kh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>M(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return I(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return M(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Pr.fromResponse(t,new Dc)})}},_h=class{constructor(e){this.cloud=e}list(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Th=class{constructor(e){T(this,"messages");this.cloud=e,this.messages=new _h(e)}list(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return M(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return M(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},Ch=class{constructor(e){this.cloud=e}pdfToImages(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return M(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Ih=class{constructor(e){T(this,"threads");T(this,"auth");T(this,"runs");T(this,"files");const t=new vh(e);this.threads=new Th(t),this.auth={tokens:new Sh(t)},this.runs=new kh(t),this.files=new Ch(t)}};function Kr(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(n=>Kr(n,t+1)):typeof e=="object"?Object.entries(e).every(([n,r])=>typeof n=="string"&&Kr(r,t+1)):!1}var Eh=e=>{var t;return m({role:e.role,content:e.content.map(n=>{const r=n.type;switch(r){case"text":return{type:"text",text:n.text};case"reasoning":return{type:"reasoning",text:n.text};case"source":return m({type:"source",sourceType:n.sourceType,id:n.id,url:n.url},n.title?{title:n.title}:void 0);case"tool-call":return Kr(n.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(n)}`),m(m(m({type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName},JSON.stringify(n.args)===n.argsText?{args:n.args}:{argsText:n.argsText}),n.result?{result:n.result}:{}),n.isError?{isError:!0}:{});default:{const i=r;throw new Error(`Message part type not supported by aui/v0: ${i}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},Ah=e=>{const t=e.content,n=sn(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:n}},Yr=new WeakMap,Mh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return M(this,null,function*(){const t=this.formatAdapter.encode(e),n=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,n,this.formatAdapter.format,t)})}load(){return M(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Ph=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Yr.has(this.store.threadListItem())||Yr.set(this.store.threadListItem(),{}),Yr.get(this.store.threadListItem())}withFormat(e){return new Mh(this,e)}append(n){return M(this,arguments,function*({parentId:e,message:t}){var s;const{remoteId:r}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(r,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:"aui/v0",content:Eh(t)}).then(({message_id:a})=>(this._getIdForLocalId[t.id]=a,a));return this._getIdForLocalId[t.id]=i,i.then(()=>{})})}load(){return M(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(r=>r.format==="aui/v0").map(Ah).reverse()}})}_appendWithFormat(e,t,n,r){return M(this,null,function*(){var a;const{remoteId:i}=yield this.store.threadListItem().initialize(),s=this.cloudRef.current.threads.messages.create(i,{parent_id:e?(a=yield this._getIdForLocalId[e])!=null?a:e:null,format:n,content:r}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=s,s.then(()=>{})})}_loadWithFormat(e,t){return M(this,null,function*(){const n=this.store.threadListItem().getState().remoteId;if(!n)return{messages:[]};const{messages:r}=yield this.cloudRef.current.threads.messages.list(n,{format:e});return{messages:r.filter(i=>i.format===e).map(i=>t({id:i.id,parent_id:i.parent_id,format:i.format,content:i.content})).reverse()}})}},Nh=e=>{const t=he(),[n]=y.useState(()=>new Ph(e,t));return n},ka=typeof process!="undefined"&&((Eu=process==null?void 0:process.env)==null?void 0:Eu.NEXT_PUBLIC_ASSISTANT_BASE_URL),Gr=ka?new Ih({baseUrl:ka,anonymous:!0}):void 0,Lh=e=>{var i;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const n=y.useCallback(function({children:a}){var d;const o=Nh({get current(){var h;return(h=t.current.cloud)!=null?h:Gr}}),l=(d=t.current.cloud)!=null?d:Gr,u=y.useMemo(()=>new td(l),[l]),c=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Fr,{adapters:c,children:a})},[]),r=(i=e.cloud)!=null?i:Gr;return r?{list:()=>M(null,null,function*(){const{threads:s}=yield r.threads.list();return{threads:s.map(a=>{var o;return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}})}}),initialize:()=>M(null,null,function*(){var u,c;const a=yield(c=(u=e.create)==null?void 0:u.call(e))!=null?c:Promise.resolve(),o=a?a.externalId:void 0,{thread_id:l}=yield r.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(s,a)=>M(null,null,function*(){return r.threads.update(s,{title:a})}),archive:s=>M(null,null,function*(){return r.threads.update(s,{is_archived:!0})}),unarchive:s=>M(null,null,function*(){return r.threads.update(s,{is_archived:!1})}),delete:s=>M(null,null,function*(){var a;return yield(a=e.delete)==null?void 0:a.call(e,s),r.threads.delete(s)}),generateTitle:(s,a)=>M(null,null,function*(){return r.runs.stream({thread_id:s,assistant_id:"system/thread_title",messages:a})}),fetch:s=>M(null,null,function*(){var o;const a=yield r.threads.get(s);return{status:a.is_archived?"archived":"regular",remoteId:a.id,title:a.title,externalId:(o=a.external_id)!=null?o:void 0}}),unstable_Provider:n}:new od},Dh=(e,r)=>{var i=r,{initialMessages:t}=i,n=q(i,["initialMessages"]);var u;const c=(u=nd())!=null?u:{},{modelContext:s}=c,a=q(c,["modelContext"]),o=y.useMemo(()=>I(m({},n),{adapters:I(m(m({},a),n.adapters),{chatModel:e})}),[e,n,a]),[l]=y.useState(()=>new yh(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(s)return l.registerModelContextProvider(s)},[s,l]),y.useMemo(()=>new Xr(l),[l])},_a=(e,r={})=>{var i=r,{cloud:t}=i,n=q(i,["cloud"]);const s=Lh({cloud:t});return Aa({runtimeHook:function(){return Dh(e,n)},adapter:s,allowNesting:!0})},Xr=class{constructor(e){T(this,"threads");T(this,"_thread");this._core=e,this.threads=new Zc(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(Lr.fromArray(e!=null?e:[]))}},Oh=e=>{const o=e,{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:s}=o,a=q(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:s},otherOptions:a}};function It(e){const t=Q.useRef(e);return Q.useEffect(()=>{t.current=e}),Q.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}var Ta=y.createContext(null),Fh=e=>({useSmoothStatus:jt(()=>e)}),zh=({children:e})=>{const t=Ca({optional:!0}),n=he(),[r]=y.useState(()=>Fh(n.part().getState().status));return t?e:p.jsx(Ta.Provider,{value:r,children:e})},Bh=e=>{const t=y.forwardRef((n,r)=>p.jsx(zh,{children:p.jsx(e,I(m({},n),{ref:r}))}));return t.displayName=e.displayName,t};function Ca(e){const t=y.useContext(Ta);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Rh,useSmoothStatusStore:jh}=la(Ca,"useSmoothStatus"),Uh=class{constructor(e,t){T(this,"animationFrameId",null);T(this,"lastUpdateTime",Date.now());T(this,"targetText","");T(this,"animate",()=>{const e=Date.now();let n=e-this.lastUpdateTime;const r=this.targetText.length-this.currentText.length,i=Math.min(5,250/r);let s=0;for(;n>=i&&s<r;)s++,n-=i;s!==r?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,s!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+s),this.lastUpdateTime=e-n,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)}},Qr=Object.freeze({type:"running"}),Ia=(e,t=!1)=>{const{text:n}=e,r=te(({message:c})=>c.id),i=y.useRef(r),[s,a]=y.useState(n),o=jh({optional:!0}),l=It(c=>{if(a(c),o){const d=s!==c||e.status.type==="running"?Qr:e.status;dn(o).setState(d,!0)}});y.useEffect(()=>{if(o){const c=t&&(s!==n||e.status.type==="running")?Qr:e.status;dn(o).setState(c,!0)}},[o,t,n,s,e.status]);const[u]=y.useState(new Uh(n,l));return y.useEffect(()=>{if(!t){u.stop();return}if(i.current!==r||!n.startsWith(u.targetText)){i.current=r,l(n),u.currentText=n,u.targetText=n,u.stop();return}u.targetText=n,u.start()},[l,u,r,t,n]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:s,status:n===s?e.status:Qr}:e,[t,s,e,n])};const $h=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Xr,BaseAssistantRuntimeCore:Er,CompositeContextProvider:Ir,DefaultThreadComposerRuntimeCore:ps,MessageRepository:As,ThreadRuntimeImpl:Hs,fromThreadMessageLike:sn,generateId:St,getAutoStatus:gs,splitLocalRuntimeOptions:Oh,useSmooth:Ia,useSmoothStatus:Rh,useToolInvocations:ad,withSmoothContextProvider:Bh},Symbol.toStringTag,{value:"Module"}));var Hh=class extends nn{constructor(t){super();T(this,"useRuntimeHook");T(this,"instances",new Map);T(this,"useAliveThreadsKeysChanged",jt(()=>({})));T(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:n}=this.useRuntimeHook(),r=n(),i=r.thread.__internal_threadBinding,s=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=i.getState(),this._notifySubscribers()},[t,i]),a=y.useRef(!1);a.current||s(),y.useEffect(()=>(a.current=!0,s(),i.outerSubscribe(s)),[i,s]);const o=he();return y.useEffect(()=>r.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=r.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[r,o]),null});T(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:n})=>p.jsx(oh,{id:t,children:p.jsx(n,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));T(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(n=>p.jsx(this._OuterActiveThreadProvider,{threadId:n,provider:t},n))));this.useRuntimeHook=jt(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((n,r)=>{const i=()=>{const a=this.instances.get(t);if(!a)s(),r(new Error("Thread was deleted before runtime was started"));else if(a.runtime)s(),n(a.runtime);else return},s=this.subscribe(i);i()})}getThreadRuntimeCore(t){const n=this.instances.get(t);if(n)return n.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},xe=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."),qh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw xe},append(){throw xe},startRun(){throw xe},resumeRun(){throw xe},cancelRun(){throw xe},addToolResult(){throw xe},resumeToolCall(){throw xe},speak(){throw xe},stopSpeaking(){throw xe},submitFeedback(){throw xe},getModelContext(){return{}},unstable_loadExternalState(){throw xe},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return M(this,null,function*(){throw xe})},removeAttachment(){return M(this,null,function*(){throw xe})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw xe},role:"user",setRole(){throw xe},runConfig:{},setRunConfig(){throw xe},reset(){return M(this,null,function*(){})},clearAttachments(){return M(this,null,function*(){})},send(){throw xe},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw xe},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 xe},export(){return{messages:[]}},reset(){throw xe},unstable_on(){return()=>{}}},Ea=(e,t,n)=>n.reduce((r,i)=>{var s;return(s=i==null?void 0:i(r,t))!=null?s:r},e),Vh=class extends nn{constructor(t){super();T(this,"_pendingTransforms",[]);T(this,"_baseValue");T(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,n)=>Ea(t,n.task,[n.loading,n.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 M(this,null,function*(){const n=t.execute(),r=I(m({},t),{task:n});try{this._pendingTransforms.push(r),this._updateState();const i=yield n;return this._baseValue=Ea(this._baseValue,i,[t.optimistic,t.then]),i}finally{const i=this._pendingTransforms.indexOf(r);i>-1&&this._pendingTransforms.splice(i,1),this._updateState()}})}};function zv(e){return e}var Xn=(e,t)=>{const n=e.threadIdMap[t];if(n!==void 0)return e.threadData[n]},Qn=(e,t,n)=>{const r=Xn(e,t);if(!r)return e;const{id:i,remoteId:s,status:a}=r;if(a===n)return e;const o=m({},e);switch(a){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==i);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==i);break;default:{const l=a;throw new Error(`Unsupported state: ${l}`)}}switch(n){case"regular":o.threadIds=[i,...o.threadIds];break;case"archived":o.archivedThreadIds=[i,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==i)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==i&&l!==s));break;default:{const l=n;throw new Error(`Unsupported state: ${l}`)}}return n!=="deleted"&&(o.threadData=I(m({},o.threadData),{[i]:I(m({},r),{status:n})})),o},Wh=class extends nn{constructor(t,n){super();T(this,"_options");T(this,"_hookManager");T(this,"_loadThreadsPromise");T(this,"_mainThreadId");T(this,"_state",new Vh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));T(this,"useProvider");T(this,"initialize",t=>M(this,null,function*(){if(this._state.value.newThreadId!==t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Unexpected new state");return n.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:n=>Qn(n,t,"regular"),loading:(n,r)=>{const i=t;return I(m({},n),{threadData:I(m({},n.threadData),{[i]:I(m({},n.threadData[i]),{initializeTask:r})})})},then:(n,{remoteId:r,externalId:i})=>{const s=Xn(n,t);if(!s)return n;const a=t;return I(m({},n),{threadIdMap:I(m({},n.threadIdMap),{[r]:a}),threadData:I(m({},n.threadData),{[a]:I(m({},s),{initializeTask:Promise.resolve({remoteId:r,externalId:i}),remoteId:r,externalId:i})})})}})}));T(this,"generateTitle",t=>M(this,null,function*(){var l;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");const{remoteId:r}=yield n.initializeTask,i=this._hookManager.getThreadRuntimeCore(n.id);if(!i)return;const s=i.messages,a=yield this._options.adapter.generateTitle(r,s),o=Oc.fromAssistantStream(a);try{for(var u=Lt(o),c,d,h;c=!(d=yield u.next()).done;c=!1){const f=d.value;const g=(l=f.parts.filter(b=>b.type==="text")[0])==null?void 0:l.text,v=this._state.baseValue;this._state.update(I(m({},v),{threadData:I(m({},v.threadData),{[n.id]:I(m({},n),{title:g})})}))}}catch(d){h=[d]}finally{try{c&&(d=u.return)&&(yield d.call(u))}finally{if(h)throw h[0]}}}));T(this,"useBoundIds",jt(()=>[]));T(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(s=>[...s,t],!0),()=>{this.useBoundIds.setState(s=>s.filter(a=>a!==t),!0)}),[t]);const n=this.useBoundIds(),{Provider:r}=this.useProvider(),i={modelContext:this.contextProvider};return(n.length===0||n[0]===t)&&p.jsx(Fr,{adapters:i,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:r})})});this.contextProvider=n,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Hh(t.runtimeHook),this.useProvider=jt(()=>{var r;return{Provider:(r=t.adapter.unstable_Provider)!=null?r: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=>I(m({},t),{isLoading:!0}),then:(t,n)=>{const r=[],i=[],s={},a={};for(const o of n.threads){switch(o.status){case"regular":r.push(o.remoteId);break;case"archived":i.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;s[o.remoteId]=l,a[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 I(m({},t),{threadIds:r,archivedThreadIds:i,threadIdMap:m(m({},t.threadIdMap),s),threadData:m(m({},t.threadData),a)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var r;if(this._options===t)return;this._options=t;const n=(r=t.adapter.unstable_Provider)!=null?r:y.Fragment;n!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:n},!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||qh}getThreadRuntimeCore(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");const r=this._hookManager.getThreadRuntimeCore(n.id);if(!r)throw new Error("Thread not found");return r}getItemById(t){return Xn(this._state.value,t)}switchToThread(t){return M(this,null,function*(){let n=this.getItemById(t);if(!n){const i=yield this._options.adapter.fetch(t),s=this._state.value,a=i.remoteId,o=I(m({},s.threadData),{[a]:{id:a,initializeTask:Promise.resolve({remoteId:i.remoteId,externalId:i.externalId}),remoteId:i.remoteId,externalId:i.externalId,status:i.status,title:i.title}}),l=I(m({},s.threadIdMap),{[i.remoteId]:a}),u=i.status==="regular"?[...s.threadIds,i.remoteId]:s.threadIds,c=i.status==="archived"?[...s.archivedThreadIds,i.remoteId]:s.archivedThreadIds;this._state.update(I(m({},s),{threadIds:u,archivedThreadIds:c,threadIdMap:l,threadData:o})),n=this.getItemById(t)}if(!n)throw new Error("Thread not found");if(this._mainThreadId===n.id)return;const r=this._hookManager.startThreadRuntime(n.id);this.mainThreadId!==void 0?yield r:r.then(()=>this._notifySubscribers()),n.status==="archived"&&(yield this.unarchive(n.id)),this._mainThreadId=n.id,this._notifySubscribers()})}switchToNewThread(){return M(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 n=this._state.value.newThreadId;if(n===void 0){do n=`__LOCALID_${St()}`;while(t.threadIdMap[n]);const r=n;this._state.update(I(m({},t),{newThreadId:n,threadIdMap:I(m({},t.threadIdMap),{[n]:r}),threadData:I(m({},t.threadData),{[r]:{status:"new",id:n,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(n)})}rename(t,n){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");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){const{remoteId:i}=yield r.initializeTask;return this._options.adapter.rename(i,n)}),optimistic:i=>{const s=Xn(i,t);return s?I(m({},i),{threadData:I(m({},i.threadData),{[s.id]:I(m({},s),{title:n})})}):i}})}_ensureThreadIsNotMain(t){return M(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 M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(n.id);const{remoteId:r}=yield n.initializeTask;return this._options.adapter.archive(r)}),optimistic:r=>Qn(r,n.id,"archived")})})}unarchive(t){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){try{const{remoteId:r}=yield n.initializeTask;return yield this._options.adapter.unarchive(r)}catch(r){throw yield this._ensureThreadIsNotMain(n.id),r}}),optimistic:r=>Qn(r,n.id,"regular")})}delete(t){return M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>M(this,null,function*(){yield this._ensureThreadIsNotMain(n.id);const{remoteId:r}=yield n.initializeTask;return yield this._options.adapter.delete(r)}),optimistic:r=>Qn(r,n.id,"deleted")})})}detach(t){return M(this,null,function*(){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status!=="regular"&&n.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(n.id),this._hookManager.stopThreadRuntime(n.id)})}},Jh=class extends Er{constructor(t){super();T(this,"threads");this.threads=new Wh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},Kh=e=>{const[t]=y.useState(()=>new Jh(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Xr(t),[t])},Aa=e=>{if(Kn().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 Kh(e)},Yh=Symbol.for("react.lazy"),Zn=Q[" use ".trim().toString()];function Gh(e){return typeof e=="object"&&e!==null&&"then"in e}function Ma(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Yh&&"_payload"in e&&Gh(e._payload)}function Pa(e){const t=Xh(e),n=Q.forwardRef((r,i)=>{let u=r,{children:s}=u,a=q(u,["children"]);Ma(s)&&typeof Zn=="function"&&(s=Zn(s._payload));const o=Q.Children.toArray(s),l=o.find(Zh);if(l){const c=l.props.children,d=o.map(h=>h===l?Q.Children.count(c)>1?Q.Children.only(null):Q.isValidElement(c)?c.props.children:null:h);return p.jsx(t,I(m({},a),{ref:i,children:Q.isValidElement(c)?Q.cloneElement(c,void 0,d):null}))}return p.jsx(t,I(m({},a),{ref:i,children:s}))});return n.displayName=`${e}.Slot`,n}var Zr=Pa("Slot");function Xh(e){const t=Q.forwardRef((n,r)=>{let a=n,{children:i}=a,s=q(a,["children"]);if(Ma(i)&&typeof Zn=="function"&&(i=Zn(i._payload)),Q.isValidElement(i)){const o=tf(i),l=ef(s,i.props);return i.type!==Q.Fragment&&(l.ref=r?ea(r,o):o),Q.cloneElement(i,l)}return Q.Children.count(i)>1?Q.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Qh=Symbol("radix.slottable");function Zh(e){return Q.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Qh}function ef(e,t){const n=m({},t);for(const r in t){const i=e[r],s=t[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(n[r]=i):r==="style"?n[r]=m(m({},i),s):r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return m(m({},e),n)}function tf(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var nf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ut=nf.reduce((e,t)=>{const n=Pa(`Primitive.${t}`),r=Q.forwardRef((i,s)=>{const u=i,{asChild:a}=u,o=q(u,["asChild"]),l=a?n:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,I(m({},o),{ref:s}))});return r.displayName=`Primitive.${t}`,I(m({},e),{[t]:r})},{});function Ut(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}var er=(e,t,n=[])=>{const r=y.forwardRef((i,s)=>{var u;const a={},o={};Object.keys(i).forEach(c=>{n.includes(c)?a[c]=i[c]:o[c]=i[c]});const l=(u=t(a))!=null?u:void 0;return p.jsx(ut.button,I(m({type:"button"},o),{ref:s,disabled:o.disabled||!l,onClick:Ut(o.onClick,l)}))});return r.displayName=e,r};function rf(e,t=globalThis==null?void 0:globalThis.document){const n=It(e);Q.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var sf=()=>{const e=he();return y.useCallback(()=>{e.attachment().remove()},[e])},af=er("AttachmentPrimitive.Remove",sf),hn=e=>{const t=y.useRef(void 0);return y.useCallback(r=>{t.current&&t.current(),r&&(t.current=e(r))},[e])},Na=(e,t)=>{const n=y.useCallback(r=>{if(!e)return;const i=e(),s=()=>{const o=t?t(r):r.offsetHeight;i.setHeight(o)},a=new ResizeObserver(s);return a.observe(r),s(),()=>{a.disconnect(),i.unregister()}},[e,t]);return hn(n)},La=y.createContext(!1),Da=(e,t)=>{const n=e.match(/^([\d.]+)(em|px|rem)$/);if(!n)return 0;const r=parseFloat(n[1]),i=n[2];if(i==="px")return r;if(i==="em"){const s=parseFloat(getComputedStyle(t).fontSize)||16;return r*s}if(i==="rem"){const s=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return r*s}return 0},Oa=({children:e,fillClampThreshold:t="10em",fillClampOffset:n="6em"})=>{const r=te(({message:l})=>l.isLast&&l.index>=2),i=qr({optional:!0}),s=y.useContext(La),a=y.useCallback(l=>{if(!i||s)return;const u=()=>{const c=i.getState();if(c.turnAnchor==="top"&&r){const{viewport:d,inset:h,userMessage:f}=c.height,g=Da(t,l),v=Da(n,l),b=f<=g?f:v,x=Math.max(0,d-h-b);l.style.minHeight=`${x}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),i.subscribe(u)},[i,r,s,t,n]),o=hn(a);return p.jsx(La.Provider,{value:!0,children:p.jsx(Zr,{ref:o,children:e})})};Oa.displayName="ThreadPrimitive.ViewportSlack";var of=()=>{const e=he(),t=te(()=>e.message()),n=y.useCallback(r=>{const i=()=>{t.setIsHovering(!0)},s=()=>{t.setIsHovering(!1)};return r.addEventListener("mouseenter",i),r.addEventListener("mouseleave",s),r.matches(":hover")&&t.setIsHovering(!0),()=>{r.removeEventListener("mouseenter",i),r.removeEventListener("mouseleave",s),t.setIsHovering(!1)}},[t]);return hn(n)},lf=()=>{const e=Yn(i=>i.turnAnchor),t=Yn(i=>i.registerUserMessageHeight),n=te(({thread:i,message:s})=>{var a;return e==="top"&&s.role==="user"&&s.index===i.messages.length-2&&((a=i.messages.at(-1))==null?void 0:a.role)==="assistant"}),r=y.useCallback(i=>i.offsetHeight,[]);return Na(n?t:null,r)},ei=y.forwardRef((e,t)=>{const n=of(),r=lf(),i=Jn(t,n,r);return p.jsx(Oa,{children:p.jsx(ut.div,I(m({},e),{ref:i}))})});ei.displayName="MessagePrimitive.Root";var Fa=()=>te(({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}),za=y.forwardRef((i,r)=>{var s=i,{smooth:e=!0,component:t="span"}=s,n=q(s,["smooth","component"]);const{text:a,status:o}=Ia(Fa(),e);return p.jsx(t,I(m({"data-status":o.type},n),{ref:r,children:a}))});za.displayName="MessagePartPrimitive.Text";var uf=()=>te(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Ba=y.forwardRef((e,t)=>{const{image:n}=uf();return p.jsx(ut.img,I(m({src:n},e),{ref:t}))});Ba.displayName="MessagePartPrimitive.Image";var Ra=({children:e})=>te(({part:n})=>n.status.type==="running")?e:null;Ra.displayName="MessagePartPrimitive.InProgress";const ja=e=>Symbol.iterator in e,Ua=e=>"entries"in e,$a=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},cf=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function df(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:ja(e)&&ja(t)?Ua(e)&&Ua(t)?$a(e,t):cf(e,t):$a({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function hf(e){const t=y.useRef(void 0);return n=>{const r=e(n);return df(t.current,r)?t.current:t.current=r}}var Ha=e=>{let t=-1;return{startGroup:n=>{t===-1&&(t=n)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},ff=e=>{const t=[],n=Ha("toolGroup"),r=Ha("reasoningGroup");for(let i=0;i<e.length;i++){const s=e[i];s==="tool-call"?(r.endGroup(i-1,t),n.startGroup(i)):s==="reasoning"?(n.endGroup(i-1,t),r.startGroup(i)):(n.endGroup(i-1,t),r.endGroup(i-1,t),t.push({type:"single",index:i}))}return n.finalize(e.length-1,t),r.finalize(e.length-1,t),t},pf=()=>{const e=te(hf(t=>t.message.parts.map(n=>n.type)));return y.useMemo(()=>e.length===0?[]:ff(e),[e])},mf=n=>{var r=n,{Fallback:e}=r,t=q(r,["Fallback"]);const i=te(({tools:s})=>{var o,l;const a=(o=s.tools[t.toolName])!=null?o:e;return Array.isArray(a)?(l=a[0])!=null?l:e:a});return i?p.jsx(i,m({},t)):null},ct={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(za,{}),p.jsx(Ra,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Ba,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},gf=({components:{Text:e=ct.Text,Reasoning:t=ct.Reasoning,Image:n=ct.Image,Source:r=ct.Source,File:i=ct.File,Unstable_Audio:s=ct.Unstable_Audio,tools:a={}}={}})=>{var c,d,h;const o=he(),l=te(({part:f})=>f),u=l.type;if(u==="tool-call"){const f=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in a)return p.jsx(a.Override,I(m({},l),{addResult:f,resume:g}));const v=(d=(c=a.by_name)==null?void 0:c[l.toolName])!=null?d:a.Fallback;return p.jsx(mf,I(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(r,m({},l));case"image":return p.jsx(n,m({},l));case"file":return p.jsx(i,m({},l));case"audio":return p.jsx(s,m({},l));case"data":return null;default:const f=u;throw new Error(`Unknown message part type: ${f}`)}},tr=y.memo(({index:e,components:t})=>p.jsx(uh,{index:e,children:p.jsx(gf,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u,c,d,h,f,g,v,b,x,E,_;return e.index===t.index&&((n=e.components)==null?void 0:n.Text)===((r=t.components)==null?void 0:r.Text)&&((i=e.components)==null?void 0:i.Reasoning)===((s=t.components)==null?void 0:s.Reasoning)&&((a=e.components)==null?void 0:a.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)&&((c=e.components)==null?void 0:c.File)===((d=t.components)==null?void 0:d.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)===((x=t.components)==null?void 0:x.ToolGroup)&&((E=e.components)==null?void 0:E.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});tr.displayName="MessagePrimitive.PartByIndex";var yf=({status:e,component:t})=>p.jsx(fh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),bf=Object.freeze({type:"complete"}),wf=({components:e})=>{var n;const t=te(r=>{var i;return(i=r.message.status)!=null?i:bf});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(yf,{status:t,component:(n=e==null?void 0:e.Text)!=null?n:ct.Text})},xf=y.memo(wf,(e,t)=>{var n,r,i,s;return((n=e.components)==null?void 0:n.Empty)===((r=t.components)==null?void 0:r.Empty)&&((i=e.components)==null?void 0:i.Text)===((s=t.components)==null?void 0:s.Text)}),ti=({components:e})=>{const t=te(({message:i})=>i.parts.length),n=pf(),r=y.useMemo(()=>t===0?p.jsx(xf,{components:e}):n.map(i=>{var s,a;if(i.type==="single")return p.jsx(tr,{index:i.index,components:e},i.index);if(i.type==="toolGroup"){const o=(s=e==null?void 0:e.ToolGroup)!=null?s:ct.ToolGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(tr,{index:i.startIndex+u,components:e},u))},`tool-${i.startIndex}`)}else{const o=(a=e==null?void 0:e.ReasoningGroup)!=null?a:ct.ReasoningGroup;return p.jsx(o,{startIndex:i.startIndex,endIndex:i.endIndex,children:Array.from({length:i.endIndex-i.startIndex+1},(l,u)=>p.jsx(tr,{index:i.startIndex+u,components:e},u))},`reasoning-${i.startIndex}`)}}),[n,e,t]);return p.jsx(p.Fragment,{children:r})};ti.displayName="MessagePrimitive.Parts";var vf=(e,t)=>{var r,i,s;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},Sf=({components:e})=>{const t=te(({attachment:r})=>r);if(!t)return null;const n=vf(e,t);return n?p.jsx(n,{}):null},qa=y.memo(({index:e,components:t})=>p.jsx(ch,{index:e,children:p.jsx(Sf,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((i=e.components)==null?void 0:i.Document)===((s=t.components)==null?void 0:s.Document)&&((a=e.components)==null?void 0:a.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)});qa.displayName="MessagePrimitive.AttachmentByIndex";var Va=({components:e})=>{const t=te(({message:r})=>r.role!=="user"?0:r.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,i)=>p.jsx(qa,{index:i,components:e},i)),[t,e])};Va.displayName="MessagePrimitive.Attachments";var Wa=()=>{const e=he(),t=te(r=>r.thread.isRunning||!r.composer.isEditing||r.composer.isEmpty),n=y.useCallback(()=>{e.composer().send()},[e]);return t?null:n},kf=er("ComposerPrimitive.Send",Wa),Ja=y.forwardRef((r,n)=>{var i=r,{onSubmit:e}=i,t=q(i,["onSubmit"]);const s=Wa(),a=o=>{o.preventDefault(),s&&s()};return p.jsx(ut.form,I(m({},t),{ref:n,onSubmit:Ut(e,a)}))});Ja.displayName="ComposerPrimitive.Root";function ni(){return ni=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ni.apply(null,arguments)}function _f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Tf=y.useLayoutEffect,Cf=function(t){var n=y.useRef(t);return Tf(function(){n.current=t}),n},Ka=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},If=function(t,n){var r=y.useRef();return y.useCallback(function(i){t.current=i,r.current&&Ka(r.current,null),r.current=n,n&&Ka(n,i)},[n])},Ya={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Ef=function(t){Object.keys(Ya).forEach(function(n){t.style.setProperty(n,Ya[n],"important")})},Ga=Ef,De=null,Xa=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function Af(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),De||(De=document.createElement("textarea"),De.setAttribute("tabindex","-1"),De.setAttribute("aria-hidden","true"),Ga(De)),De.parentNode===null&&document.body.appendChild(De);var i=e.paddingSize,s=e.borderSize,a=e.sizingStyle,o=a.boxSizing;Object.keys(a).forEach(function(h){var f=h;De.style[f]=a[f]}),Ga(De),De.value=t;var l=Xa(De,e);De.value=t,l=Xa(De,e),De.value="x";var u=De.scrollHeight-i,c=u*n;o==="border-box"&&(c=c+i+s),l=Math.max(c,l);var d=u*r;return o==="border-box"&&(d=d+i+s),l=Math.min(d,l),[l,u]}var Qa=function(){},Mf=function(t,n){return t.reduce(function(r,i){return r[i]=n[i],r},{})},Pf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Nf=!!document.documentElement.currentStyle,Lf=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=Mf(Pf,n),i=r.boxSizing;if(i==="")return null;Nf&&i==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var s=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),a=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:s,borderSize:a}},Df=Lf;function ri(e,t,n){var r=Cf(n);Q.useLayoutEffect(function(){var i=function(a){return r.current(a)};if(e)return e.addEventListener(t,i),function(){return e.removeEventListener(t,i)}},[])}var Of=function(t,n){ri(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},Ff=function(t){ri(window,"resize",t)},zf=function(t){ri(document.fonts,"loadingdone",t)},Bf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Rf=function(t,n){var r=t.cacheMeasurements,i=t.maxRows,s=t.minRows,a=t.onChange,o=a===void 0?Qa:a,l=t.onHeightChange,u=l===void 0?Qa:l,c=_f(t,Bf),d=c.value!==void 0,h=Q.useRef(null),f=If(h,n),g=Q.useRef(0),v=Q.useRef(),b=function(){var _=h.current,F=r&&v.current?v.current:Df(_);if(F){v.current=F;var B=Af(F,_.value||_.placeholder||"x",s,i),C=B[0],H=B[1];g.current!==C&&(g.current=C,_.style.setProperty("height",C+"px","important"),u(C,{rowHeight:H}))}},x=function(_){d||b(),o(_)};return Q.useLayoutEffect(b),Of(h,function(){if(!d){var E=h.current.value;requestAnimationFrame(function(){var _=h.current;_&&E!==_.value&&b()})}}),Ff(b),zf(b),Q.createElement("textarea",ni({},c,{onChange:x,ref:f}))},jf=Q.forwardRef(Rf),Za=e=>{const t=It(e),n=Yn(r=>r.onScrollToBottom);y.useEffect(()=>n(t),[n,t])},eo=y.forwardRef((g,f)=>{var v=g,{autoFocus:e=!1,asChild:t,disabled:n,onChange:r,onKeyDown:i,onPaste:s,submitOnEnter:a=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:c=!0,addAttachmentOnPaste:d=!0}=v,h=q(v,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const b=he(),x=te(({composer:k})=>k.isEditing?k.text:""),E=t?Zr:jf,_=te(({thread:k})=>k.isDisabled)||n,F=y.useRef(null),B=Jn(f,F);rf(k=>{var P;if(!o||!((P=F.current)!=null&&P.contains(k.target)))return;const O=b.composer();O.getState().canCancel&&(O.cancel(),k.preventDefault())});const C=k=>{var O,P;_||!a||k.nativeEvent.isComposing||k.key==="Enter"&&k.shiftKey===!1&&(b.thread().getState().isRunning||(k.preventDefault(),(P=(O=F.current)==null?void 0:O.closest("form"))==null||P.requestSubmit()))},H=k=>M(null,null,function*(){var R;if(!d)return;const O=b.thread().getState().capabilities,P=Array.from(((R=k.clipboardData)==null?void 0:R.files)||[]);if(O.attachments&&P.length>0)try{k.preventDefault(),yield Promise.all(P.map(L=>b.composer().addAttachment(L)))}catch(L){console.error("Error adding attachment:",L)}}),V=e&&!_,j=y.useCallback(()=>{const k=F.current;!k||!V||(k.focus({preventScroll:!0}),k.setSelectionRange(k.value.length,k.value.length))},[V]);return y.useEffect(()=>j(),[j]),Za(()=>{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"||!c))return b.on("thread-list-item.switched-to",j)},[c,j,b]),p.jsx(E,I(m({name:"input",value:x},h),{ref:B,disabled:_,onChange:Ut(r,k=>{b.composer().getState().isEditing&&(b.composer().setText(k.target.value),b.flushSync())}),onKeyDown:Ut(i,C),onPaste:Ut(s,H)}))});eo.displayName="ComposerPrimitive.Input";var Uf=({multiple:e=!0}={})=>{const t=te(({composer:i})=>!i.isEditing),n=he(),r=y.useCallback(()=>{const i=document.createElement("input");i.type="file",i.multiple=e,i.hidden=!0;const s=n.composer().getState().attachmentAccept;s!=="*"&&(i.accept=s),document.body.appendChild(i),i.onchange=a=>{const o=a.target.files;if(o){for(const l of o)n.composer().addAttachment(l);document.body.removeChild(i)}},i.oncancel=()=>{(!i.files||i.files.length===0)&&document.body.removeChild(i)},i.click()},[n,e]);return t?null:r},$f=er("ComposerPrimitive.AddAttachment",Uf,["multiple"]),Hf=(e,t)=>{var r,i,s;const n=t.type;switch(n){case"image":return(r=e==null?void 0:e.Image)!=null?r:e==null?void 0:e.Attachment;case"document":return(i=e==null?void 0:e.Document)!=null?i:e==null?void 0:e.Attachment;case"file":return(s=e==null?void 0:e.File)!=null?s:e==null?void 0:e.Attachment;default:const a=n;throw new Error(`Unknown attachment type: ${a}`)}},qf=({components:e})=>{const t=te(({attachment:r})=>r);if(!t)return null;const n=Hf(e,t);return n?p.jsx(n,{}):null},to=y.memo(({index:e,components:t})=>p.jsx(dh,{index:e,children:p.jsx(qf,{components:t})}),(e,t)=>{var n,r,i,s,a,o,l,u;return e.index===t.index&&((n=e.components)==null?void 0:n.Image)===((r=t.components)==null?void 0:r.Image)&&((i=e.components)==null?void 0:i.Document)===((s=t.components)==null?void 0:s.Document)&&((a=e.components)==null?void 0:a.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)});to.displayName="ComposerPrimitive.AttachmentByIndex";var no=({components:e})=>{const t=te(r=>r.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(r,i)=>p.jsx(to,{index:i,components:e},i)),[t,e])};no.displayName="ComposerPrimitive.Attachments";var ro=y.forwardRef((s,i)=>{var a=s,{disabled:e,asChild:t=!1,children:n}=a,r=q(a,["disabled","asChild","children"]);const[o,l]=y.useState(!1),u=he(),c=y.useCallback(b=>{e||(b.preventDefault(),l(!0))},[e]),d=y.useCallback(b=>{e||(b.preventDefault(),o||l(!0))},[e,o]),h=y.useCallback(b=>{if(e)return;b.preventDefault();const x=b.relatedTarget;x&&b.currentTarget.contains(x)||l(!1)},[e]),f=y.useCallback(b=>M(null,null,function*(){if(!e){b.preventDefault(),l(!1);for(const x of b.dataTransfer.files)try{yield u.composer().addAttachment(x)}catch(E){console.error("Failed to add attachment:",E)}}}),[e,u]),g={onDragEnterCapture:c,onDragOverCapture:d,onDragLeaveCapture:h,onDropCapture:f},v=t?Zr:"div";return p.jsx(v,I(m(m(I(m({},o?{"data-dragging":"true"}:null),{ref:i}),g),r),{children:n}))});ro.displayName="ComposerPrimitive.AttachmentDropzone";var io=y.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));io.displayName="ThreadPrimitive.Root";var so=({children:e})=>te(({thread:n})=>n.messages.length===0&&!n.isLoading)?e:null;so.displayName="ThreadPrimitive.Empty";var Vf=e=>{const t=It(e),n=y.useCallback(r=>{const i=new ResizeObserver(()=>{t()}),s=new MutationObserver(()=>{t()});return i.observe(r),s.observe(r,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{i.disconnect(),s.disconnect()}},[t]);return hn(n)},Wf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{const i=y.useRef(null),s=qr();e===void 0&&(e=s.getState().turnAnchor!=="top");const a=y.useRef(0),o=y.useRef(null),l=y.useCallback(f=>{const g=i.current;g&&(o.current=f,g.scrollTo({top:g.scrollHeight,behavior:f}))},[]),u=()=>{const f=i.current;if(!f)return;const g=s.getState().isAtBottom,v=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<1||f.scrollHeight<=f.clientHeight;!v&&a.current<f.scrollTop||(v&&(o.current=null),(v||o.current===null)&&v!==g&&dn(s).setState({isAtBottom:v})),a.current=f.scrollTop},c=Vf(()=>{const f=o.current;f?l(f):e&&s.getState().isAtBottom&&l("instant"),u()}),d=hn(f=>(f.addEventListener("scroll",u),()=>{f.removeEventListener("scroll",u)}));return Za(({behavior:f})=>{l(f)}),Hr("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),Hr("thread.initialize",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Hr("thread-list-item.switched-to",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Jn(c,d,i)},Jf=()=>{const e=Yn(n=>n.registerViewport),t=y.useCallback(n=>n.clientHeight,[]);return Na(e,t)},ao=y.forwardRef((o,a)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r,children:i}=l,s=q(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Wf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:n,scrollToBottomOnThreadSwitch:r}),c=Jf(),d=Jn(a,u,c);return p.jsx(ut.div,I(m({},s),{ref:d,children:i}))});ao.displayName="ThreadPrimitive.ViewportScrollable";var oo=y.forwardRef((r,n)=>{var i=r,{turnAnchor:e}=i,t=q(i,["turnAnchor"]);return p.jsx(ya,{options:{turnAnchor:e},children:p.jsx(ao,I(m({},t),{ref:n}))})});oo.displayName="ThreadPrimitive.Viewport";var lo=(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,Kf=()=>null,Yf=(e,t,n)=>{var r,i,s,a,o,l,u,c,d,h,f,g;switch(t){case"user":return n?(s=(i=(r=e.UserEditComposer)!=null?r:e.EditComposer)!=null?i:e.UserMessage)!=null?s:e.Message:(a=e.UserMessage)!=null?a:e.Message;case"assistant":return n?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(c=e.AssistantMessage)!=null?c:e.Message;case"system":return n?(f=(h=(d=e.SystemEditComposer)!=null?d:e.EditComposer)!=null?h:e.SystemMessage)!=null?f:e.Message:(g=e.SystemMessage)!=null?g:Kf;default:const v=t;throw new Error(`Unknown message role: ${v}`)}},Gf=({components:e})=>{const t=te(({message:i})=>i.role),n=te(({message:i})=>i.composer.isEditing),r=Yf(e,t,n);return p.jsx(r,{})},uo=y.memo(({index:e,components:t})=>p.jsx(lh,{index:e,children:p.jsx(Gf,{components:t})}),(e,t)=>e.index===t.index&&lo(e.components,t.components));uo.displayName="ThreadPrimitive.MessageByIndex";var co=({components:e})=>{const t=te(({thread:r})=>r.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(r,i)=>p.jsx(uo,{index:i,components:e},i)),[t,e])};co.displayName="ThreadPrimitive.Messages";var Xf=y.memo(co,(e,t)=>lo(e.components,t.components)),ho=y.forwardRef((i,r)=>{var s=i,{onClick:e,disabled:t}=s,n=q(s,["onClick","disabled"]);const a=te(({threads:l})=>l.newThreadId===l.mainThreadId),o=he();return p.jsx(ut.button,I(m(m({type:"button"},a?{"data-active":"true","aria-current":"true"}:null),n),{ref:r,disabled:t,onClick:Ut(e,()=>{o.threads().switchToNewThread()})}))});ho.displayName="ThreadListPrimitive.New";var fo=y.memo(({index:e,archived:t=!1,components:n})=>{const r=n.ThreadListItem;return p.jsx(ah,{index:e,archived:t,children:p.jsx(r,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);fo.displayName="ThreadListPrimitive.ItemByIndex";var po=({archived:e=!1,components:t})=>{const n=te(({threads:i})=>e?i.archivedThreadIds.length:i.threadIds.length);return y.useMemo(()=>Array.from({length:n},(i,s)=>p.jsx(fo,{index:s,archived:e,components:t},s)),[n,e,t])};po.displayName="ThreadListPrimitive.Items";var mo=y.forwardRef((e,t)=>p.jsx(ut.div,I(m({},e),{ref:t})));mo.displayName="ThreadListPrimitive.Root";var go=y.forwardRef((e,t)=>{const n=te(({threads:r,threadListItem:i})=>r.mainThreadId===i.id);return p.jsx(ut.div,I(m(m({},n?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});go.displayName="ThreadListItemPrimitive.Root";var Qf=()=>{const e=he();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},Zf=er("ThreadListItemPrimitive.Trigger",Qf);function ep(){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,n=>n.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 yo{constructor(t,n,r=!1){T(this,"baseUrl");T(this,"sessionToken",null);T(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=r,n&&(this.sessionToken=n)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const n=`${this.baseUrl}${t.replace("/v1","")}`;return n.startsWith("/")||n.startsWith("./"),n}return`${this.baseUrl}${t}`}createOrContinueChat(t,n){return M(this,null,function*(){const r=this.getUrl("/v1/chats"),s={"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&&(s.Authorization=`Bearer ${this.sessionToken}`);const a=I(m({},t),{stream:!0}),o=yield fetch(r,{method:"POST",headers:s,body:JSON.stringify(a),signal:n,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 M(this,null,function*(){const n=this.getUrl(`/v1/chats/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n,{method:"GET",headers:r});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()})}listChats(t){return M(this,null,function*(){const n=this.getUrl("/v1/chats"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(r.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}generateIdempotencyKey(){return ep()}updateChat(t,n){return M(this,null,function*(){const r=`/v1/chats/${t}`,i=this.getUrl(r),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"PATCH",headers:o,body:JSON.stringify(n)});if(!l.ok){const c=yield l.text();let d={};try{d=JSON.parse(c)}catch(h){d={detail:c}}throw new Error(d.detail||d.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(c){return{}}})}deleteChat(t){return M(this,null,function*(){const n=`/v1/chats/${t}`,r=this.getUrl(n),i=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r),a={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(i.toString(),{method:"DELETE",headers:a});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}generateChatTitle(t,n){return M(this,null,function*(){const r=`/v1/chats/${t}/title`,i=this.getUrl(r),s=i.startsWith("/")||i.startsWith("./")?new URL(i,window.location.origin):new URL(i),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(s.toString(),{method:"POST",headers:o,body:n?JSON.stringify(n):void 0});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()})}listModels(t){return M(this,null,function*(){const n=this.getUrl("/v1/models"),r=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n);t!=null&&t.limit&&r.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&r.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(a=>{r.searchParams.append("expand[]",a)});const i={"Content-Type":"application/json"};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=yield fetch(r.toString(),{method:"GET",headers:i});if(!s.ok){const a=yield s.json().catch(()=>({}));throw new Error(a.detail||a.message||`API error: ${s.status} ${s.statusText}`)}return s.json()})}getModel(t){return M(this,null,function*(){const n=this.getUrl(`/v1/models/${t}`),r={"Content-Type":"application/json"};this.sessionToken&&(r.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n,{method:"GET",headers:r});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()})}uploadFile(t,n,r){return M(this,null,function*(){const i=this.getUrl("/v1/files"),s=this.generateIdempotencyKey(),a=new FormData;a.append("file",t),n&&a.append("resource_type",n),r&&a.append("resource_id",r);const o={"Idempotency-Key":s};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i,{method:"POST",headers:o,body:a});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 tp(e,t){return Pn(this,null,function*(){const n=e.getReader(),r=new TextDecoder;let i="";try{for(;;){if(t!=null&&t.aborted){n.cancel();break}const{done:s,value:a}=yield new Ee(n.read());if(s)break;i+=r.decode(a,{stream:!0});const o=i.split(`
6
6
 
7
- `);i=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(c){}}}}finally{n.releaseLock()}})}function Xf(e){return e.map(t=>{let n="";if(typeof t.content=="string")n=t.content;else if(Array.isArray(t.content)){const r=t.content.find(i=>i.type==="text");r&&typeof r=="object"&&"text"in r&&(n=r.text)}return{role:t.role,content:n}})}function Qf(e){return g(g({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 dn=new Map,ti=new Map;function Zf(e,t){return{list(){return M(this,null,function*(){const r=[];let s,a=0;do{const l=yield e.listChats({limit:50,cursor:s}),u=l.items||[];Array.isArray(u)&&u.length>0&&r.push(...u),s=l.nextCursor||void 0,a++}while(s&&a<50);return{threads:r.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(r){return M(this,null,function*(){return{remoteId:dn.get(r)||r,externalId:void 0}})},rename(r,i){return M(this,null,function*(){const s=dn.get(r)||r;yield e.updateChat(s,{title:i})})},archive(r){return M(this,null,function*(){})},unarchive(r){return M(this,null,function*(){})},delete(r){return M(this,null,function*(){const i=dn.get(r)||r;yield e.deleteChat(i)})},generateTitle(r,i){return M(this,null,function*(){return new ReadableStream})},fetch(r){return M(this,null,function*(){try{const i=yield e.getChat(r);return{status:"regular",remoteId:i.id||r,title:i.title||"Chat",createdAt:i.createdAt?new Date(i.createdAt):new Date,updatedAt:i.updatedAt?new Date(i.updatedAt):new Date}}catch(i){return{status:"regular",remoteId:r,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(r,i){dn.set(r,i),t==null||t(r,i)},unstable_Provider:({children:r})=>{const i=ua(),s=i==null?void 0:i.remoteId,a=y.useMemo(()=>({load(){return M(this,null,function*(){if(!s)return{messages:[]};try{const u=yield e.getChat(s);if(!u.messages||u.messages.length===0)return{messages:[]};const c=u.messages.map(h=>Qf(h)),d=c.map((h,f)=>({message:h,parentId:f>0?c[f-1].id:null}));for(const h of c)ti.set(h.id,s);return{messages:d}}catch(u){return{messages:[]}}})},append(u){return M(this,null,function*(){})}}),[s,e]),o=y.useMemo(()=>({history:a}),[a]);return p.jsx(Dr,{adapters:o,children:r})}}}class ep{constructor(){T(this,"messageMetadata",new Map);T(this,"currentMessageId",null);T(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const n=this.messageMetadata.get(this.currentMessageId)||{},r=t.sources;r&&r.length>0&&(this.messageMetadata.set(this.currentMessageId,E(g({},n),{sources:r})),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 bt=new ep,fo=new Map,ni=[];let tr=[];function po(e,t,n=50,r=800){ni.push({question:e,response:t,streamingSpeed:n,initialDelay:r})}function mo(e,t){const{modelId:n,systemPrompt:r,ephemeral:i,enableReasoning:s,onChatCreated:a,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:c}=t;let d;return{run(f){return Mn(this,null,function*(){var Z,de,w,ge,ye;const{messages:m,abortSignal:v}=f,b=ni.shift();if(b){o==null||o();const U=(Z=b.initialDelay)!=null?Z:800;if(U>0&&(yield new Ee(new Promise(ee=>setTimeout(ee,U)))),v!=null&&v.aborted)throw new Error("Request aborted");const X=b.response.split(" ");let ae="";const he=b.streamingSpeed||50,Ce=`premade-${Date.now()}`;i&&(a==null||a(Ce));for(let ee=0;ee<X.length;ee++){if(v!=null&&v.aborted)throw new Error("Request aborted");ae+=(ee===0?"":" ")+X[ee],yield{content:[{type:"text",text:ae}]},yield new Ee(new Promise(xe=>setTimeout(xe,he+Math.random()*(he*.5))))}yield{content:[{type:"text",text:ae}]},tr.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let x;for(const U of m){const X=ti.get(U.id);if(X){x=X;break}}if(!x&&m.length>0){const U=m.find(X=>X.role==="user");if(U){const ae=(typeof U.content=="string"?U.content:Array.isArray(U.content)&&((de=U.content.find(he=>he.type==="text"))==null?void 0:de.text)||"").substring(0,50);x=fo.get(ae)}}!x&&d&&(x=d),o==null||o();let C=m,_=-1;for(let U=m.length-1;U>=0;U--)if(m[U].role==="assistant"){_=U;break}(x||_>=0)&&_>=0&&(C=m.slice(_+1));const F=Xf(C);if(tr.length>0&&!x){const U=tr.map(X=>({role:X.role,content:X.content}));F.unshift(...U),tr=[]}const z=[];let I;for(let U=C.length-1;U>=0;U--)if(C[U].role==="user"){I=C[U];break}if(I&&"attachments"in I){const U=I.attachments;if(U&&U.length>0){for(const X of U)if(X.file)try{const ae=yield new Ee(e.uploadFile(X.file));z.push(ae.id)}catch(ae){}}}const H={messages:F,chatId:x||null,systemPrompt:r,ephemeral:i,enableReasoning:s,stream:!0};if(n&&n.trim()!==""&&(H.modelId=n),z.length>0&&(H.fileIds=z),u&&!(yield new Ee(u()))){if(c){const X=typeof c=="function"?c():c,ae=m.filter(xe=>xe.role==="user"),he=ae.length>0?ae[ae.length-1]:void 0;let Ce="Message";if(he){if(typeof he.content=="string")Ce=he.content;else if(Array.isArray(he.content)){const xe=he.content.find(Ye=>Ye.type==="text");Ce=(xe==null?void 0:xe.text)||"Message"}}po(Ce,X,40,400);const ee=ni.shift();if(ee){o==null||o();const xe=(w=ee.initialDelay)!=null?w:400;if(xe>0&&(yield new Ee(new Promise(be=>setTimeout(be,xe)))),v!=null&&v.aborted)throw new Error("Request aborted");const Ye=ee.response.split(" ");let Ge="";const Yt=ee.streamingSpeed||40,te=`mock-${Date.now()}`;i&&(a==null||a(te));for(let be=0;be<Ye.length;be++){if(v!=null&&v.aborted)throw new Error("Request aborted");Ge+=(be===0?"":" ")+Ye[be],yield{content:[{type:"text",text:Ge}]},yield new Ee(new Promise(we=>setTimeout(we,Yt+Math.random()*(Yt*.3))))}yield{content:[{type:"text",text:Ge}]};return}}throw new Error("Request blocked")}const q=yield new Ee(e.createOrContinueChat(H,v));let j="",k="",O;const P=[];let R=0,L=!1;const N=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;bt.clear(),bt.setCurrentMessage(N);const G=()=>{P.length!==R&&(R=P.length,bt.update({sources:P.length>0?[...P]:void 0}))},J=()=>{G();const U=[];return k&&U.push({type:"reasoning",text:k}),j&&U.push({type:"text",text:j}),U.length===0&&U.push({type:"text",text:""}),{content:U}};try{for(var S=Lt(Gf(q,v)),Ie,lt,_e;Ie=!(lt=yield new Ee(S.next())).done;Ie=!1){const U=lt.value;if(v!=null&&v.aborted)throw new Error("Request aborted");const X=U.id||U.chatId||U.messageId;if(X&&!O){O=X,d=X,a==null||a(X);for(const ee of m)ti.set(ee.id,X);if(m.length>0){const ee=m.find(xe=>xe.role==="user");if(ee){const Ye=(typeof ee.content=="string"?ee.content:Array.isArray(ee.content)&&((ge=ee.content.find(Ge=>Ge.type==="text"))==null?void 0:ge.text)||"").substring(0,50);fo.set(Ye,X)}}if(l){for(const[ee,xe]of dn.entries())if(xe===X){l(ee,X);break}}}const ae=U.sources;if(ae&&Array.isArray(ae)&&ae.length>0)for(const ee of ae)P.some(xe=>xe.sourceId===ee.sourceId)||P.push({sourceId:ee.sourceId,filename:ee.filename||"Unknown",score:(ye=ee.score)!=null?ye:1,chunkId:ee.chunkId,datasetId:ee.datasetId});const he=U.reasoning;if(he&&he.length>0&&(k+=he,yield J()),U.type)switch(U.type){case"source-document":U.sourceId&&P.push({sourceId:U.sourceId,filename:U.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":U.delta&&(k+=U.delta),(j||k)&&(yield J());continue;case"reasoning-end":(j||k)&&(yield J());continue;case"text-delta":U.delta&&(k&&!L&&!j&&(L=!0,yield new Ee(new Promise(ee=>setTimeout(ee,400)))),j+=U.delta),j&&(yield J());continue;case"error":throw new Error(U.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Ce=U.delta;if(Ce!=null&&(k&&!L&&!j&&(L=!0,yield new Ee(new Promise(ee=>setTimeout(ee,400)))),j+=Ce),U.content&&(j+=U.content),U.message&&(j+=U.message.content||""),U.finished){(j||k||P.length>0)&&(yield J());break}(j||k||P.length>0)&&(yield J())}}catch(lt){_e=[lt]}finally{try{Ie&&(lt=S.return)&&(yield new Ee(lt.call(S)))}finally{if(_e)throw _e[0]}}(j||k||P.length>0)&&(yield J())})}}}class nr extends Error{constructor(t,n,r){super(t),this.code=n,this.file=r,this.name="AttachmentValidationError"}}const tp=["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"],np=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],rp=10*1024*1024;function go(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function ip(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function sp(e,t){const r={"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 r?r.includes(t.toLowerCase()):!0}function ap(){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:n,onAttachmentAdded:r,onAttachmentRemoved:i}=e,{maxFileSizeBytes:s=rp,allowedMimeTypes:a=tp,allowedExtensions:o=np,validateContentType:l=!0}=t,u=o.join(",");function c(h){if(h.size>s){const m=new nr('File "'+h.name+'" is too large ('+go(h.size)+"). Maximum size is "+go(s)+".","FILE_TOO_LARGE",h);throw n==null||n(m),m}const f=ip(h.name);if(f&&!o.some(m=>m.toLowerCase()===f)){const m=new nr('File type "'+f+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw n==null||n(m),m}if(h.type&&!a.some(m=>{if(m.endsWith("/*")){const v=m.slice(0,-1);return h.type.startsWith(v)}return h.type===m})){const m=new nr('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw n==null||n(m),m}if(l&&h.type&&f&&!sp(h.type,f)){const m=new nr('File extension "'+f+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw n==null||n(m),m}}return{accept:u,add(f){return M(this,arguments,function*({file:h}){c(h);let m="file";h.type.startsWith("image/")?m="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"))&&(m="document");const v={id:ap(),type:m,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return r==null||r(v),v})},remove(h){return M(this,null,function*(){i==null||i(h.id)})},send(h){return M(this,null,function*(){if(h.type==="image"&&h.file){const f=yield new Promise((m,v)=>{const b=new FileReader;b.onload=()=>m(b.result),b.onerror=()=>v(new Error("Failed to read file")),b.readAsDataURL(h.file)});return E(g({},h),{status:{type:"complete"},content:[{type:"image",image:f}]})}return E(g({},h),{status:{type:"complete"},content:[]})})}}}function op({children:e,baseUrl:t,sessionToken:n,isProxyMode:r=!1,mode:i="multiChat",modelId:s,onModelChange:a,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:c,onError:d,onChatCreated:h,onUserMessage:f,onThreadIdUpdate:m,onChatsLoaded:v,enableAttachments:b=!1,onBeforeRequest:x,mockResponseOnBlocked:C}){const _=y.useMemo(()=>new ho(t,n||void 0,r),[t,n,r]),[F,z]=y.useState(s||null);y.useEffect(()=>{s&&z(s)},[s]);const I=y.useCallback(j=>{h==null||h(j)},[h]),H=y.useCallback((j,k)=>{m==null||m(j,k)},[m]),q=y.useMemo(()=>mo(_,{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:x,mockResponseOnBlocked:C}),[_,F,l,o,u,I,f,x,C]);return i==="singleChat"?p.jsx(lp,{modelAdapter:q,enableAttachments:b,children:e}):p.jsx(up,{client:_,modelAdapterOptions:{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:x,mockResponseOnBlocked:C},initialThreadId:c,onChatsLoaded:v,onThreadIdUpdate:H,onError:d,enableAttachments:b,children:e})}function lp({modelAdapter:e,enableAttachments:t,children:n}){const r=y.useMemo(()=>t?yo():void 0,[t]),i=wa(e,{adapters:g({},r&&{attachments:r})});return p.jsx(fa,{runtime:i,children:n})}function up({client:e,modelAdapterOptions:t,initialThreadId:n,onChatsLoaded:r,onThreadIdUpdate:i,onError:s,enableAttachments:a,children:o}){const l=y.useMemo(()=>Zf(e,(v,b)=>{i==null||i(v,b)}),[e,i]),u=y.useCallback((v,b)=>{l.updateRemoteId&&l.updateRemoteId(v,b),i==null||i(v,b)},[l,i]),c=y.useMemo(()=>E(g({},l),{list(){return M(this,null,function*(){const b=yield l.list();return r==null||r(),b})}}),[l,r]);y.useEffect(()=>{window.__cuadraThreadListAdapter=c,window.__cuadraThreadListRuntime=null},[c]);const d=y.useMemo(()=>mo(e,E(g({},t),{onThreadIdUpdate:u})),[e,t,u]),h=y.useMemo(()=>a?yo():void 0,[a]),f=y.useCallback(()=>wa(d,{adapters:g({},h&&{attachments:h})}),[d,h]),m=_a({adapter:c,runtimeHook:f});return y.useEffect(()=>{window.__cuadraThreadListRuntime=m},[m]),p.jsx(fa,{runtime:m,children:o})}function Nv(){}function Lv(){}function cp(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const dp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,hp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fp={};function bo(e,t){return(fp.jsx?hp:dp).test(e)}const pp=/[ \t\n\f\r]/g;function mp(e){return typeof e=="object"?e.type==="text"?wo(e.value):!1:wo(e)}function wo(e){return e.replace(pp,"")===""}class hn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}hn.prototype.normal={},hn.prototype.property={},hn.prototype.space=void 0;function xo(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new hn(n,r,t)}function ri(e){return e.toLowerCase()}class ze{constructor(t,n){this.attribute=n,this.property=t}}ze.prototype.attribute="",ze.prototype.booleanish=!1,ze.prototype.boolean=!1,ze.prototype.commaOrSpaceSeparated=!1,ze.prototype.commaSeparated=!1,ze.prototype.defined=!1,ze.prototype.mustUseProperty=!1,ze.prototype.number=!1,ze.prototype.overloadedBoolean=!1,ze.prototype.property="",ze.prototype.spaceSeparated=!1,ze.prototype.space=void 0;let gp=0;const Y=Et(),Se=Et(),ii=Et(),D=Et(),ce=Et(),$t=Et(),He=Et();function Et(){return Cu(2,++gp)}const si=Object.freeze(Object.defineProperty({__proto__:null,boolean:Y,booleanish:Se,commaOrSpaceSeparated:He,commaSeparated:$t,number:D,overloadedBoolean:ii,spaceSeparated:ce},Symbol.toStringTag,{value:"Module"})),ai=Object.keys(si);class oi extends ze{constructor(t,n,r,i){let s=-1;if(super(t,n),vo(this,"space",i),typeof r=="number")for(;++s<ai.length;){const a=ai[s];vo(this,ai[s],(r&si[a])===si[a])}}}oi.prototype.defined=!0;function vo(e,t,n){n&&(e[t]=n)}function Ht(e){const t={},n={};for(const[r,i]of Object.entries(e.properties)){const s=new oi(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(s.mustUseProperty=!0),t[r]=s,n[ri(r)]=r,n[ri(s.attribute)]=r}return new hn(t,n,e.space)}const So=Ht({properties:{ariaActiveDescendant:null,ariaAtomic:Se,ariaAutoComplete:null,ariaBusy:Se,ariaChecked:Se,ariaColCount:D,ariaColIndex:D,ariaColSpan:D,ariaControls:ce,ariaCurrent:null,ariaDescribedBy:ce,ariaDetails:null,ariaDisabled:Se,ariaDropEffect:ce,ariaErrorMessage:null,ariaExpanded:Se,ariaFlowTo:ce,ariaGrabbed:Se,ariaHasPopup:null,ariaHidden:Se,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ce,ariaLevel:D,ariaLive:null,ariaModal:Se,ariaMultiLine:Se,ariaMultiSelectable:Se,ariaOrientation:null,ariaOwns:ce,ariaPlaceholder:null,ariaPosInSet:D,ariaPressed:Se,ariaReadOnly:Se,ariaRelevant:null,ariaRequired:Se,ariaRoleDescription:ce,ariaRowCount:D,ariaRowIndex:D,ariaRowSpan:D,ariaSelected:Se,ariaSetSize:D,ariaSort:null,ariaValueMax:D,ariaValueMin:D,ariaValueNow:D,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function ko(e,t){return t in e?e[t]:t}function _o(e,t){return ko(e,t.toLowerCase())}const yp=Ht({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:$t,acceptCharset:ce,accessKey:ce,action:null,allow:null,allowFullScreen:Y,allowPaymentRequest:Y,allowUserMedia:Y,alt:null,as:null,async:Y,autoCapitalize:null,autoComplete:ce,autoFocus:Y,autoPlay:Y,blocking:ce,capture:null,charSet:null,checked:Y,cite:null,className:ce,cols:D,colSpan:null,content:null,contentEditable:Se,controls:Y,controlsList:ce,coords:D|$t,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Y,defer:Y,dir:null,dirName:null,disabled:Y,download:ii,draggable:Se,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Y,formTarget:null,headers:ce,height:D,hidden:ii,high:D,href:null,hrefLang:null,htmlFor:ce,httpEquiv:ce,id:null,imageSizes:null,imageSrcSet:null,inert:Y,inputMode:null,integrity:null,is:null,isMap:Y,itemId:null,itemProp:ce,itemRef:ce,itemScope:Y,itemType:ce,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Y,low:D,manifest:null,max:null,maxLength:D,media:null,method:null,min:null,minLength:D,multiple:Y,muted:Y,name:null,nonce:null,noModule:Y,noValidate:Y,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:Y,optimum:D,pattern:null,ping:ce,placeholder:null,playsInline:Y,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Y,referrerPolicy:null,rel:ce,required:Y,reversed:Y,rows:D,rowSpan:D,sandbox:ce,scope:null,scoped:Y,seamless:Y,selected:Y,shadowRootClonable:Y,shadowRootDelegatesFocus:Y,shadowRootMode:null,shape:null,size:D,sizes:null,slot:null,span:D,spellCheck:Se,src:null,srcDoc:null,srcLang:null,srcSet:null,start:D,step:null,style:null,tabIndex:D,target:null,title:null,translate:null,type:null,typeMustMatch:Y,useMap:null,value:Se,width:D,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ce,axis:null,background:null,bgColor:null,border:D,borderColor:null,bottomMargin:D,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Y,declare:Y,event:null,face:null,frame:null,frameBorder:null,hSpace:D,leftMargin:D,link:null,longDesc:null,lowSrc:null,marginHeight:D,marginWidth:D,noResize:Y,noHref:Y,noShade:Y,noWrap:Y,object:null,profile:null,prompt:null,rev:null,rightMargin:D,rules:null,scheme:null,scrolling:Se,standby:null,summary:null,text:null,topMargin:D,valueType:null,version:null,vAlign:null,vLink:null,vSpace:D,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Y,disableRemotePlayback:Y,prefix:null,property:null,results:D,security:null,unselectable:null},space:"html",transform:_o}),bp=Ht({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:He,accentHeight:D,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:D,amplitude:D,arabicForm:null,ascent:D,attributeName:null,attributeType:null,azimuth:D,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:D,by:null,calcMode:null,capHeight:D,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:D,diffuseConstant:D,direction:null,display:null,dur:null,divisor:D,dominantBaseline:null,download:Y,dx:null,dy:null,edgeMode:null,editable:null,elevation:D,enableBackground:null,end:null,event:null,exponent:D,externalResourcesRequired:null,fill:null,fillOpacity:D,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:$t,g2:$t,glyphName:$t,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:D,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:D,horizOriginX:D,horizOriginY:D,id:null,ideographic:D,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:D,k:D,k1:D,k2:D,k3:D,k4:D,kernelMatrix:He,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:D,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:D,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:D,overlineThickness:D,paintOrder:null,panose1:null,path:null,pathLength:D,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ce,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:D,pointsAtY:D,pointsAtZ:D,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:He,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:He,rev:He,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:He,requiredFeatures:He,requiredFonts:He,requiredFormats:He,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:D,specularExponent:D,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:D,strikethroughThickness:D,string:null,stroke:null,strokeDashArray:He,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:D,strokeOpacity:D,strokeWidth:null,style:null,surfaceScale:D,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:He,tabIndex:D,tableValues:null,target:null,targetX:D,targetY:D,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:He,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:D,underlineThickness:D,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:D,values:null,vAlphabetic:D,vMathematical:D,vectorEffect:null,vHanging:D,vIdeographic:D,version:null,vertAdvY:D,vertOriginX:D,vertOriginY:D,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:D,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:ko}),To=Ht({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=Ht({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:_o}),Co=Ht({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),wp={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"},xp=/[A-Z]/g,Eo=/-[a-z]/g,vp=/^data[-\w.:]+$/i;function Sp(e,t){const n=ri(t);let r=t,i=ze;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&vp.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Eo,_p);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Eo.test(s)){let a=s.replace(xp,kp);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=oi}return new i(r,t)}function kp(e){return"-"+e.toLowerCase()}function _p(e){return e.charAt(1).toUpperCase()}const Tp=xo([So,yp,To,Io,Co],"html"),li=xo([So,bp,To,Io,Co],"svg");function Ip(e){return e.join(" ").trim()}var qt={},ui,Ao;function Cp(){if(Ao)return ui;Ao=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
- `,u="/",c="*",d="",h="comment",f="declaration";function m(b,x){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];x=x||{};var C=1,_=1;function F(L){var N=L.match(t);N&&(C+=N.length);var G=L.lastIndexOf(l);_=~G?L.length-G:_+L.length}function z(){var L={line:C,column:_};return function(N){return N.position=new I(L),j(),N}}function I(L){this.start=L,this.end={line:C,column:_},this.source=x.source}I.prototype.content=b;function H(L){var N=new Error(x.source+":"+C+":"+_+": "+L);if(N.reason=L,N.filename=x.source,N.line=C,N.column=_,N.source=b,!x.silent)throw N}function q(L){var N=L.exec(b);if(N){var G=N[0];return F(G),b=b.slice(G.length),N}}function j(){q(n)}function k(L){var N;for(L=L||[];N=O();)N!==!1&&L.push(N);return L}function O(){var L=z();if(!(u!=b.charAt(0)||c!=b.charAt(1))){for(var N=2;d!=b.charAt(N)&&(c!=b.charAt(N)||u!=b.charAt(N+1));)++N;if(N+=2,d===b.charAt(N-1))return H("End of comment missing");var G=b.slice(2,N-2);return _+=2,F(G),b=b.slice(N),_+=2,L({type:h,comment:G})}}function P(){var L=z(),N=q(r);if(N){if(O(),!q(i))return H("property missing ':'");var G=q(s),J=L({type:f,property:v(N[0].replace(e,d)),value:G?v(G[0].replace(e,d)):d});return q(a),J}}function R(){var L=[];k(L);for(var N;N=P();)N!==!1&&(L.push(N),k(L));return L}return j(),R()}function v(b){return b?b.replace(o,d):d}return ui=m,ui}var Mo;function Ep(){if(Mo)return qt;Mo=1;var e=qt&&qt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qt,"__esModule",{value:!0}),qt.default=n;const t=e(Cp());function n(r,i){let s=null;if(!r||typeof r!="string")return s;const a=(0,t.default)(r),o=typeof i=="function";return a.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;o?i(u,c,l):c&&(s=s||{},s[u]=c)}),s}return qt}var fn={},Po;function Ap(){if(Po)return fn;Po=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,s=function(u){return!u||n.test(u)||e.test(u)},a=function(u,c){return c.toUpperCase()},o=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),s(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(i,o):u=u.replace(r,o),u.replace(t,a))};return fn.camelCase=l,fn}var pn,No;function Mp(){if(No)return pn;No=1;var e=pn&&pn.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(Ep()),n=Ap();function r(i,s){var a={};return!i||typeof i!="string"||(0,t.default)(i,function(o,l){o&&l&&(a[(0,n.camelCase)(o,s)]=l)}),a}return r.default=r,pn=r,pn}var Pp=Mp();const Np=Nn(Pp),Lo=Do("end"),ci=Do("start");function Do(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Lp(e){const t=ci(e),n=Lo(e);if(t&&n)return{start:t,end:n}}function mn(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?di(e):""}function di(e){return Fo(e&&e.line)+":"+Fo(e&&e.column)}function Oo(e){return di(e&&e.start)+"-"+di(e&&e.end)}function Fo(e){return e&&typeof e=="number"?e:1}class Me extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},a=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s=g({},n)),typeof t=="string"?i=t:!s.cause&&t&&(a=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?s.ruleId=r:(s.source=r.slice(0,l),s.ruleId=r.slice(l+1))}if(!s.place&&s.ancestors&&s.ancestors){const l=s.ancestors[s.ancestors.length-1];l&&(s.place=l.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=mn(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=a&&s.cause&&typeof s.cause.stack=="string"?s.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 hi={}.hasOwnProperty,Dp=new Map,Op=/[A-Z]/g,Fp=new Set(["table","tbody","thead","tfoot","tr"]),Bp=new Set(["td","th"]),Bo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function zp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Wp(n,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");r=Vp(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?li:Tp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=zo(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function zo(e,t,n){if(t.type==="element")return Rp(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return jp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return $p(e,t,n);if(t.type==="mdxjsEsm")return Up(e,t);if(t.type==="root")return Hp(e,t,n);if(t.type==="text")return qp(e,t)}function Rp(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=li,e.schema=i),e.ancestors.push(t);const s=jo(e,t.tagName,!1),a=Jp(e,t);let o=pi(e,t);return Fp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!mp(l):!0})),Ro(e,a,s,t),fi(a,o),e.ancestors.pop(),e.schema=r,e.create(t,s,a,n)}function jp(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}gn(e,t.position)}function Up(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);gn(e,t.position)}function $p(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=li,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:jo(e,t.name,!0),a=Kp(e,t),o=pi(e,t);return Ro(e,a,s,t),fi(a,o),e.ancestors.pop(),e.schema=r,e.create(t,s,a,n)}function Hp(e,t,n){const r={};return fi(r,pi(e,t)),e.create(t,e.Fragment,r,n)}function qp(e,t){return t.value}function Ro(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function fi(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Vp(e,t,n){return r;function r(i,s,a,o){const u=Array.isArray(a.children)?n:t;return o?u(s,a,o):u(s,a)}}function Wp(e,t){return n;function n(r,i,s,a){const o=Array.isArray(s.children),l=ci(r);return t(i,s,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Jp(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&hi.call(t.properties,i)){const s=Yp(e,i,t.properties[i]);if(s){const[a,o]=s;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&Bp.has(t.tagName)?r=o:n[a]=o}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Kp(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const a=s.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else gn(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else gn(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function pi(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:Dp;for(;++r<t.children.length;){const s=t.children[r];let a;if(e.passKeys){const l=s.type==="element"?s.tagName:s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement"?s.name:void 0;if(l){const u=i.get(l)||0;a=l+"-"+u,i.set(l,u+1)}}const o=zo(e,s,a);o!==void 0&&n.push(o)}return n}function Yp(e,t,n){const r=Sp(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?cp(n):Ip(n)),r.property==="style"){let i=typeof n=="object"?n:Gp(e,String(n));return e.stylePropertyNameCase==="css"&&(i=Xp(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?wp[r.property]||r.property:r.attribute,n]}}function Gp(e,t){try{return Np(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,i=new Me("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=Bo+"#cannot-parse-style-attribute",i}}function jo(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let s=-1,a;for(;++s<i.length;){const o=bo(i[s])?{type:"Identifier",name:i[s]}:{type:"Literal",value:i[s]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(s&&o.type==="Literal"),optional:!1}:o}r=a}else r=bo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const i=r.value;return hi.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);gn(e)}function gn(e,t){const n=new Me("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=Bo+"#cannot-handle-mdx-estrees-without-createevaluater",n}function Xp(e){const t={};let n;for(n in e)hi.call(e,n)&&(t[Qp(n)]=e[n]);return t}function Qp(e){let t=e.replace(Op,Zp);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Zp(e){return"-"+e.toLowerCase()}const mi={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"]},em={};function gi(e,t){const n=em,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Uo(e,r,i)}function Uo(e,t,n){if(tm(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return $o(e.children,t,n)}return Array.isArray(e)?$o(e,t,n):""}function $o(e,t,n){const r=[];let i=-1;for(;++i<e.length;)r[i]=Uo(e[i],t,n);return r.join("")}function tm(e){return!!(e&&typeof e=="object")}const Ho=document.createElement("i");function yi(e){const t="&"+e+";";Ho.innerHTML=t;const n=Ho.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function qe(e,t,n,r){const i=e.length;let s=0,a;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);s<r.length;)a=r.slice(s,s+1e4),a.unshift(t,0),e.splice(...a),s+=1e4,t+=1e4}function Je(e,t){return e.length>0?(qe(e,e.length,0,t),e):t}const qo={}.hasOwnProperty;function Vo(e){const t={};let n=-1;for(;++n<e.length;)nm(t,e[n]);return t}function nm(e,t){let n;for(n in t){const i=(qo.call(e,n)?e[n]:void 0)||(e[n]={}),s=t[n];let a;if(s)for(a in s){qo.call(i,a)||(i[a]=[]);const o=s[a];rm(i[a],Array.isArray(o)?o:o?[o]:[])}}}function rm(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);qe(e,0,0,r)}function Wo(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function tt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Oe=wt(/[A-Za-z]/),Pe=wt(/[\dA-Za-z]/),im=wt(/[#-'*+\--9=?A-Z^-~]/);function rr(e){return e!==null&&(e<32||e===127)}const bi=wt(/\d/),sm=wt(/[\dA-Fa-f]/),am=wt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function le(e){return e!==null&&(e<0||e===32)}function re(e){return e===-2||e===-1||e===32}const ir=wt(new RegExp("\\p{P}|\\p{S}","u")),At=wt(/\s/);function wt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Vt(e){const t=[];let n=-1,r=0,i=0;for(;++n<e.length;){const s=e.charCodeAt(n);let a="";if(s===37&&Pe(e.charCodeAt(n+1))&&Pe(e.charCodeAt(n+2)))i=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(a=String.fromCharCode(s));else if(s>55295&&s<57344){const o=e.charCodeAt(n+1);s<56320&&o>56319&&o<57344?(a=String.fromCharCode(s,o),i=1):a="�"}else a=String.fromCharCode(s);a&&(t.push(e.slice(r,n),encodeURIComponent(a)),r=n+i+1,a=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function se(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return a;function a(l){return re(l)?(e.enter(n),o(l)):t(l)}function o(l){return re(l)&&s++<i?(e.consume(l),o):(e.exit(n),t(l))}}const om={tokenize:lm};function lm(e){const t=e.attempt(this.parser.constructs.contentInitial,r,i);let n;return t;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),se(e,t,"linePrefix")}function i(o){return e.enter("paragraph"),s(o)}function s(o){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return W(o)?(e.consume(o),e.exit("chunkText"),s):(e.consume(o),a)}}const um={tokenize:cm},Jo={tokenize:dm};function cm(e){const t=this,n=[];let r=0,i,s,a;return o;function o(_){if(r<n.length){const F=n[r];return t.containerState=F[1],e.attempt(F[0].continuation,l,u)(_)}return u(_)}function l(_){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&C();const F=t.events.length;let z=F,I;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){I=t.events[z][1].end;break}x(r);let H=F;for(;H<t.events.length;)t.events[H][1].end=g({},I),H++;return qe(t.events,z+1,0,t.events.slice(F)),t.events.length=H,u(_)}return o(_)}function u(_){if(r===n.length){if(!i)return h(_);if(i.currentConstruct&&i.currentConstruct.concrete)return m(_);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Jo,c,d)(_)}function c(_){return i&&C(),x(r),h(_)}function d(_){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,m(_)}function h(_){return t.containerState={},e.attempt(Jo,f,m)(_)}function f(_){return r++,n.push([t.currentConstruct,t.containerState]),h(_)}function m(_){if(_===null){i&&C(),x(0),e.consume(_);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:s}),v(_)}function v(_){if(_===null){b(e.exit("chunkFlow"),!0),x(0),e.consume(_);return}return W(_)?(e.consume(_),b(e.exit("chunkFlow")),r=0,t.interrupt=void 0,o):(e.consume(_),v)}function b(_,F){const z=t.sliceStream(_);if(F&&z.push(null),_.previous=s,s&&(s.next=_),s=_,i.defineSkip(_.start),i.write(z),t.parser.lazy[_.start.line]){let I=i.events.length;for(;I--;)if(i.events[I][1].start.offset<a&&(!i.events[I][1].end||i.events[I][1].end.offset>a))return;const H=t.events.length;let q=H,j,k;for(;q--;)if(t.events[q][0]==="exit"&&t.events[q][1].type==="chunkFlow"){if(j){k=t.events[q][1].end;break}j=!0}for(x(r),I=H;I<t.events.length;)t.events[I][1].end=g({},k),I++;qe(t.events,q+1,0,t.events.slice(H)),t.events.length=I}}function x(_){let F=n.length;for(;F-- >_;){const z=n[F];t.containerState=z[1],z[0].exit.call(t,e)}n.length=_}function C(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function dm(e,t,n){return se(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Wt(e){if(e===null||le(e)||At(e))return 1;if(ir(e))return 2}function sr(e,t,n){const r=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!r.includes(s)&&(t=s(t,n),r.push(s))}return t}const wi={name:"attention",resolveAll:hm,tokenize:fm};function hm(e,t){let n=-1,r,i,s,a,o,l,u,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d=g({},e[r][1].end),h=g({},e[n][1].start);Ko(d,-l),Ko(h,l),a={type:l>1?"strongSequence":"emphasisSequence",start:d,end:g({},e[r][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:g({},e[n][1].start),end:h},s={type:l>1?"strongText":"emphasisText",start:g({},e[r][1].end),end:g({},e[n][1].start)},i={type:l>1?"strong":"emphasis",start:g({},a.start),end:g({},o.end)},e[r][1].end=g({},a.start),e[n][1].start=g({},o.end),u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Je(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Je(u,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",s,t]]),u=Je(u,sr(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Je(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Je(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,qe(e,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function fm(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=Wt(r);let s;return a;function a(l){return s=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===s)return e.consume(l),o;const u=e.exit("attentionSequence"),c=Wt(l),d=!c||c===2&&i||n.includes(l),h=!i||i===2&&c||n.includes(r);return u._open=!!(s===42?d:d&&(i||!h)),u._close=!!(s===42?h:h&&(c||!d)),t(l)}}function Ko(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const pm={name:"autolink",tokenize:mm};function mm(e,t,n){let r=0;return i;function i(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(f){return Oe(f)?(e.consume(f),a):f===64?n(f):u(f)}function a(f){return f===43||f===45||f===46||Pe(f)?(r=1,o(f)):u(f)}function o(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||Pe(f))&&r++<32?(e.consume(f),o):(r=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||rr(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):im(f)?(e.consume(f),u):n(f)}function c(f){return Pe(f)?d(f):n(f)}function d(f){return f===46?(e.consume(f),r=0,c):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))&&r++<63){const m=f===45?h:d;return e.consume(f),m}return n(f)}}const yn={partial:!0,tokenize:gm};function gm(e,t,n){return r;function r(s){return re(s)?se(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||W(s)?t(s):n(s)}}const Yo={continuation:{tokenize:bm},exit:wm,name:"blockQuote",tokenize:ym};function ym(e,t,n){const r=this;return i;function i(a){if(a===62){const o=r.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),s}return n(a)}function s(a){return re(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function bm(e,t,n){const r=this;return i;function i(a){return re(a)?se(e,s,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):s(a)}function s(a){return e.attempt(Yo,t,n)(a)}}function wm(e){e.exit("blockQuote")}const Go={name:"characterEscape",tokenize:xm};function xm(e,t,n){return r;function r(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),i}function i(s){return am(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}const Xo={name:"characterReference",tokenize:vm};function vm(e,t,n){const r=this;let i=0,s,a;return o;function o(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),s=31,a=Pe,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,a=sm,c):(e.enter("characterReferenceValue"),s=7,a=bi,c(d))}function c(d){if(d===59&&i){const h=e.exit("characterReferenceValue");return a===Pe&&!yi(r.sliceSerialize(h))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(d)&&i++<s?(e.consume(d),c):n(d)}}const Qo={partial:!0,tokenize:km},Zo={concrete:!0,name:"codeFenced",tokenize:Sm};function Sm(e,t,n){const r=this,i={partial:!0,tokenize:z};let s=0,a=0,o;return l;function l(I){return u(I)}function u(I){const H=r.events[r.events.length-1];return s=H&&H[1].type==="linePrefix"?H[2].sliceSerialize(H[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(I)}function c(I){return I===o?(a++,e.consume(I),c):a<3?n(I):(e.exit("codeFencedFenceSequence"),re(I)?se(e,d,"whitespace")(I):d(I))}function d(I){return I===null||W(I)?(e.exit("codeFencedFence"),r.interrupt?t(I):e.check(Qo,v,F)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(I))}function h(I){return I===null||W(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(I)):re(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),se(e,f,"whitespace")(I)):I===96&&I===o?n(I):(e.consume(I),h)}function f(I){return I===null||W(I)?d(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(I))}function m(I){return I===null||W(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(I)):I===96&&I===o?n(I):(e.consume(I),m)}function v(I){return e.attempt(i,F,b)(I)}function b(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),x}function x(I){return s>0&&re(I)?se(e,C,"linePrefix",s+1)(I):C(I)}function C(I){return I===null||W(I)?e.check(Qo,v,F)(I):(e.enter("codeFlowValue"),_(I))}function _(I){return I===null||W(I)?(e.exit("codeFlowValue"),C(I)):(e.consume(I),_)}function F(I){return e.exit("codeFenced"),t(I)}function z(I,H,q){let j=0;return k;function k(N){return I.enter("lineEnding"),I.consume(N),I.exit("lineEnding"),O}function O(N){return I.enter("codeFencedFence"),re(N)?se(I,P,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):P(N)}function P(N){return N===o?(I.enter("codeFencedFenceSequence"),R(N)):q(N)}function R(N){return N===o?(j++,I.consume(N),R):j>=a?(I.exit("codeFencedFenceSequence"),re(N)?se(I,L,"whitespace")(N):L(N)):q(N)}function L(N){return N===null||W(N)?(I.exit("codeFencedFence"),H(N)):q(N)}}}function km(e,t,n){const r=this;return i;function i(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s)}function s(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}const xi={name:"codeIndented",tokenize:Tm},_m={partial:!0,tokenize:Im};function Tm(e,t,n){const r=this;return i;function i(u){return e.enter("codeIndented"),se(e,s,"linePrefix",5)(u)}function s(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?l(u):W(u)?e.attempt(_m,a,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||W(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Im(e,t,n){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?n(a):W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):se(e,s,"linePrefix",5)(a)}function s(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):W(a)?i(a):n(a)}}const Cm={name:"codeText",previous:Am,resolve:Em,tokenize:Mm};function Em(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function Am(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Mm(e,t,n){let r=0,i,s;return a;function a(d){return e.enter("codeText"),e.enter("codeTextSequence"),o(d)}function o(d){return d===96?(e.consume(d),r++,o):(e.exit("codeTextSequence"),l(d))}function l(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(s=e.enter("codeTextSequence"),i=0,c(d)):W(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||W(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),i++,c):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(s.type="codeTextData",u(d))}}class Pm{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,n){const r=n==null?Number.POSITIVE_INFINITY:n;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&bn(this.left,r),s.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),bn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bn(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 n=this.left.splice(t,Number.POSITIVE_INFINITY);bn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);bn(this.left,n.reverse())}}}function bn(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function el(e){const t={};let n=-1,r,i,s,a,o,l,u;const c=new Pm(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(r=c.get(n),n&&r[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,s=0,s<l.length&&l[s][1].type==="lineEndingBlank"&&(s+=2),s<l.length&&l[s][1].type==="content"))for(;++s<l.length&&l[s][1].type!=="content";)l[s][1].type==="chunkText"&&(l[s][1]._isInFirstContentOfListItem=!0,s++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,Nm(c,n)),n=t[n],u=!0);else if(r[1]._container){for(s=n,i=void 0;s--;)if(a=c.get(s),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(c.get(i)[1].type="lineEndingBlank"),a[1].type="lineEnding",i=s);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;i&&(r[1].end=g({},c.get(i)[1].start),o=c.slice(i,n),o.unshift(r),c.splice(i,n-i+1,o))}}return qe(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function Nm(e,t){const n=e.get(t)[1],r=e.get(t)[2];let i=t-1;const s=[];let a=n._tokenizer;a||(a=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,l=[],u={};let c,d,h=-1,f=n,m=0,v=0;const b=[v];for(;f;){for(;e.get(++i)[1]!==f;);s.push(i),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(c),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++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(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),h=b.length;h--;){const x=o.slice(b[h],b[h+1]),C=s.pop();l.push([C,C+x.length-1]),e.splice(C,2,x)}for(l.reverse(),h=-1;++h<l.length;)u[m+l[h][0]]=m+l[h][1],m+=l[h][1]-l[h][0]-1;return u}const Lm={resolve:Om,tokenize:Fm},Dm={partial:!0,tokenize:Bm};function Om(e){return el(e),e}function Fm(e,t){let n;return r;function r(o){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(o)}function i(o){return o===null?s(o):W(o)?e.check(Dm,a,s)(o):(e.consume(o),i)}function s(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function Bm(e,t,n){const r=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),se(e,s,"linePrefix")}function s(a){if(a===null||W(a))return n(a);const o=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}function tl(e,t,n,r,i,s,a,o,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return d;function d(x){return x===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(x),e.exit(s),h):x===null||x===32||x===41||rr(x)?n(x):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(x))}function h(x){return x===62?(e.enter(s),e.consume(x),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(x))}function f(x){return x===62?(e.exit("chunkString"),e.exit(o),h(x)):x===null||x===60||W(x)?n(x):(e.consume(x),x===92?m:f)}function m(x){return x===60||x===62||x===92?(e.consume(x),f):f(x)}function v(x){return!c&&(x===null||x===41||le(x))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(x)):c<u&&x===40?(e.consume(x),c++,v):x===41?(e.consume(x),c--,v):x===null||x===32||x===40||rr(x)?n(x):(e.consume(x),x===92?b:v)}function b(x){return x===40||x===41||x===92?(e.consume(x),v):v(x)}}function nl(e,t,n,r,i,s){const a=this;let o=0,l;return u;function u(f){return e.enter(r),e.enter(i),e.consume(f),e.exit(i),e.enter(s),c}function c(f){return o>999||f===null||f===91||f===93&&!l||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(e.exit(s),e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||W(f)||o++>999?(e.exit("chunkString"),c(f)):(e.consume(f),l||(l=!re(f)),f===92?h:d)}function h(f){return f===91||f===92||f===93?(e.consume(f),o++,d):d(f)}}function rl(e,t,n,r,i,s){let a;return o;function o(h){return h===34||h===39||h===40?(e.enter(r),e.enter(i),e.consume(h),e.exit(i),a=h===40?41:h,l):n(h)}function l(h){return h===a?(e.enter(i),e.consume(h),e.exit(i),e.exit(r),t):(e.enter(s),u(h))}function u(h){return h===a?(e.exit(s),l(a)):h===null?n(h):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),se(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===a||h===null||W(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?d:c)}function d(h){return h===a||h===92?(e.consume(h),c):c(h)}}function wn(e,t){let n;return r;function r(i){return W(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):re(i)?se(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const zm={name:"definition",tokenize:jm},Rm={partial:!0,tokenize:Um};function jm(e,t,n){const r=this;let i;return s;function s(f){return e.enter("definition"),a(f)}function a(f){return nl.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=tt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return le(f)?wn(e,u)(f):u(f)}function u(f){return tl(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(Rm,d,d)(f)}function d(f){return re(f)?se(e,h,"whitespace")(f):h(f)}function h(f){return f===null||W(f)?(e.exit("definition"),r.parser.defined.push(i),t(f)):n(f)}}function Um(e,t,n){return r;function r(o){return le(o)?wn(e,i)(o):n(o)}function i(o){return rl(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return re(o)?se(e,a,"whitespace")(o):a(o)}function a(o){return o===null||W(o)?t(o):n(o)}}const $m={name:"hardBreakEscape",tokenize:Hm};function Hm(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return W(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const qm={name:"headingAtx",resolve:Vm,tokenize:Wm};function Vm(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},qe(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function Wm(e,t,n){let r=0;return i;function i(c){return e.enter("atxHeading"),s(c)}function s(c){return e.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&r++<6?(e.consume(c),a):c===null||le(c)?(e.exit("atxHeadingSequence"),o(c)):n(c)}function o(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||W(c)?(e.exit("atxHeading"),t(c)):re(c)?se(e,o,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),o(c))}function u(c){return c===null||c===35||le(c)?(e.exit("atxHeadingText"),o(c)):(e.consume(c),u)}}const Jm=["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"],Km={concrete:!0,name:"htmlFlow",resolveTo:Xm,tokenize:Qm},Ym={partial:!0,tokenize:eg},Gm={partial:!0,tokenize:Zm};function Xm(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 Qm(e,t,n){const r=this;let i,s,a,o,l;return u;function u(S){return c(S)}function c(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),d}function d(S){return S===33?(e.consume(S),h):S===47?(e.consume(S),s=!0,v):S===63?(e.consume(S),i=3,r.interrupt?t:w):Oe(S)?(e.consume(S),a=String.fromCharCode(S),b):n(S)}function h(S){return S===45?(e.consume(S),i=2,f):S===91?(e.consume(S),i=5,o=0,m):Oe(S)?(e.consume(S),i=4,r.interrupt?t:w):n(S)}function f(S){return S===45?(e.consume(S),r.interrupt?t:w):n(S)}function m(S){const Ie="CDATA[";return S===Ie.charCodeAt(o++)?(e.consume(S),o===Ie.length?r.interrupt?t:P:m):n(S)}function v(S){return Oe(S)?(e.consume(S),a=String.fromCharCode(S),b):n(S)}function b(S){if(S===null||S===47||S===62||le(S)){const Ie=S===47,lt=a.toLowerCase();return!Ie&&!s&&il.includes(lt)?(i=1,r.interrupt?t(S):P(S)):Jm.includes(a.toLowerCase())?(i=6,Ie?(e.consume(S),x):r.interrupt?t(S):P(S)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):s?C(S):_(S))}return S===45||Pe(S)?(e.consume(S),a+=String.fromCharCode(S),b):n(S)}function x(S){return S===62?(e.consume(S),r.interrupt?t:P):n(S)}function C(S){return re(S)?(e.consume(S),C):k(S)}function _(S){return S===47?(e.consume(S),k):S===58||S===95||Oe(S)?(e.consume(S),F):re(S)?(e.consume(S),_):k(S)}function F(S){return S===45||S===46||S===58||S===95||Pe(S)?(e.consume(S),F):z(S)}function z(S){return S===61?(e.consume(S),I):re(S)?(e.consume(S),z):_(S)}function I(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),l=S,H):re(S)?(e.consume(S),I):q(S)}function H(S){return S===l?(e.consume(S),l=null,j):S===null||W(S)?n(S):(e.consume(S),H)}function q(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||le(S)?z(S):(e.consume(S),q)}function j(S){return S===47||S===62||re(S)?_(S):n(S)}function k(S){return S===62?(e.consume(S),O):n(S)}function O(S){return S===null||W(S)?P(S):re(S)?(e.consume(S),O):n(S)}function P(S){return S===45&&i===2?(e.consume(S),G):S===60&&i===1?(e.consume(S),J):S===62&&i===4?(e.consume(S),ge):S===63&&i===3?(e.consume(S),w):S===93&&i===5?(e.consume(S),de):W(S)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(Ym,ye,R)(S)):S===null||W(S)?(e.exit("htmlFlowData"),R(S)):(e.consume(S),P)}function R(S){return e.check(Gm,L,ye)(S)}function L(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),N}function N(S){return S===null||W(S)?R(S):(e.enter("htmlFlowData"),P(S))}function G(S){return S===45?(e.consume(S),w):P(S)}function J(S){return S===47?(e.consume(S),a="",Z):P(S)}function Z(S){if(S===62){const Ie=a.toLowerCase();return il.includes(Ie)?(e.consume(S),ge):P(S)}return Oe(S)&&a.length<8?(e.consume(S),a+=String.fromCharCode(S),Z):P(S)}function de(S){return S===93?(e.consume(S),w):P(S)}function w(S){return S===62?(e.consume(S),ge):S===45&&i===2?(e.consume(S),w):P(S)}function ge(S){return S===null||W(S)?(e.exit("htmlFlowData"),ye(S)):(e.consume(S),ge)}function ye(S){return e.exit("htmlFlow"),t(S)}}function Zm(e,t,n){const r=this;return i;function i(a){return W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):n(a)}function s(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}function eg(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(yn,t,n)}}const tg={name:"htmlText",tokenize:ng};function ng(e,t,n){const r=this;let i,s,a;return o;function o(w){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(w),l}function l(w){return w===33?(e.consume(w),u):w===47?(e.consume(w),z):w===63?(e.consume(w),_):Oe(w)?(e.consume(w),q):n(w)}function u(w){return w===45?(e.consume(w),c):w===91?(e.consume(w),s=0,m):Oe(w)?(e.consume(w),C):n(w)}function c(w){return w===45?(e.consume(w),f):n(w)}function d(w){return w===null?n(w):w===45?(e.consume(w),h):W(w)?(a=d,J(w)):(e.consume(w),d)}function h(w){return w===45?(e.consume(w),f):d(w)}function f(w){return w===62?G(w):w===45?h(w):d(w)}function m(w){const ge="CDATA[";return w===ge.charCodeAt(s++)?(e.consume(w),s===ge.length?v:m):n(w)}function v(w){return w===null?n(w):w===93?(e.consume(w),b):W(w)?(a=v,J(w)):(e.consume(w),v)}function b(w){return w===93?(e.consume(w),x):v(w)}function x(w){return w===62?G(w):w===93?(e.consume(w),x):v(w)}function C(w){return w===null||w===62?G(w):W(w)?(a=C,J(w)):(e.consume(w),C)}function _(w){return w===null?n(w):w===63?(e.consume(w),F):W(w)?(a=_,J(w)):(e.consume(w),_)}function F(w){return w===62?G(w):_(w)}function z(w){return Oe(w)?(e.consume(w),I):n(w)}function I(w){return w===45||Pe(w)?(e.consume(w),I):H(w)}function H(w){return W(w)?(a=H,J(w)):re(w)?(e.consume(w),H):G(w)}function q(w){return w===45||Pe(w)?(e.consume(w),q):w===47||w===62||le(w)?j(w):n(w)}function j(w){return w===47?(e.consume(w),G):w===58||w===95||Oe(w)?(e.consume(w),k):W(w)?(a=j,J(w)):re(w)?(e.consume(w),j):G(w)}function k(w){return w===45||w===46||w===58||w===95||Pe(w)?(e.consume(w),k):O(w)}function O(w){return w===61?(e.consume(w),P):W(w)?(a=O,J(w)):re(w)?(e.consume(w),O):j(w)}function P(w){return w===null||w===60||w===61||w===62||w===96?n(w):w===34||w===39?(e.consume(w),i=w,R):W(w)?(a=P,J(w)):re(w)?(e.consume(w),P):(e.consume(w),L)}function R(w){return w===i?(e.consume(w),i=void 0,N):w===null?n(w):W(w)?(a=R,J(w)):(e.consume(w),R)}function L(w){return w===null||w===34||w===39||w===60||w===61||w===96?n(w):w===47||w===62||le(w)?j(w):(e.consume(w),L)}function N(w){return w===47||w===62||le(w)?j(w):n(w)}function G(w){return w===62?(e.consume(w),e.exit("htmlTextData"),e.exit("htmlText"),t):n(w)}function J(w){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),Z}function Z(w){return re(w)?se(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):de(w)}function de(w){return e.enter("htmlTextData"),a(w)}}const vi={name:"labelEnd",resolveAll:ag,resolveTo:og,tokenize:lg},rg={tokenize:ug},ig={tokenize:cg},sg={tokenize:dg};function ag(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",t+=i}}return e.length!==n.length&&qe(e,0,e.length,n),e}function og(e,t){let n=e.length,r=0,i,s,a,o;for(;n--;)if(i=e[n][1],s){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(s=n,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(a=n);const l={type:e[s][1].type==="labelLink"?"link":"image",start:g({},e[s][1].start),end:g({},e[e.length-1][1].end)},u={type:"label",start:g({},e[s][1].start),end:g({},e[a][1].end)},c={type:"labelText",start:g({},e[s+r+2][1].end),end:g({},e[a-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Je(o,e.slice(s+1,s+r+3)),o=Je(o,[["enter",c,t]]),o=Je(o,sr(t.parser.constructs.insideSpan.null,e.slice(s+r+4,a-3),t)),o=Je(o,[["exit",c,t],e[a-2],e[a-1],["exit",u,t]]),o=Je(o,e.slice(a+1)),o=Je(o,[["exit",l,t]]),qe(e,s,e.length,o),e}function lg(e,t,n){const r=this;let i=r.events.length,s,a;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){s=r.events[i][1];break}return o;function o(h){return s?s._inactive?d(h):(a=r.parser.defined.includes(tt(r.sliceSerialize({start:s.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),l):n(h)}function l(h){return h===40?e.attempt(rg,c,a?c:d)(h):h===91?e.attempt(ig,c,a?u:d)(h):a?c(h):d(h)}function u(h){return e.attempt(sg,c,d)(h)}function c(h){return t(h)}function d(h){return s._balanced=!0,n(h)}}function ug(e,t,n){return r;function r(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),i}function i(d){return le(d)?wn(e,s)(d):s(d)}function s(d){return d===41?c(d):tl(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return le(d)?wn(e,l)(d):c(d)}function o(d){return n(d)}function l(d){return d===34||d===39||d===40?rl(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return le(d)?wn(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function cg(e,t,n){const r=this;return i;function i(o){return nl.call(r,e,s,a,"reference","referenceMarker","referenceString")(o)}function s(o){return r.parser.defined.includes(tt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function dg(e,t,n){return r;function r(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),i}function i(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):n(s)}}const hg={name:"labelStartImage",resolveAll:vi.resolveAll,tokenize:fg};function fg(e,t,n){const r=this;return i;function i(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),s}function s(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const pg={name:"labelStartLink",resolveAll:vi.resolveAll,tokenize:mg};function mg(e,t,n){const r=this;return i;function i(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),s}function s(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const Si={name:"lineEnding",tokenize:gg};function gg(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),se(e,t,"linePrefix")}}const ar={name:"thematicBreak",tokenize:yg};function yg(e,t,n){let r=0,i;return s;function s(u){return e.enter("thematicBreak"),a(u)}function a(u){return i=u,o(u)}function o(u){return u===i?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||W(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===i?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),re(u)?se(e,o,"whitespace")(u):o(u))}}const Re={continuation:{tokenize:vg},exit:kg,name:"list",tokenize:xg},bg={partial:!0,tokenize:_g},wg={partial:!0,tokenize:Sg};function xg(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const m=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:bi(f)){if(r.containerState.type||(r.containerState.type=m,e.enter(m,{_container:!0})),m==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(ar,n,u)(f):u(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return n(f)}function l(f){return bi(f)&&++a<10?(e.consume(f),l):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(yn,r.interrupt?n:c,e.attempt(bg,h,d))}function c(f){return r.containerState.initialBlankLine=!0,s++,h(f)}function d(f){return re(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),h):n(f)}function h(f){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function vg(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(yn,i,s);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,se(e,t,"listItemIndent",r.containerState.size+1)(o)}function s(o){return r.containerState.furtherBlankLines||!re(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(wg,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,se(e,e.attempt(Re,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Sg(e,t,n){const r=this;return se(e,i,"listItemIndent",r.containerState.size+1);function i(s){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(s):n(s)}}function kg(e){e.exit(this.containerState.type)}function _g(e,t,n){const r=this;return se(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const a=r.events[r.events.length-1];return!re(s)&&a&&a[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const sl={name:"setextUnderline",resolveTo:Tg,tokenize:Ig};function Tg(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const a={type:"setextHeading",start:g({},e[r][1].start),end:g({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",a,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end=g({},e[s][1].end)):e[r][1]=a,e.push(["exit",a,t]),e}function Ig(e,t,n){const r=this;let i;return s;function s(u){let c=r.events.length,d;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){d=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),i=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),re(u)?se(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Cg={tokenize:Eg};function Eg(e){const t=this,n=e.attempt(yn,r,e.attempt(this.parser.constructs.flowInitial,i,se(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Lm,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Ag={resolveAll:ol()},Mg=al("string"),Pg=al("text");function al(e){return{resolveAll:ol(e==="text"?Ng:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,a,o);return a;function a(c){return u(c)?s(c):o(c)}function o(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),s(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const d=i[c];let h=-1;if(d)for(;++h<d.length;){const f=d[h];if(!f.previous||f.previous.call(r,r.previous))return!0}return!1}}}function ol(e){return t;function t(n,r){let i=-1,s;for(;++i<=n.length;)s===void 0?n[i]&&n[i][1].type==="data"&&(s=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==s+2&&(n[s][1].end=n[i-1][1].end,n.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(n,r):n}}function Ng(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],i=t.sliceStream(r);let s=i.length,a=-1,o=0,l;for(;s--;){const u=i[s];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)l=!0,o++;else if(u!==-1){s++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const u={type:n===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?a:r.start._bufferIndex+a,_index:r.start._index+s,line:r.end.line,column:r.end.column-o,offset:r.end.offset-o},end:g({},r.end)};r.end=g({},u.start),r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Lg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:zm},disable:{null:[]},document:{42:Re,43:Re,45:Re,48:Re,49:Re,50:Re,51:Re,52:Re,53:Re,54:Re,55:Re,56:Re,57:Re,62:Yo},flow:{35:qm,42:ar,45:[sl,ar],60:Km,61:sl,95:ar,96:Zo,126:Zo},flowInitial:{[-2]:xi,[-1]:xi,32:xi},insideSpan:{null:[wi,Ag]},string:{38:Xo,92:Go},text:{[-5]:Si,[-4]:Si,[-3]:Si,33:hg,38:Xo,42:wi,60:[pm,tg],91:pg,92:[$m,Go],93:vi,95:wi,96:Cm}},Symbol.toStringTag,{value:"Module"}));function Dg(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},s=[];let a=[],o=[];const l={attempt:H(z),check:H(I),consume:C,enter:_,exit:F,interrupt:H(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:v,events:[],now:m,parser:e,previous:null,sliceSerialize:h,sliceStream:f,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&s.push(t),u;function d(O){return a=Je(a,O),b(),a[a.length-1]!==null?[]:(q(t,0),u.events=sr(s,u.events,u),u.events)}function h(O,P){return Fg(f(O),P)}function f(O){return Og(a,O)}function m(){const{_bufferIndex:O,_index:P,line:R,column:L,offset:N}=r;return{_bufferIndex:O,_index:P,line:R,column:L,offset:N}}function v(O){i[O.line]=O.column,k()}function b(){let O;for(;r._index<a.length;){const P=a[r._index];if(typeof P=="string")for(O=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===O&&r._bufferIndex<P.length;)x(P.charCodeAt(r._bufferIndex));else x(P)}}function x(O){c=c(O)}function C(O){W(O)?(r.line++,r.column=1,r.offset+=O===-3?2:1,k()):O!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=O}function _(O,P){const R=P||{};return R.type=O,R.start=m(),u.events.push(["enter",R,u]),o.push(R),R}function F(O){const P=o.pop();return P.end=m(),u.events.push(["exit",P,u]),P}function z(O,P){q(O,P.from)}function I(O,P){P.restore()}function H(O,P){return R;function R(L,N,G){let J,Z,de,w;return Array.isArray(L)?ye(L):"tokenize"in L?ye([L]):ge(L);function ge(_e){return U;function U(X){const ae=X!==null&&_e[X],he=X!==null&&_e.null,Ce=[...Array.isArray(ae)?ae:ae?[ae]:[],...Array.isArray(he)?he:he?[he]:[]];return ye(Ce)(X)}}function ye(_e){return J=_e,Z=0,_e.length===0?G:S(_e[Z])}function S(_e){return U;function U(X){return w=j(),de=_e,_e.partial||(u.currentConstruct=_e),_e.name&&u.parser.constructs.disable.null.includes(_e.name)?lt():_e.tokenize.call(P?Object.assign(Object.create(u),P):u,l,Ie,lt)(X)}}function Ie(_e){return O(de,w),N}function lt(_e){return w.restore(),++Z<J.length?S(J[Z]):G}}}function q(O,P){O.resolveAll&&!s.includes(O)&&s.push(O),O.resolve&&qe(u.events,P,u.events.length-P,O.resolve(u.events.slice(P),u)),O.resolveTo&&(u.events=O.resolveTo(u.events,u))}function j(){const O=m(),P=u.previous,R=u.currentConstruct,L=u.events.length,N=Array.from(o);return{from:L,restore:G};function G(){r=O,u.previous=P,u.currentConstruct=R,u.events.length=L,o=N,k()}}function k(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function Og(e,t){const n=t.start._index,r=t.start._bufferIndex,i=t.end._index,s=t.end._bufferIndex;let a;if(n===i)a=[e[n].slice(r,s)];else{if(a=e.slice(n,i),r>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}s>0&&a.push(e[i].slice(0,s))}return a}function Fg(e,t){let n=-1;const r=[];let i;for(;++n<e.length;){const s=e[n];let a;if(typeof s=="string")a=s;else switch(s){case-5:{a="\r";break}case-4:{a=`
7
+ `);i=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(c){}}}}finally{n.releaseLock()}})}function np(e){return e.map(t=>{let n="";if(typeof t.content=="string")n=t.content;else if(Array.isArray(t.content)){const r=t.content.find(i=>i.type==="text");r&&typeof r=="object"&&"text"in r&&(n=r.text)}return{role:t.role,content:n}})}function rp(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 $t=new Map,nr=new Map;let Ht;function ii(e,t){const n=$t.get(e);if(n)return n;if(t)for(const r of t){const i=nr.get(r.id);if(i)return $t.set(e,i),i}return e}function ip(e,t){return{list(){return M(this,null,function*(){const r=[];let s,a=0;do{const l=yield e.listChats({limit:50,cursor:s}),u=l.items||[];Array.isArray(u)&&u.length>0&&r.push(...u),s=l.nextCursor||void 0,a++}while(s&&a<50);return{threads:r.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(r){return M(this,null,function*(){return{remoteId:$t.get(r)||r,externalId:void 0}})},rename(r,i){return M(this,null,function*(){const s=ii(r);yield e.updateChat(s,{title:i})})},archive(r){return M(this,null,function*(){})},unarchive(r){return M(this,null,function*(){})},delete(r){return M(this,null,function*(){const i=ii(r);yield e.deleteChat(i)})},generateTitle(r,i){return M(this,null,function*(){var o;const s=ii(r,i);let a;try{a=(yield e.generateChatTitle(s)).title}catch(l){console.error("[generateTitle] API call failed, falling back to first message",l);const u=i.find(d=>d.role==="user"),c=(o=u==null?void 0:u.content)==null?void 0:o.filter(d=>d.type==="text").map(d=>d.text).join(" ").trim();a=c?c.length>60?c.slice(0,57)+"...":c:void 0}return Is(l=>{const u=l.addTextPart();a&&u.append(a),u.close(),l.close()})})},fetch(r){return M(this,null,function*(){try{const i=yield e.getChat(r);return{status:"regular",remoteId:i.id||r,title:i.title||"Chat",createdAt:i.createdAt?new Date(i.createdAt):new Date,updatedAt:i.updatedAt?new Date(i.updatedAt):new Date}}catch(i){return{status:"regular",remoteId:r,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(r,i){$t.set(r,i),t==null||t(r,i)},unstable_Provider:({children:r})=>{const i=pa(),s=i==null?void 0:i.remoteId;y.useEffect(()=>{s&&(Ht=s)},[s]);const a=y.useMemo(()=>({load(){return M(this,null,function*(){if(!s)return{messages:[]};try{const u=yield e.getChat(s);if(!u.messages||u.messages.length===0)return{messages:[]};const c=u.messages.map(h=>rp(h)),d=c.map((h,f)=>({message:h,parentId:f>0?c[f-1].id:null}));for(const h of c)nr.set(h.id,s);return{messages:d}}catch(u){return{messages:[]}}})},append(u){return M(this,null,function*(){})}}),[s,e]),o=y.useMemo(()=>({history:a}),[a]);return p.jsx(Fr,{adapters:o,children:r})}}}class sp{constructor(){T(this,"messageMetadata",new Map);T(this,"currentMessageId",null);T(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const n=this.messageMetadata.get(this.currentMessageId)||{},r=t.sources;r&&r.length>0&&(this.messageMetadata.set(this.currentMessageId,I(m({},n),{sources:r})),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 bt=new sp,bo=new Map,si=[];let rr=[];function wo(e,t,n=50,r=800){si.push({question:e,response:t,streamingSpeed:n,initialDelay:r})}function xo(e,t){const{modelId:n,systemPrompt:r,ephemeral:i,enableReasoning:s,onChatCreated:a,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:c}=t;let d;return{run(f){return Pn(this,null,function*(){var Z,de,w,ge,ye;const{messages:g,abortSignal:v}=f,b=si.shift();if(b){o==null||o();const U=(Z=b.initialDelay)!=null?Z:800;if(U>0&&(yield new Ee(new Promise(re=>setTimeout(re,U)))),v!=null&&v.aborted)throw new Error("Request aborted");const X=b.response.split(" ");let ae="";const fe=b.streamingSpeed||50,Ie=`premade-${Date.now()}`;i&&(a==null||a(Ie));for(let re=0;re<X.length;re++){if(v!=null&&v.aborted)throw new Error("Request aborted");ae+=(re===0?"":" ")+X[re],yield{content:[{type:"text",text:ae}]},yield new Ee(new Promise(_e=>setTimeout(_e,fe+Math.random()*(fe*.5))))}yield{content:[{type:"text",text:ae}]},rr.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let x;for(const U of g){const X=nr.get(U.id);if(X){x=X;break}}if(!x&&g.length>0){const U=g.find(X=>X.role==="user");if(U){const ae=(typeof U.content=="string"?U.content:Array.isArray(U.content)&&((de=U.content.find(fe=>fe.type==="text"))==null?void 0:de.text)||"").substring(0,50);x=bo.get(ae)}}!x&&d&&(x=d),o==null||o();let E=g,_=-1;for(let U=g.length-1;U>=0;U--)if(g[U].role==="assistant"){_=U;break}(x||_>=0)&&_>=0&&(E=g.slice(_+1));const F=np(E);if(rr.length>0&&!x){const U=rr.map(X=>({role:X.role,content:X.content}));F.unshift(...U),rr=[]}const B=[];let C;for(let U=E.length-1;U>=0;U--)if(E[U].role==="user"){C=E[U];break}if(C&&"attachments"in C){const U=C.attachments;if(U&&U.length>0){for(const X of U)if(X.file)try{const ae=yield new Ee(e.uploadFile(X.file));B.push(ae.id)}catch(ae){}}}const H={messages:F,chatId:x||null,systemPrompt:r,ephemeral:i,enableReasoning:s,stream:!0};if(n&&n.trim()!==""&&(H.modelId=n),B.length>0&&(H.fileIds=B),u&&!(yield new Ee(u()))){if(c){const X=typeof c=="function"?c():c,ae=g.filter(_e=>_e.role==="user"),fe=ae.length>0?ae[ae.length-1]:void 0;let Ie="Message";if(fe){if(typeof fe.content=="string")Ie=fe.content;else if(Array.isArray(fe.content)){const _e=fe.content.find(Ye=>Ye.type==="text");Ie=(_e==null?void 0:_e.text)||"Message"}}wo(Ie,X,40,400);const re=si.shift();if(re){o==null||o();const _e=(w=re.initialDelay)!=null?w:400;if(_e>0&&(yield new Ee(new Promise(be=>setTimeout(be,_e)))),v!=null&&v.aborted)throw new Error("Request aborted");const Ye=re.response.split(" ");let Ge="";const Xt=re.streamingSpeed||40,ee=`mock-${Date.now()}`;i&&(a==null||a(ee));for(let be=0;be<Ye.length;be++){if(v!=null&&v.aborted)throw new Error("Request aborted");Ge+=(be===0?"":" ")+Ye[be],yield{content:[{type:"text",text:Ge}]},yield new Ee(new Promise(we=>setTimeout(we,Xt+Math.random()*(Xt*.3))))}yield{content:[{type:"text",text:Ge}]};return}}throw new Error("Request blocked")}const V=yield new Ee(e.createOrContinueChat(H,v));let j="",k="",O;const P=[];let R=0,L=!1;const N=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;bt.clear(),bt.setCurrentMessage(N);const G=()=>{P.length!==R&&(R=P.length,bt.update({sources:P.length>0?[...P]:void 0}))},J=()=>{G();const U=[];return k&&U.push({type:"reasoning",text:k}),j&&U.push({type:"text",text:j}),U.length===0&&U.push({type:"text",text:""}),{content:U}};try{for(var S=Lt(tp(V,v)),Ce,lt,ke;Ce=!(lt=yield new Ee(S.next())).done;Ce=!1){const U=lt.value;if(v!=null&&v.aborted)throw new Error("Request aborted");const X=U.id||U.chatId||U.messageId;if(X&&!O){O=X,d=X,a==null||a(X);for(const re of g)nr.set(re.id,X);if(g.length>0){const re=g.find(_e=>_e.role==="user");if(re){const Ye=(typeof re.content=="string"?re.content:Array.isArray(re.content)&&((ge=re.content.find(Ge=>Ge.type==="text"))==null?void 0:ge.text)||"").substring(0,50);bo.set(Ye,X)}}Ht&&!$t.has(Ht)&&$t.set(Ht,X),l&&Ht&&l(Ht,X)}const ae=U.sources;if(ae&&Array.isArray(ae)&&ae.length>0)for(const re of ae)P.some(_e=>_e.sourceId===re.sourceId)||P.push({sourceId:re.sourceId,filename:re.filename||"Unknown",score:(ye=re.score)!=null?ye:1,chunkId:re.chunkId,datasetId:re.datasetId});const fe=U.reasoning;if(fe&&fe.length>0&&(k+=fe,yield J()),U.type)switch(U.type){case"source-document":U.sourceId&&P.push({sourceId:U.sourceId,filename:U.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":U.delta&&(k+=U.delta),(j||k)&&(yield J());continue;case"reasoning-end":(j||k)&&(yield J());continue;case"text-delta":U.delta&&(k&&!L&&!j&&(L=!0,yield new Ee(new Promise(re=>setTimeout(re,400)))),j+=U.delta),j&&(yield J());continue;case"error":throw new Error(U.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Ie=U.delta;if(Ie!=null&&(k&&!L&&!j&&(L=!0,yield new Ee(new Promise(re=>setTimeout(re,400)))),j+=Ie),U.content&&(j+=U.content),U.message&&(j+=U.message.content||""),U.finished){(j||k||P.length>0)&&(yield J());break}(j||k||P.length>0)&&(yield J())}}catch(lt){ke=[lt]}finally{try{Ce&&(lt=S.return)&&(yield new Ee(lt.call(S)))}finally{if(ke)throw ke[0]}}(j||k||P.length>0)&&(yield J())})}}}class ir extends Error{constructor(t,n,r){super(t),this.code=n,this.file=r,this.name="AttachmentValidationError"}}const ap=["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"],op=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],lp=10*1024*1024;function vo(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function up(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function cp(e,t){const r={"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 r?r.includes(t.toLowerCase()):!0}function dp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function So(e={}){const{validation:t={},onValidationError:n,onAttachmentAdded:r,onAttachmentRemoved:i}=e,{maxFileSizeBytes:s=lp,allowedMimeTypes:a=ap,allowedExtensions:o=op,validateContentType:l=!0}=t,u=o.join(",");function c(h){if(h.size>s){const g=new ir('File "'+h.name+'" is too large ('+vo(h.size)+"). Maximum size is "+vo(s)+".","FILE_TOO_LARGE",h);throw n==null||n(g),g}const f=up(h.name);if(f&&!o.some(g=>g.toLowerCase()===f)){const g=new ir('File type "'+f+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw n==null||n(g),g}if(h.type&&!a.some(g=>{if(g.endsWith("/*")){const v=g.slice(0,-1);return h.type.startsWith(v)}return h.type===g})){const g=new ir('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw n==null||n(g),g}if(l&&h.type&&f&&!cp(h.type,f)){const g=new ir('File extension "'+f+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw n==null||n(g),g}}return{accept:u,add(f){return M(this,arguments,function*({file:h}){c(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:dp(),type:g,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return r==null||r(v),v})},remove(h){return M(this,null,function*(){i==null||i(h.id)})},send(h){return M(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 I(m({},h),{status:{type:"complete"},content:[{type:"image",image:f}]})}return I(m({},h),{status:{type:"complete"},content:[]})})}}}function hp({children:e,baseUrl:t,sessionToken:n,isProxyMode:r=!1,mode:i="multiChat",modelId:s,onModelChange:a,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:c,onError:d,onChatCreated:h,onUserMessage:f,onThreadIdUpdate:g,onChatsLoaded:v,enableAttachments:b=!1,onBeforeRequest:x,mockResponseOnBlocked:E}){const _=y.useMemo(()=>new yo(t,n||void 0,r),[t,n,r]),[F,B]=y.useState(s||null);y.useEffect(()=>{s&&B(s)},[s]);const C=y.useCallback(j=>{h==null||h(j)},[h]),H=y.useCallback((j,k)=>{g==null||g(j,k)},[g]),V=y.useMemo(()=>xo(_,{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:C,onUserMessage:f,onBeforeRequest:x,mockResponseOnBlocked:E}),[_,F,l,o,u,C,f,x,E]);return i==="singleChat"?p.jsx(fp,{modelAdapter:V,enableAttachments:b,children:e}):p.jsx(pp,{client:_,modelAdapterOptions:{modelId:F||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:C,onUserMessage:f,onBeforeRequest:x,mockResponseOnBlocked:E},initialThreadId:c,onChatsLoaded:v,onThreadIdUpdate:H,onError:d,enableAttachments:b,children:e})}function fp({modelAdapter:e,enableAttachments:t,children:n}){const r=y.useMemo(()=>t?So():void 0,[t]),i=_a(e,{adapters:m({},r&&{attachments:r})});return p.jsx(ba,{runtime:i,children:n})}function pp({client:e,modelAdapterOptions:t,initialThreadId:n,onChatsLoaded:r,onThreadIdUpdate:i,onError:s,enableAttachments:a,children:o}){const l=y.useMemo(()=>ip(e,(v,b)=>{i==null||i(v,b)}),[e,i]),u=y.useCallback((v,b)=>{l.updateRemoteId&&l.updateRemoteId(v,b),i==null||i(v,b)},[l,i]),c=y.useMemo(()=>I(m({},l),{list(){return M(this,null,function*(){const b=yield l.list();return r==null||r(),b})}}),[l,r]);y.useEffect(()=>{window.__cuadraThreadListAdapter=c,window.__cuadraThreadListRuntime=null},[c]);const d=y.useMemo(()=>xo(e,I(m({},t),{onThreadIdUpdate:u})),[e,t,u]),h=y.useMemo(()=>a?So():void 0,[a]),f=y.useCallback(()=>_a(d,{adapters:m({},h&&{attachments:h})}),[d,h]),g=Aa({adapter:c,runtimeHook:f});return y.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),p.jsx(ba,{runtime:g,children:o})}function Bv(){}function Rv(){}function mp(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const gp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,yp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,bp={};function ko(e,t){return(bp.jsx?yp:gp).test(e)}const wp=/[ \t\n\f\r]/g;function xp(e){return typeof e=="object"?e.type==="text"?_o(e.value):!1:_o(e)}function _o(e){return e.replace(wp,"")===""}class fn{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}fn.prototype.normal={},fn.prototype.property={},fn.prototype.space=void 0;function To(e,t){const n={},r={};for(const i of e)Object.assign(n,i.property),Object.assign(r,i.normal);return new fn(n,r,t)}function ai(e){return e.toLowerCase()}class Re{constructor(t,n){this.attribute=n,this.property=t}}Re.prototype.attribute="",Re.prototype.booleanish=!1,Re.prototype.boolean=!1,Re.prototype.commaOrSpaceSeparated=!1,Re.prototype.commaSeparated=!1,Re.prototype.defined=!1,Re.prototype.mustUseProperty=!1,Re.prototype.number=!1,Re.prototype.overloadedBoolean=!1,Re.prototype.property="",Re.prototype.spaceSeparated=!1,Re.prototype.space=void 0;let vp=0;const Y=Et(),ve=Et(),oi=Et(),D=Et(),ce=Et(),qt=Et(),He=Et();function Et(){return Nu(2,++vp)}const li=Object.freeze(Object.defineProperty({__proto__:null,boolean:Y,booleanish:ve,commaOrSpaceSeparated:He,commaSeparated:qt,number:D,overloadedBoolean:oi,spaceSeparated:ce},Symbol.toStringTag,{value:"Module"})),ui=Object.keys(li);class ci extends Re{constructor(t,n,r,i){let s=-1;if(super(t,n),Co(this,"space",i),typeof r=="number")for(;++s<ui.length;){const a=ui[s];Co(this,ui[s],(r&li[a])===li[a])}}}ci.prototype.defined=!0;function Co(e,t,n){n&&(e[t]=n)}function Vt(e){const t={},n={};for(const[r,i]of Object.entries(e.properties)){const s=new ci(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(s.mustUseProperty=!0),t[r]=s,n[ai(r)]=r,n[ai(s.attribute)]=r}return new fn(t,n,e.space)}const Io=Vt({properties:{ariaActiveDescendant:null,ariaAtomic:ve,ariaAutoComplete:null,ariaBusy:ve,ariaChecked:ve,ariaColCount:D,ariaColIndex:D,ariaColSpan:D,ariaControls:ce,ariaCurrent:null,ariaDescribedBy:ce,ariaDetails:null,ariaDisabled:ve,ariaDropEffect:ce,ariaErrorMessage:null,ariaExpanded:ve,ariaFlowTo:ce,ariaGrabbed:ve,ariaHasPopup:null,ariaHidden:ve,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ce,ariaLevel:D,ariaLive:null,ariaModal:ve,ariaMultiLine:ve,ariaMultiSelectable:ve,ariaOrientation:null,ariaOwns:ce,ariaPlaceholder:null,ariaPosInSet:D,ariaPressed:ve,ariaReadOnly:ve,ariaRelevant:null,ariaRequired:ve,ariaRoleDescription:ce,ariaRowCount:D,ariaRowIndex:D,ariaRowSpan:D,ariaSelected:ve,ariaSetSize:D,ariaSort:null,ariaValueMax:D,ariaValueMin:D,ariaValueNow:D,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Eo(e,t){return t in e?e[t]:t}function Ao(e,t){return Eo(e,t.toLowerCase())}const Sp=Vt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:qt,acceptCharset:ce,accessKey:ce,action:null,allow:null,allowFullScreen:Y,allowPaymentRequest:Y,allowUserMedia:Y,alt:null,as:null,async:Y,autoCapitalize:null,autoComplete:ce,autoFocus:Y,autoPlay:Y,blocking:ce,capture:null,charSet:null,checked:Y,cite:null,className:ce,cols:D,colSpan:null,content:null,contentEditable:ve,controls:Y,controlsList:ce,coords:D|qt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Y,defer:Y,dir:null,dirName:null,disabled:Y,download:oi,draggable:ve,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Y,formTarget:null,headers:ce,height:D,hidden:oi,high:D,href:null,hrefLang:null,htmlFor:ce,httpEquiv:ce,id:null,imageSizes:null,imageSrcSet:null,inert:Y,inputMode:null,integrity:null,is:null,isMap:Y,itemId:null,itemProp:ce,itemRef:ce,itemScope:Y,itemType:ce,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Y,low:D,manifest:null,max:null,maxLength:D,media:null,method:null,min:null,minLength:D,multiple:Y,muted:Y,name:null,nonce:null,noModule:Y,noValidate:Y,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:Y,optimum:D,pattern:null,ping:ce,placeholder:null,playsInline:Y,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Y,referrerPolicy:null,rel:ce,required:Y,reversed:Y,rows:D,rowSpan:D,sandbox:ce,scope:null,scoped:Y,seamless:Y,selected:Y,shadowRootClonable:Y,shadowRootDelegatesFocus:Y,shadowRootMode:null,shape:null,size:D,sizes:null,slot:null,span:D,spellCheck:ve,src:null,srcDoc:null,srcLang:null,srcSet:null,start:D,step:null,style:null,tabIndex:D,target:null,title:null,translate:null,type:null,typeMustMatch:Y,useMap:null,value:ve,width:D,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ce,axis:null,background:null,bgColor:null,border:D,borderColor:null,bottomMargin:D,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Y,declare:Y,event:null,face:null,frame:null,frameBorder:null,hSpace:D,leftMargin:D,link:null,longDesc:null,lowSrc:null,marginHeight:D,marginWidth:D,noResize:Y,noHref:Y,noShade:Y,noWrap:Y,object:null,profile:null,prompt:null,rev:null,rightMargin:D,rules:null,scheme:null,scrolling:ve,standby:null,summary:null,text:null,topMargin:D,valueType:null,version:null,vAlign:null,vLink:null,vSpace:D,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Y,disableRemotePlayback:Y,prefix:null,property:null,results:D,security:null,unselectable:null},space:"html",transform:Ao}),kp=Vt({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:He,accentHeight:D,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:D,amplitude:D,arabicForm:null,ascent:D,attributeName:null,attributeType:null,azimuth:D,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:D,by:null,calcMode:null,capHeight:D,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:D,diffuseConstant:D,direction:null,display:null,dur:null,divisor:D,dominantBaseline:null,download:Y,dx:null,dy:null,edgeMode:null,editable:null,elevation:D,enableBackground:null,end:null,event:null,exponent:D,externalResourcesRequired:null,fill:null,fillOpacity:D,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:qt,g2:qt,glyphName:qt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:D,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:D,horizOriginX:D,horizOriginY:D,id:null,ideographic:D,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:D,k:D,k1:D,k2:D,k3:D,k4:D,kernelMatrix:He,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:D,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:D,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:D,overlineThickness:D,paintOrder:null,panose1:null,path:null,pathLength:D,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ce,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:D,pointsAtY:D,pointsAtZ:D,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:He,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:He,rev:He,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:He,requiredFeatures:He,requiredFonts:He,requiredFormats:He,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:D,specularExponent:D,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:D,strikethroughThickness:D,string:null,stroke:null,strokeDashArray:He,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:D,strokeOpacity:D,strokeWidth:null,style:null,surfaceScale:D,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:He,tabIndex:D,tableValues:null,target:null,targetX:D,targetY:D,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:He,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:D,underlineThickness:D,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:D,values:null,vAlphabetic:D,vMathematical:D,vectorEffect:null,vHanging:D,vIdeographic:D,version:null,vertAdvY:D,vertOriginX:D,vertOriginY:D,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:D,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Eo}),Mo=Vt({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()}}),Po=Vt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ao}),No=Vt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),_p={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"},Tp=/[A-Z]/g,Lo=/-[a-z]/g,Cp=/^data[-\w.:]+$/i;function Ip(e,t){const n=ai(t);let r=t,i=Re;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Cp.test(t)){if(t.charAt(4)==="-"){const s=t.slice(5).replace(Lo,Ap);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{const s=t.slice(4);if(!Lo.test(s)){let a=s.replace(Tp,Ep);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}i=ci}return new i(r,t)}function Ep(e){return"-"+e.toLowerCase()}function Ap(e){return e.charAt(1).toUpperCase()}const Mp=To([Io,Sp,Mo,Po,No],"html"),di=To([Io,kp,Mo,Po,No],"svg");function Pp(e){return e.join(" ").trim()}var Wt={},hi,Do;function Np(){if(Do)return hi;Do=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
+ `,u="/",c="*",d="",h="comment",f="declaration";function g(b,x){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];x=x||{};var E=1,_=1;function F(L){var N=L.match(t);N&&(E+=N.length);var G=L.lastIndexOf(l);_=~G?L.length-G:_+L.length}function B(){var L={line:E,column:_};return function(N){return N.position=new C(L),j(),N}}function C(L){this.start=L,this.end={line:E,column:_},this.source=x.source}C.prototype.content=b;function H(L){var N=new Error(x.source+":"+E+":"+_+": "+L);if(N.reason=L,N.filename=x.source,N.line=E,N.column=_,N.source=b,!x.silent)throw N}function V(L){var N=L.exec(b);if(N){var G=N[0];return F(G),b=b.slice(G.length),N}}function j(){V(n)}function k(L){var N;for(L=L||[];N=O();)N!==!1&&L.push(N);return L}function O(){var L=B();if(!(u!=b.charAt(0)||c!=b.charAt(1))){for(var N=2;d!=b.charAt(N)&&(c!=b.charAt(N)||u!=b.charAt(N+1));)++N;if(N+=2,d===b.charAt(N-1))return H("End of comment missing");var G=b.slice(2,N-2);return _+=2,F(G),b=b.slice(N),_+=2,L({type:h,comment:G})}}function P(){var L=B(),N=V(r);if(N){if(O(),!V(i))return H("property missing ':'");var G=V(s),J=L({type:f,property:v(N[0].replace(e,d)),value:G?v(G[0].replace(e,d)):d});return V(a),J}}function R(){var L=[];k(L);for(var N;N=P();)N!==!1&&(L.push(N),k(L));return L}return j(),R()}function v(b){return b?b.replace(o,d):d}return hi=g,hi}var Oo;function Lp(){if(Oo)return Wt;Oo=1;var e=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.default=n;const t=e(Np());function n(r,i){let s=null;if(!r||typeof r!="string")return s;const a=(0,t.default)(r),o=typeof i=="function";return a.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:c}=l;o?i(u,c,l):c&&(s=s||{},s[u]=c)}),s}return Wt}var pn={},Fo;function Dp(){if(Fo)return pn;Fo=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,s=function(u){return!u||n.test(u)||e.test(u)},a=function(u,c){return c.toUpperCase()},o=function(u,c){return"".concat(c,"-")},l=function(u,c){return c===void 0&&(c={}),s(u)?u:(u=u.toLowerCase(),c.reactCompat?u=u.replace(i,o):u=u.replace(r,o),u.replace(t,a))};return pn.camelCase=l,pn}var mn,zo;function Op(){if(zo)return mn;zo=1;var e=mn&&mn.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(Lp()),n=Dp();function r(i,s){var a={};return!i||typeof i!="string"||(0,t.default)(i,function(o,l){o&&l&&(a[(0,n.camelCase)(o,s)]=l)}),a}return r.default=r,mn=r,mn}var Fp=Op();const zp=Ln(Fp),Bo=Ro("end"),fi=Ro("start");function Ro(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Bp(e){const t=fi(e),n=Bo(e);if(t&&n)return{start:t,end:n}}function gn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?jo(e.position):"start"in e||"end"in e?jo(e):"line"in e||"column"in e?pi(e):""}function pi(e){return Uo(e&&e.line)+":"+Uo(e&&e.column)}function jo(e){return pi(e&&e.start)+"-"+pi(e&&e.end)}function Uo(e){return e&&typeof e=="number"?e:1}class Me extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",s={},a=!1;if(n&&("line"in n&&"column"in n?s={place:n}:"start"in n&&"end"in n?s={place:n}:"type"in n?s={ancestors:[n],place:n.position}:s=m({},n)),typeof t=="string"?i=t:!s.cause&&t&&(a=!0,i=t.message,s.cause=t),!s.ruleId&&!s.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?s.ruleId=r:(s.source=r.slice(0,l),s.ruleId=r.slice(l+1))}if(!s.place&&s.ancestors&&s.ancestors){const l=s.ancestors[s.ancestors.length-1];l&&(s.place=l.position)}const o=s.place&&"start"in s.place?s.place.start:s.place;this.ancestors=s.ancestors||void 0,this.cause=s.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=o?o.line:void 0,this.name=gn(s.place)||"1:1",this.place=s.place||void 0,this.reason=this.message,this.ruleId=s.ruleId||void 0,this.source=s.source||void 0,this.stack=a&&s.cause&&typeof s.cause.stack=="string"?s.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 mi={}.hasOwnProperty,Rp=new Map,jp=/[A-Z]/g,Up=new Set(["table","tbody","thead","tfoot","tr"]),$p=new Set(["td","th"]),$o="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Hp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Xp(n,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");r=Gp(n,t.jsx,t.jsxs)}const i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?di:Mp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},s=Ho(i,e,void 0);return s&&typeof s!="string"?s:i.create(e,i.Fragment,{children:s||void 0},void 0)}function Ho(e,t,n){if(t.type==="element")return qp(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Vp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Jp(e,t,n);if(t.type==="mdxjsEsm")return Wp(e,t);if(t.type==="root")return Kp(e,t,n);if(t.type==="text")return Yp(e,t)}function qp(e,t,n){const r=e.schema;let i=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(i=di,e.schema=i),e.ancestors.push(t);const s=Vo(e,t.tagName,!1),a=Qp(e,t);let o=yi(e,t);return Up.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!xp(l):!0})),qo(e,a,s,t),gi(a,o),e.ancestors.pop(),e.schema=r,e.create(t,s,a,n)}function Vp(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}yn(e,t.position)}function Wp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);yn(e,t.position)}function Jp(e,t,n){const r=e.schema;let i=r;t.name==="svg"&&r.space==="html"&&(i=di,e.schema=i),e.ancestors.push(t);const s=t.name===null?e.Fragment:Vo(e,t.name,!0),a=Zp(e,t),o=yi(e,t);return qo(e,a,s,t),gi(a,o),e.ancestors.pop(),e.schema=r,e.create(t,s,a,n)}function Kp(e,t,n){const r={};return gi(r,yi(e,t)),e.create(t,e.Fragment,r,n)}function Yp(e,t){return t.value}function qo(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function gi(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Gp(e,t,n){return r;function r(i,s,a,o){const u=Array.isArray(a.children)?n:t;return o?u(s,a,o):u(s,a)}}function Xp(e,t){return n;function n(r,i,s,a){const o=Array.isArray(s.children),l=fi(r);return t(i,s,a,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function Qp(e,t){const n={};let r,i;for(i in t.properties)if(i!=="children"&&mi.call(t.properties,i)){const s=em(e,i,t.properties[i]);if(s){const[a,o]=s;e.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&$p.has(t.tagName)?r=o:n[a]=o}}if(r){const s=n.style||(n.style={});s[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Zp(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const s=r.data.estree.body[0];s.type;const a=s.expression;a.type;const o=a.properties[0];o.type,Object.assign(n,e.evaluater.evaluateExpression(o.argument))}else yn(e,t.position);else{const i=r.name;let s;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const o=r.value.data.estree.body[0];o.type,s=e.evaluater.evaluateExpression(o.expression)}else yn(e,t.position);else s=r.value===null?!0:r.value;n[i]=s}return n}function yi(e,t){const n=[];let r=-1;const i=e.passKeys?new Map:Rp;for(;++r<t.children.length;){const s=t.children[r];let a;if(e.passKeys){const l=s.type==="element"?s.tagName:s.type==="mdxJsxFlowElement"||s.type==="mdxJsxTextElement"?s.name:void 0;if(l){const u=i.get(l)||0;a=l+"-"+u,i.set(l,u+1)}}const o=Ho(e,s,a);o!==void 0&&n.push(o)}return n}function em(e,t,n){const r=Ip(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?mp(n):Pp(n)),r.property==="style"){let i=typeof n=="object"?n:tm(e,String(n));return e.stylePropertyNameCase==="css"&&(i=nm(i)),["style",i]}return[e.elementAttributeNameCase==="react"&&r.space?_p[r.property]||r.property:r.attribute,n]}}function tm(e,t){try{return zp(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,i=new Me("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=e.filePath||void 0,i.url=$o+"#cannot-parse-style-attribute",i}}function Vo(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const i=t.split(".");let s=-1,a;for(;++s<i.length;){const o=ko(i[s])?{type:"Identifier",name:i[s]}:{type:"Literal",value:i[s]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(s&&o.type==="Literal"),optional:!1}:o}r=a}else r=ko(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const i=r.value;return mi.call(e.components,i)?e.components[i]:i}if(e.evaluater)return e.evaluater.evaluateExpression(r);yn(e)}function yn(e,t){const n=new Me("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=$o+"#cannot-handle-mdx-estrees-without-createevaluater",n}function nm(e){const t={};let n;for(n in e)mi.call(e,n)&&(t[rm(n)]=e[n]);return t}function rm(e){let t=e.replace(jp,im);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function im(e){return"-"+e.toLowerCase()}const bi={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"]},sm={};function wi(e,t){const n=sm,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,i=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return Wo(e,r,i)}function Wo(e,t,n){if(am(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Jo(e.children,t,n)}return Array.isArray(e)?Jo(e,t,n):""}function Jo(e,t,n){const r=[];let i=-1;for(;++i<e.length;)r[i]=Wo(e[i],t,n);return r.join("")}function am(e){return!!(e&&typeof e=="object")}const Ko=document.createElement("i");function xi(e){const t="&"+e+";";Ko.innerHTML=t;const n=Ko.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function qe(e,t,n,r){const i=e.length;let s=0,a;if(t<0?t=-t>i?0:i+t:t=t>i?i:t,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);s<r.length;)a=r.slice(s,s+1e4),a.unshift(t,0),e.splice(...a),s+=1e4,t+=1e4}function Je(e,t){return e.length>0?(qe(e,e.length,0,t),e):t}const Yo={}.hasOwnProperty;function Go(e){const t={};let n=-1;for(;++n<e.length;)om(t,e[n]);return t}function om(e,t){let n;for(n in t){const i=(Yo.call(e,n)?e[n]:void 0)||(e[n]={}),s=t[n];let a;if(s)for(a in s){Yo.call(i,a)||(i[a]=[]);const o=s[a];lm(i[a],Array.isArray(o)?o:o?[o]:[])}}}function lm(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);qe(e,0,0,r)}function Xo(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function tt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Oe=wt(/[A-Za-z]/),Pe=wt(/[\dA-Za-z]/),um=wt(/[#-'*+\--9=?A-Z^-~]/);function sr(e){return e!==null&&(e<32||e===127)}const vi=wt(/\d/),cm=wt(/[\dA-Fa-f]/),dm=wt(/[!-/:-@[-`{-~]/);function W(e){return e!==null&&e<-2}function le(e){return e!==null&&(e<0||e===32)}function ne(e){return e===-2||e===-1||e===32}const ar=wt(new RegExp("\\p{P}|\\p{S}","u")),At=wt(/\s/);function wt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Jt(e){const t=[];let n=-1,r=0,i=0;for(;++n<e.length;){const s=e.charCodeAt(n);let a="";if(s===37&&Pe(e.charCodeAt(n+1))&&Pe(e.charCodeAt(n+2)))i=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(a=String.fromCharCode(s));else if(s>55295&&s<57344){const o=e.charCodeAt(n+1);s<56320&&o>56319&&o<57344?(a=String.fromCharCode(s,o),i=1):a="�"}else a=String.fromCharCode(s);a&&(t.push(e.slice(r,n),encodeURIComponent(a)),r=n+i+1,a=""),i&&(n+=i,i=0)}return t.join("")+e.slice(r)}function se(e,t,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let s=0;return a;function a(l){return ne(l)?(e.enter(n),o(l)):t(l)}function o(l){return ne(l)&&s++<i?(e.consume(l),o):(e.exit(n),t(l))}}const hm={tokenize:fm};function fm(e){const t=e.attempt(this.parser.constructs.contentInitial,r,i);let n;return t;function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),se(e,t,"linePrefix")}function i(o){return e.enter("paragraph"),s(o)}function s(o){const l=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=l),n=l,a(o)}function a(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return W(o)?(e.consume(o),e.exit("chunkText"),s):(e.consume(o),a)}}const pm={tokenize:mm},Qo={tokenize:gm};function mm(e){const t=this,n=[];let r=0,i,s,a;return o;function o(_){if(r<n.length){const F=n[r];return t.containerState=F[1],e.attempt(F[0].continuation,l,u)(_)}return u(_)}function l(_){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&E();const F=t.events.length;let B=F,C;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){C=t.events[B][1].end;break}x(r);let H=F;for(;H<t.events.length;)t.events[H][1].end=m({},C),H++;return qe(t.events,B+1,0,t.events.slice(F)),t.events.length=H,u(_)}return o(_)}function u(_){if(r===n.length){if(!i)return h(_);if(i.currentConstruct&&i.currentConstruct.concrete)return g(_);t.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Qo,c,d)(_)}function c(_){return i&&E(),x(r),h(_)}function d(_){return t.parser.lazy[t.now().line]=r!==n.length,a=t.now().offset,g(_)}function h(_){return t.containerState={},e.attempt(Qo,f,g)(_)}function f(_){return r++,n.push([t.currentConstruct,t.containerState]),h(_)}function g(_){if(_===null){i&&E(),x(0),e.consume(_);return}return i=i||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:s}),v(_)}function v(_){if(_===null){b(e.exit("chunkFlow"),!0),x(0),e.consume(_);return}return W(_)?(e.consume(_),b(e.exit("chunkFlow")),r=0,t.interrupt=void 0,o):(e.consume(_),v)}function b(_,F){const B=t.sliceStream(_);if(F&&B.push(null),_.previous=s,s&&(s.next=_),s=_,i.defineSkip(_.start),i.write(B),t.parser.lazy[_.start.line]){let C=i.events.length;for(;C--;)if(i.events[C][1].start.offset<a&&(!i.events[C][1].end||i.events[C][1].end.offset>a))return;const H=t.events.length;let V=H,j,k;for(;V--;)if(t.events[V][0]==="exit"&&t.events[V][1].type==="chunkFlow"){if(j){k=t.events[V][1].end;break}j=!0}for(x(r),C=H;C<t.events.length;)t.events[C][1].end=m({},k),C++;qe(t.events,V+1,0,t.events.slice(H)),t.events.length=C}}function x(_){let F=n.length;for(;F-- >_;){const B=n[F];t.containerState=B[1],B[0].exit.call(t,e)}n.length=_}function E(){i.write([null]),s=void 0,i=void 0,t.containerState._closeFlow=void 0}}function gm(e,t,n){return se(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Kt(e){if(e===null||le(e)||At(e))return 1;if(ar(e))return 2}function or(e,t,n){const r=[];let i=-1;for(;++i<e.length;){const s=e[i].resolveAll;s&&!r.includes(s)&&(t=s(t,n),r.push(s))}return t}const Si={name:"attention",resolveAll:ym,tokenize:bm};function ym(e,t){let n=-1,r,i,s,a,o,l,u,c;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;l=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const d=m({},e[r][1].end),h=m({},e[n][1].start);Zo(d,-l),Zo(h,l),a={type:l>1?"strongSequence":"emphasisSequence",start:d,end:m({},e[r][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[n][1].start),end:h},s={type:l>1?"strongText":"emphasisText",start:m({},e[r][1].end),end:m({},e[n][1].start)},i={type:l>1?"strong":"emphasis",start:m({},a.start),end:m({},o.end)},e[r][1].end=m({},a.start),e[n][1].start=m({},o.end),u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Je(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Je(u,[["enter",i,t],["enter",a,t],["exit",a,t],["enter",s,t]]),u=Je(u,or(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Je(u,[["exit",s,t],["enter",o,t],["exit",o,t],["exit",i,t]]),e[n][1].end.offset-e[n][1].start.offset?(c=2,u=Je(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):c=0,qe(e,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function bm(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=Kt(r);let s;return a;function a(l){return s=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===s)return e.consume(l),o;const u=e.exit("attentionSequence"),c=Kt(l),d=!c||c===2&&i||n.includes(l),h=!i||i===2&&c||n.includes(r);return u._open=!!(s===42?d:d&&(i||!h)),u._close=!!(s===42?h:h&&(c||!d)),t(l)}}function Zo(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const wm={name:"autolink",tokenize:xm};function xm(e,t,n){let r=0;return i;function i(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),s}function s(f){return Oe(f)?(e.consume(f),a):f===64?n(f):u(f)}function a(f){return f===43||f===45||f===46||Pe(f)?(r=1,o(f)):u(f)}function o(f){return f===58?(e.consume(f),r=0,l):(f===43||f===45||f===46||Pe(f))&&r++<32?(e.consume(f),o):(r=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||sr(f)?n(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),c):um(f)?(e.consume(f),u):n(f)}function c(f){return Pe(f)?d(f):n(f)}function d(f){return f===46?(e.consume(f),r=0,c):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))&&r++<63){const g=f===45?h:d;return e.consume(f),g}return n(f)}}const bn={partial:!0,tokenize:vm};function vm(e,t,n){return r;function r(s){return ne(s)?se(e,i,"linePrefix")(s):i(s)}function i(s){return s===null||W(s)?t(s):n(s)}}const el={continuation:{tokenize:km},exit:_m,name:"blockQuote",tokenize:Sm};function Sm(e,t,n){const r=this;return i;function i(a){if(a===62){const o=r.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),s}return n(a)}function s(a){return ne(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function km(e,t,n){const r=this;return i;function i(a){return ne(a)?se(e,s,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):s(a)}function s(a){return e.attempt(el,t,n)(a)}}function _m(e){e.exit("blockQuote")}const tl={name:"characterEscape",tokenize:Tm};function Tm(e,t,n){return r;function r(s){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(s),e.exit("escapeMarker"),i}function i(s){return dm(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}const nl={name:"characterReference",tokenize:Cm};function Cm(e,t,n){const r=this;let i=0,s,a;return o;function o(d){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),l}function l(d){return d===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(d),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),s=31,a=Pe,c(d))}function u(d){return d===88||d===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(d),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),s=6,a=cm,c):(e.enter("characterReferenceValue"),s=7,a=vi,c(d))}function c(d){if(d===59&&i){const h=e.exit("characterReferenceValue");return a===Pe&&!xi(r.sliceSerialize(h))?n(d):(e.enter("characterReferenceMarker"),e.consume(d),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(d)&&i++<s?(e.consume(d),c):n(d)}}const rl={partial:!0,tokenize:Em},il={concrete:!0,name:"codeFenced",tokenize:Im};function Im(e,t,n){const r=this,i={partial:!0,tokenize:B};let s=0,a=0,o;return l;function l(C){return u(C)}function u(C){const H=r.events[r.events.length-1];return s=H&&H[1].type==="linePrefix"?H[2].sliceSerialize(H[1],!0).length:0,o=C,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(C)}function c(C){return C===o?(a++,e.consume(C),c):a<3?n(C):(e.exit("codeFencedFenceSequence"),ne(C)?se(e,d,"whitespace")(C):d(C))}function d(C){return C===null||W(C)?(e.exit("codeFencedFence"),r.interrupt?t(C):e.check(rl,v,F)(C)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(C))}function h(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),d(C)):ne(C)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),se(e,f,"whitespace")(C)):C===96&&C===o?n(C):(e.consume(C),h)}function f(C){return C===null||W(C)?d(C):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(C))}function g(C){return C===null||W(C)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),d(C)):C===96&&C===o?n(C):(e.consume(C),g)}function v(C){return e.attempt(i,F,b)(C)}function b(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),x}function x(C){return s>0&&ne(C)?se(e,E,"linePrefix",s+1)(C):E(C)}function E(C){return C===null||W(C)?e.check(rl,v,F)(C):(e.enter("codeFlowValue"),_(C))}function _(C){return C===null||W(C)?(e.exit("codeFlowValue"),E(C)):(e.consume(C),_)}function F(C){return e.exit("codeFenced"),t(C)}function B(C,H,V){let j=0;return k;function k(N){return C.enter("lineEnding"),C.consume(N),C.exit("lineEnding"),O}function O(N){return C.enter("codeFencedFence"),ne(N)?se(C,P,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):P(N)}function P(N){return N===o?(C.enter("codeFencedFenceSequence"),R(N)):V(N)}function R(N){return N===o?(j++,C.consume(N),R):j>=a?(C.exit("codeFencedFenceSequence"),ne(N)?se(C,L,"whitespace")(N):L(N)):V(N)}function L(N){return N===null||W(N)?(C.exit("codeFencedFence"),H(N)):V(N)}}}function Em(e,t,n){const r=this;return i;function i(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s)}function s(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}const ki={name:"codeIndented",tokenize:Mm},Am={partial:!0,tokenize:Pm};function Mm(e,t,n){const r=this;return i;function i(u){return e.enter("codeIndented"),se(e,s,"linePrefix",5)(u)}function s(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?l(u):W(u)?e.attempt(Am,a,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||W(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Pm(e,t,n){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?n(a):W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):se(e,s,"linePrefix",5)(a)}function s(a){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):W(a)?i(a):n(a)}}const Nm={name:"codeText",previous:Dm,resolve:Lm,tokenize:Om};function Lm(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="codeTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function Dm(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Om(e,t,n){let r=0,i,s;return a;function a(d){return e.enter("codeText"),e.enter("codeTextSequence"),o(d)}function o(d){return d===96?(e.consume(d),r++,o):(e.exit("codeTextSequence"),l(d))}function l(d){return d===null?n(d):d===32?(e.enter("space"),e.consume(d),e.exit("space"),l):d===96?(s=e.enter("codeTextSequence"),i=0,c(d)):W(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(d))}function u(d){return d===null||d===32||d===96||W(d)?(e.exit("codeTextData"),l(d)):(e.consume(d),u)}function c(d){return d===96?(e.consume(d),i++,c):i===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(d)):(s.type="codeTextData",u(d))}}class Fm{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,n){const r=n==null?Number.POSITIVE_INFINITY:n;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const i=n||0;this.setCursor(Math.trunc(t));const s=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&wn(this.left,r),s.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),wn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),wn(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 n=this.left.splice(t,Number.POSITIVE_INFINITY);wn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);wn(this.left,n.reverse())}}}function wn(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function sl(e){const t={};let n=-1,r,i,s,a,o,l,u;const c=new Fm(e);for(;++n<c.length;){for(;n in t;)n=t[n];if(r=c.get(n),n&&r[1].type==="chunkFlow"&&c.get(n-1)[1].type==="listItemPrefix"&&(l=r[1]._tokenizer.events,s=0,s<l.length&&l[s][1].type==="lineEndingBlank"&&(s+=2),s<l.length&&l[s][1].type==="content"))for(;++s<l.length&&l[s][1].type!=="content";)l[s][1].type==="chunkText"&&(l[s][1]._isInFirstContentOfListItem=!0,s++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,zm(c,n)),n=t[n],u=!0);else if(r[1]._container){for(s=n,i=void 0;s--;)if(a=c.get(s),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(i&&(c.get(i)[1].type="lineEndingBlank"),a[1].type="lineEnding",i=s);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;i&&(r[1].end=m({},c.get(i)[1].start),o=c.slice(i,n),o.unshift(r),c.splice(i,n-i+1,o))}}return qe(e,0,Number.POSITIVE_INFINITY,c.slice(0)),!u}function zm(e,t){const n=e.get(t)[1],r=e.get(t)[2];let i=t-1;const s=[];let a=n._tokenizer;a||(a=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const o=a.events,l=[],u={};let c,d,h=-1,f=n,g=0,v=0;const b=[v];for(;f;){for(;e.get(++i)[1]!==f;);s.push(i),f._tokenizer||(c=r.sliceStream(f),f.next||c.push(null),d&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(c),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=n;++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(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),h=b.length;h--;){const x=o.slice(b[h],b[h+1]),E=s.pop();l.push([E,E+x.length-1]),e.splice(E,2,x)}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 Bm={resolve:jm,tokenize:Um},Rm={partial:!0,tokenize:$m};function jm(e){return sl(e),e}function Um(e,t){let n;return r;function r(o){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),i(o)}function i(o){return o===null?s(o):W(o)?e.check(Rm,a,s)(o):(e.consume(o),i)}function s(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function a(o){return e.consume(o),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,i}}function $m(e,t,n){const r=this;return i;function i(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),se(e,s,"linePrefix")}function s(a){if(a===null||W(a))return n(a);const o=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}function al(e,t,n,r,i,s,a,o,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return d;function d(x){return x===60?(e.enter(r),e.enter(i),e.enter(s),e.consume(x),e.exit(s),h):x===null||x===32||x===41||sr(x)?n(x):(e.enter(r),e.enter(a),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(x))}function h(x){return x===62?(e.enter(s),e.consume(x),e.exit(s),e.exit(i),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(x))}function f(x){return x===62?(e.exit("chunkString"),e.exit(o),h(x)):x===null||x===60||W(x)?n(x):(e.consume(x),x===92?g:f)}function g(x){return x===60||x===62||x===92?(e.consume(x),f):f(x)}function v(x){return!c&&(x===null||x===41||le(x))?(e.exit("chunkString"),e.exit(o),e.exit(a),e.exit(r),t(x)):c<u&&x===40?(e.consume(x),c++,v):x===41?(e.consume(x),c--,v):x===null||x===32||x===40||sr(x)?n(x):(e.consume(x),x===92?b:v)}function b(x){return x===40||x===41||x===92?(e.consume(x),v):v(x)}}function ol(e,t,n,r,i,s){const a=this;let o=0,l;return u;function u(f){return e.enter(r),e.enter(i),e.consume(f),e.exit(i),e.enter(s),c}function c(f){return o>999||f===null||f===91||f===93&&!l||f===94&&!o&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(e.exit(s),e.enter(i),e.consume(f),e.exit(i),e.exit(r),t):W(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||W(f)||o++>999?(e.exit("chunkString"),c(f)):(e.consume(f),l||(l=!ne(f)),f===92?h:d)}function h(f){return f===91||f===92||f===93?(e.consume(f),o++,d):d(f)}}function ll(e,t,n,r,i,s){let a;return o;function o(h){return h===34||h===39||h===40?(e.enter(r),e.enter(i),e.consume(h),e.exit(i),a=h===40?41:h,l):n(h)}function l(h){return h===a?(e.enter(i),e.consume(h),e.exit(i),e.exit(r),t):(e.enter(s),u(h))}function u(h){return h===a?(e.exit(s),l(a)):h===null?n(h):W(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),se(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(h))}function c(h){return h===a||h===null||W(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?d:c)}function d(h){return h===a||h===92?(e.consume(h),c):c(h)}}function xn(e,t){let n;return r;function r(i){return W(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,r):ne(i)?se(e,r,n?"linePrefix":"lineSuffix")(i):t(i)}}const Hm={name:"definition",tokenize:Vm},qm={partial:!0,tokenize:Wm};function Vm(e,t,n){const r=this;let i;return s;function s(f){return e.enter("definition"),a(f)}function a(f){return ol.call(r,e,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return i=tt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):n(f)}function l(f){return le(f)?xn(e,u)(f):u(f)}function u(f){return al(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function c(f){return e.attempt(qm,d,d)(f)}function d(f){return ne(f)?se(e,h,"whitespace")(f):h(f)}function h(f){return f===null||W(f)?(e.exit("definition"),r.parser.defined.push(i),t(f)):n(f)}}function Wm(e,t,n){return r;function r(o){return le(o)?xn(e,i)(o):n(o)}function i(o){return ll(e,s,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function s(o){return ne(o)?se(e,a,"whitespace")(o):a(o)}function a(o){return o===null||W(o)?t(o):n(o)}}const Jm={name:"hardBreakEscape",tokenize:Km};function Km(e,t,n){return r;function r(s){return e.enter("hardBreakEscape"),e.consume(s),i}function i(s){return W(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}const Ym={name:"headingAtx",resolve:Gm,tokenize:Xm};function Gm(e,t){let n=e.length-2,r=3,i,s;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},s={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},qe(e,r,n-r+1,[["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t]])),e}function Xm(e,t,n){let r=0;return i;function i(c){return e.enter("atxHeading"),s(c)}function s(c){return e.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&r++<6?(e.consume(c),a):c===null||le(c)?(e.exit("atxHeadingSequence"),o(c)):n(c)}function o(c){return c===35?(e.enter("atxHeadingSequence"),l(c)):c===null||W(c)?(e.exit("atxHeading"),t(c)):ne(c)?se(e,o,"whitespace")(c):(e.enter("atxHeadingText"),u(c))}function l(c){return c===35?(e.consume(c),l):(e.exit("atxHeadingSequence"),o(c))}function u(c){return c===null||c===35||le(c)?(e.exit("atxHeadingText"),o(c)):(e.consume(c),u)}}const Qm=["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"],ul=["pre","script","style","textarea"],Zm={concrete:!0,name:"htmlFlow",resolveTo:ng,tokenize:rg},eg={partial:!0,tokenize:sg},tg={partial:!0,tokenize:ig};function ng(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 rg(e,t,n){const r=this;let i,s,a,o,l;return u;function u(S){return c(S)}function c(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),d}function d(S){return S===33?(e.consume(S),h):S===47?(e.consume(S),s=!0,v):S===63?(e.consume(S),i=3,r.interrupt?t:w):Oe(S)?(e.consume(S),a=String.fromCharCode(S),b):n(S)}function h(S){return S===45?(e.consume(S),i=2,f):S===91?(e.consume(S),i=5,o=0,g):Oe(S)?(e.consume(S),i=4,r.interrupt?t:w):n(S)}function f(S){return S===45?(e.consume(S),r.interrupt?t:w):n(S)}function g(S){const Ce="CDATA[";return S===Ce.charCodeAt(o++)?(e.consume(S),o===Ce.length?r.interrupt?t:P:g):n(S)}function v(S){return Oe(S)?(e.consume(S),a=String.fromCharCode(S),b):n(S)}function b(S){if(S===null||S===47||S===62||le(S)){const Ce=S===47,lt=a.toLowerCase();return!Ce&&!s&&ul.includes(lt)?(i=1,r.interrupt?t(S):P(S)):Qm.includes(a.toLowerCase())?(i=6,Ce?(e.consume(S),x):r.interrupt?t(S):P(S)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(S):s?E(S):_(S))}return S===45||Pe(S)?(e.consume(S),a+=String.fromCharCode(S),b):n(S)}function x(S){return S===62?(e.consume(S),r.interrupt?t:P):n(S)}function E(S){return ne(S)?(e.consume(S),E):k(S)}function _(S){return S===47?(e.consume(S),k):S===58||S===95||Oe(S)?(e.consume(S),F):ne(S)?(e.consume(S),_):k(S)}function F(S){return S===45||S===46||S===58||S===95||Pe(S)?(e.consume(S),F):B(S)}function B(S){return S===61?(e.consume(S),C):ne(S)?(e.consume(S),B):_(S)}function C(S){return S===null||S===60||S===61||S===62||S===96?n(S):S===34||S===39?(e.consume(S),l=S,H):ne(S)?(e.consume(S),C):V(S)}function H(S){return S===l?(e.consume(S),l=null,j):S===null||W(S)?n(S):(e.consume(S),H)}function V(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||le(S)?B(S):(e.consume(S),V)}function j(S){return S===47||S===62||ne(S)?_(S):n(S)}function k(S){return S===62?(e.consume(S),O):n(S)}function O(S){return S===null||W(S)?P(S):ne(S)?(e.consume(S),O):n(S)}function P(S){return S===45&&i===2?(e.consume(S),G):S===60&&i===1?(e.consume(S),J):S===62&&i===4?(e.consume(S),ge):S===63&&i===3?(e.consume(S),w):S===93&&i===5?(e.consume(S),de):W(S)&&(i===6||i===7)?(e.exit("htmlFlowData"),e.check(eg,ye,R)(S)):S===null||W(S)?(e.exit("htmlFlowData"),R(S)):(e.consume(S),P)}function R(S){return e.check(tg,L,ye)(S)}function L(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),N}function N(S){return S===null||W(S)?R(S):(e.enter("htmlFlowData"),P(S))}function G(S){return S===45?(e.consume(S),w):P(S)}function J(S){return S===47?(e.consume(S),a="",Z):P(S)}function Z(S){if(S===62){const Ce=a.toLowerCase();return ul.includes(Ce)?(e.consume(S),ge):P(S)}return Oe(S)&&a.length<8?(e.consume(S),a+=String.fromCharCode(S),Z):P(S)}function de(S){return S===93?(e.consume(S),w):P(S)}function w(S){return S===62?(e.consume(S),ge):S===45&&i===2?(e.consume(S),w):P(S)}function ge(S){return S===null||W(S)?(e.exit("htmlFlowData"),ye(S)):(e.consume(S),ge)}function ye(S){return e.exit("htmlFlow"),t(S)}}function ig(e,t,n){const r=this;return i;function i(a){return W(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),s):n(a)}function s(a){return r.parser.lazy[r.now().line]?n(a):t(a)}}function sg(e,t,n){return r;function r(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),e.attempt(bn,t,n)}}const ag={name:"htmlText",tokenize:og};function og(e,t,n){const r=this;let i,s,a;return o;function o(w){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(w),l}function l(w){return w===33?(e.consume(w),u):w===47?(e.consume(w),B):w===63?(e.consume(w),_):Oe(w)?(e.consume(w),V):n(w)}function u(w){return w===45?(e.consume(w),c):w===91?(e.consume(w),s=0,g):Oe(w)?(e.consume(w),E):n(w)}function c(w){return w===45?(e.consume(w),f):n(w)}function d(w){return w===null?n(w):w===45?(e.consume(w),h):W(w)?(a=d,J(w)):(e.consume(w),d)}function h(w){return w===45?(e.consume(w),f):d(w)}function f(w){return w===62?G(w):w===45?h(w):d(w)}function g(w){const ge="CDATA[";return w===ge.charCodeAt(s++)?(e.consume(w),s===ge.length?v:g):n(w)}function v(w){return w===null?n(w):w===93?(e.consume(w),b):W(w)?(a=v,J(w)):(e.consume(w),v)}function b(w){return w===93?(e.consume(w),x):v(w)}function x(w){return w===62?G(w):w===93?(e.consume(w),x):v(w)}function E(w){return w===null||w===62?G(w):W(w)?(a=E,J(w)):(e.consume(w),E)}function _(w){return w===null?n(w):w===63?(e.consume(w),F):W(w)?(a=_,J(w)):(e.consume(w),_)}function F(w){return w===62?G(w):_(w)}function B(w){return Oe(w)?(e.consume(w),C):n(w)}function C(w){return w===45||Pe(w)?(e.consume(w),C):H(w)}function H(w){return W(w)?(a=H,J(w)):ne(w)?(e.consume(w),H):G(w)}function V(w){return w===45||Pe(w)?(e.consume(w),V):w===47||w===62||le(w)?j(w):n(w)}function j(w){return w===47?(e.consume(w),G):w===58||w===95||Oe(w)?(e.consume(w),k):W(w)?(a=j,J(w)):ne(w)?(e.consume(w),j):G(w)}function k(w){return w===45||w===46||w===58||w===95||Pe(w)?(e.consume(w),k):O(w)}function O(w){return w===61?(e.consume(w),P):W(w)?(a=O,J(w)):ne(w)?(e.consume(w),O):j(w)}function P(w){return w===null||w===60||w===61||w===62||w===96?n(w):w===34||w===39?(e.consume(w),i=w,R):W(w)?(a=P,J(w)):ne(w)?(e.consume(w),P):(e.consume(w),L)}function R(w){return w===i?(e.consume(w),i=void 0,N):w===null?n(w):W(w)?(a=R,J(w)):(e.consume(w),R)}function L(w){return w===null||w===34||w===39||w===60||w===61||w===96?n(w):w===47||w===62||le(w)?j(w):(e.consume(w),L)}function N(w){return w===47||w===62||le(w)?j(w):n(w)}function G(w){return w===62?(e.consume(w),e.exit("htmlTextData"),e.exit("htmlText"),t):n(w)}function J(w){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),Z}function Z(w){return ne(w)?se(e,de,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):de(w)}function de(w){return e.enter("htmlTextData"),a(w)}}const _i={name:"labelEnd",resolveAll:dg,resolveTo:hg,tokenize:fg},lg={tokenize:pg},ug={tokenize:mg},cg={tokenize:gg};function dg(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const i=r.type==="labelImage"?4:2;r.type="data",t+=i}}return e.length!==n.length&&qe(e,0,e.length,n),e}function hg(e,t){let n=e.length,r=0,i,s,a,o;for(;n--;)if(i=e[n][1],s){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;e[n][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(a){if(e[n][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(s=n,i.type!=="labelLink")){r=2;break}}else i.type==="labelEnd"&&(a=n);const l={type:e[s][1].type==="labelLink"?"link":"image",start:m({},e[s][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[s][1].start),end:m({},e[a][1].end)},c={type:"labelText",start:m({},e[s+r+2][1].end),end:m({},e[a-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Je(o,e.slice(s+1,s+r+3)),o=Je(o,[["enter",c,t]]),o=Je(o,or(t.parser.constructs.insideSpan.null,e.slice(s+r+4,a-3),t)),o=Je(o,[["exit",c,t],e[a-2],e[a-1],["exit",u,t]]),o=Je(o,e.slice(a+1)),o=Je(o,[["exit",l,t]]),qe(e,s,e.length,o),e}function fg(e,t,n){const r=this;let i=r.events.length,s,a;for(;i--;)if((r.events[i][1].type==="labelImage"||r.events[i][1].type==="labelLink")&&!r.events[i][1]._balanced){s=r.events[i][1];break}return o;function o(h){return s?s._inactive?d(h):(a=r.parser.defined.includes(tt(r.sliceSerialize({start:s.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),l):n(h)}function l(h){return h===40?e.attempt(lg,c,a?c:d)(h):h===91?e.attempt(ug,c,a?u:d)(h):a?c(h):d(h)}function u(h){return e.attempt(cg,c,d)(h)}function c(h){return t(h)}function d(h){return s._balanced=!0,n(h)}}function pg(e,t,n){return r;function r(d){return e.enter("resource"),e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),i}function i(d){return le(d)?xn(e,s)(d):s(d)}function s(d){return d===41?c(d):al(e,a,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function a(d){return le(d)?xn(e,l)(d):c(d)}function o(d){return n(d)}function l(d){return d===34||d===39||d===40?ll(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):c(d)}function u(d){return le(d)?xn(e,c)(d):c(d)}function c(d){return d===41?(e.enter("resourceMarker"),e.consume(d),e.exit("resourceMarker"),e.exit("resource"),t):n(d)}}function mg(e,t,n){const r=this;return i;function i(o){return ol.call(r,e,s,a,"reference","referenceMarker","referenceString")(o)}function s(o){return r.parser.defined.includes(tt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function a(o){return n(o)}}function gg(e,t,n){return r;function r(s){return e.enter("reference"),e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),i}function i(s){return s===93?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):n(s)}}const yg={name:"labelStartImage",resolveAll:_i.resolveAll,tokenize:bg};function bg(e,t,n){const r=this;return i;function i(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),s}function s(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),a):n(o)}function a(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const wg={name:"labelStartLink",resolveAll:_i.resolveAll,tokenize:xg};function xg(e,t,n){const r=this;return i;function i(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),s}function s(a){return a===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(a):t(a)}}const Ti={name:"lineEnding",tokenize:vg};function vg(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),se(e,t,"linePrefix")}}const lr={name:"thematicBreak",tokenize:Sg};function Sg(e,t,n){let r=0,i;return s;function s(u){return e.enter("thematicBreak"),a(u)}function a(u){return i=u,o(u)}function o(u){return u===i?(e.enter("thematicBreakSequence"),l(u)):r>=3&&(u===null||W(u))?(e.exit("thematicBreak"),t(u)):n(u)}function l(u){return u===i?(e.consume(u),r++,l):(e.exit("thematicBreakSequence"),ne(u)?se(e,o,"whitespace")(u):o(u))}}const je={continuation:{tokenize:Cg},exit:Eg,name:"list",tokenize:Tg},kg={partial:!0,tokenize:Ag},_g={partial:!0,tokenize:Ig};function Tg(e,t,n){const r=this,i=r.events[r.events.length-1];let s=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return o;function o(f){const g=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:vi(f)){if(r.containerState.type||(r.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(lr,n,u)(f):u(f);if(!r.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return n(f)}function l(f){return vi(f)&&++a<10?(e.consume(f),l):(!r.interrupt||a<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,e.check(bn,r.interrupt?n:c,e.attempt(kg,h,d))}function c(f){return r.containerState.initialBlankLine=!0,s++,h(f)}function d(f){return ne(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),h):n(f)}function h(f){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Cg(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(bn,i,s);function i(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,se(e,t,"listItemIndent",r.containerState.size+1)(o)}function s(o){return r.containerState.furtherBlankLines||!ne(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(_g,t,a)(o))}function a(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,se(e,e.attempt(je,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Ig(e,t,n){const r=this;return se(e,i,"listItemIndent",r.containerState.size+1);function i(s){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(s):n(s)}}function Eg(e){e.exit(this.containerState.type)}function Ag(e,t,n){const r=this;return se(e,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(s){const a=r.events[r.events.length-1];return!ne(s)&&a&&a[1].type==="listItemPrefixWhitespace"?t(s):n(s)}}const cl={name:"setextUnderline",resolveTo:Mg,tokenize:Pg};function Mg(e,t){let n=e.length,r,i,s;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(i=n)}else e[n][1].type==="content"&&e.splice(n,1),!s&&e[n][1].type==="definition"&&(s=n);const a={type:"setextHeading",start:m({},e[r][1].start),end:m({},e[e.length-1][1].end)};return e[i][1].type="setextHeadingText",s?(e.splice(i,0,["enter",a,t]),e.splice(s+1,0,["exit",e[r][1],t]),e[r][1].end=m({},e[s][1].end)):e[r][1]=a,e.push(["exit",a,t]),e}function Pg(e,t,n){const r=this;let i;return s;function s(u){let c=r.events.length,d;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){d=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||d)?(e.enter("setextHeadingLine"),i=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===i?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),ne(u)?se(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||W(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Ng={tokenize:Lg};function Lg(e){const t=this,n=e.attempt(bn,r,e.attempt(this.parser.constructs.flowInitial,i,se(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Bm,i)),"linePrefix")));return n;function r(s){if(s===null){e.consume(s);return}return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function i(s){if(s===null){e.consume(s);return}return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Dg={resolveAll:hl()},Og=dl("string"),Fg=dl("text");function dl(e){return{resolveAll:hl(e==="text"?zg:void 0),tokenize:t};function t(n){const r=this,i=this.parser.constructs[e],s=n.attempt(i,a,o);return a;function a(c){return u(c)?s(c):o(c)}function o(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),s(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const d=i[c];let h=-1;if(d)for(;++h<d.length;){const f=d[h];if(!f.previous||f.previous.call(r,r.previous))return!0}return!1}}}function hl(e){return t;function t(n,r){let i=-1,s;for(;++i<=n.length;)s===void 0?n[i]&&n[i][1].type==="data"&&(s=i,i++):(!n[i]||n[i][1].type!=="data")&&(i!==s+2&&(n[s][1].end=n[i-1][1].end,n.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(n,r):n}}function zg(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],i=t.sliceStream(r);let s=i.length,a=-1,o=0,l;for(;s--;){const u=i[s];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)o++,a--;if(a)break;a=-1}else if(u===-2)l=!0,o++;else if(u!==-1){s++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(o=0),o){const u={type:n===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:s?a:r.start._bufferIndex+a,_index:r.start._index+s,line:r.end.line,column:r.end.column-o,offset:r.end.offset-o},end:m({},r.end)};r.end=m({},u.start),r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Bg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Hm},disable:{null:[]},document:{42:je,43:je,45:je,48:je,49:je,50:je,51:je,52:je,53:je,54:je,55:je,56:je,57:je,62:el},flow:{35:Ym,42:lr,45:[cl,lr],60:Zm,61:cl,95:lr,96:il,126:il},flowInitial:{[-2]:ki,[-1]:ki,32:ki},insideSpan:{null:[Si,Dg]},string:{38:nl,92:tl},text:{[-5]:Ti,[-4]:Ti,[-3]:Ti,33:yg,38:nl,42:Si,60:[wm,ag],91:wg,92:[Jm,tl],93:_i,95:Si,96:Nm}},Symbol.toStringTag,{value:"Module"}));function Rg(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},s=[];let a=[],o=[];const l={attempt:H(B),check:H(C),consume:E,enter:_,exit:F,interrupt:H(C,{interrupt:!0})},u={code:null,containerState:{},defineSkip:v,events:[],now:g,parser:e,previous:null,sliceSerialize:h,sliceStream:f,write:d};let c=t.tokenize.call(u,l);return t.resolveAll&&s.push(t),u;function d(O){return a=Je(a,O),b(),a[a.length-1]!==null?[]:(V(t,0),u.events=or(s,u.events,u),u.events)}function h(O,P){return Ug(f(O),P)}function f(O){return jg(a,O)}function g(){const{_bufferIndex:O,_index:P,line:R,column:L,offset:N}=r;return{_bufferIndex:O,_index:P,line:R,column:L,offset:N}}function v(O){i[O.line]=O.column,k()}function b(){let O;for(;r._index<a.length;){const P=a[r._index];if(typeof P=="string")for(O=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===O&&r._bufferIndex<P.length;)x(P.charCodeAt(r._bufferIndex));else x(P)}}function x(O){c=c(O)}function E(O){W(O)?(r.line++,r.column=1,r.offset+=O===-3?2:1,k()):O!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===a[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=O}function _(O,P){const R=P||{};return R.type=O,R.start=g(),u.events.push(["enter",R,u]),o.push(R),R}function F(O){const P=o.pop();return P.end=g(),u.events.push(["exit",P,u]),P}function B(O,P){V(O,P.from)}function C(O,P){P.restore()}function H(O,P){return R;function R(L,N,G){let J,Z,de,w;return Array.isArray(L)?ye(L):"tokenize"in L?ye([L]):ge(L);function ge(ke){return U;function U(X){const ae=X!==null&&ke[X],fe=X!==null&&ke.null,Ie=[...Array.isArray(ae)?ae:ae?[ae]:[],...Array.isArray(fe)?fe:fe?[fe]:[]];return ye(Ie)(X)}}function ye(ke){return J=ke,Z=0,ke.length===0?G:S(ke[Z])}function S(ke){return U;function U(X){return w=j(),de=ke,ke.partial||(u.currentConstruct=ke),ke.name&&u.parser.constructs.disable.null.includes(ke.name)?lt():ke.tokenize.call(P?Object.assign(Object.create(u),P):u,l,Ce,lt)(X)}}function Ce(ke){return O(de,w),N}function lt(ke){return w.restore(),++Z<J.length?S(J[Z]):G}}}function V(O,P){O.resolveAll&&!s.includes(O)&&s.push(O),O.resolve&&qe(u.events,P,u.events.length-P,O.resolve(u.events.slice(P),u)),O.resolveTo&&(u.events=O.resolveTo(u.events,u))}function j(){const O=g(),P=u.previous,R=u.currentConstruct,L=u.events.length,N=Array.from(o);return{from:L,restore:G};function G(){r=O,u.previous=P,u.currentConstruct=R,u.events.length=L,o=N,k()}}function k(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function jg(e,t){const n=t.start._index,r=t.start._bufferIndex,i=t.end._index,s=t.end._bufferIndex;let a;if(n===i)a=[e[n].slice(r,s)];else{if(a=e.slice(n,i),r>-1){const o=a[0];typeof o=="string"?a[0]=o.slice(r):a.shift()}s>0&&a.push(e[i].slice(0,s))}return a}function Ug(e,t){let n=-1;const r=[];let i;for(;++n<e.length;){const s=e[n];let a;if(typeof s=="string")a=s;else switch(s){case-5:{a="\r";break}case-4:{a=`
9
9
  `;break}case-3:{a=`\r
10
- `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&i)continue;a=" ";break}default:a=String.fromCharCode(s)}i=s===-2,r.push(a)}return r.join("")}function Bg(e){const r={constructs:Vo([Lg,...(e||{}).extensions||[]]),content:i(om),defined:[],document:i(um),flow:i(Cg),lazy:{},string:i(Mg),text:i(Pg)};return r;function i(s){return a;function a(o){return Dg(r,s,o)}}}function zg(e){for(;!el(e););return e}const ll=/[\0\t\n\r]/g;function Rg(){let e=1,t="",n=!0,r;return i;function i(s,a,o){const l=[];let u,c,d,h,f;for(s=t+(typeof s=="string"?s.toString():new TextDecoder(a||void 0).decode(s)),d=0,t="",n&&(s.charCodeAt(0)===65279&&d++,n=void 0);d<s.length;){if(ll.lastIndex=d,u=ll.exec(s),h=u&&u.index!==void 0?u.index:s.length,f=s.charCodeAt(h),!u){t=s.slice(d);break}if(f===10&&d===h&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),d<h&&(l.push(s.slice(d,h)),e+=h-d),f){case 0:{l.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,l.push(-2);e++<c;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:r=!0,e=1}d=h+1}return o&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const jg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Ug(e){return e.replace(jg,$g)}function $g(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),s=i===120||i===88;return Wo(n.slice(s?2:1),s?16:10)}return yi(n)||e}const ul={}.hasOwnProperty;function Hg(e,t,n){return typeof t!="string"&&(n=t,t=void 0),qg(n)(zg(Bg(n).document().write(Rg()(e,t,!0))))}function qg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(we),autolinkProtocol:j,autolinkEmail:j,atxHeading:s(Ge),blockQuote:s(he),characterEscape:j,characterReference:j,codeFenced:s(Ce),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:s(Ce,a),codeText:s(ee,a),codeTextData:j,data:j,codeFlowValue:j,definition:s(xe),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:s(Ye),hardBreakEscape:s(Yt),hardBreakTrailing:s(Yt),htmlFlow:s(te,a),htmlFlowData:j,htmlText:s(te,a),htmlTextData:j,image:s(be),label:a,link:s(we),listItem:s(br),listItemValue:h,listOrdered:s(vt,d),listUnordered:s(vt),paragraph:s(wr),reference:S,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:s(Ge),strong:s(hv),thematicBreak:s(pv)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:ae,autolinkProtocol:X,blockQuote:l(),characterEscapeValue:k,characterReferenceMarkerHexadecimal:lt,characterReferenceMarkerNumeric:lt,characterReferenceValue:_e,characterReference:U,codeFenced:l(b),codeFencedFence:v,codeFencedFenceInfo:f,codeFencedFenceMeta:m,codeFlowValue:k,codeIndented:l(x),codeText:l(N),codeTextData:k,data:k,definition:l(),definitionDestinationString:F,definitionLabelString:C,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(P),hardBreakTrailing:l(P),htmlFlow:l(R),htmlFlowData:k,htmlText:l(L),htmlTextData:k,image:l(J),label:de,labelText:Z,lineEnding:O,link:l(G),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Ie,resourceDestinationString:w,resourceTitleString:ge,resource:ye,setextHeading:l(q),setextHeadingLineSequence:H,setextHeadingText:I,strong:l(),thematicBreak:l()}};cl(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(A){let B={type:"root",children:[]};const K={stack:[B],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:c,data:n},ie=[];let ue=-1;for(;++ue<A.length;)if(A[ue][1].type==="listOrdered"||A[ue][1].type==="listUnordered")if(A[ue][0]==="enter")ie.push(ue);else{const rt=ie.pop();ue=i(A,rt,ue)}for(ue=-1;++ue<A.length;){const rt=t[A[ue][0]];ul.call(rt,A[ue][1].type)&&rt[A[ue][1].type].call(Object.assign({sliceSerialize:A[ue][2].sliceSerialize},K),A[ue][1])}if(K.tokenStack.length>0){const rt=K.tokenStack[K.tokenStack.length-1];(rt[1]||dl).call(K,void 0,rt[0])}for(B.position={start:xt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:xt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},ue=-1;++ue<t.transforms.length;)B=t.transforms[ue](B)||B;return B}function i(A,B,K){let ie=B-1,ue=-1,rt=!1,Nt,ht,En,An;for(;++ie<=K;){const Ve=A[ie];switch(Ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ve[0]==="enter"?ue++:ue--,An=void 0;break}case"lineEndingBlank":{Ve[0]==="enter"&&(Nt&&!An&&!ue&&!En&&(En=ie),An=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:An=void 0}if(!ue&&Ve[0]==="enter"&&Ve[1].type==="listItemPrefix"||ue===-1&&Ve[0]==="exit"&&(Ve[1].type==="listUnordered"||Ve[1].type==="listOrdered")){if(Nt){let Gt=ie;for(ht=void 0;Gt--;){const ft=A[Gt];if(ft[1].type==="lineEnding"||ft[1].type==="lineEndingBlank"){if(ft[0]==="exit")continue;ht&&(A[ht][1].type="lineEndingBlank",rt=!0),ft[1].type="lineEnding",ht=Gt}else if(!(ft[1].type==="linePrefix"||ft[1].type==="blockQuotePrefix"||ft[1].type==="blockQuotePrefixWhitespace"||ft[1].type==="blockQuoteMarker"||ft[1].type==="listItemIndent"))break}En&&(!ht||En<ht)&&(Nt._spread=!0),Nt.end=Object.assign({},ht?A[ht][1].start:Ve[1].end),A.splice(ht||ie,0,["exit",Nt,Ve[2]]),ie++,K++}if(Ve[1].type==="listItemPrefix"){const Gt={type:"listItem",_spread:!1,start:Object.assign({},Ve[1].start),end:void 0};Nt=Gt,A.splice(ie,0,["enter",Gt,Ve[2]]),ie++,K++,En=void 0,An=!0}}}return A[B][1]._spread=rt,K}function s(A,B){return K;function K(ie){o.call(this,A(ie),ie),B&&B.call(this,ie)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(A,B,K){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([B,K||void 0]),A.position={start:xt(B.start),end:void 0}}function l(A){return B;function B(K){A&&A.call(this,K),u.call(this,K)}}function u(A,B){const K=this.stack.pop(),ie=this.tokenStack.pop();if(ie)ie[0].type!==A.type&&(B?B.call(this,A,ie[0]):(ie[1]||dl).call(this,A,ie[0]));else throw new Error("Cannot close `"+A.type+"` ("+mn({start:A.start,end:A.end})+"): it’s not open");K.position.end=xt(A.end)}function c(){return gi(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function h(A){if(this.data.expectingFirstListItemValue){const B=this.stack[this.stack.length-2];B.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function f(){const A=this.resume(),B=this.stack[this.stack.length-1];B.lang=A}function m(){const A=this.resume(),B=this.stack[this.stack.length-1];B.meta=A}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const A=this.resume(),B=this.stack[this.stack.length-1];B.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const A=this.resume(),B=this.stack[this.stack.length-1];B.value=A.replace(/(\r?\n|\r)$/g,"")}function C(A){const B=this.resume(),K=this.stack[this.stack.length-1];K.label=B,K.identifier=tt(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),B=this.stack[this.stack.length-1];B.title=A}function F(){const A=this.resume(),B=this.stack[this.stack.length-1];B.url=A}function z(A){const B=this.stack[this.stack.length-1];if(!B.depth){const K=this.sliceSerialize(A).length;B.depth=K}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function H(A){const B=this.stack[this.stack.length-1];B.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function q(){this.data.setextHeadingSlurpLineEnding=void 0}function j(A){const K=this.stack[this.stack.length-1].children;let ie=K[K.length-1];(!ie||ie.type!=="text")&&(ie=fv(),ie.position={start:xt(A.start),end:void 0},K.push(ie)),this.stack.push(ie)}function k(A){const B=this.stack.pop();B.value+=this.sliceSerialize(A),B.position.end=xt(A.end)}function O(A){const B=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=B.children[B.children.length-1];K.position.end=xt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(B.type)&&(j.call(this,A),k.call(this,A))}function P(){this.data.atHardBreak=!0}function R(){const A=this.resume(),B=this.stack[this.stack.length-1];B.value=A}function L(){const A=this.resume(),B=this.stack[this.stack.length-1];B.value=A}function N(){const A=this.resume(),B=this.stack[this.stack.length-1];B.value=A}function G(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const B=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=B,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function J(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const B=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=B,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function Z(A){const B=this.sliceSerialize(A),K=this.stack[this.stack.length-2];K.label=Ug(B),K.identifier=tt(B).toLowerCase()}function de(){const A=this.stack[this.stack.length-1],B=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const ie=A.children;K.children=ie}else K.alt=B}function w(){const A=this.resume(),B=this.stack[this.stack.length-1];B.url=A}function ge(){const A=this.resume(),B=this.stack[this.stack.length-1];B.title=A}function ye(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function Ie(A){const B=this.resume(),K=this.stack[this.stack.length-1];K.label=B,K.identifier=tt(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function lt(A){this.data.characterReferenceType=A.type}function _e(A){const B=this.sliceSerialize(A),K=this.data.characterReferenceType;let ie;K?(ie=Wo(B,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ie=yi(B);const ue=this.stack[this.stack.length-1];ue.value+=ie}function U(A){const B=this.stack.pop();B.position.end=xt(A.end)}function X(A){k.call(this,A);const B=this.stack[this.stack.length-1];B.url=this.sliceSerialize(A)}function ae(A){k.call(this,A);const B=this.stack[this.stack.length-1];B.url="mailto:"+this.sliceSerialize(A)}function he(){return{type:"blockquote",children:[]}}function Ce(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function xe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Ye(){return{type:"emphasis",children:[]}}function Ge(){return{type:"heading",depth:0,children:[]}}function Yt(){return{type:"break"}}function te(){return{type:"html",value:""}}function be(){return{type:"image",title:null,url:"",alt:null}}function we(){return{type:"link",title:null,url:"",children:[]}}function vt(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function br(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function wr(){return{type:"paragraph",children:[]}}function hv(){return{type:"strong",children:[]}}function fv(){return{type:"text",value:""}}function pv(){return{type:"thematicBreak"}}}function xt(e){return{line:e.line,column:e.column,offset:e.offset}}function cl(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?cl(e,r):Vg(e,r)}}function Vg(e,t){let n;for(n in t)if(ul.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function dl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+mn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+mn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+mn({start:t.start,end:t.end})+") is still open")}function Wg(e){const t=this;t.parser=n;function n(r){return Hg(r,E(g(g({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function Jg(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function Kg(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
11
- `}]}function Yg(e,t){const n=t.value?t.value+`
12
- `:"",r={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(r.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function Gg(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Xg(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Qg(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=Vt(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let a,o=e.footnoteCounts.get(r);o===void 0?(o=0,e.footnoteOrder.push(r),a=e.footnoteOrder.length):a=s+1,o+=1,e.footnoteCounts.set(r,o);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function Zg(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ey(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function hl(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&a.type==="text"?a.value+=r:i.push({type:"text",value:r}),i}function ty(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return hl(e,t);const i={src:Vt(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function ny(e,t){const n={src:Vt(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function ry(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function iy(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return hl(e,t);const i={href:Vt(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function sy(e,t){const n={href:Vt(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function ay(e,t,n){const r=e.all(t),i=n?oy(n):fl(t),s={},a=[];if(typeof t.checked=="boolean"){const c=r[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<r.length;){const c=r[o];(i||o!==0||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
10
+ `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&i)continue;a=" ";break}default:a=String.fromCharCode(s)}i=s===-2,r.push(a)}return r.join("")}function $g(e){const r={constructs:Go([Bg,...(e||{}).extensions||[]]),content:i(hm),defined:[],document:i(pm),flow:i(Ng),lazy:{},string:i(Og),text:i(Fg)};return r;function i(s){return a;function a(o){return Rg(r,s,o)}}}function Hg(e){for(;!sl(e););return e}const fl=/[\0\t\n\r]/g;function qg(){let e=1,t="",n=!0,r;return i;function i(s,a,o){const l=[];let u,c,d,h,f;for(s=t+(typeof s=="string"?s.toString():new TextDecoder(a||void 0).decode(s)),d=0,t="",n&&(s.charCodeAt(0)===65279&&d++,n=void 0);d<s.length;){if(fl.lastIndex=d,u=fl.exec(s),h=u&&u.index!==void 0?u.index:s.length,f=s.charCodeAt(h),!u){t=s.slice(d);break}if(f===10&&d===h&&r)l.push(-3),r=void 0;else switch(r&&(l.push(-5),r=void 0),d<h&&(l.push(s.slice(d,h)),e+=h-d),f){case 0:{l.push(65533),e++;break}case 9:{for(c=Math.ceil(e/4)*4,l.push(-2);e++<c;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:r=!0,e=1}d=h+1}return o&&(r&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Vg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Wg(e){return e.replace(Vg,Jg)}function Jg(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const i=n.charCodeAt(1),s=i===120||i===88;return Xo(n.slice(s?2:1),s?16:10)}return xi(n)||e}const pl={}.hasOwnProperty;function Kg(e,t,n){return typeof t!="string"&&(n=t,t=void 0),Yg(n)(Hg($g(n).document().write(qg()(e,t,!0))))}function Yg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(we),autolinkProtocol:j,autolinkEmail:j,atxHeading:s(Ge),blockQuote:s(fe),characterEscape:j,characterReference:j,codeFenced:s(Ie),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:s(Ie,a),codeText:s(re,a),codeTextData:j,data:j,codeFlowValue:j,definition:s(_e),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:s(Ye),hardBreakEscape:s(Xt),hardBreakTrailing:s(Xt),htmlFlow:s(ee,a),htmlFlowData:j,htmlText:s(ee,a),htmlTextData:j,image:s(be),label:a,link:s(we),listItem:s(xr),listItemValue:h,listOrdered:s(vt,d),listUnordered:s(vt),paragraph:s(vr),reference:S,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:s(Ge),strong:s(yv),thematicBreak:s(wv)},exit:{atxHeading:l(),atxHeadingSequence:B,autolink:l(),autolinkEmail:ae,autolinkProtocol:X,blockQuote:l(),characterEscapeValue:k,characterReferenceMarkerHexadecimal:lt,characterReferenceMarkerNumeric:lt,characterReferenceValue:ke,characterReference:U,codeFenced:l(b),codeFencedFence:v,codeFencedFenceInfo:f,codeFencedFenceMeta:g,codeFlowValue:k,codeIndented:l(x),codeText:l(N),codeTextData:k,data:k,definition:l(),definitionDestinationString:F,definitionLabelString:E,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(P),hardBreakTrailing:l(P),htmlFlow:l(R),htmlFlowData:k,htmlText:l(L),htmlTextData:k,image:l(J),label:de,labelText:Z,lineEnding:O,link:l(G),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Ce,resourceDestinationString:w,resourceTitleString:ge,resource:ye,setextHeading:l(V),setextHeadingLineSequence:H,setextHeadingText:C,strong:l(),thematicBreak:l()}};ml(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(A){let z={type:"root",children:[]};const K={stack:[z],tokenStack:[],config:t,enter:o,exit:u,buffer:a,resume:c,data:n},ie=[];let ue=-1;for(;++ue<A.length;)if(A[ue][1].type==="listOrdered"||A[ue][1].type==="listUnordered")if(A[ue][0]==="enter")ie.push(ue);else{const rt=ie.pop();ue=i(A,rt,ue)}for(ue=-1;++ue<A.length;){const rt=t[A[ue][0]];pl.call(rt,A[ue][1].type)&&rt[A[ue][1].type].call(Object.assign({sliceSerialize:A[ue][2].sliceSerialize},K),A[ue][1])}if(K.tokenStack.length>0){const rt=K.tokenStack[K.tokenStack.length-1];(rt[1]||gl).call(K,void 0,rt[0])}for(z.position={start:xt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:xt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},ue=-1;++ue<t.transforms.length;)z=t.transforms[ue](z)||z;return z}function i(A,z,K){let ie=z-1,ue=-1,rt=!1,Nt,ht,An,Mn;for(;++ie<=K;){const Ve=A[ie];switch(Ve[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ve[0]==="enter"?ue++:ue--,Mn=void 0;break}case"lineEndingBlank":{Ve[0]==="enter"&&(Nt&&!Mn&&!ue&&!An&&(An=ie),Mn=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Mn=void 0}if(!ue&&Ve[0]==="enter"&&Ve[1].type==="listItemPrefix"||ue===-1&&Ve[0]==="exit"&&(Ve[1].type==="listUnordered"||Ve[1].type==="listOrdered")){if(Nt){let Qt=ie;for(ht=void 0;Qt--;){const ft=A[Qt];if(ft[1].type==="lineEnding"||ft[1].type==="lineEndingBlank"){if(ft[0]==="exit")continue;ht&&(A[ht][1].type="lineEndingBlank",rt=!0),ft[1].type="lineEnding",ht=Qt}else if(!(ft[1].type==="linePrefix"||ft[1].type==="blockQuotePrefix"||ft[1].type==="blockQuotePrefixWhitespace"||ft[1].type==="blockQuoteMarker"||ft[1].type==="listItemIndent"))break}An&&(!ht||An<ht)&&(Nt._spread=!0),Nt.end=Object.assign({},ht?A[ht][1].start:Ve[1].end),A.splice(ht||ie,0,["exit",Nt,Ve[2]]),ie++,K++}if(Ve[1].type==="listItemPrefix"){const Qt={type:"listItem",_spread:!1,start:Object.assign({},Ve[1].start),end:void 0};Nt=Qt,A.splice(ie,0,["enter",Qt,Ve[2]]),ie++,K++,An=void 0,Mn=!0}}}return A[z][1]._spread=rt,K}function s(A,z){return K;function K(ie){o.call(this,A(ie),ie),z&&z.call(this,ie)}}function a(){this.stack.push({type:"fragment",children:[]})}function o(A,z,K){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([z,K||void 0]),A.position={start:xt(z.start),end:void 0}}function l(A){return z;function z(K){A&&A.call(this,K),u.call(this,K)}}function u(A,z){const K=this.stack.pop(),ie=this.tokenStack.pop();if(ie)ie[0].type!==A.type&&(z?z.call(this,A,ie[0]):(ie[1]||gl).call(this,A,ie[0]));else throw new Error("Cannot close `"+A.type+"` ("+gn({start:A.start,end:A.end})+"): it’s not open");K.position.end=xt(A.end)}function c(){return wi(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function h(A){if(this.data.expectingFirstListItemValue){const z=this.stack[this.stack.length-2];z.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function f(){const A=this.resume(),z=this.stack[this.stack.length-1];z.lang=A}function g(){const A=this.resume(),z=this.stack[this.stack.length-1];z.meta=A}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A.replace(/(\r?\n|\r)$/g,"")}function E(A){const z=this.resume(),K=this.stack[this.stack.length-1];K.label=z,K.identifier=tt(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),z=this.stack[this.stack.length-1];z.title=A}function F(){const A=this.resume(),z=this.stack[this.stack.length-1];z.url=A}function B(A){const z=this.stack[this.stack.length-1];if(!z.depth){const K=this.sliceSerialize(A).length;z.depth=K}}function C(){this.data.setextHeadingSlurpLineEnding=!0}function H(A){const z=this.stack[this.stack.length-1];z.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function j(A){const K=this.stack[this.stack.length-1].children;let ie=K[K.length-1];(!ie||ie.type!=="text")&&(ie=bv(),ie.position={start:xt(A.start),end:void 0},K.push(ie)),this.stack.push(ie)}function k(A){const z=this.stack.pop();z.value+=this.sliceSerialize(A),z.position.end=xt(A.end)}function O(A){const z=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=z.children[z.children.length-1];K.position.end=xt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(z.type)&&(j.call(this,A),k.call(this,A))}function P(){this.data.atHardBreak=!0}function R(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function L(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function N(){const A=this.resume(),z=this.stack[this.stack.length-1];z.value=A}function G(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const z=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=z,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function J(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const z=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=z,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function Z(A){const z=this.sliceSerialize(A),K=this.stack[this.stack.length-2];K.label=Wg(z),K.identifier=tt(z).toLowerCase()}function de(){const A=this.stack[this.stack.length-1],z=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const ie=A.children;K.children=ie}else K.alt=z}function w(){const A=this.resume(),z=this.stack[this.stack.length-1];z.url=A}function ge(){const A=this.resume(),z=this.stack[this.stack.length-1];z.title=A}function ye(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function Ce(A){const z=this.resume(),K=this.stack[this.stack.length-1];K.label=z,K.identifier=tt(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function lt(A){this.data.characterReferenceType=A.type}function ke(A){const z=this.sliceSerialize(A),K=this.data.characterReferenceType;let ie;K?(ie=Xo(z,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ie=xi(z);const ue=this.stack[this.stack.length-1];ue.value+=ie}function U(A){const z=this.stack.pop();z.position.end=xt(A.end)}function X(A){k.call(this,A);const z=this.stack[this.stack.length-1];z.url=this.sliceSerialize(A)}function ae(A){k.call(this,A);const z=this.stack[this.stack.length-1];z.url="mailto:"+this.sliceSerialize(A)}function fe(){return{type:"blockquote",children:[]}}function Ie(){return{type:"code",lang:null,meta:null,value:""}}function re(){return{type:"inlineCode",value:""}}function _e(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Ye(){return{type:"emphasis",children:[]}}function Ge(){return{type:"heading",depth:0,children:[]}}function Xt(){return{type:"break"}}function ee(){return{type:"html",value:""}}function be(){return{type:"image",title:null,url:"",alt:null}}function we(){return{type:"link",title:null,url:"",children:[]}}function vt(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function xr(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function vr(){return{type:"paragraph",children:[]}}function yv(){return{type:"strong",children:[]}}function bv(){return{type:"text",value:""}}function wv(){return{type:"thematicBreak"}}}function xt(e){return{line:e.line,column:e.column,offset:e.offset}}function ml(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?ml(e,r):Gg(e,r)}}function Gg(e,t){let n;for(n in t)if(pl.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function gl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+gn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+gn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+gn({start:t.start,end:t.end})+") is still open")}function Xg(e){const t=this;t.parser=n;function n(r){return Kg(r,I(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function Qg(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function Zg(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
11
+ `}]}function ey(e,t){const n=t.value?t.value+`
12
+ `:"",r={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(r.className=["language-"+i[0]]);let s={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(s.data={meta:t.meta}),e.patch(t,s),s=e.applyData(t,s),s={type:"element",tagName:"pre",properties:{},children:[s]},e.patch(t,s),s}function ty(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ny(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ry(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),i=Jt(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let a,o=e.footnoteCounts.get(r);o===void 0?(o=0,e.footnoteOrder.push(r),a=e.footnoteOrder.length):a=s+1,o+=1,e.footnoteCounts.set(r,o);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+i,id:n+"fnref-"+i+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function iy(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function sy(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function yl(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const i=e.all(t),s=i[0];s&&s.type==="text"?s.value="["+s.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&a.type==="text"?a.value+=r:i.push({type:"text",value:r}),i}function ay(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return yl(e,t);const i={src:Jt(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function oy(e,t){const n={src:Jt(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function ly(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function uy(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return yl(e,t);const i={href:Jt(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function cy(e,t){const n={href:Jt(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function dy(e,t,n){const r=e.all(t),i=n?hy(n):bl(t),s={},a=[];if(typeof t.checked=="boolean"){const c=r[0];let d;c&&c.type==="element"&&c.tagName==="p"?d=c:(d={type:"element",tagName:"p",properties:{},children:[]},r.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<r.length;){const c=r[o];(i||o!==0||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
13
13
  `}),c.type==="element"&&c.tagName==="p"&&!i?a.push(...c.children):a.push(c)}const l=r[r.length-1];l&&(i||l.type!=="element"||l.tagName!=="p")&&a.push({type:"text",value:`
14
- `});const u={type:"element",tagName:"li",properties:s,children:a};return e.patch(t,u),e.applyData(t,u)}function oy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=fl(n[r])}return t}function fl(e){const t=e.spread;return t==null?e.children.length>1:t}function ly(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i<r.length;){const a=r[i];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const s={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,s),e.applyData(t,s)}function uy(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function cy(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function dy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function hy(e,t){const n=e.all(t),r=n.shift(),i=[];if(r){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],a),i.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=ci(t.children[1]),l=Lo(t.children[t.children.length-1]);o&&l&&(a.position={start:o,end:l}),i.push(a)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function fy(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,o=a?a.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const d=t.children[l],h={},f=a?a[l]:void 0;f&&(h.align=f);let m={type:"element",tagName:s,properties:h,children:[]};d&&(m.children=e.all(d),e.patch(d,m),m=e.applyData(d,m)),u.push(m)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function py(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const pl=9,ml=32;function my(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),i=0;const s=[];for(;r;)s.push(gl(t.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(gl(t.slice(i),i>0,!1)),s.join("")}function gl(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===pl||s===ml;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===pl||s===ml;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function gy(e,t){const n={type:"text",value:my(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const by={blockquote:Jg,break:Kg,code:Yg,delete:Gg,emphasis:Xg,footnoteReference:Qg,heading:Zg,html:ey,imageReference:ty,image:ny,inlineCode:ry,linkReference:iy,link:sy,listItem:ay,list:ly,paragraph:uy,root:cy,strong:dy,table:hy,tableCell:py,tableRow:fy,text:gy,thematicBreak:yy,toml:or,yaml:or,definition:or,footnoteDefinition:or};function or(){}const yl=-1,lr=0,xn=1,ur=2,ki=3,_i=4,Ti=5,Ii=6,bl=7,wl=8,xl=typeof self=="object"?self:globalThis,wy=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,a]=t[i];switch(s){case lr:case yl:return n(a,i);case xn:{const o=n([],i);for(const l of a)o.push(r(l));return o}case ur:{const o=n({},i);for(const[l,u]of a)o[r(l)]=r(u);return o}case ki:return n(new Date(a),i);case _i:{const{source:o,flags:l}=a;return n(new RegExp(o,l),i)}case Ti:{const o=n(new Map,i);for(const[l,u]of a)o.set(r(l),r(u));return o}case Ii:{const o=n(new Set,i);for(const l of a)o.add(r(l));return o}case bl:{const{name:o,message:l}=a;return n(new xl[o](l),i)}case wl:return n(BigInt(a),i);case"BigInt":return n(Object(BigInt(a)),i);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return n(new DataView(o),a)}}return n(new xl[s](a),i)};return r},vl=e=>wy(new Map,e)(0),Jt="",{toString:xy}={},{keys:vy}=Object,vn=e=>{const t=typeof e;if(t!=="object"||!e)return[lr,t];const n=xy.call(e).slice(8,-1);switch(n){case"Array":return[xn,Jt];case"Object":return[ur,Jt];case"Date":return[ki,Jt];case"RegExp":return[_i,Jt];case"Map":return[Ti,Jt];case"Set":return[Ii,Jt];case"DataView":return[xn,n]}return n.includes("Array")?[xn,n]:n.includes("Error")?[bl,n]:[ur,n]},cr=([e,t])=>e===lr&&(t==="function"||t==="symbol"),Sy=(e,t,n,r)=>{const i=(a,o)=>{const l=r.push(a)-1;return n.set(o,l),l},s=a=>{if(n.has(a))return n.get(a);let[o,l]=vn(a);switch(o){case lr:{let c=a;switch(l){case"bigint":o=wl,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return i([yl],a)}return i([o,c],a)}case xn:{if(l){let h=a;return l==="DataView"?h=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(h=new Uint8Array(a)),i([l,[...h]],a)}const c=[],d=i([o,c],a);for(const h of a)c.push(s(h));return d}case ur:{if(l)switch(l){case"BigInt":return i([l,a.toString()],a);case"Boolean":case"Number":case"String":return i([l,a.valueOf()],a)}if(t&&"toJSON"in a)return s(a.toJSON());const c=[],d=i([o,c],a);for(const h of vy(a))(e||!cr(vn(a[h])))&&c.push([s(h),s(a[h])]);return d}case ki:return i([o,a.toISOString()],a);case _i:{const{source:c,flags:d}=a;return i([o,{source:c,flags:d}],a)}case Ti:{const c=[],d=i([o,c],a);for(const[h,f]of a)(e||!(cr(vn(h))||cr(vn(f))))&&c.push([s(h),s(f)]);return d}case Ii:{const c=[],d=i([o,c],a);for(const h of a)(e||!cr(vn(h)))&&c.push(s(h));return d}}const{message:u}=a;return i([o,{name:l,message:u}],a)};return s},Sl=(e,{json:t,lossy:n}={})=>{const r=[];return Sy(!(t||n),!!t,new Map,r)(e),r},dr=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?vl(Sl(e,t)):structuredClone(e):(e,t)=>vl(Sl(e,t));function ky(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function _y(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Ty(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||ky,r=e.options.footnoteBackLabel||_y,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",a=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 c=e.all(u),d=String(u.identifier).toUpperCase(),h=Vt(d.toLowerCase());let f=0;const m=[],v=e.footnoteCounts.get(d);for(;v!==void 0&&++f<=v;){m.length>0&&m.push({type:"text",value:" "});let C=typeof n=="string"?n:n(l,f);typeof C=="string"&&(C={type:"text",value:C}),m.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(l,f),className:["data-footnote-backref"]},children:Array.isArray(C)?C:[C]})}const b=c[c.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const C=b.children[b.children.length-1];C&&C.type==="text"?C.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...m)}else c.push(...m);const x={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(c,!0)};e.patch(u,x),o.push(x)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:E(g({},dr(a)),{id:"footnote-label"}),children:[{type:"text",value:i}]},{type:"text",value:`
14
+ `});const u={type:"element",tagName:"li",properties:s,children:a};return e.patch(t,u),e.applyData(t,u)}function hy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=bl(n[r])}return t}function bl(e){const t=e.spread;return t==null?e.children.length>1:t}function fy(e,t){const n={},r=e.all(t);let i=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++i<r.length;){const a=r[i];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const s={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,s),e.applyData(t,s)}function py(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function my(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function gy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const n=e.all(t),r=n.shift(),i=[];if(r){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],a),i.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},o=fi(t.children[1]),l=Bo(t.children[t.children.length-1]);o&&l&&(a.position={start:o,end:l}),i.push(a)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(i,!0)};return e.patch(t,s),e.applyData(t,s)}function by(e,t,n){const r=n?n.children:void 0,s=(r?r.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,o=a?a.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const d=t.children[l],h={},f=a?a[l]:void 0;f&&(h.align=f);let g={type:"element",tagName:s,properties:h,children:[]};d&&(g.children=e.all(d),e.patch(d,g),g=e.applyData(d,g)),u.push(g)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,c),e.applyData(t,c)}function wy(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const wl=9,xl=32;function xy(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),i=0;const s=[];for(;r;)s.push(vl(t.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return s.push(vl(t.slice(i),i>0,!1)),s.join("")}function vl(e,t,n){let r=0,i=e.length;if(t){let s=e.codePointAt(r);for(;s===wl||s===xl;)r++,s=e.codePointAt(r)}if(n){let s=e.codePointAt(i-1);for(;s===wl||s===xl;)i--,s=e.codePointAt(i-1)}return i>r?e.slice(r,i):""}function vy(e,t){const n={type:"text",value:xy(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Sy(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const ky={blockquote:Qg,break:Zg,code:ey,delete:ty,emphasis:ny,footnoteReference:ry,heading:iy,html:sy,imageReference:ay,image:oy,inlineCode:ly,linkReference:uy,link:cy,listItem:dy,list:fy,paragraph:py,root:my,strong:gy,table:yy,tableCell:wy,tableRow:by,text:vy,thematicBreak:Sy,toml:ur,yaml:ur,definition:ur,footnoteDefinition:ur};function ur(){}const Sl=-1,cr=0,vn=1,dr=2,Ci=3,Ii=4,Ei=5,Ai=6,kl=7,_l=8,Tl=typeof self=="object"?self:globalThis,_y=(e,t)=>{const n=(i,s)=>(e.set(s,i),i),r=i=>{if(e.has(i))return e.get(i);const[s,a]=t[i];switch(s){case cr:case Sl:return n(a,i);case vn:{const o=n([],i);for(const l of a)o.push(r(l));return o}case dr:{const o=n({},i);for(const[l,u]of a)o[r(l)]=r(u);return o}case Ci:return n(new Date(a),i);case Ii:{const{source:o,flags:l}=a;return n(new RegExp(o,l),i)}case Ei:{const o=n(new Map,i);for(const[l,u]of a)o.set(r(l),r(u));return o}case Ai:{const o=n(new Set,i);for(const l of a)o.add(r(l));return o}case kl:{const{name:o,message:l}=a;return n(new Tl[o](l),i)}case _l:return n(BigInt(a),i);case"BigInt":return n(Object(BigInt(a)),i);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:o}=new Uint8Array(a);return n(new DataView(o),a)}}return n(new Tl[s](a),i)};return r},Cl=e=>_y(new Map,e)(0),Yt="",{toString:Ty}={},{keys:Cy}=Object,Sn=e=>{const t=typeof e;if(t!=="object"||!e)return[cr,t];const n=Ty.call(e).slice(8,-1);switch(n){case"Array":return[vn,Yt];case"Object":return[dr,Yt];case"Date":return[Ci,Yt];case"RegExp":return[Ii,Yt];case"Map":return[Ei,Yt];case"Set":return[Ai,Yt];case"DataView":return[vn,n]}return n.includes("Array")?[vn,n]:n.includes("Error")?[kl,n]:[dr,n]},hr=([e,t])=>e===cr&&(t==="function"||t==="symbol"),Iy=(e,t,n,r)=>{const i=(a,o)=>{const l=r.push(a)-1;return n.set(o,l),l},s=a=>{if(n.has(a))return n.get(a);let[o,l]=Sn(a);switch(o){case cr:{let c=a;switch(l){case"bigint":o=_l,c=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return i([Sl],a)}return i([o,c],a)}case vn:{if(l){let h=a;return l==="DataView"?h=new Uint8Array(a.buffer):l==="ArrayBuffer"&&(h=new Uint8Array(a)),i([l,[...h]],a)}const c=[],d=i([o,c],a);for(const h of a)c.push(s(h));return d}case dr:{if(l)switch(l){case"BigInt":return i([l,a.toString()],a);case"Boolean":case"Number":case"String":return i([l,a.valueOf()],a)}if(t&&"toJSON"in a)return s(a.toJSON());const c=[],d=i([o,c],a);for(const h of Cy(a))(e||!hr(Sn(a[h])))&&c.push([s(h),s(a[h])]);return d}case Ci:return i([o,a.toISOString()],a);case Ii:{const{source:c,flags:d}=a;return i([o,{source:c,flags:d}],a)}case Ei:{const c=[],d=i([o,c],a);for(const[h,f]of a)(e||!(hr(Sn(h))||hr(Sn(f))))&&c.push([s(h),s(f)]);return d}case Ai:{const c=[],d=i([o,c],a);for(const h of a)(e||!hr(Sn(h)))&&c.push(s(h));return d}}const{message:u}=a;return i([o,{name:l,message:u}],a)};return s},Il=(e,{json:t,lossy:n}={})=>{const r=[];return Iy(!(t||n),!!t,new Map,r)(e),r},fr=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Cl(Il(e,t)):structuredClone(e):(e,t)=>Cl(Il(e,t));function Ey(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function Ay(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function My(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Ey,r=e.options.footnoteBackLabel||Ay,i=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",a=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 c=e.all(u),d=String(u.identifier).toUpperCase(),h=Jt(d.toLowerCase());let f=0;const g=[],v=e.footnoteCounts.get(d);for(;v!==void 0&&++f<=v;){g.length>0&&g.push({type:"text",value:" "});let E=typeof n=="string"?n:n(l,f);typeof E=="string"&&(E={type:"text",value:E}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(l,f),className:["data-footnote-backref"]},children:Array.isArray(E)?E:[E]})}const b=c[c.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const E=b.children[b.children.length-1];E&&E.type==="text"?E.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...g)}else c.push(...g);const x={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(c,!0)};e.patch(u,x),o.push(x)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:I(m({},fr(a)),{id:"footnote-label"}),children:[{type:"text",value:i}]},{type:"text",value:`
15
15
  `},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
16
- `}]}}const hr=(function(e){if(e==null)return Ay;if(typeof e=="function")return fr(e);if(typeof e=="object")return Array.isArray(e)?Iy(e):Cy(e);if(typeof e=="string")return Ey(e);throw new Error("Expected function, string, or object as test")});function Iy(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=hr(e[n]);return fr(r);function r(...i){let s=-1;for(;++s<t.length;)if(t[s].apply(this,i))return!0;return!1}}function Cy(e){const t=e;return fr(n);function n(r){const i=r;let s;for(s in e)if(i[s]!==t[s])return!1;return!0}}function Ey(e){return fr(t);function t(n){return n&&n.type===e}}function fr(e){return t;function t(n,r,i){return!!(My(n)&&e.call(this,n,typeof r=="number"?r:void 0,i||void 0))}}function Ay(){return!0}function My(e){return e!==null&&typeof e=="object"&&"type"in e}function Hv(e){return e}const kl=[],Py=!0,Ci=!1,Ny="skip";function _l(e,t,n,r){let i;typeof t=="function"&&typeof n!="function"?(r=n,n=t):i=t;const s=hr(i),a=r?-1:1;o(e,void 0,[])();function o(l,u,c){const d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){const f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=kl,m,v,b;if((!t||s(l,u,c[c.length-1]||void 0))&&(f=Ly(n(l,c)),f[0]===Ci))return f;if("children"in l&&l.children){const x=l;if(x.children&&f[0]!==Ny)for(v=(r?x.children.length:-1)+a,b=c.concat(x);v>-1&&v<x.children.length;){const C=x.children[v];if(m=o(C,v,b)(),m[0]===Ci)return m;v=typeof m[1]=="number"?m[1]:v+a}}return f}}}function Ly(e){return Array.isArray(e)?e:typeof e=="number"?[Py,e]:e==null?kl:[e]}function Ei(e,t,n,r){let i,s,a;typeof t=="function"&&typeof n!="function"?(s=void 0,a=t,i=n):(s=t,a=n,i=r),_l(e,s,o,i);function o(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return a(l,d,c)}}const Ai={}.hasOwnProperty,Dy={};function Oy(e,t){const n=t||Dy,r=new Map,i=new Map,s=new Map,a=g(g({},by),n.handlers),o={all:u,applyData:By,definitionById:r,footnoteById:i,footnoteCounts:s,footnoteOrder:[],handlers:a,one:l,options:n,patch:Fy,wrap:Ry};return Ei(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?r:i,h=String(c.identifier).toUpperCase();d.has(h)||d.set(h,c)}}),o;function l(c,d){const h=c.type,f=o.handlers[h];if(Ai.call(o.handlers,h)&&f)return f(o,c,d);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in c){const v=c,{children:b}=v,x=V(v,["children"]),C=dr(x);return C.children=o.all(c),C}return dr(c)}return(o.options.unknownHandler||zy)(o,c,d)}function u(c){const d=[];if("children"in c){const h=c.children;let f=-1;for(;++f<h.length;){const m=o.one(h[f],c);if(m){if(f&&h[f-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=Tl(m.value)),!Array.isArray(m)&&m.type==="element")){const v=m.children[0];v&&v.type==="text"&&(v.value=Tl(v.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function Fy(e,t){e.position&&(t.position=Lp(e))}function By(e,t){let n=t;if(e&&e.data){const r=e.data.hName,i=e.data.hChildren,s=e.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const a="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:a}}n.type==="element"&&s&&Object.assign(n.properties,dr(s)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function zy(e,t){const n=t.data||{},r="value"in t&&!(Ai.call(n,"hProperties")||Ai.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Ry(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
16
+ `}]}}const pr=(function(e){if(e==null)return Dy;if(typeof e=="function")return mr(e);if(typeof e=="object")return Array.isArray(e)?Py(e):Ny(e);if(typeof e=="string")return Ly(e);throw new Error("Expected function, string, or object as test")});function Py(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=pr(e[n]);return mr(r);function r(...i){let s=-1;for(;++s<t.length;)if(t[s].apply(this,i))return!0;return!1}}function Ny(e){const t=e;return mr(n);function n(r){const i=r;let s;for(s in e)if(i[s]!==t[s])return!1;return!0}}function Ly(e){return mr(t);function t(n){return n&&n.type===e}}function mr(e){return t;function t(n,r,i){return!!(Oy(n)&&e.call(this,n,typeof r=="number"?r:void 0,i||void 0))}}function Dy(){return!0}function Oy(e){return e!==null&&typeof e=="object"&&"type"in e}function Yv(e){return e}const El=[],Fy=!0,Mi=!1,zy="skip";function Al(e,t,n,r){let i;typeof t=="function"&&typeof n!="function"?(r=n,n=t):i=t;const s=pr(i),a=r?-1:1;o(e,void 0,[])();function o(l,u,c){const d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){const f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=El,g,v,b;if((!t||s(l,u,c[c.length-1]||void 0))&&(f=By(n(l,c)),f[0]===Mi))return f;if("children"in l&&l.children){const x=l;if(x.children&&f[0]!==zy)for(v=(r?x.children.length:-1)+a,b=c.concat(x);v>-1&&v<x.children.length;){const E=x.children[v];if(g=o(E,v,b)(),g[0]===Mi)return g;v=typeof g[1]=="number"?g[1]:v+a}}return f}}}function By(e){return Array.isArray(e)?e:typeof e=="number"?[Fy,e]:e==null?El:[e]}function Pi(e,t,n,r){let i,s,a;typeof t=="function"&&typeof n!="function"?(s=void 0,a=t,i=n):(s=t,a=n,i=r),Al(e,s,o,i);function o(l,u){const c=u[u.length-1],d=c?c.children.indexOf(l):void 0;return a(l,d,c)}}const Ni={}.hasOwnProperty,Ry={};function jy(e,t){const n=t||Ry,r=new Map,i=new Map,s=new Map,a=m(m({},ky),n.handlers),o={all:u,applyData:$y,definitionById:r,footnoteById:i,footnoteCounts:s,footnoteOrder:[],handlers:a,one:l,options:n,patch:Uy,wrap:qy};return Pi(e,function(c){if(c.type==="definition"||c.type==="footnoteDefinition"){const d=c.type==="definition"?r:i,h=String(c.identifier).toUpperCase();d.has(h)||d.set(h,c)}}),o;function l(c,d){const h=c.type,f=o.handlers[h];if(Ni.call(o.handlers,h)&&f)return f(o,c,d);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in c){const v=c,{children:b}=v,x=q(v,["children"]),E=fr(x);return E.children=o.all(c),E}return fr(c)}return(o.options.unknownHandler||Hy)(o,c,d)}function u(c){const d=[];if("children"in c){const h=c.children;let f=-1;for(;++f<h.length;){const g=o.one(h[f],c);if(g){if(f&&h[f-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Ml(g.value)),!Array.isArray(g)&&g.type==="element")){const v=g.children[0];v&&v.type==="text"&&(v.value=Ml(v.value))}Array.isArray(g)?d.push(...g):d.push(g)}}}return d}}function Uy(e,t){e.position&&(t.position=Bp(e))}function $y(e,t){let n=t;if(e&&e.data){const r=e.data.hName,i=e.data.hChildren,s=e.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const a="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:a}}n.type==="element"&&s&&Object.assign(n.properties,fr(s)),"children"in n&&n.children&&i!==null&&i!==void 0&&(n.children=i)}return n}function Hy(e,t){const n=t.data||{},r="value"in t&&!(Ni.call(n,"hProperties")||Ni.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function qy(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:`
17
17
  `});++r<e.length;)r&&n.push({type:"text",value:`
18
18
  `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
19
- `}),n}function Tl(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Il(e,t){const n=Oy(e,t),r=n.one(e,void 0),i=Ty(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:`
20
- `},i),s}function jy(e,t){return e&&"run"in e?function(n,r){return M(this,null,function*(){const i=Il(n,g({file:r},t));yield e.run(i,r)})}:function(n,r){return Il(n,g({file:r},e||t))}}function Cl(e){if(e)throw e}var Mi,El;function Uy(){if(El)return Mi;El=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var c=e.call(u,"constructor"),d=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!d)return!1;var h;for(h in u);return typeof h=="undefined"||e.call(u,h)},a=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},o=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return Mi=function l(){var u,c,d,h,f,m,v=arguments[0],b=1,x=arguments.length,C=!1;for(typeof v=="boolean"&&(C=v,v=arguments[1]||{},b=2),(v==null||typeof v!="object"&&typeof v!="function")&&(v={});b<x;++b)if(u=arguments[b],u!=null)for(c in u)d=o(v,c),h=o(u,c),v!==h&&(C&&h&&(s(h)||(f=i(h)))?(f?(f=!1,m=d&&i(d)?d:[]):m=d&&s(d)?d:{},a(v,{name:c,newValue:l(C,m,h)})):typeof h!="undefined"&&a(v,{name:c,newValue:h}));return v},Mi}var $y=Uy();const Pi=Nn($y);function Ni(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 Hy(){const e=[],t={run:n,use:r};return t;function n(...i){let s=-1;const a=i.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...i);function o(l,...u){const c=e[++s];let d=-1;if(l){a(l);return}for(;++d<i.length;)(u[d]===null||u[d]===void 0)&&(u[d]=i[d]);i=u,c?qy(c,o)(...u):a(null,...u)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function qy(e,t){let n;return r;function r(...a){const o=e.length>a.length;let l;o&&a.push(i);try{l=e.apply(this,a)}catch(u){const c=u;if(o&&n)throw c;return i(c)}o||(l&&l.then&&typeof l.then=="function"?l.then(s,i):l instanceof Error?i(l):s(l))}function i(a,...o){n||(n=!0,t(a,...o))}function s(a){i(null,a)}}const at={basename:Vy,dirname:Wy,extname:Jy,join:Ky,sep:"/"};function Vy(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Sn(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let a=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else a<0&&(s=!0,a=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(r=i):(o=-1,r=a));return n===r?r=a:r<0&&(r=e.length),e.slice(n,r)}function Wy(e){if(Sn(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Jy(e){Sn(e);let t=e.length,n=-1,r=0,i=-1,s=0,a;for(;t--;){const o=e.codePointAt(t);if(o===47){if(a){r=t+1;break}continue}n<0&&(a=!0,n=t+1),o===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Ky(...e){let t=-1,n;for(;++t<e.length;)Sn(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":Yy(n)}function Yy(e){Sn(e);const t=e.codePointAt(0)===47;let n=Gy(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function Gy(e,t){let n="",r=0,i=-1,s=0,a=-1,o,l;for(;++a<=e.length;){if(a<e.length)o=e.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(i===a-1||s===1))if(i!==a-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=a,s=0;continue}}else if(n.length>0){n="",r=0,i=a,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,a):n=e.slice(i+1,a),r=a-i-1;i=a,s=0}else o===46&&s>-1?s++:s=-1}return n}function Sn(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Xy={cwd:Qy};function Qy(){return"/"}function Li(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Zy(e){if(typeof e=="string")e=new URL(e);else if(!Li(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 eb(e)}function eb(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const Di=["history","path","basename","stem","extname","dirname"];class Al{constructor(t){let n;t?Li(t)?n={path:t}:typeof t=="string"||tb(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":Xy.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<Di.length;){const s=Di[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let i;for(i in n)Di.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){Fi(t,"basename"),Oi(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){Ml(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(Oi(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=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Li(t)&&(t=Zy(t)),Fi(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){Fi(t,"stem"),Oi(t,"stem"),this.path=at.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const i=this.message(t,n,r);throw i.fatal=!0,i}info(t,n,r){const i=this.message(t,n,r);return i.fatal=void 0,i}message(t,n,r){const i=new Me(t,n,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Oi(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function Fi(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 tb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const nb=(function(e){const r=this.constructor.prototype,i=r[e],s=function(){return i.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),rb={}.hasOwnProperty;class Bi extends nb{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=Hy()}copy(){const t=new Bi;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Pi(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(ji("data",this.frozen),this.namespace[t]=n,this):rb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(ji("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[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=n.call(t,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=pr(t),r=this.parser||this.Parser;return zi("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),zi("process",this.parser||this.Parser),Ri("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(s,a){const o=pr(t),l=r.parse(o);r.run(l,o,function(c,d,h){if(c||!d||!h)return u(c);const f=d,m=r.stringify(f,h);ab(m)?h.value=m:h.result=m,u(c,h)});function u(c,d){c||!d?a(c):s?s(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),zi("processSync",this.parser||this.Parser),Ri("processSync",this.compiler||this.Compiler),this.process(t,i),Nl("processSync","process",n),r;function i(s,a){n=!0,Cl(s),r=a}}run(t,n,r){Pl(t),this.freeze();const i=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(a,o){const l=pr(n);i.run(t,l,u);function u(c,d,h){const f=d||t;c?o(c):a?a(f):r(void 0,f,h)}}}runSync(t,n){let r=!1,i;return this.run(t,n,s),Nl("runSync","run",r),i;function s(a,o){Cl(a),i=o,r=!0}}stringify(t,n){this.freeze();const r=pr(n),i=this.compiler||this.Compiler;return Ri("stringify",i),Pl(t),i(t,r)}use(t,...n){const r=this.attachers,i=this.namespace;if(ji("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?o(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[c,...d]=u;l(c,d)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(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&&(i.settings=Pi(!0,i.settings,u.settings))}function o(u){let c=-1;if(u!=null)if(Array.isArray(u))for(;++c<u.length;){const d=u[c];s(d)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,c){let d=-1,h=-1;for(;++d<r.length;)if(r[d][0]===u){h=d;break}if(h===-1)r.push([u,...c]);else if(c.length>0){let[f,...m]=c;const v=r[h][1];Ni(v)&&Ni(f)&&(f=Pi(!0,v,f)),r[h]=[u,f,...m]}}}}const ib=new Bi().freeze();function zi(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ri(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ji(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(!Ni(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Nl(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function pr(e){return sb(e)?e:new Al(e)}function sb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ab(e){return typeof e=="string"||ob(e)}function ob(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const lb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ll=[],Dl={allowDangerousHtml:!0},ub=/^(https?|ircs?|mailto|xmpp)$/i,cb=[{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 db(e){const t=hb(e),n=fb(e);return pb(t.runSync(t.parse(n),n),e)}function hb(e){const t=e.rehypePlugins||Ll,n=e.remarkPlugins||Ll,r=e.remarkRehypeOptions?g(g({},e.remarkRehypeOptions),Dl):Dl;return ib().use(Wg).use(n).use(jy,r).use(t)}function fb(e){const t=e.children||"",n=new Al;return typeof t=="string"&&(n.value=t),n}function pb(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||mb;for(const c of cb)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+lb+c.id,void 0);return Ei(e,u),zp(e,{Fragment:p.Fragment,components:i,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(c,d,h){if(c.type==="raw"&&h&&typeof d=="number")return a?h.children.splice(d,1):h.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let f;for(f in mi)if(Object.hasOwn(mi,f)&&Object.hasOwn(c.properties,f)){const m=c.properties[f],v=mi[f];(v===null||v.includes(c.tagName))&&(c.properties[f]=l(String(m||""),f,c))}}if(c.type==="element"){let f=n?!n.includes(c.tagName):s?s.includes(c.tagName):!1;if(!f&&r&&typeof d=="number"&&(f=!r(c,d,h)),f&&h&&typeof d=="number")return o&&c.children?h.children.splice(d,1,...c.children):h.children.splice(d,1),d}}}function mb(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||ub.test(e.slice(0,t))?e:""}var gb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),yb=(e,t)=>{if(!e||!t)return!1;const n=r=>{const o=r||{},{position:i,data:s}=o;return V(o,["position","data"])};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&gb(e.children,t.children)},Ui=(e,t)=>yb(e.node,t.node),bb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,n])=>{if(!n)return[t,n];const r=n,i=o=>{var l=o,{node:s}=l,a=V(l,["node"]);return p.jsx(r,g({},a))};return[t,y.memo(i,Ui)]})),$i=y.createContext(null),Ol=()=>y.useContext($i)!==null,wb=n=>{var r=n,{children:e}=r,t=V(r,["children"]);return p.jsx($i.Provider,{value:t,children:e})},xb=y.memo(wb,Ui),vb=n=>{var r=n,{node:e}=r,t=V(r,["node"]);return p.jsx("pre",g({},t))},Sb=n=>{var r=n,{node:e}=r,t=V(r,["node"]);return p.jsx("code",g({},t))},Hi=({node:e,components:{Pre:t,Code:n},code:r})=>p.jsx(t,{children:p.jsx(n,{node:e,children:r})}),kb=()=>null,_b=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},language:s,code:a})=>{const o=y.useMemo(()=>({Pre:t,Code:n}),[t,n]),l=s?r:Hi;return p.jsxs(p.Fragment,{children:[p.jsx(i,{node:e,language:s,code:a}),p.jsx(l,{node:e,components:o,language:s!=null?s:"unknown",code:a})]})},qi={exports:{}};var Fl;function Tb(){return Fl||(Fl=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=i(s,r(o)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)t.call(s,o)&&s[o]&&(a=i(a,o));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(qi)),qi.exports}var Ib=Tb();const Bl=Nn(Ib);var zl=n=>{var r=n,{className:e}=r,t=V(r,["className"]);return a=>{var o=a,{className:i}=o,s=V(o,["className"]);return g(g({className:Bl(e,i)},t),s)}},Cb=l=>{var u=l,{node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},componentsByLanguage:s={},children:a}=u,o=V(u,["node","components","componentsByLanguage","children"]);var C,_,F,z,I,H;const c=y.useContext($i),d=zl(c),h=Ct(q=>p.jsx(t,g({},d(q)))),f=zl(o),m=Ct(q=>p.jsx(n,g({},f(q)))),v=(_=(C=/language-(\w+)/.exec(o.className||""))==null?void 0:C[1])!=null?_:"";if(typeof a!="string")return p.jsx(Hi,{node:e,components:{Pre:h,Code:m},code:a});const b=(z=(F=s[v])==null?void 0:F.SyntaxHighlighter)!=null?z:r,x=(H=(I=s[v])==null?void 0:I.CodeHeader)!=null?H:i;return p.jsx(_b,{node:e,components:{Pre:h,Code:m,SyntaxHighlighter:b,CodeHeader:x},language:v||"unknown",code:a})},Eb=i=>{var s=i,{node:e,components:t,componentsByLanguage:n}=s,r=V(s,["node","components","componentsByLanguage"]);return Ol()?p.jsx(Cb,g({node:e,components:t,componentsByLanguage:n},r)):p.jsx(t.Code,g({},r))},Ab=y.memo(Eb,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Ui(e,t)),{useSmooth:Mb,useSmoothStatus:Pb,withSmoothContextProvider:Nb}=Bh,Lb=s=>{var a=s,{components:e,componentsByLanguage:t,smooth:n=!0,preprocess:r}=a,i=V(a,["components","componentsByLanguage","smooth","preprocess"]);const o=Na(),l=y.useMemo(()=>r?E(g({},o),{text:r(o.text)}):o,[o,r]),{text:u}=Mb(l,n),{pre:c=vb,code:d=Sb,SyntaxHighlighter:h=Hi,CodeHeader:f=kb}=e!=null?e:{},m=y.useMemo(()=>({Pre:c,Code:d,SyntaxHighlighter:h,CodeHeader:f}),[c,d,h,f]),v=Ct(x=>p.jsx(Ab,g({components:m,componentsByLanguage:t},x))),b=y.useMemo(()=>{const I=e!=null?e:{},{pre:x,code:C,SyntaxHighlighter:_,CodeHeader:F}=I,z=V(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(g({},z),{pre:xb,code:v})},[v,e]);return p.jsx(db,E(g({components:b},i),{children:u}))},Rl=y.forwardRef((s,i)=>{var a=s,{className:e,containerProps:t,containerComponent:n="div"}=a,r=V(a,["className","containerProps","containerComponent"]);const o=Pb();return p.jsx(n,E(g({"data-status":o.type},t),{className:Bl(e,t==null?void 0:t.className),ref:i,children:p.jsx(Lb,g({},r))}))});Rl.displayName="MarkdownTextPrimitive";var Db=Nb(Rl);function jl(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function Ob(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Fb(e,t,n){const i=hr((n||{}).ignore||[]),s=Bb(t);let a=-1;for(;++a<s.length;)_l(e,"text",o);function o(u,c){let d=-1,h;for(;++d<c.length;){const f=c[d],m=h?h.children:void 0;if(i(f,m?m.indexOf(f):void 0,h))return;h=f}if(h)return l(u,c)}function l(u,c){const d=c[c.length-1],h=s[a][0],f=s[a][1];let m=0;const b=d.children.indexOf(u);let x=!1,C=[];h.lastIndex=0;let _=h.exec(u.value);for(;_;){const F=_.index,z={index:_.index,input:_.input,stack:[...c,u]};let I=f(..._,z);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?h.lastIndex=F+1:(m!==F&&C.push({type:"text",value:u.value.slice(m,F)}),Array.isArray(I)?C.push(...I):I&&C.push(I),m=F+_[0].length,x=!0),!h.global)break;_=h.exec(u.value)}return x?(m<u.value.length&&C.push({type:"text",value:u.value.slice(m)}),d.children.splice(b,1,...C)):C=[u],b+C.length}}function Bb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const i=n[r];t.push([zb(i[0]),Rb(i[1])])}return t}function zb(e){return typeof e=="string"?new RegExp(Ob(e),"g"):e}function Rb(e){return typeof e=="function"?e:function(){return e}}const Vi="phrasing",Wi=["autolink","link","image","label"];function jb(){return{transforms:[Jb],enter:{literalAutolink:$b,literalAutolinkEmail:Ji,literalAutolinkHttp:Ji,literalAutolinkWww:Ji},exit:{literalAutolink:Wb,literalAutolinkEmail:Vb,literalAutolinkHttp:Hb,literalAutolinkWww:qb}}}function Ub(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Vi,notInConstruct:Wi},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Vi,notInConstruct:Wi},{character:":",before:"[ps]",after:"\\/",inConstruct:Vi,notInConstruct:Wi}]}}function $b(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ji(e){this.config.enter.autolinkProtocol.call(this,e)}function Hb(e){this.config.exit.autolinkProtocol.call(this,e)}function qb(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 Vb(e){this.config.exit.autolinkEmail.call(this,e)}function Wb(e){this.exit(e)}function Jb(e){Fb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Kb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),Yb]],{ignore:["link","linkReference"]})}function Kb(e,t,n,r,i){let s="";if(!Ul(i)||(/^w/i.test(t)&&(n=t+n,t="",s="http://"),!Gb(n)))return!1;const a=Xb(n+r);if(!a[0])return!1;const o={type:"link",title:null,url:s+t+a[0],children:[{type:"text",value:t+a[0]}]};return a[1]?[o,{type:"text",value:a[1]}]:o}function Yb(e,t,n,r){return!Ul(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function Gb(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 Xb(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=jl(e,"(");let s=jl(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function Ul(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||At(n)||ir(n))&&(!t||n!==47)}$l.peek=aw;function Qb(){this.buffer()}function Zb(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function ew(){this.buffer()}function tw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function nw(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=tt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function rw(e){this.exit(e)}function iw(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=tt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function sw(e){this.exit(e)}function aw(){return"["}function $l(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const a=n.enter("footnoteReference"),o=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),o(),a(),s+=i.move("]"),s}function ow(){return{enter:{gfmFootnoteCallString:Qb,gfmFootnoteCall:Zb,gfmFootnoteDefinitionLabelString:ew,gfmFootnoteDefinition:tw},exit:{gfmFootnoteCallString:nw,gfmFootnoteCall:rw,gfmFootnoteDefinitionLabelString:iw,gfmFootnoteDefinition:sw}}}function lw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:$l},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,a){const o=s.createTracker(a);let l=o.move("[^");const u=s.enter("footnoteDefinition"),c=s.enter("label");return l+=o.move(s.safe(s.associationId(r),{before:l,after:"]"})),c(),l+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),l+=o.move((t?`
21
- `:" ")+s.indentLines(s.containerFlow(r,o.current()),t?Hl:uw))),u(),l}}function uw(e,t,n){return t===0?e:Hl(e,t,n)}function Hl(e,t,n){return(n?"":" ")+e}const cw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];ql.peek=mw;function dw(){return{canContainEols:["delete"],enter:{strikethrough:fw},exit:{strikethrough:pw}}}function hw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:cw}],handlers:{delete:ql}}}function fw(e){this.enter({type:"delete",children:[]},e)}function pw(e){this.exit(e)}function ql(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let a=i.move("~~");return a+=n.containerPhrasing(e,E(g({},i.current()),{before:a,after:"~"})),a+=i.move("~~"),s(),a}function mw(){return"~"}function gw(e){return e.length}function yw(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||gw,s=[],a=[],o=[],l=[];let u=0,c=-1;for(;++c<e.length;){const v=[],b=[];let x=-1;for(e[c].length>u&&(u=e[c].length);++x<e[c].length;){const C=bw(e[c][x]);if(n.alignDelimiters!==!1){const _=i(C);b[x]=_,(l[x]===void 0||_>l[x])&&(l[x]=_)}v.push(C)}a[c]=v,o[c]=b}let d=-1;if(typeof r=="object"&&"length"in r)for(;++d<u;)s[d]=Vl(r[d]);else{const v=Vl(r);for(;++d<u;)s[d]=v}d=-1;const h=[],f=[];for(;++d<u;){const v=s[d];let b="",x="";v===99?(b=":",x=":"):v===108?b=":":v===114&&(x=":");let C=n.alignDelimiters===!1?1:Math.max(1,l[d]-b.length-x.length);const _=b+"-".repeat(C)+x;n.alignDelimiters!==!1&&(C=b.length+C+x.length,C>l[d]&&(l[d]=C),f[d]=C),h[d]=_}a.splice(1,0,h),o.splice(1,0,f),c=-1;const m=[];for(;++c<a.length;){const v=a[c],b=o[c];d=-1;const x=[];for(;++d<u;){const C=v[d]||"";let _="",F="";if(n.alignDelimiters!==!1){const z=l[d]-(b[d]||0),I=s[d];I===114?_=" ".repeat(z):I===99?z%2?(_=" ".repeat(z/2+.5),F=" ".repeat(z/2-.5)):(_=" ".repeat(z/2),F=_):F=" ".repeat(z)}n.delimiterStart!==!1&&!d&&x.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&C==="")&&(n.delimiterStart!==!1||d)&&x.push(" "),n.alignDelimiters!==!1&&x.push(_),x.push(C),n.alignDelimiters!==!1&&x.push(F),n.padding!==!1&&x.push(" "),(n.delimiterEnd!==!1||d!==u-1)&&x.push("|")}m.push(n.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return m.join(`
22
- `)}function bw(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 ww(e,t,n,r){const i=n.enter("blockquote"),s=n.createTracker(r);s.move("> "),s.shift(2);const a=n.indentLines(n.containerFlow(e,s.current()),xw);return i(),a}function xw(e,t,n){return">"+(n?"":" ")+e}function vw(e,t){return Wl(e,t.inConstruct,!0)&&!Wl(e,t.notInConstruct,!1)}function Wl(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Jl(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
23
- `&&vw(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?"":" ";return`\\
24
- `}function Sw(e,t){const n=String(e);let r=n.indexOf(t),i=r,s=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===i?++s>a&&(a=s):s=1,i=r+t.length,r=n.indexOf(t,i);return a}function kw(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 _w(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 Tw(e,t,n,r){const i=_w(n),s=e.value||"",a=i==="`"?"GraveAccent":"Tilde";if(kw(e,n)){const d=n.enter("codeIndented"),h=n.indentLines(s,Iw);return d(),h}const o=n.createTracker(r),l=i.repeat(Math.max(Sw(s,i)+1,3)),u=n.enter("codeFenced");let c=o.move(l);if(e.lang){const d=n.enter(`codeFencedLang${a}`);c+=o.move(n.safe(e.lang,g({before:c,after:" ",encode:["`"]},o.current()))),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${a}`);c+=o.move(" "),c+=o.move(n.safe(e.meta,g({before:c,after:`
19
+ `}),n}function Ml(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Pl(e,t){const n=jy(e,t),r=n.one(e,void 0),i=My(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&s.children.push({type:"text",value:`
20
+ `},i),s}function Vy(e,t){return e&&"run"in e?function(n,r){return M(this,null,function*(){const i=Pl(n,m({file:r},t));yield e.run(i,r)})}:function(n,r){return Pl(n,m({file:r},e||t))}}function Nl(e){if(e)throw e}var Li,Ll;function Wy(){if(Ll)return Li;Ll=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},s=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var c=e.call(u,"constructor"),d=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!d)return!1;var h;for(h in u);return typeof h=="undefined"||e.call(u,h)},a=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},o=function(u,c){if(c==="__proto__")if(e.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return Li=function l(){var u,c,d,h,f,g,v=arguments[0],b=1,x=arguments.length,E=!1;for(typeof v=="boolean"&&(E=v,v=arguments[1]||{},b=2),(v==null||typeof v!="object"&&typeof v!="function")&&(v={});b<x;++b)if(u=arguments[b],u!=null)for(c in u)d=o(v,c),h=o(u,c),v!==h&&(E&&h&&(s(h)||(f=i(h)))?(f?(f=!1,g=d&&i(d)?d:[]):g=d&&s(d)?d:{},a(v,{name:c,newValue:l(E,g,h)})):typeof h!="undefined"&&a(v,{name:c,newValue:h}));return v},Li}var Jy=Wy();const Di=Ln(Jy);function Oi(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 Ky(){const e=[],t={run:n,use:r};return t;function n(...i){let s=-1;const a=i.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);o(null,...i);function o(l,...u){const c=e[++s];let d=-1;if(l){a(l);return}for(;++d<i.length;)(u[d]===null||u[d]===void 0)&&(u[d]=i[d]);i=u,c?Yy(c,o)(...u):a(null,...u)}}function r(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return e.push(i),t}}function Yy(e,t){let n;return r;function r(...a){const o=e.length>a.length;let l;o&&a.push(i);try{l=e.apply(this,a)}catch(u){const c=u;if(o&&n)throw c;return i(c)}o||(l&&l.then&&typeof l.then=="function"?l.then(s,i):l instanceof Error?i(l):s(l))}function i(a,...o){n||(n=!0,t(a,...o))}function s(a){i(null,a)}}const at={basename:Gy,dirname:Xy,extname:Qy,join:Zy,sep:"/"};function Gy(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');kn(e);let n=0,r=-1,i=e.length,s;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else r<0&&(s=!0,r=i+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let a=-1,o=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(s){n=i+1;break}}else a<0&&(s=!0,a=i+1),o>-1&&(e.codePointAt(i)===t.codePointAt(o--)?o<0&&(r=i):(o=-1,r=a));return n===r?r=a:r<0&&(r=e.length),e.slice(n,r)}function Xy(e){if(kn(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function Qy(e){kn(e);let t=e.length,n=-1,r=0,i=-1,s=0,a;for(;t--;){const o=e.codePointAt(t);if(o===47){if(a){r=t+1;break}continue}n<0&&(a=!0,n=t+1),o===46?i<0?i=t:s!==1&&(s=1):i>-1&&(s=-1)}return i<0||n<0||s===0||s===1&&i===n-1&&i===r+1?"":e.slice(i,n)}function Zy(...e){let t=-1,n;for(;++t<e.length;)kn(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":eb(n)}function eb(e){kn(e);const t=e.codePointAt(0)===47;let n=tb(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function tb(e,t){let n="",r=0,i=-1,s=0,a=-1,o,l;for(;++a<=e.length;){if(a<e.length)o=e.codePointAt(a);else{if(o===47)break;o=47}if(o===47){if(!(i===a-1||s===1))if(i!==a-1&&s===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=a,s=0;continue}}else if(n.length>0){n="",r=0,i=a,s=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(i+1,a):n=e.slice(i+1,a),r=a-i-1;i=a,s=0}else o===46&&s>-1?s++:s=-1}return n}function kn(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const nb={cwd:rb};function rb(){return"/"}function Fi(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function ib(e){if(typeof e=="string")e=new URL(e);else if(!Fi(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 sb(e)}function sb(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(t)}const zi=["history","path","basename","stem","extname","dirname"];class Dl{constructor(t){let n;t?Fi(t)?n={path:t}:typeof t=="string"||ab(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":nb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<zi.length;){const s=zi[r];s in n&&n[s]!==void 0&&n[s]!==null&&(this[s]=s==="history"?[...n[s]]:n[s])}let i;for(i in n)zi.includes(i)||(this[i]=n[i])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){Ri(t,"basename"),Bi(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){Ol(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(Bi(t,"extname"),Ol(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=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Fi(t)&&(t=ib(t)),Ri(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){Ri(t,"stem"),Bi(t,"stem"),this.path=at.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const i=this.message(t,n,r);throw i.fatal=!0,i}info(t,n,r){const i=this.message(t,n,r);return i.fatal=void 0,i}message(t,n,r){const i=new Me(t,n,r);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Bi(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function Ri(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Ol(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function ab(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ob=(function(e){const r=this.constructor.prototype,i=r[e],s=function(){return i.apply(s,arguments)};return Object.setPrototypeOf(s,r),s}),lb={}.hasOwnProperty;class ji extends ob{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=Ky()}copy(){const t=new ji;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(Di(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Hi("data",this.frozen),this.namespace[t]=n,this):lb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Hi("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[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const i=n.call(t,...r);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=gr(t),r=this.parser||this.Parser;return Ui("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Ui("process",this.parser||this.Parser),$i("process",this.compiler||this.Compiler),n?i(void 0,n):new Promise(i);function i(s,a){const o=gr(t),l=r.parse(o);r.run(l,o,function(c,d,h){if(c||!d||!h)return u(c);const f=d,g=r.stringify(f,h);db(g)?h.value=g:h.result=g,u(c,h)});function u(c,d){c||!d?a(c):s?s(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),Ui("processSync",this.parser||this.Parser),$i("processSync",this.compiler||this.Compiler),this.process(t,i),zl("processSync","process",n),r;function i(s,a){n=!0,Nl(s),r=a}}run(t,n,r){Fl(t),this.freeze();const i=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?s(void 0,r):new Promise(s);function s(a,o){const l=gr(n);i.run(t,l,u);function u(c,d,h){const f=d||t;c?o(c):a?a(f):r(void 0,f,h)}}}runSync(t,n){let r=!1,i;return this.run(t,n,s),zl("runSync","run",r),i;function s(a,o){Nl(a),i=o,r=!0}}stringify(t,n){this.freeze();const r=gr(n),i=this.compiler||this.Compiler;return $i("stringify",i),Fl(t),i(t,r)}use(t,...n){const r=this.attachers,i=this.namespace;if(Hi("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?o(t):a(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function s(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[c,...d]=u;l(c,d)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(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&&(i.settings=Di(!0,i.settings,u.settings))}function o(u){let c=-1;if(u!=null)if(Array.isArray(u))for(;++c<u.length;){const d=u[c];s(d)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,c){let d=-1,h=-1;for(;++d<r.length;)if(r[d][0]===u){h=d;break}if(h===-1)r.push([u,...c]);else if(c.length>0){let[f,...g]=c;const v=r[h][1];Oi(v)&&Oi(f)&&(f=Di(!0,v,f)),r[h]=[u,f,...g]}}}}const ub=new ji().freeze();function Ui(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function $i(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Hi(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 Fl(e){if(!Oi(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function zl(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function gr(e){return cb(e)?e:new Dl(e)}function cb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function db(e){return typeof e=="string"||hb(e)}function hb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const fb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Bl=[],Rl={allowDangerousHtml:!0},pb=/^(https?|ircs?|mailto|xmpp)$/i,mb=[{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 gb(e){const t=yb(e),n=bb(e);return wb(t.runSync(t.parse(n),n),e)}function yb(e){const t=e.rehypePlugins||Bl,n=e.remarkPlugins||Bl,r=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Rl):Rl;return ub().use(Xg).use(n).use(Vy,r).use(t)}function bb(e){const t=e.children||"",n=new Dl;return typeof t=="string"&&(n.value=t),n}function wb(e,t){const n=t.allowedElements,r=t.allowElement,i=t.components,s=t.disallowedElements,a=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||xb;for(const c of mb)Object.hasOwn(t,c.from)&&(""+c.from+(c.to?"use `"+c.to+"` instead":"remove it")+fb+c.id,void 0);return Pi(e,u),Hp(e,{Fragment:p.Fragment,components:i,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(c,d,h){if(c.type==="raw"&&h&&typeof d=="number")return a?h.children.splice(d,1):h.children[d]={type:"text",value:c.value},d;if(c.type==="element"){let f;for(f in bi)if(Object.hasOwn(bi,f)&&Object.hasOwn(c.properties,f)){const g=c.properties[f],v=bi[f];(v===null||v.includes(c.tagName))&&(c.properties[f]=l(String(g||""),f,c))}}if(c.type==="element"){let f=n?!n.includes(c.tagName):s?s.includes(c.tagName):!1;if(!f&&r&&typeof d=="number"&&(f=!r(c,d,h)),f&&h&&typeof d=="number")return o&&c.children?h.children.splice(d,1,...c.children):h.children.splice(d,1),d}}}function xb(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),i=e.indexOf("/");return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||pb.test(e.slice(0,t))?e:""}var vb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),Sb=(e,t)=>{if(!e||!t)return!1;const n=r=>{const o=r||{},{position:i,data:s}=o;return q(o,["position","data"])};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&vb(e.children,t.children)},qi=(e,t)=>Sb(e.node,t.node),kb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,n])=>{if(!n)return[t,n];const r=n,i=o=>{var l=o,{node:s}=l,a=q(l,["node"]);return p.jsx(r,m({},a))};return[t,y.memo(i,qi)]})),Vi=y.createContext(null),jl=()=>y.useContext(Vi)!==null,_b=n=>{var r=n,{children:e}=r,t=q(r,["children"]);return p.jsx(Vi.Provider,{value:t,children:e})},Tb=y.memo(_b,qi),Cb=n=>{var r=n,{node:e}=r,t=q(r,["node"]);return p.jsx("pre",m({},t))},Ib=n=>{var r=n,{node:e}=r,t=q(r,["node"]);return p.jsx("code",m({},t))},Wi=({node:e,components:{Pre:t,Code:n},code:r})=>p.jsx(t,{children:p.jsx(n,{node:e,children:r})}),Eb=()=>null,Ab=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},language:s,code:a})=>{const o=y.useMemo(()=>({Pre:t,Code:n}),[t,n]),l=s?r:Wi;return p.jsxs(p.Fragment,{children:[p.jsx(i,{node:e,language:s,code:a}),p.jsx(l,{node:e,components:o,language:s!=null?s:"unknown",code:a})]})},Ji={exports:{}};var Ul;function Mb(){return Ul||(Ul=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=i(s,r(o)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)t.call(s,o)&&s[o]&&(a=i(a,o));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(Ji)),Ji.exports}var Pb=Mb();const $l=Ln(Pb);var Hl=n=>{var r=n,{className:e}=r,t=q(r,["className"]);return a=>{var o=a,{className:i}=o,s=q(o,["className"]);return m(m({className:$l(e,i)},t),s)}},Nb=l=>{var u=l,{node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},componentsByLanguage:s={},children:a}=u,o=q(u,["node","components","componentsByLanguage","children"]);var E,_,F,B,C,H;const c=y.useContext(Vi),d=Hl(c),h=It(V=>p.jsx(t,m({},d(V)))),f=Hl(o),g=It(V=>p.jsx(n,m({},f(V)))),v=(_=(E=/language-(\w+)/.exec(o.className||""))==null?void 0:E[1])!=null?_:"";if(typeof a!="string")return p.jsx(Wi,{node:e,components:{Pre:h,Code:g},code:a});const b=(B=(F=s[v])==null?void 0:F.SyntaxHighlighter)!=null?B:r,x=(H=(C=s[v])==null?void 0:C.CodeHeader)!=null?H:i;return p.jsx(Ab,{node:e,components:{Pre:h,Code:g,SyntaxHighlighter:b,CodeHeader:x},language:v||"unknown",code:a})},Lb=i=>{var s=i,{node:e,components:t,componentsByLanguage:n}=s,r=q(s,["node","components","componentsByLanguage"]);return jl()?p.jsx(Nb,m({node:e,components:t,componentsByLanguage:n},r)):p.jsx(t.Code,m({},r))},Db=y.memo(Lb,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&qi(e,t)),{useSmooth:Ob,useSmoothStatus:Fb,withSmoothContextProvider:zb}=$h,Bb=s=>{var a=s,{components:e,componentsByLanguage:t,smooth:n=!0,preprocess:r}=a,i=q(a,["components","componentsByLanguage","smooth","preprocess"]);const o=Fa(),l=y.useMemo(()=>r?I(m({},o),{text:r(o.text)}):o,[o,r]),{text:u}=Ob(l,n),{pre:c=Cb,code:d=Ib,SyntaxHighlighter:h=Wi,CodeHeader:f=Eb}=e!=null?e:{},g=y.useMemo(()=>({Pre:c,Code:d,SyntaxHighlighter:h,CodeHeader:f}),[c,d,h,f]),v=It(x=>p.jsx(Db,m({components:g,componentsByLanguage:t},x))),b=y.useMemo(()=>{const C=e!=null?e:{},{pre:x,code:E,SyntaxHighlighter:_,CodeHeader:F}=C,B=q(C,["pre","code","SyntaxHighlighter","CodeHeader"]);return I(m({},B),{pre:Tb,code:v})},[v,e]);return p.jsx(gb,I(m({components:b},i),{children:u}))},ql=y.forwardRef((s,i)=>{var a=s,{className:e,containerProps:t,containerComponent:n="div"}=a,r=q(a,["className","containerProps","containerComponent"]);const o=Fb();return p.jsx(n,I(m({"data-status":o.type},t),{className:$l(e,t==null?void 0:t.className),ref:i,children:p.jsx(Bb,m({},r))}))});ql.displayName="MarkdownTextPrimitive";var Rb=zb(ql);function Vl(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function jb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Ub(e,t,n){const i=pr((n||{}).ignore||[]),s=$b(t);let a=-1;for(;++a<s.length;)Al(e,"text",o);function o(u,c){let d=-1,h;for(;++d<c.length;){const f=c[d],g=h?h.children:void 0;if(i(f,g?g.indexOf(f):void 0,h))return;h=f}if(h)return l(u,c)}function l(u,c){const d=c[c.length-1],h=s[a][0],f=s[a][1];let g=0;const b=d.children.indexOf(u);let x=!1,E=[];h.lastIndex=0;let _=h.exec(u.value);for(;_;){const F=_.index,B={index:_.index,input:_.input,stack:[...c,u]};let C=f(..._,B);if(typeof C=="string"&&(C=C.length>0?{type:"text",value:C}:void 0),C===!1?h.lastIndex=F+1:(g!==F&&E.push({type:"text",value:u.value.slice(g,F)}),Array.isArray(C)?E.push(...C):C&&E.push(C),g=F+_[0].length,x=!0),!h.global)break;_=h.exec(u.value)}return x?(g<u.value.length&&E.push({type:"text",value:u.value.slice(g)}),d.children.splice(b,1,...E)):E=[u],b+E.length}}function $b(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const i=n[r];t.push([Hb(i[0]),qb(i[1])])}return t}function Hb(e){return typeof e=="string"?new RegExp(jb(e),"g"):e}function qb(e){return typeof e=="function"?e:function(){return e}}const Ki="phrasing",Yi=["autolink","link","image","label"];function Vb(){return{transforms:[Qb],enter:{literalAutolink:Jb,literalAutolinkEmail:Gi,literalAutolinkHttp:Gi,literalAutolinkWww:Gi},exit:{literalAutolink:Xb,literalAutolinkEmail:Gb,literalAutolinkHttp:Kb,literalAutolinkWww:Yb}}}function Wb(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ki,notInConstruct:Yi},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ki,notInConstruct:Yi},{character:":",before:"[ps]",after:"\\/",inConstruct:Ki,notInConstruct:Yi}]}}function Jb(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Gi(e){this.config.enter.autolinkProtocol.call(this,e)}function Kb(e){this.config.exit.autolinkProtocol.call(this,e)}function Yb(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 Gb(e){this.config.exit.autolinkEmail.call(this,e)}function Xb(e){this.exit(e)}function Qb(e){Ub(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Zb],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),ew]],{ignore:["link","linkReference"]})}function Zb(e,t,n,r,i){let s="";if(!Wl(i)||(/^w/i.test(t)&&(n=t+n,t="",s="http://"),!tw(n)))return!1;const a=nw(n+r);if(!a[0])return!1;const o={type:"link",title:null,url:s+t+a[0],children:[{type:"text",value:t+a[0]}]};return a[1]?[o,{type:"text",value:a[1]}]:o}function ew(e,t,n,r){return!Wl(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function tw(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 nw(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const i=Vl(e,"(");let s=Vl(e,")");for(;r!==-1&&i>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}function Wl(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||At(n)||ar(n))&&(!t||n!==47)}Jl.peek=dw;function rw(){this.buffer()}function iw(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function sw(){this.buffer()}function aw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function ow(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=tt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function lw(e){this.exit(e)}function uw(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=tt(this.sliceSerialize(e)).toLowerCase(),n.label=t}function cw(e){this.exit(e)}function dw(){return"["}function Jl(e,t,n,r){const i=n.createTracker(r);let s=i.move("[^");const a=n.enter("footnoteReference"),o=n.enter("reference");return s+=i.move(n.safe(n.associationId(e),{after:"]",before:s})),o(),a(),s+=i.move("]"),s}function hw(){return{enter:{gfmFootnoteCallString:rw,gfmFootnoteCall:iw,gfmFootnoteDefinitionLabelString:sw,gfmFootnoteDefinition:aw},exit:{gfmFootnoteCallString:ow,gfmFootnoteCall:lw,gfmFootnoteDefinitionLabelString:uw,gfmFootnoteDefinition:cw}}}function fw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Jl},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,i,s,a){const o=s.createTracker(a);let l=o.move("[^");const u=s.enter("footnoteDefinition"),c=s.enter("label");return l+=o.move(s.safe(s.associationId(r),{before:l,after:"]"})),c(),l+=o.move("]:"),r.children&&r.children.length>0&&(o.shift(4),l+=o.move((t?`
21
+ `:" ")+s.indentLines(s.containerFlow(r,o.current()),t?Kl:pw))),u(),l}}function pw(e,t,n){return t===0?e:Kl(e,t,n)}function Kl(e,t,n){return(n?"":" ")+e}const mw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Yl.peek=xw;function gw(){return{canContainEols:["delete"],enter:{strikethrough:bw},exit:{strikethrough:ww}}}function yw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:mw}],handlers:{delete:Yl}}}function bw(e){this.enter({type:"delete",children:[]},e)}function ww(e){this.exit(e)}function Yl(e,t,n,r){const i=n.createTracker(r),s=n.enter("strikethrough");let a=i.move("~~");return a+=n.containerPhrasing(e,I(m({},i.current()),{before:a,after:"~"})),a+=i.move("~~"),s(),a}function xw(){return"~"}function vw(e){return e.length}function Sw(e,t){const n=t||{},r=(n.align||[]).concat(),i=n.stringLength||vw,s=[],a=[],o=[],l=[];let u=0,c=-1;for(;++c<e.length;){const v=[],b=[];let x=-1;for(e[c].length>u&&(u=e[c].length);++x<e[c].length;){const E=kw(e[c][x]);if(n.alignDelimiters!==!1){const _=i(E);b[x]=_,(l[x]===void 0||_>l[x])&&(l[x]=_)}v.push(E)}a[c]=v,o[c]=b}let d=-1;if(typeof r=="object"&&"length"in r)for(;++d<u;)s[d]=Gl(r[d]);else{const v=Gl(r);for(;++d<u;)s[d]=v}d=-1;const h=[],f=[];for(;++d<u;){const v=s[d];let b="",x="";v===99?(b=":",x=":"):v===108?b=":":v===114&&(x=":");let E=n.alignDelimiters===!1?1:Math.max(1,l[d]-b.length-x.length);const _=b+"-".repeat(E)+x;n.alignDelimiters!==!1&&(E=b.length+E+x.length,E>l[d]&&(l[d]=E),f[d]=E),h[d]=_}a.splice(1,0,h),o.splice(1,0,f),c=-1;const g=[];for(;++c<a.length;){const v=a[c],b=o[c];d=-1;const x=[];for(;++d<u;){const E=v[d]||"";let _="",F="";if(n.alignDelimiters!==!1){const B=l[d]-(b[d]||0),C=s[d];C===114?_=" ".repeat(B):C===99?B%2?(_=" ".repeat(B/2+.5),F=" ".repeat(B/2-.5)):(_=" ".repeat(B/2),F=_):F=" ".repeat(B)}n.delimiterStart!==!1&&!d&&x.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&E==="")&&(n.delimiterStart!==!1||d)&&x.push(" "),n.alignDelimiters!==!1&&x.push(_),x.push(E),n.alignDelimiters!==!1&&x.push(F),n.padding!==!1&&x.push(" "),(n.delimiterEnd!==!1||d!==u-1)&&x.push("|")}g.push(n.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
22
+ `)}function kw(e){return e==null?"":String(e)}function Gl(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 _w(e,t,n,r){const i=n.enter("blockquote"),s=n.createTracker(r);s.move("> "),s.shift(2);const a=n.indentLines(n.containerFlow(e,s.current()),Tw);return i(),a}function Tw(e,t,n){return">"+(n?"":" ")+e}function Cw(e,t){return Xl(e,t.inConstruct,!0)&&!Xl(e,t.notInConstruct,!1)}function Xl(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Ql(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
23
+ `&&Cw(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?"":" ";return`\\
24
+ `}function Iw(e,t){const n=String(e);let r=n.indexOf(t),i=r,s=0,a=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===i?++s>a&&(a=s):s=1,i=r+t.length,r=n.indexOf(t,i);return a}function Ew(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 Aw(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 Mw(e,t,n,r){const i=Aw(n),s=e.value||"",a=i==="`"?"GraveAccent":"Tilde";if(Ew(e,n)){const d=n.enter("codeIndented"),h=n.indentLines(s,Pw);return d(),h}const o=n.createTracker(r),l=i.repeat(Math.max(Iw(s,i)+1,3)),u=n.enter("codeFenced");let c=o.move(l);if(e.lang){const d=n.enter(`codeFencedLang${a}`);c+=o.move(n.safe(e.lang,m({before:c,after:" ",encode:["`"]},o.current()))),d()}if(e.lang&&e.meta){const d=n.enter(`codeFencedMeta${a}`);c+=o.move(" "),c+=o.move(n.safe(e.meta,m({before:c,after:`
25
25
  `,encode:["`"]},o.current()))),d()}return c+=o.move(`
26
26
  `),s&&(c+=o.move(s+`
27
- `)),c+=o.move(l),u(),c}function Iw(e,t,n){return(n?"":" ")+e}function Ki(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 Cw(e,t,n,r){const i=Ki(n),s=i==='"'?"Quote":"Apostrophe",a=n.enter("definition");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("[");return u+=l.move(n.safe(n.associationId(e),g({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,g({before:u,after:">"},l.current()))),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,g({before:u,after:e.title?" ":`
28
- `},l.current())))),o(),e.title&&(o=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,g({before:u,after:i},l.current()))),u+=l.move(i),o()),a(),u}function Ew(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 kn(e){return"&#x"+e.toString(16).toUpperCase()+";"}function mr(e,t,n){const r=Wt(e),i=Wt(t);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Kl.peek=Aw;function Kl(e,t,n,r){const i=Ew(n),s=n.enter("emphasis"),a=n.createTracker(r),o=a.move(i);let l=a.move(n.containerPhrasing(e,g({after:i,before:o},a.current())));const u=l.charCodeAt(0),c=mr(r.before.charCodeAt(r.before.length-1),u,i);c.inside&&(l=kn(u)+l.slice(1));const d=l.charCodeAt(l.length-1),h=mr(r.after.charCodeAt(0),d,i);h.inside&&(l=l.slice(0,-1)+kn(d));const f=a.move(i);return s(),n.attentionEncodeSurroundingInfo={after:h.outside,before:c.outside},o+l+f}function Aw(e,t,n){return n.options.emphasis||"*"}function Mw(e,t){let n=!1;return Ei(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Ci}),!!((!e.depth||e.depth<3)&&gi(e)&&(t.options.setext||n))}function Pw(e,t,n,r){const i=Math.max(Math.min(6,e.depth||1),1),s=n.createTracker(r);if(Mw(e,n)){const c=n.enter("headingSetext"),d=n.enter("phrasing"),h=n.containerPhrasing(e,E(g({},s.current()),{before:`
27
+ `)),c+=o.move(l),u(),c}function Pw(e,t,n){return(n?"":" ")+e}function Xi(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 Nw(e,t,n,r){const i=Xi(n),s=i==='"'?"Quote":"Apostrophe",a=n.enter("definition");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("[");return u+=l.move(n.safe(n.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,m({before:u,after:e.title?" ":`
28
+ `},l.current())))),o(),e.title&&(o=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,m({before:u,after:i},l.current()))),u+=l.move(i),o()),a(),u}function Lw(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 _n(e){return"&#x"+e.toString(16).toUpperCase()+";"}function yr(e,t,n){const r=Kt(e),i=Kt(t);return r===void 0?i===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Zl.peek=Dw;function Zl(e,t,n,r){const i=Lw(n),s=n.enter("emphasis"),a=n.createTracker(r),o=a.move(i);let l=a.move(n.containerPhrasing(e,m({after:i,before:o},a.current())));const u=l.charCodeAt(0),c=yr(r.before.charCodeAt(r.before.length-1),u,i);c.inside&&(l=_n(u)+l.slice(1));const d=l.charCodeAt(l.length-1),h=yr(r.after.charCodeAt(0),d,i);h.inside&&(l=l.slice(0,-1)+_n(d));const f=a.move(i);return s(),n.attentionEncodeSurroundingInfo={after:h.outside,before:c.outside},o+l+f}function Dw(e,t,n){return n.options.emphasis||"*"}function Ow(e,t){let n=!1;return Pi(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,Mi}),!!((!e.depth||e.depth<3)&&wi(e)&&(t.options.setext||n))}function Fw(e,t,n,r){const i=Math.max(Math.min(6,e.depth||1),1),s=n.createTracker(r);if(Ow(e,n)){const c=n.enter("headingSetext"),d=n.enter("phrasing"),h=n.containerPhrasing(e,I(m({},s.current()),{before:`
29
29
  `,after:`
30
30
  `}));return d(),c(),h+`
31
31
  `+(i===1?"=":"-").repeat(h.length-(Math.max(h.lastIndexOf("\r"),h.lastIndexOf(`
32
- `))+1))}const a="#".repeat(i),o=n.enter("headingAtx"),l=n.enter("phrasing");s.move(a+" ");let u=n.containerPhrasing(e,g({before:"# ",after:`
33
- `},s.current()));return/^[\t ]/.test(u)&&(u=kn(u.charCodeAt(0))+u.slice(1)),u=u?a+" "+u:a,n.options.closeAtx&&(u+=" "+a),l(),o(),u}Yl.peek=Nw;function Yl(e){return e.value||""}function Nw(){return"<"}Gl.peek=Lw;function Gl(e,t,n,r){const i=Ki(n),s=i==='"'?"Quote":"Apostrophe",a=n.enter("image");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("![");return u+=l.move(n.safe(e.alt,g({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,g({before:u,after:">"},l.current()))),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,g({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,g({before:u,after:i},l.current()))),u+=l.move(i),o()),u+=l.move(")"),a(),u}function Lw(){return"!"}Xl.peek=Dw;function Xl(e,t,n,r){const i=e.referenceType,s=n.enter("imageReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("![");const u=n.safe(e.alt,g({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),g({before:l,after:"]"},o.current()));return a(),n.stack=c,s(),i==="full"||!u||u!==d?l+=o.move(d+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Dw(){return"!"}Ql.peek=Ow;function Ql(e,t,n){let r=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s<n.unsafe.length;){const a=n.unsafe[s],o=n.compilePattern(a);let l;if(a.atBreak)for(;l=o.exec(r);){let u=l.index;r.charCodeAt(u)===10&&r.charCodeAt(u-1)===13&&u--,r=r.slice(0,u)+" "+r.slice(l.index+1)}}return i+r+i}function Ow(){return"`"}function Zl(e,t){const n=gi(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}eu.peek=Fw;function eu(e,t,n,r){const i=Ki(n),s=i==='"'?"Quote":"Apostrophe",a=n.createTracker(r);let o,l;if(Zl(e,n)){const c=n.stack;n.stack=[],o=n.enter("autolink");let d=a.move("<");return d+=a.move(n.containerPhrasing(e,g({before:d,after:">"},a.current()))),d+=a.move(">"),o(),n.stack=c,d}o=n.enter("link"),l=n.enter("label");let u=a.move("[");return u+=a.move(n.containerPhrasing(e,g({before:u,after:"]("},a.current()))),u+=a.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=a.move("<"),u+=a.move(n.safe(e.url,g({before:u,after:">"},a.current()))),u+=a.move(">")):(l=n.enter("destinationRaw"),u+=a.move(n.safe(e.url,g({before:u,after:e.title?" ":")"},a.current())))),l(),e.title&&(l=n.enter(`title${s}`),u+=a.move(" "+i),u+=a.move(n.safe(e.title,g({before:u,after:i},a.current()))),u+=a.move(i),l()),u+=a.move(")"),o(),u}function Fw(e,t,n){return Zl(e,n)?"<":"["}tu.peek=Bw;function tu(e,t,n,r){const i=e.referenceType,s=n.enter("linkReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("[");const u=n.containerPhrasing(e,g({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),g({before:l,after:"]"},o.current()));return a(),n.stack=c,s(),i==="full"||!u||u!==d?l+=o.move(d+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Bw(){return"["}function Yi(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 zw(e){const t=Yi(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function Rw(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 jw(e,t,n,r){const i=n.enter("list"),s=n.bulletCurrent;let a=e.ordered?Rw(n):Yi(n);const o=e.ordered?a==="."?")":".":zw(n);let l=t&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&c&&(!c.children||!c.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(l=!0),nu(n)===a&&c){let d=-1;for(;++d<e.children.length;){const h=e.children[d];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(a=o),n.bulletCurrent=a;const u=n.containerFlow(e,r);return n.bulletLastUsed=a,n.bulletCurrent=s,i(),u}function Uw(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 $w(e,t,n,r){const i=Uw(n);let s=n.bulletCurrent||Yi(n);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let a=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(a=Math.ceil(a/4)*4);const o=n.createTracker(r);o.move(s+" ".repeat(a-s.length)),o.shift(a);const l=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,o.current()),c);return l(),u;function c(d,h,f){return h?(f?"":" ".repeat(a))+d:(f?s:s+" ".repeat(a-s.length))+d}}function Hw(e,t,n,r){const i=n.enter("paragraph"),s=n.enter("phrasing"),a=n.containerPhrasing(e,r);return s(),i(),a}const qw=hr(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Vw(e,t,n,r){return(e.children.some(function(a){return qw(a)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function Ww(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}ru.peek=Jw;function ru(e,t,n,r){const i=Ww(n),s=n.enter("strong"),a=n.createTracker(r),o=a.move(i+i);let l=a.move(n.containerPhrasing(e,g({after:i,before:o},a.current())));const u=l.charCodeAt(0),c=mr(r.before.charCodeAt(r.before.length-1),u,i);c.inside&&(l=kn(u)+l.slice(1));const d=l.charCodeAt(l.length-1),h=mr(r.after.charCodeAt(0),d,i);h.inside&&(l=l.slice(0,-1)+kn(d));const f=a.move(i+i);return s(),n.attentionEncodeSurroundingInfo={after:h.outside,before:c.outside},o+l+f}function Jw(e,t,n){return n.options.strong||"*"}function Kw(e,t,n,r){return n.safe(e.value,r)}function Yw(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 Gw(e,t,n){const r=(nu(n)+(n.options.ruleSpaces?" ":"")).repeat(Yw(n));return n.options.ruleSpaces?r.slice(0,-1):r}const iu={blockquote:ww,break:Jl,code:Tw,definition:Cw,emphasis:Kl,hardBreak:Jl,heading:Pw,html:Yl,image:Gl,imageReference:Xl,inlineCode:Ql,link:eu,linkReference:tu,list:jw,listItem:$w,paragraph:Hw,root:Vw,strong:ru,text:Kw,thematicBreak:Gw};function Xw(){return{enter:{table:Qw,tableData:su,tableHeader:su,tableRow:ex},exit:{codeText:tx,table:Zw,tableData:Gi,tableHeader:Gi,tableRow:Gi}}}function Qw(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function Zw(e){this.exit(e),this.data.inTable=void 0}function ex(e){this.enter({type:"tableRow",children:[]},e)}function Gi(e){this.exit(e)}function su(e){this.enter({type:"tableCell",children:[]},e)}function tx(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,nx));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function nx(e,t){return t==="|"?t:e}function rx(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,s=n?" ":"|";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:a,tableCell:l,tableRow:o}};function a(f,m,v,b){return u(c(f,v,b),f.align)}function o(f,m,v,b){const x=d(f,v,b),C=u([x]);return C.slice(0,C.indexOf(`
35
- `))}function l(f,m,v,b){const x=v.enter("tableCell"),C=v.enter("phrasing"),_=v.containerPhrasing(f,E(g({},b),{before:s,after:s}));return C(),x(),_}function u(f,m){return yw(f,{align:m,alignDelimiters:r,padding:n,stringLength:i})}function c(f,m,v){const b=f.children;let x=-1;const C=[],_=m.enter("table");for(;++x<b.length;)C[x]=d(b[x],m,v);return _(),C}function d(f,m,v){const b=f.children;let x=-1;const C=[],_=m.enter("tableRow");for(;++x<b.length;)C[x]=l(b[x],f,m,v);return _(),C}function h(f,m,v){let b=iu.inlineCode(f,m,v);return v.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function ix(){return{exit:{taskListCheckValueChecked:au,taskListCheckValueUnchecked:au,paragraph:ax}}}function sx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:ox}}}function au(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function ax(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const i=t.children;let s=-1,a;for(;++s<i.length;){const o=i[s];if(o.type==="paragraph"){a=o;break}}a===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function ox(e,t,n,r){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",o=n.createTracker(r);s&&o.move(a);let l=iu.listItem(e,t,n,g(g({},r),o.current()));return s&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+a}}function lx(){return[jb(),ow(),dw(),Xw(),ix()]}function ux(e){return{extensions:[Ub(),lw(e),hw(),rx(e),sx()]}}const cx={tokenize:gx,partial:!0},ou={tokenize:yx,partial:!0},lu={tokenize:bx,partial:!0},uu={tokenize:wx,partial:!0},dx={tokenize:xx,partial:!0},cu={name:"wwwAutolink",tokenize:px,previous:hu},du={name:"protocolAutolink",tokenize:mx,previous:fu},dt={name:"emailAutolink",tokenize:fx,previous:pu},ot={};function hx(){return{text:ot}}let Mt=48;for(;Mt<123;)ot[Mt]=dt,Mt++,Mt===58?Mt=65:Mt===91&&(Mt=97);ot[43]=dt,ot[45]=dt,ot[46]=dt,ot[95]=dt,ot[72]=[dt,du],ot[104]=[dt,du],ot[87]=[dt,cu],ot[119]=[dt,cu];function fx(e,t,n){const r=this;let i,s;return a;function a(d){return!Xi(d)||!pu.call(r,r.previous)||Qi(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(d))}function o(d){return Xi(d)?(e.consume(d),o):d===64?(e.consume(d),l):n(d)}function l(d){return d===46?e.check(dx,c,u)(d):d===45||d===95||Pe(d)?(s=!0,e.consume(d),l):c(d)}function u(d){return e.consume(d),i=!0,l}function c(d){return s&&i&&Oe(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function px(e,t,n){const r=this;return i;function i(a){return a!==87&&a!==119||!hu.call(r,r.previous)||Qi(r.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(cx,e.attempt(ou,e.attempt(lu,s),n),n)(a))}function s(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function mx(e,t,n){const r=this;let i="",s=!1;return a;function a(d){return(d===72||d===104)&&fu.call(r,r.previous)&&!Qi(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(d),e.consume(d),o):n(d)}function o(d){if(Oe(d)&&i.length<5)return i+=String.fromCodePoint(d),e.consume(d),o;if(d===58){const h=i.toLowerCase();if(h==="http"||h==="https")return e.consume(d),l}return n(d)}function l(d){return d===47?(e.consume(d),s?u:(s=!0,l)):n(d)}function u(d){return d===null||rr(d)||le(d)||At(d)||ir(d)?n(d):e.attempt(ou,e.attempt(lu,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function gx(e,t,n){let r=0;return i;function i(a){return(a===87||a===119)&&r<3?(r++,e.consume(a),i):a===46&&r===3?(e.consume(a),s):n(a)}function s(a){return a===null?n(a):t(a)}}function yx(e,t,n){let r,i,s;return a;function a(u){return u===46||u===95?e.check(uu,l,o)(u):u===null||le(u)||At(u)||u!==45&&ir(u)?l(u):(s=!0,e.consume(u),a)}function o(u){return u===95?r=!0:(i=r,r=void 0),e.consume(u),a}function l(u){return i||r||!s?n(u):t(u)}}function bx(e,t){let n=0,r=0;return i;function i(a){return a===40?(n++,e.consume(a),i):a===41&&r<n?s(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(uu,t,s)(a):a===null||le(a)||At(a)?t(a):(e.consume(a),i)}function s(a){return a===41&&r++,e.consume(a),i}}function wx(e,t,n){return r;function r(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),r):o===38?(e.consume(o),s):o===93?(e.consume(o),i):o===60||o===null||le(o)||At(o)?t(o):n(o)}function i(o){return o===null||o===40||o===91||le(o)||At(o)?t(o):r(o)}function s(o){return Oe(o)?a(o):n(o)}function a(o){return o===59?(e.consume(o),r):Oe(o)?(e.consume(o),a):n(o)}}function xx(e,t,n){return r;function r(s){return e.consume(s),i}function i(s){return Pe(s)?n(s):t(s)}}function hu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||le(e)}function fu(e){return!Oe(e)}function pu(e){return!(e===47||Xi(e))}function Xi(e){return e===43||e===45||e===46||e===95||Pe(e)}function Qi(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const vx={tokenize:Ax,partial:!0};function Sx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Ix,continuation:{tokenize:Cx},exit:Ex}},text:{91:{name:"gfmFootnoteCall",tokenize:Tx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:kx,resolveTo:_x}}}}function kx(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;i--;){const l=r.events[i][1];if(l.type==="labelImage"){a=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(!a||!a._balanced)return n(l);const u=tt(r.sliceSerialize({start:a.end,end:r.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?n(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function _x(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",a,t],["exit",a,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function Tx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,a;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),l}function l(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(s>999||d===93&&!a||d===null||d===91||le(d))return n(d);if(d===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return i.includes(tt(r.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return le(d)||(a=!0),s++,e.consume(d),d===92?c:u}function c(d){return d===91||d===92||d===93?(e.consume(d),s++,u):u(d)}}function Ix(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,a=0,o;return l;function l(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(m)}function c(m){if(a>999||m===93&&!o||m===null||m===91||le(m))return n(m);if(m===93){e.exit("chunkString");const v=e.exit("gfmFootnoteDefinitionLabelString");return s=tt(r.sliceSerialize(v)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return le(m)||(o=!0),a++,e.consume(m),m===92?d:c}function d(m){return m===91||m===92||m===93?(e.consume(m),a++,c):c(m)}function h(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),i.includes(s)||i.push(s),se(e,f,"gfmFootnoteDefinitionWhitespace")):n(m)}function f(m){return t(m)}}function Cx(e,t,n){return e.check(yn,t,e.attempt(vx,t,n))}function Ex(e){e.exit("gfmFootnoteDefinition")}function Ax(e,t,n){const r=this;return se(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(s):n(s)}}function Mx(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(a,o){let l=-1;for(;++l<a.length;)if(a[l][0]==="enter"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._close){let u=l;for(;u--;)if(a[u][0]==="exit"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._open&&a[l][1].end.offset-a[l][1].start.offset===a[u][1].end.offset-a[u][1].start.offset){a[l][1].type="strikethroughSequence",a[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},a[u][1].start),end:Object.assign({},a[l][1].end)},d={type:"strikethroughText",start:Object.assign({},a[u][1].end),end:Object.assign({},a[l][1].start)},h=[["enter",c,o],["enter",a[u][1],o],["exit",a[u][1],o],["enter",d,o]],f=o.parser.constructs.insideSpan.null;f&&qe(h,h.length,0,sr(f,a.slice(u+1,l),o)),qe(h,h.length,0,[["exit",d,o],["enter",a[l][1],o],["exit",a[l][1],o],["exit",c,o]]),qe(a,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<a.length;)a[l][1].type==="strikethroughSequenceTemporary"&&(a[l][1].type="data");return a}function s(a,o,l){const u=this.previous,c=this.events;let d=0;return h;function h(m){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(m):(a.enter("strikethroughSequenceTemporary"),f(m))}function f(m){const v=Wt(u);if(m===126)return d>1?l(m):(a.consume(m),d++,f);if(d<2&&!n)return l(m);const b=a.exit("strikethroughSequenceTemporary"),x=Wt(m);return b._open=!x||x===2&&!!v,b._close=!v||v===2&&!!x,o(m)}}}class Px{constructor(){this.map=[]}add(t,n,r){Nx(this,t,n,r)}consume(t){if(this.map.sort(function(s,a){return s[0]-a[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function Nx(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=n,e.map[i][2].push(...r);return}i+=1}e.map.push([t,n,r])}}function Lx(e,t){let n=!1;const r=[];for(;t<e.length;){const i=e[t];if(n){if(i[0]==="enter")i[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const s=r.length-1;r[s]=r[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function Dx(){return{flow:{null:{name:"table",tokenize:Ox,resolveAll:Fx}}}}function Ox(e,t,n){const r=this;let i=0,s=0,a;return o;function o(k){let O=r.events.length-1;for(;O>-1;){const L=r.events[O][1].type;if(L==="lineEnding"||L==="linePrefix")O--;else break}const P=O>-1?r.events[O][1].type:null,R=P==="tableHead"||P==="tableRow"?I:l;return R===I&&r.parser.lazy[r.now().line]?n(k):R(k)}function l(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(a=!0,s+=1),c(k)}function c(k){return k===null?n(k):W(k)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),f):n(k):re(k)?se(e,c,"whitespace")(k):(s+=1,a&&(a=!1,i+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),a=!0,c):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||le(k)?(e.exit("data"),c(k)):(e.consume(k),k===92?h:d)}function h(k){return k===92||k===124?(e.consume(k),d):d(k)}function f(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),a=!1,re(k)?se(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):m(k))}function m(k){return k===45||k===58?b(k):k===124?(a=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),v):z(k)}function v(k){return re(k)?se(e,b,"whitespace")(k):b(k)}function b(k){return k===58?(s+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),x):k===45?(s+=1,x(k)):k===null||W(k)?F(k):z(k)}function x(k){return k===45?(e.enter("tableDelimiterFiller"),C(k)):z(k)}function C(k){return k===45?(e.consume(k),C):k===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(k))}function _(k){return re(k)?se(e,F,"whitespace")(k):F(k)}function F(k){return k===124?m(k):k===null||W(k)?!a||i!==s?z(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):z(k)}function z(k){return n(k)}function I(k){return e.enter("tableRow"),H(k)}function H(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),H):k===null||W(k)?(e.exit("tableRow"),t(k)):re(k)?se(e,H,"whitespace")(k):(e.enter("data"),q(k))}function q(k){return k===null||k===124||le(k)?(e.exit("data"),H(k)):(e.consume(k),k===92?j:q)}function j(k){return k===92||k===124?(e.consume(k),q):q(k)}}function Fx(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],a=[0,0,0,0],o=!1,l=0,u,c,d;const h=new Px;for(;++n<e.length;){const f=e[n],m=f[1];f[0]==="enter"?m.type==="tableHead"?(o=!1,l!==0&&(mu(h,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},m.start),end:Object.assign({},m.end)},h.add(n,0,[["enter",u,t]])):m.type==="tableRow"||m.type==="tableDelimiterRow"?(r=!0,d=void 0,s=[0,0,0,0],a=[0,n+1,0,0],o&&(o=!1,c={type:"tableBody",start:Object.assign({},m.start),end:Object.assign({},m.end)},h.add(n,0,[["enter",c,t]])),i=m.type==="tableDelimiterRow"?2:c?3:1):i&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(s[1]!==0&&(a[0]=a[1],d=gr(h,t,s,i,void 0,d),s=[0,0,0,0]),a[2]=n)):m.type==="tableCellDivider"&&(r?r=!1:(s[1]!==0&&(a[0]=a[1],d=gr(h,t,s,i,void 0,d)),s=a,a=[s[1],n,0,0])):m.type==="tableHead"?(o=!0,l=n):m.type==="tableRow"||m.type==="tableDelimiterRow"?(l=n,s[1]!==0?(a[0]=a[1],d=gr(h,t,s,i,n,d)):a[1]!==0&&(d=gr(h,t,a,i,n,d)),i=0):i&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")&&(a[3]=n)}for(l!==0&&mu(h,t,l,u,c),h.consume(t.events),n=-1;++n<t.events.length;){const f=t.events[n];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=Lx(t.events,n))}return e}function gr(e,t,n,r,i,s){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",o="tableContent";n[0]!==0&&(s.end=Object.assign({},Kt(t.events,n[0])),e.add(n[0],0,[["exit",s,t]]));const l=Kt(t.events,n[1]);if(s={type:a,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",s,t]]),n[2]!==0){const u=Kt(t.events,n[2]),c=Kt(t.events,n[3]),d={type:o,start:Object.assign({},u),end:Object.assign({},c)};if(e.add(n[2],0,[["enter",d,t]]),r!==2){const h=t.events[n[2]],f=t.events[n[3]];if(h[1].end=Object.assign({},f[1].end),h[1].type="chunkText",h[1].contentType="text",n[3]>n[2]+1){const m=n[2]+1,v=n[3]-n[2]-1;e.add(m,v,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return i!==void 0&&(s.end=Object.assign({},Kt(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function mu(e,t,n,r,i){const s=[],a=Kt(t.events,n);i&&(i.end=Object.assign({},a),s.push(["exit",i,t])),r.end=Object.assign({},a),s.push(["exit",r,t]),e.add(n+1,0,s)}function Kt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Bx={name:"tasklistCheck",tokenize:Rx};function zx(){return{text:{91:Bx}}}function Rx(e,t,n){const r=this;return i;function i(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),s)}function s(l){return le(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),a):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),a):n(l)}function a(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(l)}function o(l){return W(l)?t(l):re(l)?e.check({tokenize:jx},t,n)(l):n(l)}}function jx(e,t,n){return se(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function Ux(e){return Vo([hx(),Sx(),Mx(e),Dx(),zx()])}const $x={};function Hx(e){const t=this,n=e||$x,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(Ux(n)),s.push(lx()),a.push(ux(n))}function ke(...e){return e.filter(Boolean).join(" ")}const qx=({content:e})=>p.jsx(Db,{remarkPlugins:[Hx],className:"cuadra-aui-md",components:Jx,children:e}),Zi=y.memo(qx),Vx=({language:e,code:t})=>{const{isCopied:n,copyToClipboard:r}=Wx(),i=()=>{!t||n||r(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:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!n&&p.jsx(Pu,{className:"cuadra-h-4 cuadra-w-4"}),n&&p.jsx(ss,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Wx=({copiedDuration:e=3e3}={})=>{const[t,n]=y.useState(!1);return{isCopied:t,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},Jx=bb({h1:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h1",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h2",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h3",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h4",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h5",g({className:ke("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("h6",g({className:ke("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("p",g({className:ke("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("a",g({className:ke("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("blockquote",g({className:ke("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("ul",g({className:ke("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("ol",g({className:ke("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("hr",g({className:ke("cuadra-my-5 cuadra-border-b",e)},t))},table:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("table",g({className:ke("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("th",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("td",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("tr",g({className:ke("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:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("sup",g({className:ke("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:n=>{var r=n,{className:e}=r,t=V(r,["className"]);return p.jsx("pre",g({className:ke("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(r){var i=r,{className:t}=i,n=V(i,["className"]);const s=Ol();return p.jsx("code",g({className:ke(!s&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},n))},CodeHeader:Vx});function gu(r){var i=r,{className:e="",variant:t="default"}=i,n=V(i,["className","variant"]);const s="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",a={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",g({className:`${s} ${a[t]||a.default} ${e}`},n))}function Kx(e){const t=new Map;for(const n of e){const r=t.get(n.filename);(!r||n.score>r.score)&&t.set(n.filename,n)}return Array.from(t.values()).sort((n,r)=>r.score-n.score)}function Yx({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const n=Kx(e),r=n.slice(0,t),i=n.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(as,{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:[r.map((s,a)=>p.jsx(Xx,{source:s},s.sourceId||a)),i>0&&p.jsxs(gu,{variant:"subtle",children:["+",i," more"]})]})]})}function Gx(e){var n;switch((n=e.split(".").pop())==null?void 0:n.toLowerCase()){case"csv":case"xlsx":case"xls":return Nu;case"md":case"txt":return Lu;default:return as}}function Xx({source:e}){const{filename:t,score:n}=e,r=Gx(t);return p.jsxs(gu,{className:"cuadra-gap-2 cuadra-cursor-default",title:n<1?`${Math.round(n*100)}% relevant`:void 0,children:[p.jsx(r,{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}),n<1&&n>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(n*100),"%"]})]})}const Qx=y.forwardRef(function({welcomeTitle:t="What shall we explore today?",extraTopPadding:n,suggestions:r,inputPlaceholder:i="Reply...",enableAttachments:s=!1,preMadeResponseDelay:a=1e3,streamingSpeed:o=50,safeArea:l=!1,composerBorder:u=!1,models:c,selectedModelId:d,onModelChange:h,showChatHeader:f=!1},m){const v=oa(),b=me(),[x,C]=y.useState(!1),[_,F]=y.useState(null),[z,I]=y.useState(!1),H=la(R=>{const L=R.messages;return!L||L.length===0}),q=H&&!x,j=y.useCallback((R,L,N)=>{var G,J;if(!z)try{const Z=(G=N==null?void 0:N.streamingSpeed)!=null?G:o,de=(J=N==null?void 0:N.delay)!=null?J:a;po(R,L,Z,de),b.composer().setText(R),setTimeout(()=>{b.composer().send()},10)}catch(Z){}},[z,o,a,b]),k=y.useCallback(R=>{try{b.composer().setText(R),setTimeout(()=>{b.composer().send()},10)}catch(L){}},[b]),O=y.useCallback(R=>M(null,null,function*(){var L;if(!(z||!v))try{if(R.response){const N=(L=R.responseDelay)!=null?L:a;yield j(R.prompt,R.response,{delay:N,streamingSpeed:o})}else k(R.prompt)}catch(N){}}),[v,z,a,o,j,k]),P=y.useCallback(()=>M(null,null,function*(){try{const R=window.__cuadraThreadListRuntime,L=R==null?void 0:R.threadList;L!=null&&L.switchToNewThread&&(yield L.switchToNewThread())}catch(R){}}),[]);return y.useImperativeHandle(m,()=>({sendMessage:k,sendPreMadeQA:j,clearChat:P}),[k,j,P]),y.useEffect(()=>{var R,L;if(!v){C(!1);return}try{const N=v==null?void 0:v.store;if(!N){C(!1);return}const G=(R=N.subscribe)==null?void 0:R.call(N,Z=>{const de=Z==null?void 0:Z.threadId,w=(Z==null?void 0:Z.messages)||[],ge=(Z==null?void 0:Z.isLoadingHistory)||!1,ye=w.length;de&&de!==_&&F(de),C(ge&&ye===0)}),J=(L=N.getState)==null?void 0:L.call(N);if(J){const Z=J==null?void 0:J.threadId,de=(J==null?void 0:J.messages)||[],w=(J==null?void 0:J.isLoadingHistory)||!1,ge=de.length;Z&&Z!==_&&F(Z),C(w&&ge===0)}return()=>{G&&G()}}catch(N){C(!1)}},[v,_]),p.jsxs(Za,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[f&&p.jsx(sv,{}),p.jsxs("div",{className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 ${q?"cuadra-justify-center":""}`,children:[p.jsx(no,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${q?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:q?"0":n||(f?"0.5rem":"2rem")},children:x?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-3",children:[p.jsx(os,{className:"cuadra-h-5 cuadra-w-5 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("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[p.jsx(eo,{children:p.jsx(Zx,{title:t})}),p.jsx(Wf,{components:{UserMessage:ev,AssistantMessage:rv}})]})}),p.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${q?"cuadra-pb-2":"cuadra-pb-4"}`,style:l?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[s&&p.jsx(Qa,{components:{Attachment:()=>{const R=ne(({attachment:L})=>L);return R?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-1.5 cuadra-rounded-lg cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx(ls,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:R.name||"Attachment"}),p.jsx(ef,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:p.jsx(Fu,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(Ha,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:u?"1px solid hsl(var(--cuadra-border))":"none"},children:[p.jsx(Ga,{asChild:!0,children:p.jsx("textarea",{rows:1,placeholder:i,className:"cuadra-flex cuadra-min-h-[44px] cuadra-w-full cuadra-rounded-t-2xl cuadra-border-0 cuadra-bg-transparent cuadra-px-4 cuadra-pt-3.5 cuadra-pb-1 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:{fontSize:"1rem",lineHeight:"1.5"}})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:s&&p.jsx(Bf,{multiple:!0,asChild:!0,children:p.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[p.jsx(us,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[c&&c.length>0&&p.jsx(iv,{models:c,selectedModelId:d,onModelChange:h,threadIsEmpty:H,onNewChat:P}),p.jsx(bf,{asChild:!0,children:p.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:p.jsx(Mu,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),q&&r&&r.length>0&&p.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:r.map((R,L)=>p.jsx("button",{type:"button",onClick:()=>O(R),disabled:z,className:"cuadra-px-3.5 cuadra-py-2 cuadra-rounded-full cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-all cuadra-duration-200 font-brand cuadra-cursor-pointer disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"0 0 0 1px rgba(0,0,0,0.06)"},children:R.prompt},`suggestion-${L}`))})]})]})});function Zx({title:e}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:p.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e})})}function ev(){return p.jsx(Xr,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[p.jsx(Ua,{components:{Attachment:()=>{var s;const e=ne(({attachment:a})=>a);if(!e)return null;const t=e.type==="image",n=e.file,r=(s=e.content)==null?void 0:s.find(a=>a.type==="image"),i=n?URL.createObjectURL(n):r==null?void 0:r.image;return p.jsx("div",{className:"cuadra-mb-1",children:t&&i?p.jsx("img",{src:i,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-xl cuadra-px-3 cuadra-py-2",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx(ls,{className:"cuadra-h-3.5 cuadra-w-3.5 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-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:p.jsx(Qr,{components:{Text:({text:e})=>p.jsx(Zi,{content:e||""})}})})]})})}function tv({text:e}){const[t,n]=y.useState(!1),r=ne(({message:i})=>{var s;return((s=i==null?void 0:i.status)==null?void 0:s.type)==="running"});return e?r?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:()=>n(!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(_r,{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(Zi,{content:e})})})]}):null}function nv(){return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-3",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-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms",backgroundColor:"var(--cuadra-primary)",opacity:.7}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms",backgroundColor:"var(--cuadra-primary)",opacity:.5}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms",backgroundColor:"var(--cuadra-primary)",opacity:.3}})]}),p.jsx("span",{children:"Thinking..."})]})}function rv(){const e=ne(({message:a})=>{var o;return((o=a==null?void 0:a.status)==null?void 0:o.type)==="running"}),t=ne(({message:a})=>{const o=a==null?void 0:a.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))}),n=y.useRef(!1),[r,i]=y.useState(null);y.useEffect(()=>{if(e&&t&&!n.current){const a=bt.getCurrentMessageId();a&&(n.current=!0,i(a))}},[e,t]);const s=y.useSyncExternalStore(a=>bt.subscribe(a),()=>{var a,o;if(r){const l=bt.getForMessage(r);return(a=l.sources)!=null&&a.length?l.sources:null}if(e&&t){const l=bt.getCurrentMessageId();if(l){const u=bt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(Xr,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[p.jsx(Qr,{components:{Text:({text:a})=>p.jsx(Zi,{content:a||""}),Reasoning:({text:a})=>p.jsx(tv,{text:a||""})}}),e&&!t&&p.jsx(nv,{}),s&&s.length>0&&p.jsx(Yx,{sources:s})]})})}function iv({models:e,selectedModelId:t,onModelChange:n,threadIsEmpty:r,onNewChat:i}){const[s,a]=y.useState(!1),o=e.find(u=>u.id===t)||e[0];if(!o)return null;const l=u=>M(null,null,function*(){a(!1),!r&&u!==t&&(yield i==null?void 0:i()),n==null||n(u)});return p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>a(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx("span",{children:o.name}),p.jsx(_r,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>a(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-overflow-hidden cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(u=>p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>l(u.id),children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("span",{className:"cuadra-text-foreground",children:u.name}),u.description&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===t&&p.jsx(ss,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]})]})}function sv(){const e=ne(({threadListItem:i})=>{var s;return(s=i==null?void 0:i.title)!=null?s:null}),[t,n]=y.useState(!1),r=e||"Untitled chat";return p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>n(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[p.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:r}),p.jsx(_r,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"cuadra-rotate-180":""}`})]}),t&&p.jsx(av,{onClose:()=>n(!1)})]})})}function av({onClose:e}){return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),p.jsx("div",{className:"cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:p.jsxs(uo,{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:p.jsxs(ao,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[p.jsx(us,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),p.jsx(ov,{onSelect:e})]})})]})}function ov({onSelect:e}){const t=ne(({threads:i})=>{var s;return(s=i==null?void 0:i.threadIds)!=null?s:[]}),n=ne(({threads:i})=>i==null?void 0:i.newThreadId);return t.some(i=>i!==n)?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),p.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:p.jsx(lo,{components:{ThreadListItem:i=>p.jsx(lv,E(g({},i),{onSelect:e}))}})})]}):null}function lv({onSelect:e}){const t=ua(),n=la(m=>m.threadId),r=(t==null?void 0:t.id)===n,[i,s]=y.useState(!1),[a,o]=y.useState(!1),[l,u]=y.useState((t==null?void 0:t.title)||""),[c,d]=y.useState(!1),h=()=>M(null,null,function*(){if(!(t!=null&&t.remoteId)||!l||l===t.title){o(!1);return}try{d(!0);const m=window.__cuadraThreadListAdapter;m!=null&&m.rename&&(yield m.rename(t.remoteId,l))}catch(m){}finally{d(!1),o(!1)}}),f=m=>M(null,null,function*(){var b;m.stopPropagation();const v=t==null?void 0:t.id;if(v)try{const x=window.__cuadraThreadListRuntime,C=x==null?void 0:x.threadList,_=(b=C==null?void 0:C.getItemById)==null?void 0:b.call(C,v);C!=null&&C.switchToNewThread&&(yield C.switchToNewThread()),_!=null&&_.delete&&(yield _.delete())}catch(x){}});return y.useEffect(()=>{t!=null&&t.title&&!a&&u(t.title)},[t==null?void 0:t.title,a]),t?p.jsxs(co,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${r?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:[a?p.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onKeyDown:m=>m.stopPropagation(),onKeyUp:m=>m.stopPropagation(),onKeyPress:m=>m.stopPropagation(),children:p.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:l,onChange:m=>u(m.target.value),onKeyDown:m=>{m.stopPropagation(),m.key==="Enter"&&h(),m.key==="Escape"&&(o(!1),u(t.title||""))},onBlur:()=>void h(),disabled:c,autoFocus:!0})}):p.jsx(Kf,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),(i||r)&&!a&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:m=>{m.stopPropagation(),o(!0),u(t.title||"Chat")},title:"Rename",children:p.jsx(Du,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:f,title:"Delete",children:p.jsx(Ou,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const es=({children:e,className:t="",paddingX:n="px-0",paddingY:r="py-0",borderSizePx:i=2,style:s,contentStyle:a})=>p.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${n} ${r} ${t}`,style:g(g({border:i>0?`${i}px solid var(--cuadra-primary)`:"none"},s),a),children:e}),uv=y.createContext(void 0),ts=({children:e,value:t})=>p.jsx(uv.Provider,{value:t,children:e});function cv(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const n=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),n)return;const r=document.createElement("link");r.setAttribute("data-cuadra-uikit","true"),r.rel="stylesheet",r.type="text/css";const i=["/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:je&&je.tagName.toUpperCase()==="SCRIPT"&&je.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let s=!1;for(const a of i)if(r.href=a,r.onload=()=>{s=!0},r.onerror=()=>{},document.head.appendChild(r),s)break},[])}const yu=y.forwardRef(function({config:t},n){cv();const r=y.useRef(null),i=y.useRef(!1),{baseUrl:s,proxyUrl:a,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:c,onModelChange:d,ephemeral:h=!1,systemPrompt:f,enableReasoning:m=!1,initialThreadId:v,welcomeTitle:b,welcomeSubtitle:x,extraTopPadding:C,suggestions:_,inputPlaceholder:F,preMadeResponseDelay:z=1e3,streamingSpeed:I=50,initialMessage:H,initialPreMadeQA:q,theme:j="system",onError:k,onChatCreated:O,onUserMessage:P,onThreadIdUpdate:R,enableAttachments:L=!1,onBeforeRequest:N,mockResponseOnBlocked:G}=t;y.useImperativeHandle(n,()=>({sendMessage:te=>{var be;(be=r.current)==null||be.sendMessage(te)},sendPreMadeQA:(te,be,we)=>{var vt;(vt=r.current)==null||vt.sendPreMadeQA(te,be,we)},clearChat:()=>{var te;(te=r.current)==null||te.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const te=setTimeout(()=>{var be,we;q?(i.current=!0,(be=r.current)==null||be.sendPreMadeQA(q.question,q.answer,{delay:z,streamingSpeed:I})):H&&(i.current=!0,(we=r.current)==null||we.sendMessage(H))},500);return()=>clearTimeout(te)},[H,q,z,I]);const J=a||s||"",Z=!!a,de=y.useMemo(()=>new ho(J,o||void 0,Z),[J,o,Z]),[w,ge]=y.useState(null),[ye,S]=y.useState(!1),[Ie,lt]=y.useState(null),[_e,U]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&U(!0)},[l]);const X=y.useCallback(()=>M(null,null,function*(){if(u==="selector"){S(!0),lt(null);try{const te=yield de.listModels();ge(te)}catch(te){lt(te instanceof Error?te:new Error("Failed to load models"))}finally{S(!1)}}}),[de,u]);y.useEffect(()=>{u==="selector"&&X()},[u,X]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=X),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[X]);const[ae,he]=y.useState(u==="fixed"&&c||null),Ce=y.useRef(ae),ee=y.useCallback(te=>{const be=Ce.current;he(te),Ce.current=te,d==null||d(te),be!==null&&be!==te&&l==="multiChat"&&setTimeout(()=>{var vt,br;const we=window.__cuadraThreadListRuntime;if((vt=we==null?void 0:we.threads)!=null&&vt.switchToNewThread)try{we.threads.switchToNewThread()}catch(wr){}else if((br=we==null?void 0:we.threads)!=null&&br.createThread)try{we.threads.createThread()}catch(wr){}else if(we!=null&&we.switchToNewThread)try{we.switchToNewThread()}catch(wr){}},100)},[d,l]);y.useEffect(()=>{if(u==="selector"&&(w!=null&&w.items)&&w.items.length>0&&!ae){const te=w.items[0];if(te!=null&&te.id){const be=te.id;he(be),d==null||d(be)}}},[u,w==null?void 0:w.items,ae,d]);const xe=u==="fixed"?!!c:!!ae,Ye=y.useMemo(()=>((w==null?void 0:w.items)||[]).filter(te=>(te==null?void 0:te.id)&&(te==null?void 0:te.displayName)).map(te=>({id:te.id,name:te.displayName})),[w]),Ge=y.useMemo(()=>({currentModelId:ae||"",models:Ye,modelsLoading:ye,modelsError:Ie,onModelChange:ee,refetchModels:X}),[ae,Ye,ye,Ie,ee,X]);return u==="selector"&&ye||l==="multiChat"&&_e?p.jsx(ts,{value:Ge,children:p.jsx(es,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:2,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(os,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!xe&&Ie?p.jsx(ts,{value:Ge,children:p.jsx(es,{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(ts,{value:Ge,children:p.jsx(op,{baseUrl:Z?J:s||J,sessionToken:o,isProxyMode:Z,mode:l,modelMode:u,modelId:ae||c||void 0,onModelChange:ee,ephemeral:h,systemPrompt:f,enableReasoning:m,initialThreadId:v,enableAttachments:L,onError:k,onChatCreated:O,onUserMessage:P,onThreadIdUpdate:R,onBeforeRequest:N,mockResponseOnBlocked:G,onChatsLoaded:()=>{l==="multiChat"&&U(!1)},children:p.jsx(es,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:2,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:p.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:p.jsx(Qx,{ref:r,welcomeTitle:b,welcomeSubtitle:x,extraTopPadding:C,suggestions:_,inputPlaceholder:F,enableAttachments:L,preMadeResponseDelay:z,streamingSpeed:I,safeArea:t.safeArea,showChatHeader:l==="multiChat",models:u==="selector"?Ye:void 0,selectedModelId:ae||void 0,onModelChange:u==="selector"?ee:void 0,theme:j})})})})})})})})});class yr{constructor(){T(this,"config",null);T(this,"root",null);T(this,"container",null);T(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 n=t.containerId||"cuadra-chat";let r=document.getElementById(n);r||(r=document.createElement("div"),r.id=n,document.body.appendChild(r)),t.containerClass&&r.classList.add(...t.containerClass.split(" ")),this.config=E(g({},t),{containerId:n}),this.container=r,this.root=fe.createRoot(r),this.root.render(y.createElement(bu,{config:this.config})),this.instances.set(n,this)}destroy(t){var i;const n=t||((i=this.config)==null?void 0:i.containerId);if(!n)return;const r=this.instances.get(n);r!=null&&r.root&&(r.root.unmount(),r.root=null),r!=null&&r.container&&r.container.parentNode&&r.container.parentNode.removeChild(r.container),this.instances.delete(n)}updateConfig(t,n){var a;const r=n||((a=this.config)==null?void 0:a.containerId);if(!r)return;const i=this.instances.get(r);if(!(i!=null&&i.config))return;const s=g(g({},i.config),t);i.config=s,i.root&&i.container&&i.root.render(y.createElement(bu,{config:s}))}getInstance(t){var r;const n=t||((r=this.config)==null?void 0:r.containerId);return n&&this.instances.get(n)||null}static parseConfigFromAttributes(t,n){const r={};return t.dataset.baseUrl&&(r.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(r.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(r.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(r.containerId=t.dataset.containerId),t.dataset.containerClass&&(r.containerClass=t.dataset.containerClass),t.dataset.mode&&(r.mode=t.dataset.mode),t.dataset.modelMode&&(r.modelMode=t.dataset.modelMode),t.dataset.modelId&&(r.modelId=t.dataset.modelId),t.dataset.ephemeral&&(r.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(r.systemPrompt=t.dataset.systemPrompt),n&&(n.dataset.baseUrl&&(r.baseUrl=n.dataset.baseUrl),n.dataset.proxyUrl&&(r.proxyUrl=n.dataset.proxyUrl),n.dataset.sessionToken&&(r.sessionToken=n.dataset.sessionToken),n.dataset.mode&&(r.mode=n.dataset.mode),n.dataset.modelMode&&(r.modelMode=n.dataset.modelMode),n.dataset.modelId&&(r.modelId=n.dataset.modelId)),r}}const bu=({config:e})=>p.jsx(yu,{config:e});let Fe=null;typeof window!="undefined"&&(Fe=new yr);const wu={init:e=>(Fe||(Fe=new yr),Fe.init(e)),destroy:e=>Fe==null?void 0:Fe.destroy(e),updateConfig:(e,t)=>Fe==null?void 0:Fe.updateConfig(e,t),getInstance:e=>Fe==null?void 0:Fe.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=wu;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),n=Array.from(t).find(r=>(r.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));n&&n.dataset.autoInit!=="false"&&dv(n)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function dv(e){if(!e||!Fe)return;const t=yr.parseConfigFromAttributes(e),n=t.containerId||"cuadra-chat",r=document.getElementById(n);if(r){const i=yr.parseConfigFromAttributes(e,r);Object.assign(t,i)}(t.baseUrl||t.proxyUrl)&&Fe.init(t)}$.WidgetContent=yu,$.default=wu,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
32
+ `))+1))}const a="#".repeat(i),o=n.enter("headingAtx"),l=n.enter("phrasing");s.move(a+" ");let u=n.containerPhrasing(e,m({before:"# ",after:`
33
+ `},s.current()));return/^[\t ]/.test(u)&&(u=_n(u.charCodeAt(0))+u.slice(1)),u=u?a+" "+u:a,n.options.closeAtx&&(u+=" "+a),l(),o(),u}eu.peek=zw;function eu(e){return e.value||""}function zw(){return"<"}tu.peek=Bw;function tu(e,t,n,r){const i=Xi(n),s=i==='"'?"Quote":"Apostrophe",a=n.enter("image");let o=n.enter("label");const l=n.createTracker(r);let u=l.move("![");return u+=l.move(n.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(n.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=n.enter("destinationRaw"),u+=l.move(n.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=n.enter(`title${s}`),u+=l.move(" "+i),u+=l.move(n.safe(e.title,m({before:u,after:i},l.current()))),u+=l.move(i),o()),u+=l.move(")"),a(),u}function Bw(){return"!"}nu.peek=Rw;function nu(e,t,n,r){const i=e.referenceType,s=n.enter("imageReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("![");const u=n.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),m({before:l,after:"]"},o.current()));return a(),n.stack=c,s(),i==="full"||!u||u!==d?l+=o.move(d+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Rw(){return"!"}ru.peek=jw;function ru(e,t,n){let r=e.value||"",i="`",s=-1;for(;new RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s<n.unsafe.length;){const a=n.unsafe[s],o=n.compilePattern(a);let l;if(a.atBreak)for(;l=o.exec(r);){let u=l.index;r.charCodeAt(u)===10&&r.charCodeAt(u-1)===13&&u--,r=r.slice(0,u)+" "+r.slice(l.index+1)}}return i+r+i}function jw(){return"`"}function iu(e,t){const n=wi(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}su.peek=Uw;function su(e,t,n,r){const i=Xi(n),s=i==='"'?"Quote":"Apostrophe",a=n.createTracker(r);let o,l;if(iu(e,n)){const c=n.stack;n.stack=[],o=n.enter("autolink");let d=a.move("<");return d+=a.move(n.containerPhrasing(e,m({before:d,after:">"},a.current()))),d+=a.move(">"),o(),n.stack=c,d}o=n.enter("link"),l=n.enter("label");let u=a.move("[");return u+=a.move(n.containerPhrasing(e,m({before:u,after:"]("},a.current()))),u+=a.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=a.move("<"),u+=a.move(n.safe(e.url,m({before:u,after:">"},a.current()))),u+=a.move(">")):(l=n.enter("destinationRaw"),u+=a.move(n.safe(e.url,m({before:u,after:e.title?" ":")"},a.current())))),l(),e.title&&(l=n.enter(`title${s}`),u+=a.move(" "+i),u+=a.move(n.safe(e.title,m({before:u,after:i},a.current()))),u+=a.move(i),l()),u+=a.move(")"),o(),u}function Uw(e,t,n){return iu(e,n)?"<":"["}au.peek=$w;function au(e,t,n,r){const i=e.referenceType,s=n.enter("linkReference");let a=n.enter("label");const o=n.createTracker(r);let l=o.move("[");const u=n.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),a();const c=n.stack;n.stack=[],a=n.enter("reference");const d=n.safe(n.associationId(e),m({before:l,after:"]"},o.current()));return a(),n.stack=c,s(),i==="full"||!u||u!==d?l+=o.move(d+"]"):i==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function $w(){return"["}function Qi(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 Hw(e){const t=Qi(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}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 ou(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 Vw(e,t,n,r){const i=n.enter("list"),s=n.bulletCurrent;let a=e.ordered?qw(n):Qi(n);const o=e.ordered?a==="."?")":".":Hw(n);let l=t&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!e.ordered){const c=e.children?e.children[0]:void 0;if((a==="*"||a==="-")&&c&&(!c.children||!c.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(l=!0),ou(n)===a&&c){let d=-1;for(;++d<e.children.length;){const h=e.children[d];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(a=o),n.bulletCurrent=a;const u=n.containerFlow(e,r);return n.bulletLastUsed=a,n.bulletCurrent=s,i(),u}function Ww(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 Jw(e,t,n,r){const i=Ww(n);let s=n.bulletCurrent||Qi(n);t&&t.type==="list"&&t.ordered&&(s=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+s);let a=s.length+1;(i==="tab"||i==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(a=Math.ceil(a/4)*4);const o=n.createTracker(r);o.move(s+" ".repeat(a-s.length)),o.shift(a);const l=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,o.current()),c);return l(),u;function c(d,h,f){return h?(f?"":" ".repeat(a))+d:(f?s:s+" ".repeat(a-s.length))+d}}function Kw(e,t,n,r){const i=n.enter("paragraph"),s=n.enter("phrasing"),a=n.containerPhrasing(e,r);return s(),i(),a}const Yw=pr(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Gw(e,t,n,r){return(e.children.some(function(a){return Yw(a)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function Xw(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}lu.peek=Qw;function lu(e,t,n,r){const i=Xw(n),s=n.enter("strong"),a=n.createTracker(r),o=a.move(i+i);let l=a.move(n.containerPhrasing(e,m({after:i,before:o},a.current())));const u=l.charCodeAt(0),c=yr(r.before.charCodeAt(r.before.length-1),u,i);c.inside&&(l=_n(u)+l.slice(1));const d=l.charCodeAt(l.length-1),h=yr(r.after.charCodeAt(0),d,i);h.inside&&(l=l.slice(0,-1)+_n(d));const f=a.move(i+i);return s(),n.attentionEncodeSurroundingInfo={after:h.outside,before:c.outside},o+l+f}function Qw(e,t,n){return n.options.strong||"*"}function Zw(e,t,n,r){return n.safe(e.value,r)}function ex(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 tx(e,t,n){const r=(ou(n)+(n.options.ruleSpaces?" ":"")).repeat(ex(n));return n.options.ruleSpaces?r.slice(0,-1):r}const uu={blockquote:_w,break:Ql,code:Mw,definition:Nw,emphasis:Zl,hardBreak:Ql,heading:Fw,html:eu,image:tu,imageReference:nu,inlineCode:ru,link:su,linkReference:au,list:Vw,listItem:Jw,paragraph:Kw,root:Gw,strong:lu,text:Zw,thematicBreak:tx};function nx(){return{enter:{table:rx,tableData:cu,tableHeader:cu,tableRow:sx},exit:{codeText:ax,table:ix,tableData:Zi,tableHeader:Zi,tableRow:Zi}}}function rx(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function ix(e){this.exit(e),this.data.inTable=void 0}function sx(e){this.enter({type:"tableRow",children:[]},e)}function Zi(e){this.exit(e)}function cu(e){this.enter({type:"tableCell",children:[]},e)}function ax(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,ox));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function ox(e,t){return t==="|"?t:e}function lx(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,s=n?" ":"|";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:a,tableCell:l,tableRow:o}};function a(f,g,v,b){return u(c(f,v,b),f.align)}function o(f,g,v,b){const x=d(f,v,b),E=u([x]);return E.slice(0,E.indexOf(`
35
+ `))}function l(f,g,v,b){const x=v.enter("tableCell"),E=v.enter("phrasing"),_=v.containerPhrasing(f,I(m({},b),{before:s,after:s}));return E(),x(),_}function u(f,g){return Sw(f,{align:g,alignDelimiters:r,padding:n,stringLength:i})}function c(f,g,v){const b=f.children;let x=-1;const E=[],_=g.enter("table");for(;++x<b.length;)E[x]=d(b[x],g,v);return _(),E}function d(f,g,v){const b=f.children;let x=-1;const E=[],_=g.enter("tableRow");for(;++x<b.length;)E[x]=l(b[x],f,g,v);return _(),E}function h(f,g,v){let b=uu.inlineCode(f,g,v);return v.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function ux(){return{exit:{taskListCheckValueChecked:du,taskListCheckValueUnchecked:du,paragraph:dx}}}function cx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:hx}}}function du(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function dx(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const i=t.children;let s=-1,a;for(;++s<i.length;){const o=i[s];if(o.type==="paragraph"){a=o;break}}a===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function hx(e,t,n,r){const i=e.children[0],s=typeof e.checked=="boolean"&&i&&i.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",o=n.createTracker(r);s&&o.move(a);let l=uu.listItem(e,t,n,m(m({},r),o.current()));return s&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(c){return c+a}}function fx(){return[Vb(),hw(),gw(),nx(),ux()]}function px(e){return{extensions:[Wb(),fw(e),yw(),lx(e),cx()]}}const mx={tokenize:vx,partial:!0},hu={tokenize:Sx,partial:!0},fu={tokenize:kx,partial:!0},pu={tokenize:_x,partial:!0},gx={tokenize:Tx,partial:!0},mu={name:"wwwAutolink",tokenize:wx,previous:yu},gu={name:"protocolAutolink",tokenize:xx,previous:bu},dt={name:"emailAutolink",tokenize:bx,previous:wu},ot={};function yx(){return{text:ot}}let Mt=48;for(;Mt<123;)ot[Mt]=dt,Mt++,Mt===58?Mt=65:Mt===91&&(Mt=97);ot[43]=dt,ot[45]=dt,ot[46]=dt,ot[95]=dt,ot[72]=[dt,gu],ot[104]=[dt,gu],ot[87]=[dt,mu],ot[119]=[dt,mu];function bx(e,t,n){const r=this;let i,s;return a;function a(d){return!es(d)||!wu.call(r,r.previous)||ts(r.events)?n(d):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(d))}function o(d){return es(d)?(e.consume(d),o):d===64?(e.consume(d),l):n(d)}function l(d){return d===46?e.check(gx,c,u)(d):d===45||d===95||Pe(d)?(s=!0,e.consume(d),l):c(d)}function u(d){return e.consume(d),i=!0,l}function c(d){return s&&i&&Oe(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(d)):n(d)}}function wx(e,t,n){const r=this;return i;function i(a){return a!==87&&a!==119||!yu.call(r,r.previous)||ts(r.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(mx,e.attempt(hu,e.attempt(fu,s),n),n)(a))}function s(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function xx(e,t,n){const r=this;let i="",s=!1;return a;function a(d){return(d===72||d===104)&&bu.call(r,r.previous)&&!ts(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),i+=String.fromCodePoint(d),e.consume(d),o):n(d)}function o(d){if(Oe(d)&&i.length<5)return i+=String.fromCodePoint(d),e.consume(d),o;if(d===58){const h=i.toLowerCase();if(h==="http"||h==="https")return e.consume(d),l}return n(d)}function l(d){return d===47?(e.consume(d),s?u:(s=!0,l)):n(d)}function u(d){return d===null||sr(d)||le(d)||At(d)||ar(d)?n(d):e.attempt(hu,e.attempt(fu,c),n)(d)}function c(d){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(d)}}function vx(e,t,n){let r=0;return i;function i(a){return(a===87||a===119)&&r<3?(r++,e.consume(a),i):a===46&&r===3?(e.consume(a),s):n(a)}function s(a){return a===null?n(a):t(a)}}function Sx(e,t,n){let r,i,s;return a;function a(u){return u===46||u===95?e.check(pu,l,o)(u):u===null||le(u)||At(u)||u!==45&&ar(u)?l(u):(s=!0,e.consume(u),a)}function o(u){return u===95?r=!0:(i=r,r=void 0),e.consume(u),a}function l(u){return i||r||!s?n(u):t(u)}}function kx(e,t){let n=0,r=0;return i;function i(a){return a===40?(n++,e.consume(a),i):a===41&&r<n?s(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(pu,t,s)(a):a===null||le(a)||At(a)?t(a):(e.consume(a),i)}function s(a){return a===41&&r++,e.consume(a),i}}function _x(e,t,n){return r;function r(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),r):o===38?(e.consume(o),s):o===93?(e.consume(o),i):o===60||o===null||le(o)||At(o)?t(o):n(o)}function i(o){return o===null||o===40||o===91||le(o)||At(o)?t(o):r(o)}function s(o){return Oe(o)?a(o):n(o)}function a(o){return o===59?(e.consume(o),r):Oe(o)?(e.consume(o),a):n(o)}}function Tx(e,t,n){return r;function r(s){return e.consume(s),i}function i(s){return Pe(s)?n(s):t(s)}}function yu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||le(e)}function bu(e){return!Oe(e)}function wu(e){return!(e===47||es(e))}function es(e){return e===43||e===45||e===46||e===95||Pe(e)}function ts(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const Cx={tokenize:Dx,partial:!0};function Ix(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Px,continuation:{tokenize:Nx},exit:Lx}},text:{91:{name:"gfmFootnoteCall",tokenize:Mx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Ex,resolveTo:Ax}}}}function Ex(e,t,n){const r=this;let i=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;i--;){const l=r.events[i][1];if(l.type==="labelImage"){a=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(!a||!a._balanced)return n(l);const u=tt(r.sliceSerialize({start:a.end,end:r.now()}));return u.codePointAt(0)!==94||!s.includes(u.slice(1))?n(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function Ax(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",i,t],["exit",i,t],["enter",s,t],["enter",a,t],["exit",a,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function Mx(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s=0,a;return o;function o(d){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),l}function l(d){return d!==94?n(d):(e.enter("gfmFootnoteCallMarker"),e.consume(d),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(d){if(s>999||d===93&&!a||d===null||d===91||le(d))return n(d);if(d===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return i.includes(tt(r.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(d)}return le(d)||(a=!0),s++,e.consume(d),d===92?c:u}function c(d){return d===91||d===92||d===93?(e.consume(d),s++,u):u(d)}}function Px(e,t,n){const r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,a=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",c):n(g)}function c(g){if(a>999||g===93&&!o||g===null||g===91||le(g))return n(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteDefinitionLabelString");return s=tt(r.sliceSerialize(v)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return le(g)||(o=!0),a++,e.consume(g),g===92?d:c}function d(g){return g===91||g===92||g===93?(e.consume(g),a++,c):c(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),i.includes(s)||i.push(s),se(e,f,"gfmFootnoteDefinitionWhitespace")):n(g)}function f(g){return t(g)}}function Nx(e,t,n){return e.check(bn,t,e.attempt(Cx,t,n))}function Lx(e){e.exit("gfmFootnoteDefinition")}function Dx(e,t,n){const r=this;return se(e,i,"gfmFootnoteDefinitionIndent",5);function i(s){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(s):n(s)}}function Ox(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:s,resolveAll:i};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function i(a,o){let l=-1;for(;++l<a.length;)if(a[l][0]==="enter"&&a[l][1].type==="strikethroughSequenceTemporary"&&a[l][1]._close){let u=l;for(;u--;)if(a[u][0]==="exit"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._open&&a[l][1].end.offset-a[l][1].start.offset===a[u][1].end.offset-a[u][1].start.offset){a[l][1].type="strikethroughSequence",a[u][1].type="strikethroughSequence";const c={type:"strikethrough",start:Object.assign({},a[u][1].start),end:Object.assign({},a[l][1].end)},d={type:"strikethroughText",start:Object.assign({},a[u][1].end),end:Object.assign({},a[l][1].start)},h=[["enter",c,o],["enter",a[u][1],o],["exit",a[u][1],o],["enter",d,o]],f=o.parser.constructs.insideSpan.null;f&&qe(h,h.length,0,or(f,a.slice(u+1,l),o)),qe(h,h.length,0,[["exit",d,o],["enter",a[l][1],o],["exit",a[l][1],o],["exit",c,o]]),qe(a,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<a.length;)a[l][1].type==="strikethroughSequenceTemporary"&&(a[l][1].type="data");return a}function s(a,o,l){const u=this.previous,c=this.events;let d=0;return h;function h(g){return u===126&&c[c.length-1][1].type!=="characterEscape"?l(g):(a.enter("strikethroughSequenceTemporary"),f(g))}function f(g){const v=Kt(u);if(g===126)return d>1?l(g):(a.consume(g),d++,f);if(d<2&&!n)return l(g);const b=a.exit("strikethroughSequenceTemporary"),x=Kt(g);return b._open=!x||x===2&&!!v,b._close=!v||v===2&&!!x,o(g)}}}class Fx{constructor(){this.map=[]}add(t,n,r){zx(this,t,n,r)}consume(t){if(this.map.sort(function(s,a){return s[0]-a[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let i=r.pop();for(;i;){for(const s of i)t.push(s);i=r.pop()}this.map.length=0}}function zx(e,t,n,r){let i=0;if(!(n===0&&r.length===0)){for(;i<e.map.length;){if(e.map[i][0]===t){e.map[i][1]+=n,e.map[i][2].push(...r);return}i+=1}e.map.push([t,n,r])}}function Bx(e,t){let n=!1;const r=[];for(;t<e.length;){const i=e[t];if(n){if(i[0]==="enter")i[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(i[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const s=r.length-1;r[s]=r[s]==="left"?"center":"right"}}else if(i[1].type==="tableDelimiterRow")break}else i[0]==="enter"&&i[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function Rx(){return{flow:{null:{name:"table",tokenize:jx,resolveAll:Ux}}}}function jx(e,t,n){const r=this;let i=0,s=0,a;return o;function o(k){let O=r.events.length-1;for(;O>-1;){const L=r.events[O][1].type;if(L==="lineEnding"||L==="linePrefix")O--;else break}const P=O>-1?r.events[O][1].type:null,R=P==="tableHead"||P==="tableRow"?C:l;return R===C&&r.parser.lazy[r.now().line]?n(k):R(k)}function l(k){return e.enter("tableHead"),e.enter("tableRow"),u(k)}function u(k){return k===124||(a=!0,s+=1),c(k)}function c(k){return k===null?n(k):W(k)?s>1?(s=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),f):n(k):ne(k)?se(e,c,"whitespace")(k):(s+=1,a&&(a=!1,i+=1),k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),a=!0,c):(e.enter("data"),d(k)))}function d(k){return k===null||k===124||le(k)?(e.exit("data"),c(k)):(e.consume(k),k===92?h:d)}function h(k){return k===92||k===124?(e.consume(k),d):d(k)}function f(k){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(k):(e.enter("tableDelimiterRow"),a=!1,ne(k)?se(e,g,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):g(k))}function g(k){return k===45||k===58?b(k):k===124?(a=!0,e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),v):B(k)}function v(k){return ne(k)?se(e,b,"whitespace")(k):b(k)}function b(k){return k===58?(s+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),x):k===45?(s+=1,x(k)):k===null||W(k)?F(k):B(k)}function x(k){return k===45?(e.enter("tableDelimiterFiller"),E(k)):B(k)}function E(k){return k===45?(e.consume(k),E):k===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(k),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(k))}function _(k){return ne(k)?se(e,F,"whitespace")(k):F(k)}function F(k){return k===124?g(k):k===null||W(k)?!a||i!==s?B(k):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(k)):B(k)}function B(k){return n(k)}function C(k){return e.enter("tableRow"),H(k)}function H(k){return k===124?(e.enter("tableCellDivider"),e.consume(k),e.exit("tableCellDivider"),H):k===null||W(k)?(e.exit("tableRow"),t(k)):ne(k)?se(e,H,"whitespace")(k):(e.enter("data"),V(k))}function V(k){return k===null||k===124||le(k)?(e.exit("data"),H(k)):(e.consume(k),k===92?j:V)}function j(k){return k===92||k===124?(e.consume(k),V):V(k)}}function Ux(e,t){let n=-1,r=!0,i=0,s=[0,0,0,0],a=[0,0,0,0],o=!1,l=0,u,c,d;const h=new Fx;for(;++n<e.length;){const f=e[n],g=f[1];f[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(xu(h,t,l,u,c),c=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(r=!0,d=void 0,s=[0,0,0,0],a=[0,n+1,0,0],o&&(o=!1,c={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(n,0,[["enter",c,t]])),i=g.type==="tableDelimiterRow"?2:c?3:1):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(s[1]!==0&&(a[0]=a[1],d=br(h,t,s,i,void 0,d),s=[0,0,0,0]),a[2]=n)):g.type==="tableCellDivider"&&(r?r=!1:(s[1]!==0&&(a[0]=a[1],d=br(h,t,s,i,void 0,d)),s=a,a=[s[1],n,0,0])):g.type==="tableHead"?(o=!0,l=n):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=n,s[1]!==0?(a[0]=a[1],d=br(h,t,s,i,n,d)):a[1]!==0&&(d=br(h,t,a,i,n,d)),i=0):i&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(a[3]=n)}for(l!==0&&xu(h,t,l,u,c),h.consume(t.events),n=-1;++n<t.events.length;){const f=t.events[n];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=Bx(t.events,n))}return e}function br(e,t,n,r,i,s){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",o="tableContent";n[0]!==0&&(s.end=Object.assign({},Gt(t.events,n[0])),e.add(n[0],0,[["exit",s,t]]));const l=Gt(t.events,n[1]);if(s={type:a,start:Object.assign({},l),end:Object.assign({},l)},e.add(n[1],0,[["enter",s,t]]),n[2]!==0){const u=Gt(t.events,n[2]),c=Gt(t.events,n[3]),d={type:o,start:Object.assign({},u),end:Object.assign({},c)};if(e.add(n[2],0,[["enter",d,t]]),r!==2){const h=t.events[n[2]],f=t.events[n[3]];if(h[1].end=Object.assign({},f[1].end),h[1].type="chunkText",h[1].contentType="text",n[3]>n[2]+1){const g=n[2]+1,v=n[3]-n[2]-1;e.add(g,v,[])}}e.add(n[3]+1,0,[["exit",d,t]])}return i!==void 0&&(s.end=Object.assign({},Gt(t.events,i)),e.add(i,0,[["exit",s,t]]),s=void 0),s}function xu(e,t,n,r,i){const s=[],a=Gt(t.events,n);i&&(i.end=Object.assign({},a),s.push(["exit",i,t])),r.end=Object.assign({},a),s.push(["exit",r,t]),e.add(n+1,0,s)}function Gt(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const $x={name:"tasklistCheck",tokenize:qx};function Hx(){return{text:{91:$x}}}function qx(e,t,n){const r=this;return i;function i(l){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),s)}function s(l){return le(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),a):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),a):n(l)}function a(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):n(l)}function o(l){return W(l)?t(l):ne(l)?e.check({tokenize:Vx},t,n)(l):n(l)}}function Vx(e,t,n){return se(e,r,"whitespace");function r(i){return i===null?n(i):t(i)}}function Wx(e){return Go([yx(),Ix(),Ox(e),Rx(),Hx()])}const Jx={};function Kx(e){const t=this,n=e||Jx,r=t.data(),i=r.micromarkExtensions||(r.micromarkExtensions=[]),s=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);i.push(Wx(n)),s.push(fx()),a.push(px(n))}function Se(...e){return e.filter(Boolean).join(" ")}const Yx=({content:e})=>p.jsx(Rb,{remarkPlugins:[Kx],className:"cuadra-aui-md",components:Qx,children:e}),ns=y.memo(Yx),Gx=({language:e,code:t})=>{const{isCopied:n,copyToClipboard:r}=Xx(),i=()=>{!t||n||r(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:i,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!n&&p.jsx(Fu,{className:"cuadra-h-4 cuadra-w-4"}),n&&p.jsx(ls,{className:"cuadra-h-4 cuadra-w-4"})]})]})},Xx=({copiedDuration:e=3e3}={})=>{const[t,n]=y.useState(!1);return{isCopied:t,copyToClipboard:i=>{i&&navigator.clipboard.writeText(i).then(()=>{n(!0),setTimeout(()=>n(!1),e)})}}},Qx=kb({h1:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h1",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h2",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h3",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h4",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h5",m({className:Se("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("h6",m({className:Se("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("p",m({className:Se("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("a",m({className:Se("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("blockquote",m({className:Se("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("ul",m({className:Se("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("ol",m({className:Se("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("hr",m({className:Se("cuadra-my-5 cuadra-border-b",e)},t))},table:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("table",m({className:Se("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("th",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("td",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("tr",m({className:Se("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:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("sup",m({className:Se("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:n=>{var r=n,{className:e}=r,t=q(r,["className"]);return p.jsx("pre",m({className:Se("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(r){var i=r,{className:t}=i,n=q(i,["className"]);const s=jl();return p.jsx("code",m({className:Se(!s&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},n))},CodeHeader:Gx});function vu(r){var i=r,{className:e="",variant:t="default"}=i,n=q(i,["className","variant"]);const s="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",a={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:`${s} ${a[t]||a.default} ${e}`},n))}function Zx(e){const t=new Map;for(const n of e){const r=t.get(n.filename);(!r||n.score>r.score)&&t.set(n.filename,n)}return Array.from(t.values()).sort((n,r)=>r.score-n.score)}function ev({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const n=Zx(e),r=n.slice(0,t),i=n.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(us,{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:[r.map((s,a)=>p.jsx(nv,{source:s},s.sourceId||a)),i>0&&p.jsxs(vu,{variant:"subtle",children:["+",i," more"]})]})]})}function tv(e){var n;switch((n=e.split(".").pop())==null?void 0:n.toLowerCase()){case"csv":case"xlsx":case"xls":return zu;case"md":case"txt":return Bu;default:return us}}function nv({source:e}){const{filename:t,score:n}=e,r=tv(t);return p.jsxs(vu,{className:"cuadra-gap-2 cuadra-cursor-default",title:n<1?`${Math.round(n*100)}% relevant`:void 0,children:[p.jsx(r,{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}),n<1&&n>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(n*100),"%"]})]})}const rv=y.forwardRef(function({welcomeTitle:t="What shall we explore today?",extraTopPadding:n,suggestions:r,inputPlaceholder:i="Reply...",enableAttachments:s=!1,preMadeResponseDelay:a=1e3,streamingSpeed:o=50,safeArea:l=!1,composerBorder:u=!1,models:c,selectedModelId:d,onModelChange:h,showChatHeader:f=!1},g){const v=da(),b=he(),[x,E]=y.useState(!1),[_,F]=y.useState(null),[B,C]=y.useState(!1),H=ha(R=>{const L=R.messages;return!L||L.length===0}),V=H&&!x,j=y.useCallback((R,L,N)=>{var G,J;if(!B)try{const Z=(G=N==null?void 0:N.streamingSpeed)!=null?G:o,de=(J=N==null?void 0:N.delay)!=null?J:a;wo(R,L,Z,de),b.composer().setText(R),setTimeout(()=>{b.composer().send()},10)}catch(Z){}},[B,o,a,b]),k=y.useCallback(R=>{try{b.composer().setText(R),setTimeout(()=>{b.composer().send()},10)}catch(L){}},[b]),O=y.useCallback(R=>M(null,null,function*(){var L;if(!(B||!v))try{if(R.response){const N=(L=R.responseDelay)!=null?L:a;yield j(R.prompt,R.response,{delay:N,streamingSpeed:o})}else k(R.prompt)}catch(N){}}),[v,B,a,o,j,k]),P=y.useCallback(()=>M(null,null,function*(){try{const R=window.__cuadraThreadListRuntime,L=R==null?void 0:R.threadList;L!=null&&L.switchToNewThread&&(yield L.switchToNewThread())}catch(R){}}),[]);return y.useImperativeHandle(g,()=>({sendMessage:k,sendPreMadeQA:j,clearChat:P}),[k,j,P]),y.useEffect(()=>{var R,L;if(!v){E(!1);return}try{const N=v==null?void 0:v.store;if(!N){E(!1);return}const G=(R=N.subscribe)==null?void 0:R.call(N,Z=>{const de=Z==null?void 0:Z.threadId,w=(Z==null?void 0:Z.messages)||[],ge=(Z==null?void 0:Z.isLoadingHistory)||!1,ye=w.length;de&&de!==_&&F(de),E(ge&&ye===0)}),J=(L=N.getState)==null?void 0:L.call(N);if(J){const Z=J==null?void 0:J.threadId,de=(J==null?void 0:J.messages)||[],w=(J==null?void 0:J.isLoadingHistory)||!1,ge=de.length;Z&&Z!==_&&F(Z),E(w&&ge===0)}return()=>{G&&G()}}catch(N){E(!1)}},[v,_]),p.jsxs(io,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full cuadra-relative",children:[f&&p.jsx(cv,{}),p.jsxs(ro,{disabled:!s,className:`cuadra-flex-1 cuadra-flex cuadra-flex-col cuadra-min-h-0 cuadra-relative ${V?"cuadra-justify-center":""}`,children:[p.jsx("div",{className:"cuadra-dropzone-overlay cuadra-pointer-events-none cuadra-absolute cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-items-center cuadra-justify-center cuadra-rounded-lg cuadra-transition-opacity cuadra-duration-200",style:{opacity:0},children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-3",children:[p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-14 cuadra-rounded-2xl",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},children:p.jsx(Uu,{className:"cuadra-h-6 cuadra-w-6"})}),p.jsx("p",{className:"cuadra-text-sm cuadra-font-medium cuadra-text-foreground font-brand",children:"Drop files here"})]})}),p.jsx(oo,{className:`cuadra-w-full cuadra-bg-inherit cuadra-relative scrollbar-thin ${V?"cuadra-flex-none":"cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto"}`,style:{paddingTop:V?"0":n||(f?"0.5rem":"2rem")},children:x?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-3",children:[p.jsx(cs,{className:"cuadra-h-5 cuadra-w-5 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("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full cuadra-px-4",children:[p.jsx(so,{children:p.jsx(iv,{title:t})}),p.jsx(Xf,{components:{UserMessage:sv,AssistantMessage:lv}})]})}),p.jsx("div",{className:`cuadra-w-full cuadra-px-4 cuadra-pt-2 ${V?"cuadra-pb-2":"cuadra-pb-4"}`,style:l?{paddingBottom:"calc(env(safe-area-inset-bottom) + 1rem)"}:void 0,children:p.jsxs("div",{className:"cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:[s&&p.jsx(no,{components:{Attachment:()=>{const R=te(({attachment:L})=>L);return R?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-3 cuadra-py-1.5 cuadra-rounded-lg cuadra-transition-colors",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx(ds,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-text-xs cuadra-text-foreground font-brand",children:R.name||"Attachment"}),p.jsx(af,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded-full hover:cuadra-bg-background/60 cuadra-transition-colors cuadra-ml-1","aria-label":"Remove attachment",children:p.jsx($u,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(Ja,{className:"cuadra-relative cuadra-w-full cuadra-rounded-2xl cuadra-transition-shadow cuadra-duration-300 cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"var(--cuadra-composer-shadow)",border:u?"1px solid hsl(var(--cuadra-border))":"none"},children:[p.jsx(eo,{asChild:!0,children:p.jsx("textarea",{rows:1,placeholder:i,className:"cuadra-flex cuadra-min-h-[44px] cuadra-w-full cuadra-rounded-t-2xl cuadra-border-0 cuadra-bg-transparent cuadra-px-4 cuadra-pt-3.5 cuadra-pb-1 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:{fontSize:"1rem",lineHeight:"1.5"}})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-pb-2.5 cuadra-pt-1",children:[p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:s&&p.jsx($f,{multiple:!0,asChild:!0,children:p.jsxs("button",{type:"button",className:"cuadra-group cuadra-relative cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-lg hover:cuadra-bg-muted/60 cuadra-transition-colors","aria-label":"Attach files",children:[p.jsx(hs,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5}),p.jsx("span",{className:"cuadra-pointer-events-none cuadra-absolute cuadra-bottom-full cuadra-left-1/2 cuadra--translate-x-1/2 cuadra-mb-1.5 cuadra-whitespace-nowrap cuadra-rounded-md cuadra-px-2.5 cuadra-py-1 cuadra-text-xs cuadra-text-foreground cuadra-opacity-0 group-hover:cuadra-opacity-100 cuadra-transition-opacity cuadra-duration-150 cuadra-delay-300 font-brand",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:"Attach files"})]})})}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[c&&c.length>0&&p.jsx(uv,{models:c,selectedModelId:d,onModelChange:h,threadIsEmpty:H,onNewChat:P}),p.jsx(kf,{asChild:!0,children:p.jsx("button",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-8 cuadra-rounded-full cuadra-transition-all cuadra-duration-200 hover:cuadra-opacity-90 disabled:cuadra-opacity-30 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-primary)",color:"white"},"aria-label":"Send message",type:"button",children:p.jsx(Ou,{className:"cuadra-h-4 cuadra-w-4",strokeWidth:2})})})]})]})]})]})}),V&&r&&r.length>0&&p.jsx("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-justify-center cuadra-gap-2 cuadra-px-4 cuadra-pb-6 cuadra-pt-1 cuadra-max-w-3xl cuadra-mx-auto cuadra-w-full",children:r.map((R,L)=>p.jsx("button",{type:"button",onClick:()=>O(R),disabled:B,className:"cuadra-px-3.5 cuadra-py-2 cuadra-rounded-full cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-all cuadra-duration-200 font-brand cuadra-cursor-pointer disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{backgroundColor:"var(--cuadra-composer)",boxShadow:"0 0 0 1px rgba(0,0,0,0.06)"},children:R.prompt},`suggestion-${L}`))})]})]})});function iv({title:e}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-text-center cuadra-py-6",children:p.jsx("h2",{className:"cuadra-text-4xl cuadra-font-normal cuadra-text-muted-foreground cuadra-tracking-tight",style:{fontFamily:"var(--cuadra-font-logo), Outfit, -apple-system, sans-serif"},children:e})})}function sv(){return p.jsx(ei,{className:"cuadra-flex cuadra-w-full cuadra-justify-end cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-end cuadra-gap-2 cuadra-max-w-[80%]",children:[p.jsx(Va,{components:{Attachment:()=>{var s;const e=te(({attachment:a})=>a);if(!e)return null;const t=e.type==="image",n=e.file,r=(s=e.content)==null?void 0:s.find(a=>a.type==="image"),i=n?URL.createObjectURL(n):r==null?void 0:r.image;return p.jsx("div",{className:"cuadra-mb-1",children:t&&i?p.jsx("img",{src:i,alt:e.name||"Attachment",className:"cuadra-rounded-2xl cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{border:"1px solid rgba(0,0,0,0.06)"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-xl cuadra-px-3 cuadra-py-2",style:{backgroundColor:"var(--cuadra-muted)",border:"1px solid rgba(0,0,0,0.06)"},children:[p.jsx(ds,{className:"cuadra-h-3.5 cuadra-w-3.5 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-break-words cuadra-text-foreground font-brand",style:{borderRadius:"1.25rem",backgroundColor:"var(--cuadra-muted)",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",fontSize:"0.9375rem",lineHeight:"1.625"},children:p.jsx(ti,{components:{Text:({text:e})=>p.jsx(ns,{content:e||""})}})})]})})}function av({text:e}){const[t,n]=y.useState(!1),r=te(({message:i})=>{var s;return((s=i==null?void 0:i.status)==null?void 0:s.type)==="running"});return e?r?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:()=>n(!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(Cr,{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(ns,{content:e})})})]}):null}function ov(){return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-3",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-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms",backgroundColor:"var(--cuadra-primary)",opacity:.7}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms",backgroundColor:"var(--cuadra-primary)",opacity:.5}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms",backgroundColor:"var(--cuadra-primary)",opacity:.3}})]}),p.jsx("span",{children:"Thinking..."})]})}function lv(){const e=te(({message:a})=>{var o;return((o=a==null?void 0:a.status)==null?void 0:o.type)==="running"}),t=te(({message:a})=>{const o=a==null?void 0:a.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))}),n=y.useRef(!1),[r,i]=y.useState(null);y.useEffect(()=>{if(e&&t&&!n.current){const a=bt.getCurrentMessageId();a&&(n.current=!0,i(a))}},[e,t]);const s=y.useSyncExternalStore(a=>bt.subscribe(a),()=>{var a,o;if(r){const l=bt.getForMessage(r);return(a=l.sources)!=null&&a.length?l.sources:null}if(e&&t){const l=bt.getCurrentMessageId();if(l){const u=bt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(ei,{className:"cuadra-flex cuadra-w-full cuadra-justify-start cuadra-py-2.5",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-max-w-full cuadra-break-words font-brand",style:{fontSize:"0.9375rem",lineHeight:"1.75"},children:[p.jsx(ti,{components:{Text:({text:a})=>p.jsx(ns,{content:a||""}),Reasoning:({text:a})=>p.jsx(av,{text:a||""})}}),e&&!t&&p.jsx(ov,{}),s&&s.length>0&&p.jsx(ev,{sources:s})]})})}function uv({models:e,selectedModelId:t,onModelChange:n,threadIsEmpty:r,onNewChat:i}){const[s,a]=y.useState(!1),o=e.find(u=>u.id===t)||e[0];if(!o)return null;const l=u=>M(null,null,function*(){a(!1),!r&&u!==t&&(yield i==null?void 0:i()),n==null||n(u)});return p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>a(!s),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-px-2.5 cuadra-py-1.5 cuadra-rounded-lg cuadra-text-xs cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx("span",{children:o.name}),p.jsx(Cr,{className:"cuadra-h-3 cuadra-w-3"})]}),s&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>a(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-bottom-full cuadra-right-0 cuadra-mb-2 cuadra-z-50 cuadra-rounded-xl cuadra-min-w-[200px] cuadra-overflow-hidden cuadra-py-1",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:e.map(u=>p.jsxs("button",{type:"button",className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted/60 cuadra-transition-colors font-brand",onClick:()=>l(u.id),children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("span",{className:"cuadra-text-foreground",children:u.name}),u.description&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground",children:u.description})]}),u.id===t&&p.jsx(ls,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-primary cuadra-flex-shrink-0"})]},u.id))})]})]})}function cv(){const e=te(({threadListItem:i})=>{var s;return(s=i==null?void 0:i.title)!=null?s:null}),[t,n]=y.useState(!1),r=e||"Untitled chat";return p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-px-3 cuadra-py-2 cuadra-min-h-[48px]",children:p.jsxs("div",{className:"cuadra-relative",children:[p.jsxs("button",{type:"button",onClick:()=>n(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1 cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted/60 cuadra-rounded-lg cuadra-px-2 cuadra-py-1.5 cuadra-transition-colors font-brand",children:[p.jsx("span",{className:"cuadra-font-medium cuadra-truncate cuadra-max-w-[200px]",children:r}),p.jsx(Cr,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground cuadra-flex-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"cuadra-rotate-180":""}`})]}),t&&p.jsx(dv,{onClose:()=>n(!1)})]})})}function dv({onClose:e}){return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:e}),p.jsx("div",{className:"cuadra-absolute cuadra-left-0 cuadra-top-full cuadra-mt-1 cuadra-z-50 cuadra-w-[300px] cuadra-rounded-xl cuadra-overflow-hidden cuadra-flex cuadra-flex-col",style:{backgroundColor:"var(--cuadra-popover)",boxShadow:"0 4px 24px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)"},children:p.jsxs(mo,{className:"cuadra-flex cuadra-flex-col",children:[p.jsx("div",{className:"cuadra-px-2 cuadra-py-1.5",children:p.jsxs(ho,{className:"cuadra-w-full cuadra-flex cuadra-items-center cuadra-gap-2.5 cuadra-px-3 cuadra-py-2 cuadra-rounded-lg cuadra-text-sm cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors cuadra-cursor-pointer font-brand",onClick:e,children:[p.jsx(hs,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),"New Chat"]})}),p.jsx(hv,{onSelect:e})]})})]})}function hv({onSelect:e}){const t=te(({threads:i})=>{var s;return(s=i==null?void 0:i.threadIds)!=null?s:[]}),n=te(({threads:i})=>i==null?void 0:i.newThreadId);return t.some(i=>i!==n)?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-mx-3 cuadra-my-0.5",style:{borderTop:"1px solid rgba(0,0,0,0.06)"}}),p.jsx("div",{className:"cuadra-overflow-y-auto cuadra-px-2 cuadra-pb-1.5 scrollbar-thin",style:{maxHeight:"340px"},children:p.jsx(po,{components:{ThreadListItem:i=>p.jsx(fv,I(m({},i),{onSelect:e}))}})})]}):null}function fv({onSelect:e}){const t=pa(),n=fa(),r=qd(),i=ha(b=>b.threadId),s=(t==null?void 0:t.id)===i,[a,o]=y.useState(!1),[l,u]=y.useState(!1),[c,d]=y.useState((t==null?void 0:t.title)||""),[h,f]=y.useState(!1),g=()=>M(null,null,function*(){if(!(t!=null&&t.remoteId)||!c||c===t.title){u(!1);return}try{f(!0),yield n.rename(c)}catch(b){}finally{f(!1),u(!1)}}),v=b=>M(null,null,function*(){b.stopPropagation();try{s&&(yield r.switchToNewThread()),yield n.delete()}catch(x){console.error("[CuadraChat] Failed to delete thread:",x)}});return y.useEffect(()=>{t!=null&&t.title&&!l&&d(t.title)},[t==null?void 0:t.title,l]),t?p.jsxs(go,{className:`cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer ${s?"cuadra-bg-muted":"hover:cuadra-bg-muted/60"}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[l?p.jsx("div",{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0",onClick:b=>b.stopPropagation(),onMouseDown:b=>b.stopPropagation(),onKeyDown:b=>b.stopPropagation(),onKeyUp:b=>b.stopPropagation(),onKeyPress:b=>b.stopPropagation(),children:p.jsx("input",{className:"cuadra-w-full cuadra-bg-transparent cuadra-border-0 cuadra-border-b cuadra-text-sm cuadra-text-foreground cuadra-py-0.5 cuadra-px-0 cuadra-outline-none font-brand",style:{borderBottomColor:"var(--cuadra-primary)",borderBottomWidth:"1.5px"},value:c,onChange:b=>d(b.target.value),onKeyDown:b=>{b.stopPropagation(),b.key==="Enter"&&g(),b.key==="Escape"&&(u(!1),d(t.title||""))},onBlur:()=>void g(),disabled:h,autoFocus:!0})}):p.jsx(Zf,{className:"cuadra-flex-1 cuadra-px-3 cuadra-py-2 cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground cuadra-truncate cuadra-block cuadra-text-left font-brand",children:t.title||"Chat"})}),(a||s)&&!l&&p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-0.5 cuadra-mr-1.5 cuadra-flex-shrink-0",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/60 cuadra-transition-colors",onClick:b=>{b.stopPropagation(),u(!0),d(t.title||"Chat")},title:"Rename",children:p.jsx(Ru,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})}),p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-destructive/10 cuadra-transition-colors",onClick:v,title:"Delete",children:p.jsx(ju,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-destructive"})})]})]}):null}const rs=({children:e,className:t="",paddingX:n="px-0",paddingY:r="py-0",borderSizePx:i=2,style:s,contentStyle:a})=>p.jsx("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-lg cuadra-overflow-hidden cuadra-flex cuadra-flex-col ${n} ${r} ${t}`,style:m(m({border:i>0?`${i}px solid var(--cuadra-primary)`:"none"},s),a),children:e}),pv=y.createContext(void 0),is=({children:e,value:t})=>p.jsx(pv.Provider,{value:t,children:e});function mv(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const n=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),n)return;const r=document.createElement("link");r.setAttribute("data-cuadra-uikit","true"),r.rel="stylesheet",r.type="text/css";const i=["/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:Ue&&Ue.tagName.toUpperCase()==="SCRIPT"&&Ue.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let s=!1;for(const a of i)if(r.href=a,r.onload=()=>{s=!0},r.onerror=()=>{},document.head.appendChild(r),s)break},[])}const Su=y.forwardRef(function({config:t},n){mv();const r=y.useRef(null),i=y.useRef(!1),{baseUrl:s,proxyUrl:a,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:c,onModelChange:d,ephemeral:h=!1,systemPrompt:f,enableReasoning:g=!1,initialThreadId:v,welcomeTitle:b,welcomeSubtitle:x,extraTopPadding:E,suggestions:_,inputPlaceholder:F,preMadeResponseDelay:B=1e3,streamingSpeed:C=50,initialMessage:H,initialPreMadeQA:V,theme:j="system",onError:k,onChatCreated:O,onUserMessage:P,onThreadIdUpdate:R,enableAttachments:L=!1,onBeforeRequest:N,mockResponseOnBlocked:G}=t;y.useImperativeHandle(n,()=>({sendMessage:ee=>{var be;(be=r.current)==null||be.sendMessage(ee)},sendPreMadeQA:(ee,be,we)=>{var vt;(vt=r.current)==null||vt.sendPreMadeQA(ee,be,we)},clearChat:()=>{var ee;(ee=r.current)==null||ee.clearChat()}}),[]),y.useEffect(()=>{if(i.current)return;const ee=setTimeout(()=>{var be,we;V?(i.current=!0,(be=r.current)==null||be.sendPreMadeQA(V.question,V.answer,{delay:B,streamingSpeed:C})):H&&(i.current=!0,(we=r.current)==null||we.sendMessage(H))},500);return()=>clearTimeout(ee)},[H,V,B,C]);const J=a||s||"",Z=!!a,de=y.useMemo(()=>new yo(J,o||void 0,Z),[J,o,Z]),[w,ge]=y.useState(null),[ye,S]=y.useState(!1),[Ce,lt]=y.useState(null),[ke,U]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&U(!0)},[l]);const X=y.useCallback(()=>M(null,null,function*(){if(u==="selector"){S(!0),lt(null);try{const ee=yield de.listModels();ge(ee)}catch(ee){lt(ee instanceof Error?ee:new Error("Failed to load models"))}finally{S(!1)}}}),[de,u]);y.useEffect(()=>{u==="selector"&&X()},[u,X]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=X),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[X]);const[ae,fe]=y.useState(u==="fixed"&&c||null),Ie=y.useRef(ae),re=y.useCallback(ee=>{const be=Ie.current;fe(ee),Ie.current=ee,d==null||d(ee),be!==null&&be!==ee&&l==="multiChat"&&setTimeout(()=>{var vt,xr;const we=window.__cuadraThreadListRuntime;if((vt=we==null?void 0:we.threads)!=null&&vt.switchToNewThread)try{we.threads.switchToNewThread()}catch(vr){}else if((xr=we==null?void 0:we.threads)!=null&&xr.createThread)try{we.threads.createThread()}catch(vr){}else if(we!=null&&we.switchToNewThread)try{we.switchToNewThread()}catch(vr){}},100)},[d,l]);y.useEffect(()=>{if(u==="selector"&&(w!=null&&w.items)&&w.items.length>0&&!ae){const ee=w.items[0];if(ee!=null&&ee.id){const be=ee.id;fe(be),d==null||d(be)}}},[u,w==null?void 0:w.items,ae,d]);const _e=u==="fixed"?!!c:!!ae,Ye=y.useMemo(()=>((w==null?void 0:w.items)||[]).filter(ee=>(ee==null?void 0:ee.id)&&(ee==null?void 0:ee.displayName)).map(ee=>({id:ee.id,name:ee.displayName})),[w]),Ge=y.useMemo(()=>({currentModelId:ae||"",models:Ye,modelsLoading:ye,modelsError:Ce,onModelChange:re,refetchModels:X}),[ae,Ye,ye,Ce,re,X]);return u==="selector"&&ye||l==="multiChat"&&ke?p.jsx(is,{value:Ge,children:p.jsx(rs,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:2,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(cs,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!_e&&Ce?p.jsx(is,{value:Ge,children:p.jsx(rs,{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(is,{value:Ge,children:p.jsx(hp,{baseUrl:Z?J:s||J,sessionToken:o,isProxyMode:Z,mode:l,modelMode:u,modelId:ae||c||void 0,onModelChange:re,ephemeral:h,systemPrompt:f,enableReasoning:g,initialThreadId:v,enableAttachments:L,onError:k,onChatCreated:O,onUserMessage:P,onThreadIdUpdate:R,onBeforeRequest:N,mockResponseOnBlocked:G,onChatsLoaded:()=>{l==="multiChat"&&U(!1)},children:p.jsx(rs,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:2,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},children:p.jsx("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0",children:p.jsx(rv,{ref:r,welcomeTitle:b,welcomeSubtitle:x,extraTopPadding:E,suggestions:_,inputPlaceholder:F,enableAttachments:L,preMadeResponseDelay:B,streamingSpeed:C,safeArea:t.safeArea,showChatHeader:l==="multiChat",models:u==="selector"?Ye:void 0,selectedModelId:ae||void 0,onModelChange:u==="selector"?re:void 0,theme:j})})})})})})})})});class wr{constructor(){T(this,"config",null);T(this,"root",null);T(this,"container",null);T(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 n=t.containerId||"cuadra-chat";let r=document.getElementById(n);r||(r=document.createElement("div"),r.id=n,document.body.appendChild(r)),t.containerClass&&r.classList.add(...t.containerClass.split(" ")),this.config=I(m({},t),{containerId:n}),this.container=r,this.root=pe.createRoot(r),this.root.render(y.createElement(ku,{config:this.config})),this.instances.set(n,this)}destroy(t){var i;const n=t||((i=this.config)==null?void 0:i.containerId);if(!n)return;const r=this.instances.get(n);r!=null&&r.root&&(r.root.unmount(),r.root=null),r!=null&&r.container&&r.container.parentNode&&r.container.parentNode.removeChild(r.container),this.instances.delete(n)}updateConfig(t,n){var a;const r=n||((a=this.config)==null?void 0:a.containerId);if(!r)return;const i=this.instances.get(r);if(!(i!=null&&i.config))return;const s=m(m({},i.config),t);i.config=s,i.root&&i.container&&i.root.render(y.createElement(ku,{config:s}))}getInstance(t){var r;const n=t||((r=this.config)==null?void 0:r.containerId);return n&&this.instances.get(n)||null}static parseConfigFromAttributes(t,n){const r={};return t.dataset.baseUrl&&(r.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(r.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(r.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(r.containerId=t.dataset.containerId),t.dataset.containerClass&&(r.containerClass=t.dataset.containerClass),t.dataset.mode&&(r.mode=t.dataset.mode),t.dataset.modelMode&&(r.modelMode=t.dataset.modelMode),t.dataset.modelId&&(r.modelId=t.dataset.modelId),t.dataset.ephemeral&&(r.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(r.systemPrompt=t.dataset.systemPrompt),n&&(n.dataset.baseUrl&&(r.baseUrl=n.dataset.baseUrl),n.dataset.proxyUrl&&(r.proxyUrl=n.dataset.proxyUrl),n.dataset.sessionToken&&(r.sessionToken=n.dataset.sessionToken),n.dataset.mode&&(r.mode=n.dataset.mode),n.dataset.modelMode&&(r.modelMode=n.dataset.modelMode),n.dataset.modelId&&(r.modelId=n.dataset.modelId)),r}}const ku=({config:e})=>p.jsx(Su,{config:e});let Fe=null;typeof window!="undefined"&&(Fe=new wr);const _u={init:e=>(Fe||(Fe=new wr),Fe.init(e)),destroy:e=>Fe==null?void 0:Fe.destroy(e),updateConfig:(e,t)=>Fe==null?void 0:Fe.updateConfig(e,t),getInstance:e=>Fe==null?void 0:Fe.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"]'),n=Array.from(t).find(r=>(r.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));n&&n.dataset.autoInit!=="false"&&gv(n)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function gv(e){if(!e||!Fe)return;const t=wr.parseConfigFromAttributes(e),n=t.containerId||"cuadra-chat",r=document.getElementById(n);if(r){const i=wr.parseConfigFromAttributes(e,r);Object.assign(t,i)}(t.baseUrl||t.proxyUrl)&&Fe.init(t)}$.WidgetContent=Su,$.default=_u,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
36
36
  //# sourceMappingURL=cuadra-uikit.umd.js.map