From 7b1a3eece7e33ce197324f44e839dec430162108 Mon Sep 17 00:00:00 2001 From: firecoperana Date: Thu, 12 Jun 2025 00:19:26 -0500 Subject: Add top n sigma sampler and other webui fix (#512) Co-authored-by: firecoperana --- examples/server/public/index.html.gz | Bin 1263503 -> 1263655 bytes examples/server/server.cpp | 23 ++++++++++++--------- examples/server/webui/dist/index.html | 8 +++---- examples/server/webui/src/Config.ts | 7 +++++-- examples/server/webui/src/components/Header.tsx | 2 +- .../server/webui/src/components/SettingDialog.tsx | 19 +++++++++-------- examples/server/webui/src/utils/app.context.tsx | 1 + 7 files changed, 34 insertions(+), 26 deletions(-) (limited to 'examples/server') diff --git a/examples/server/public/index.html.gz b/examples/server/public/index.html.gz index d4018b81..4a29a921 100644 Binary files a/examples/server/public/index.html.gz and b/examples/server/public/index.html.gz differ diff --git a/examples/server/server.cpp b/examples/server/server.cpp index 9e80bd7e..f9991035 100644 --- a/examples/server/server.cpp +++ b/examples/server/server.cpp @@ -970,6 +970,9 @@ struct server_context { slot.sparams.temp = json_value(data, "temperature", default_sparams.temp); slot.sparams.dynatemp_range = json_value(data, "dynatemp_range", default_sparams.dynatemp_range); slot.sparams.dynatemp_exponent = json_value(data, "dynatemp_exponent", default_sparams.dynatemp_exponent); + slot.sparams.xtc_probability = json_value(data, "xtc_probability", default_sparams.xtc_probability); + slot.sparams.xtc_threshold = json_value(data, "xtc_threshold", default_sparams.xtc_threshold); + slot.sparams.top_n_sigma = json_value(data, "top_n_sigma", default_sparams.top_n_sigma); slot.sparams.penalty_last_n = json_value(data, "repeat_last_n", default_sparams.penalty_last_n); slot.sparams.penalty_repeat = json_value(data, "repeat_penalty", default_sparams.penalty_repeat); slot.sparams.penalty_freq = json_value(data, "frequency_penalty", default_sparams.penalty_freq); @@ -1135,17 +1138,17 @@ struct server_context { } { - const auto & samplers_sequence = data.find("samplers"); - if (samplers_sequence != data.end() && samplers_sequence->is_array()) { - std::vector sampler_names; - for (const auto & sampler_name : *samplers_sequence) { - if (sampler_name.is_string()) { - sampler_names.emplace_back(sampler_name); - } + const auto samplers = data.find("samplers"); + if (samplers != data.end()) { + if (samplers->is_array()) { + slot.sparams.samplers_sequence = llama_sampling_types_from_names(*samplers, false); + } + else if (samplers->is_string()) { + slot.sparams.samplers_sequence = llama_sampling_types_from_chars(samplers->get()); + } + else { + slot.sparams.samplers_sequence = default_sparams.samplers_sequence; } - slot.sparams.samplers_sequence = llama_sampling_types_from_names(sampler_names, false); - } else { - slot.sparams.samplers_sequence = default_sparams.samplers_sequence; } } diff --git a/examples/server/webui/dist/index.html b/examples/server/webui/dist/index.html index a569b65d..e042d5cc 100644 --- a/examples/server/webui/dist/index.html +++ b/examples/server/webui/dist/index.html @@ -62,9 +62,9 @@ Please change the parent to n);ci(this,uu,(n==null?void 0:n.allowCR)??!1),ci(this,as,(n==null?void 0:n.returnEmptyLines)??!1),ci(this,hl,(n==null?void 0:n.mapperFun)??Dn(this,hl))}}su=new WeakMap,uu=new WeakMap,as=new WeakMap,hl=new WeakMap,cu=new WeakSet,Kf=function(n,i){for(n=Dn(this,su)+n;;){const o=n.indexOf(` `);if(Dn(this,uu)){const l=n.indexOf("\r");if(l!==-1&&l!==n.length-1&&(o===-1||o-1>l)){const s=Dn(this,hl).call(this,n.slice(0,crOrLfIndex));(Dn(this,as)||s)&&i.enqueue(s),n=n.slice(l+1);continue}}if(o!==-1){let l=o;n[o-1]==="\r"&&l--;const s=Dn(this,hl).call(this,n.slice(0,l));(Dn(this,as)||s)&&i.enqueue(s),n=n.slice(o+1);continue}break}ci(this,su,n)};const N6=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);var da,du,bo,Vi,ss,v2,b2;class A6{constructor(t,n){Ki(this,ss);Ki(this,da);Ki(this,du);Ki(this,bo,!1);Ki(this,Vi);ci(this,da,t),ci(this,du,n)}next(){const t=()=>qs(this,ss,v2).call(this);return ci(this,Vi,Dn(this,Vi)?Dn(this,Vi).then(t,t):t()),Dn(this,Vi)}return(t){const n=()=>qs(this,ss,b2).call(this,t);return Dn(this,Vi)?Dn(this,Vi).then(n,n):n()}}da=new WeakMap,du=new WeakMap,bo=new WeakMap,Vi=new WeakMap,ss=new WeakSet,v2=async function(){if(Dn(this,bo))return{done:!0,value:void 0};let t;try{t=await Dn(this,da).read()}catch(n){throw ci(this,Vi,void 0),ci(this,bo,!0),Dn(this,da).releaseLock(),n}return t.done&&(ci(this,Vi,void 0),ci(this,bo,!0),Dn(this,da).releaseLock()),t},b2=async function(t){if(Dn(this,bo))return{done:!0,value:t};if(ci(this,bo,!0),!Dn(this,du)){const n=Dn(this,da).cancel(t);return Dn(this,da).releaseLock(),await n,{done:!0,value:t}}return Dn(this,da).releaseLock(),{done:!0,value:t}};const xh=Symbol();function w2(){return this[xh].next()}Object.defineProperty(w2,"name",{value:"next"});function k2(e){return this[xh].return(e)}Object.defineProperty(k2,"name",{value:"return"});const M6=Object.create(N6,{next:{enumerable:!0,configurable:!0,writable:!0,value:w2},return:{enumerable:!0,configurable:!0,writable:!0,value:k2}});function R6(e,{preventCancel:t=!1}={}){const n=e.getReader(),i=new A6(n,t),o=Object.create(M6);return o[xh]=i,o}const Vf=e=>!!e.toLowerCase,Gf=e=>e===!0||e===!1,Wf=e=>!Vf(e)&&!isNaN(e)&&!Gf(e);async function*O6(e){if(!e.body)throw new Error("Response body is empty");const t=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new T6);for await(const n of R6(t))if(n.startsWith("data:")&&!n.endsWith("[DONE]"))yield JSON.parse(n.slice(5));else if(n.startsWith("error:")){const i=JSON.parse(n.slice(6));throw new Error(i.message||"Unknown error")}}const I6=e=>{if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.style.position="absolute",t.style.left="-999999px",document.body.prepend(t),t.select(),document.execCommand("copy")}};function D6(e){return e.map(t=>{let n="";for(const i of t.extra??[])i.type==="context"&&i.content!=""&&(n+=`${i.content} -`);return n+=t.content,{role:t.role,content:n}})}function L6(e){return e.map(t=>({role:t.role,content:t.role==="assistant"?t.content.split("").at(-1).trim():t.content}))}function Dr(e){return Object.entries(e).filter(([t,n])=>n).map(([t,n])=>t).join(" ")}const z6=(e,t)=>{let n=!1;return(...i)=>{n||(e(...i),n=!0,setTimeout(()=>{n=!1},t))}},P6=e=>{const t=new URL(window.location.href);e.forEach(n=>{t.searchParams.delete(n)}),window.history.replaceState({},"",t.toString())},B6=!1,F6=new URL(".",document.baseURI).href.toString().replace(/\/$/,""),wo={apiKey:"",systemMessage:"You are a helpful assistant.",showTokensPerSecond:!1,showThoughtInProgress:!1,excludeThoughtOnReq:!0,samplers:"dkypmxt",temperature:.8,dynatemp_range:0,dynatemp_exponent:1,top_k:40,top_p:.95,min_p:.05,xtc_probability:0,xtc_threshold:.1,typical_p:1,repeat_last_n:64,repeat_penalty:1,presence_penalty:0,frequency_penalty:0,dry_multiplier:0,dry_base:1.75,dry_allowed_length:2,dry_penalty_last_n:-1,max_tokens:-1,custom:"",pyIntepreterEnabled:!1},U6={apiKey:"Set the API Key if you are using --api-key option for the server.",systemMessage:"The starting message that defines how model should behave.",samplers:'The order at which samplers are applied, in simplified way. Default is "dkypmxt": dry->top_k->typ_p->top_p->min_p->xtc->temperature',temperature:"Controls the randomness of the generated text by affecting the probability distribution of the output tokens. Higher = more random, lower = more focused.",dynatemp_range:"Addon for the temperature sampler. The added value to the range of dynamic temperature, which adjusts probabilities by entropy of tokens.",dynatemp_exponent:"Addon for the temperature sampler. Smoothes out the probability redistribution based on the most probable token.",top_k:"Keeps only k top tokens.",top_p:"Limits tokens to those that together have a cumulative probability of at least p",min_p:"Limits tokens based on the minimum probability for a token to be considered, relative to the probability of the most likely token.",xtc_probability:"XTC sampler cuts out top tokens; this parameter controls the chance of cutting tokens at all. 0 disables XTC.",xtc_threshold:"XTC sampler cuts out top tokens; this parameter controls the token probability that is required to cut that token.",typical_p:"Sorts and limits tokens based on the difference between log-probability and entropy.",repeat_last_n:"Last n tokens to consider for penalizing repetition",repeat_penalty:"Controls the repetition of token sequences in the generated text",presence_penalty:"Limits tokens based on whether they appear in the output or not.",frequency_penalty:"Limits tokens based on how often they appear in the output.",dry_multiplier:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the DRY sampling multiplier.",dry_base:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the DRY sampling base value.",dry_allowed_length:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the allowed length for DRY sampling.",dry_penalty_last_n:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets DRY penalty for the last n tokens.",max_tokens:"The maximum number of token per output.",custom:""};Object.entries(wo).filter(e=>Wf(e[1])).map(e=>e[0]);const $6=["light","dark"].concat(Object.keys(y2).filter(e=>e!=="light"&&e!=="dark"));var Yc={exports:{}},q6=Yc.exports,o1;function H6(){return o1||(o1=1,function(e,t){(function(n,i){e.exports=i()})(q6,function(){var n=function(f,m){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,_){w.__proto__=_}||function(w,_){for(var T in _)Object.prototype.hasOwnProperty.call(_,T)&&(w[T]=_[T])})(f,m)},i=function(){return(i=Object.assign||function(f){for(var m,w=1,_=arguments.length;w<_;w++)for(var T in m=arguments[w])Object.prototype.hasOwnProperty.call(m,T)&&(f[T]=m[T]);return f}).apply(this,arguments)};function o(f,m,w){for(var _,T=0,O=m.length;T"u"||l.Promise||(l.Promise=Promise);var p=Object.getPrototypeOf,y={}.hasOwnProperty;function g(f,m){return y.call(f,m)}function k(f,m){typeof m=="function"&&(m=m(p(f))),(typeof Reflect>"u"?s:Reflect.ownKeys)(m).forEach(function(w){C(f,w,m[w])})}var x=Object.defineProperty;function C(f,m,w,_){x(f,m,d(w&&g(w,"get")&&typeof w.get=="function"?{get:w.get,set:w.set,configurable:!0}:{value:w,configurable:!0,writable:!0},_))}function N(f){return{from:function(m){return f.prototype=Object.create(m.prototype),C(f.prototype,"constructor",f),{extend:k.bind(null,f.prototype)}}}}var D=Object.getOwnPropertyDescriptor,R=[].slice;function L(f,m,w){return R.call(f,m,w)}function F(f,m){return m(f)}function ae(f){if(!f)throw new Error("Assertion Failed")}function le(f){l.setImmediate?setImmediate(f):setTimeout(f,0)}function V(f,m){if(typeof m=="string"&&g(f,m))return f[m];if(!m)return f;if(typeof m!="string"){for(var w=[],_=0,T=m.length;_({role:t.role,content:t.role==="assistant"?t.content.split("").at(-1).trim():t.content}))}function Dr(e){return Object.entries(e).filter(([t,n])=>n).map(([t,n])=>t).join(" ")}const z6=(e,t)=>{let n=!1;return(...i)=>{n||(e(...i),n=!0,setTimeout(()=>{n=!1},t))}},P6=e=>{const t=new URL(window.location.href);e.forEach(n=>{t.searchParams.delete(n)}),window.history.replaceState({},"",t.toString())},B6=!1,F6=new URL(".",document.baseURI).href.toString().replace(/\/$/,""),wo={apiKey:"",systemMessage:"You are a helpful assistant.",showTokensPerSecond:!1,showThoughtInProgress:!1,excludeThoughtOnReq:!0,samplers:"dkypmxnt",temperature:.8,dynatemp_range:0,dynatemp_exponent:1,top_k:40,top_p:.95,min_p:.05,xtc_probability:0,xtc_threshold:.1,top_n_sigma:0,typical_p:1,repeat_last_n:64,repeat_penalty:1,presence_penalty:0,frequency_penalty:0,dry_multiplier:0,dry_base:1.75,dry_allowed_length:2,dry_penalty_last_n:-1,max_tokens:-1,custom:"",pyIntepreterEnabled:!1},U6={apiKey:"Set the API Key if you are using --api-key option for the server.",systemMessage:"The starting message that defines how model should behave.",samplers:'The order at which samplers are applied, in simplified way. Default is "dkypmxt": dry->top_k->typ_p->top_p->min_p->xtc->top_sigma->temperature',temperature:"Controls the randomness of the generated text by affecting the probability distribution of the output tokens. Higher = more random, lower = more focused.",dynatemp_range:"Addon for the temperature sampler. The added value to the range of dynamic temperature, which adjusts probabilities by entropy of tokens.",dynatemp_exponent:"Addon for the temperature sampler. Smoothes out the probability redistribution based on the most probable token.",top_k:"Keeps only k top tokens.",top_p:"Limits tokens to those that together have a cumulative probability of at least p",min_p:"Limits tokens based on the minimum probability for a token to be considered, relative to the probability of the most likely token.",xtc_probability:"XTC sampler cuts out top tokens; this parameter controls the chance of cutting tokens at all. 0 disables XTC.",xtc_threshold:"XTC sampler cuts out top tokens; this parameter controls the token probability that is required to cut that token.",top_n_sigma:"Top-n-sigma sampling filters out low-value tokens by discarding tokens that fall more than n standard deviations below the maximum probability",typical_p:"Sorts and limits tokens based on the difference between log-probability and entropy.",repeat_last_n:"Last n tokens to consider for penalizing repetition",repeat_penalty:"Controls the repetition of token sequences in the generated text",presence_penalty:"Limits tokens based on whether they appear in the output or not.",frequency_penalty:"Limits tokens based on how often they appear in the output.",dry_multiplier:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the DRY sampling multiplier.",dry_base:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the DRY sampling base value.",dry_allowed_length:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets the allowed length for DRY sampling.",dry_penalty_last_n:"DRY sampling reduces repetition in generated text even across long contexts. This parameter sets DRY penalty for the last n tokens.",max_tokens:"The maximum number of token per output.",custom:""};Object.entries(wo).filter(e=>Wf(e[1])).map(e=>e[0]);const $6=["light","dark"].concat(Object.keys(y2).filter(e=>e!=="light"&&e!=="dark"));var Yc={exports:{}},q6=Yc.exports,o1;function H6(){return o1||(o1=1,function(e,t){(function(n,i){e.exports=i()})(q6,function(){var n=function(f,m){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,_){w.__proto__=_}||function(w,_){for(var T in _)Object.prototype.hasOwnProperty.call(_,T)&&(w[T]=_[T])})(f,m)},i=function(){return(i=Object.assign||function(f){for(var m,w=1,_=arguments.length;w<_;w++)for(var T in m=arguments[w])Object.prototype.hasOwnProperty.call(m,T)&&(f[T]=m[T]);return f}).apply(this,arguments)};function o(f,m,w){for(var _,T=0,O=m.length;T"u"||l.Promise||(l.Promise=Promise);var p=Object.getPrototypeOf,y={}.hasOwnProperty;function g(f,m){return y.call(f,m)}function k(f,m){typeof m=="function"&&(m=m(p(f))),(typeof Reflect>"u"?s:Reflect.ownKeys)(m).forEach(function(w){C(f,w,m[w])})}var x=Object.defineProperty;function C(f,m,w,_){x(f,m,d(w&&g(w,"get")&&typeof w.get=="function"?{get:w.get,set:w.set,configurable:!0}:{value:w,configurable:!0,writable:!0},_))}function N(f){return{from:function(m){return f.prototype=Object.create(m.prototype),C(f.prototype,"constructor",f),{extend:k.bind(null,f.prototype)}}}}var D=Object.getOwnPropertyDescriptor,R=[].slice;function L(f,m,w){return R.call(f,m,w)}function F(f,m){return m(f)}function ae(f){if(!f)throw new Error("Assertion Failed")}function le(f){l.setImmediate?setImmediate(f):setTimeout(f,0)}function V(f,m){if(typeof m=="string"&&g(f,m))return f[m];if(!m)return f;if(typeof m!="string"){for(var w=[],_=0,T=m.length;_"u"?[]:function(){var f=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[f,p(f),f];var m=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[m,p(m),f]}(),Qr=ke[0],$r=ke[1],ke=ke[2],$r=$r&&$r.then,Ie=Qr&&Qr.constructor,xt=!!ke,Ot=function(f,m){rr.push([f,m]),wn&&(queueMicrotask(At),wn=!1)},Kt=!0,wn=!0,Wn=[],Yn=[],Cr=tr,nr={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ht,pgp:!1,env:{},finalize:Ht},Je=nr,rr=[],yn=0,Pi=[];function Ze(f){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var m=this._PSD=Je;if(typeof f!="function"){if(f!==Zr)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Jr(this,this._value))}this._state=null,this._value=null,++m.ref,function w(_,T){try{T(function(O){if(_._state===null){if(O===_)throw new TypeError("A promise cannot be resolved with itself.");var P=_._lib&&tn();O&&typeof O.then=="function"?w(_,function(H,Z){O instanceof Ze?O._then(H,Z):O.then(H,Z)}):(_._state=!0,_._value=O,W(_)),P&&rn()}},Jr.bind(null,_))}catch(O){Jr(_,O)}}(this,f)}var gi={get:function(){var f=Je,m=vi;function w(_,T){var O=this,P=!f.global&&(f!==Je||m!==vi),H=P&&!ir(),Z=new Ze(function(te,oe){Ce(O,new yi(Ro(_,f,P,H),Ro(T,f,P,H),te,oe,f))});return this._consoleTask&&(Z._consoleTask=this._consoleTask),Z}return w.prototype=Zr,w},set:function(f){C(this,"then",f&&f.prototype===Zr?gi:{get:function(){return f},set:gi.set})}};function yi(f,m,w,_,T){this.onFulfilled=typeof f=="function"?f:null,this.onRejected=typeof m=="function"?m:null,this.resolve=w,this.reject=_,this.psd=T}function Jr(f,m){var w,_;Yn.push(m),f._state===null&&(w=f._lib&&tn(),m=Cr(m),f._state=!1,f._value=m,_=f,Wn.some(function(T){return T._value===_._value})||Wn.push(_),W(f),w&&rn())}function W(f){var m=f._listeners;f._listeners=[];for(var w=0,_=m.length;w<_;++w)Ce(f,m[w]);var T=f._PSD;--T.ref||T.finalize(),yn===0&&(++yn,Ot(function(){--yn==0&&at()},[]))}function Ce(f,m){if(f._state!==null){var w=f._state?m.onFulfilled:m.onRejected;if(w===null)return(f._state?m.resolve:m.reject)(f._value);++m.psd.ref,++yn,Ot(Xe,[w,f,m])}else f._listeners.push(m)}function Xe(f,m,w){try{var _,T=m._value;!m._state&&Yn.length&&(Yn=[]),_=zn&&m._consoleTask?m._consoleTask.run(function(){return f(T)}):f(T),m._state||Yn.indexOf(T)!==-1||function(O){for(var P=Wn.length;P;)if(Wn[--P]._value===O._value)return Wn.splice(P,1)}(m),w.resolve(_)}catch(O){w.reject(O)}finally{--yn==0&&at(),--w.psd.ref||w.psd.finalize()}}function At(){bi(nr,function(){tn()&&rn()})}function tn(){var f=Kt;return wn=Kt=!1,f}function rn(){var f,m,w;do for(;0.",wl="String expected.",ki=[],xi="__dbnames",ea="readonly",Fe="readwrite";function pt(f,m){return f?m?function(){return f.apply(this,arguments)&&m.apply(this,arguments)}:f:m}var zt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Bt(f){return typeof f!="string"||/\./.test(f)?function(m){return m}:function(m){return m[f]===void 0&&f in m&&delete(m=we(m))[f],m}}function kn(){throw Be.Type()}function bt(f,m){try{var w=ti(f),_=ti(m);if(w!==_)return w==="Array"?1:_==="Array"?-1:w==="binary"?1:_==="binary"?-1:w==="string"?1:_==="string"?-1:w==="Date"?1:_!=="Date"?NaN:-1;switch(w){case"number":case"Date":case"string":return mve+Ee&&he(ve+oe)})})}var ye=Ur(w)&&w.limit===1/0&&(typeof f!="function"||f===ka)&&{index:w.index,range:w.range};return he(0).then(function(){if(0=se})).length!==0?(oe.forEach(function(he){ue.push(function(){var ye=re,ve=he._cfg.dbschema;lr(K,ye,ie),lr(K,ve,ie),re=K._dbSchema=ve;var Ee=Qa(ye,ve);Ee.add.forEach(function(Ye){El(ie,Ye[0],Ye[1].primKey,Ye[1].indexes)}),Ee.change.forEach(function(Ye){if(Ye.recreate)throw new Be.Upgrade("Not yet support for changing primary key");var je=ie.objectStore(Ye.name);Ye.add.forEach(function(it){return Sa(je,it)}),Ye.change.forEach(function(it){je.deleteIndex(it.name),Sa(je,it)}),Ye.del.forEach(function(it){return je.deleteIndex(it)})});var ze=he._cfg.contentUpgrade;if(ze&&he._cfg.version>se){Za(K,ie),Q._memoizedTables={};var Ve=Ne(ve);Ee.del.forEach(function(Ye){Ve[Ye]=ye[Ye]}),Fo(K,[K.Transaction.prototype]),Ea(K,[K.Transaction.prototype],s(Ve),Ve),Q.schema=Ve;var Pe,He=G(ze);return He&&Ji(),Ee=Ze.follow(function(){var Ye;(Pe=ze(Q))&&He&&(Ye=ir.bind(null,null),Pe.then(Ye,Ye))}),Pe&&typeof Pe.then=="function"?Ze.resolve(Pe):Ee.then(function(){return Pe})}}),ue.push(function(ye){var ve,Ee,ze=he._cfg.dbschema;ve=ze,Ee=ye,[].slice.call(Ee.db.objectStoreNames).forEach(function(Ve){return ve[Ve]==null&&Ee.db.deleteObjectStore(Ve)}),Fo(K,[K.Transaction.prototype]),Ea(K,[K.Transaction.prototype],K._storeNames,K._dbSchema),Q.schema=K._dbSchema}),ue.push(function(ye){K.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(K.idbdb.version/10)===he._cfg.version?(K.idbdb.deleteObjectStore("$meta"),delete K._dbSchema.$meta,K._storeNames=K._storeNames.filter(function(ve){return ve!=="$meta"})):ye.objectStore("$meta").put(he._cfg.version,"version"))})}),function he(){return ue.length?Ze.resolve(ue.shift()(Q.idbtrans)).then(he):Ze.resolve()}().then(function(){Uo(re,ie)})):Ze.resolve();var K,se,Q,ie,ue,re}).catch(P)):(s(T).forEach(function(oe){El(w,oe,T[oe].primKey,T[oe].indexes)}),Za(f,w),void Ze.follow(function(){return f.on.populate.fire(O)}).catch(P));var Z,te})}function ms(f,m){Uo(f._dbSchema,m),m.db.version%10!=0||m.objectStoreNames.contains("$meta")||m.db.createObjectStore("$meta").add(Math.ceil(m.db.version/10-1),"version");var w=$o(0,f.idbdb,m);lr(f,f._dbSchema,m);for(var _=0,T=Qa(w,f._dbSchema).change;_Math.pow(2,62)?0:re.oldVersion,K=re<1,f.idbdb=ue.result,O&&ms(f,oe),ra(f,re/10,oe,Q))},Q),ue.onsuccess=et(function(){oe=null;var re,he,ye,ve,Ee,ze=f.idbdb=ue.result,Ve=L(ze.objectStoreNames);if(0"u"?Ze.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(se){function Q(){return indexedDB.databases().finally(se)}Z=setInterval(Q,100),Q()}).finally(function(){return clearInterval(Z)}):Promise.resolve()).then(H)]).then(function(){return P(),m.onReadyBeingFired=[],Ze.resolve(Ho(function(){return f.on.ready.fire(f.vip)})).then(function se(){if(0m.limit?se.length=m.limit:f.length===m.limit&&se.length=he.limit&&(!he.values||ze.req.values)&&Ru(ze.req.query.range,he.query.range)}),!1,ye,ve];case"count":return Ee=ve.find(function(ze){return Mu(ze.req.query.range,he.query.range)}),[Ee,!!Ee,ye,ve]}}(m,w,"query",O),oe=te[0],K=te[1],se=te[2],Q=te[3];return oe&&K?oe.obsSet=O.obsSet:(K=_.query(O).then(function(ie){var ue=ie.result;if(oe&&(oe.res=ue),P){for(var re=0,he=ue.length;re{Xf.dispatchEvent(new CustomEvent("conversationChange",{detail:{convId:e}}))},_n=new Jc("LlamacppWebui");_n.version(1).stores({conversations:"&id, lastModified",messages:"&id, convId, [convId+id], timestamp"});const mn={async getAllConversations(){return await K6().catch(console.error),(await _n.conversations.toArray()).sort((e,t)=>t.lastModified-e.lastModified)},async getOneConversation(e){return await _n.conversations.where("id").equals(e).first()??null},async getMessages(e){return await _n.messages.where({convId:e}).toArray()},filterByLeafNodeId(e,t,n){const i=[],o=new Map;for(const c of e)o.set(c.id,c);let l=o.get(t);if(!l){let c=-1;for(const d of e)d.timestamp>c&&(l=d,c=d.timestamp)}let s=l;for(;s;)(s.type!=="root"||s.type==="root"&&n)&&i.push(s),s=o.get(s.parent??-1);return i.sort((c,d)=>c.timestamp-d.timestamp),i},async createConversation(e){const t=Date.now(),n=t,i={id:`conv-${t}`,lastModified:t,currNode:n,name:e};return await _n.conversations.add(i),await _n.messages.add({id:n,convId:i.id,type:"root",timestamp:t,role:"system",content:"",parent:-1,children:[]}),i},async appendMsg(e,t){if(e.content===null)return;const{convId:n}=e;await _n.transaction("rw",_n.conversations,_n.messages,async()=>{const i=await mn.getOneConversation(n),o=await _n.messages.where({convId:n,id:t}).first();if(!i)throw new Error(`Conversation ${n} does not exist`);if(!o)throw new Error(`Parent message ID ${t} does not exist in conversation ${n}`);await _n.conversations.update(n,{lastModified:Date.now(),currNode:e.id}),await _n.messages.update(t,{children:[...o.children,e.id]}),await _n.messages.add({...e,parent:t,children:[]})}),s1(n)},async remove(e){await _n.transaction("rw",_n.conversations,_n.messages,async()=>{await _n.conversations.delete(e),await _n.messages.where({convId:e}).delete()}),s1(e)},onConversationChanged(e){const t=n=>e(n.detail.convId);rf.push([e,t]),Xf.addEventListener("conversationChange",t)},offConversationChanged(e){const t=rf.find(([n,i])=>n===e);t&&Xf.removeEventListener("conversationChange",t[1]),rf=[]},getConfig(){const e=JSON.parse(localStorage.getItem("config")||"{}");return{...wo,...e}},setConfig(e){localStorage.setItem("config",JSON.stringify(e))},getTheme(){return localStorage.getItem("theme")||"auto"},setTheme(e){e==="auto"?localStorage.removeItem("theme"):localStorage.setItem("theme",e)}};async function K6(){if(localStorage.getItem("migratedToIDB"))return;const e=[];for(const t in localStorage)t.startsWith("conv-")&&e.push(JSON.parse(localStorage.getItem(t)??"{}"));e.length!==0&&await _n.transaction("rw",_n.conversations,_n.messages,async()=>{let t=0;for(const n of e){const{id:i,lastModified:o,messages:l}=n,s=l[0],c=l.at(-1);if(l.length<2||!s||!c){console.log(`Skipping conversation ${i} with ${l.length} messages`);continue}const d=s.content??"(no messages)";await _n.conversations.add({id:i,lastModified:o,currNode:c.id,name:d});const p=l[0].id-2;await _n.messages.add({id:p,convId:i,type:"root",timestamp:p,role:"system",content:"",parent:-1,children:[s.id]});for(let y=0;y{const t=await mn.getOneConversation(e);return t?{conv:t,messages:await mn.getMessages(e)}:null},V6=({children:e})=>{var xe;const{pathname:t}=Co(),n=p0(),i=nu("/chat/:convId",t),o=(xe=i==null?void 0:i.params)==null?void 0:xe.convId,[l,s]=ee.useState(null),[c,d]=ee.useState({}),[p,y]=ee.useState({}),[g,k]=ee.useState(mn.getConfig()),[x,C]=ee.useState(null),[N,D]=ee.useState(!1);ee.useEffect(()=>{C(null);const Y=async Se=>{Se===o&&s(await u1(Se))};return mn.onConversationChanged(Y),u1(o??"").then(s),()=>{mn.offConversationChanged(Y)}},[o]);const R=(Y,Se)=>{d(Se?_e=>({..._e,[Y]:Se}):_e=>{const we={..._e};return delete we[Y],we})},L=(Y,Se)=>{y(Se?_e=>({..._e,[Y]:Se}):_e=>{const we={..._e};return delete we[Y],we})},F=Y=>!!c[Y],ae=async(Y,Se,_e)=>{var Ue,z;if(F(Y))return;const we=mn.getConfig();if(!await mn.getOneConversation(Y))throw new Error("Current conversation is not found");const Re=mn.filterByLeafNodeId(await mn.getMessages(Y),Se,!1),nt=new AbortController;if(L(Y,nt),!Re)throw new Error("Current messages are not found");const ct=Date.now()+fl.timercount+1;fl.timercount=fl.timercount+2;let be={id:ct,convId:Y,type:"text",timestamp:ct,role:"assistant",content:null,parent:Se,children:[]};R(Y,be);try{let G=[...we.systemMessage.length===0?[]:[{role:"system",content:we.systemMessage}],...D6(Re)];we.excludeThoughtOnReq&&(G=L6(G));const me={messages:G,stream:!0,cache_prompt:!0,samplers:we.samplers,temperature:we.temperature,dynatemp_range:we.dynatemp_range,dynatemp_exponent:we.dynatemp_exponent,top_k:we.top_k,top_p:we.top_p,min_p:we.min_p,typical_p:we.typical_p,xtc_probability:we.xtc_probability,xtc_threshold:we.xtc_threshold,repeat_last_n:we.repeat_last_n,repeat_penalty:we.repeat_penalty,presence_penalty:we.presence_penalty,frequency_penalty:we.frequency_penalty,dry_multiplier:we.dry_multiplier,dry_base:we.dry_base,dry_allowed_length:we.dry_allowed_length,dry_penalty_last_n:we.dry_penalty_last_n,max_tokens:we.max_tokens,timings_per_token:!!we.showTokensPerSecond,...we.custom.length?JSON.parse(we.custom):{}},B=await fetch(`${F6}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",...we.apiKey?{Authorization:`Bearer ${we.apiKey}`}:{}},body:JSON.stringify(me),signal:nt.signal});if(B.status!==200){const ft=await B.json();throw new Error(((Ue=ft==null?void 0:ft.error)==null?void 0:Ue.message)||"Unknown error")}const gt=O6(B);for await(const ft of gt){if(ft.error)throw new Error(((z=ft.error)==null?void 0:z.message)||"Unknown error");const lt=ft.choices[0].delta.content,Nt=be.content||"";lt&&(be={...be,content:Nt+lt});const kt=ft.timings;kt&&we.showTokensPerSecond&&(be.timings={prompt_n:kt.prompt_n,prompt_ms:kt.prompt_ms,predicted_n:kt.predicted_n,predicted_ms:kt.predicted_ms}),R(Y,be),_e()}}catch(G){R(Y,null),G.name==="AbortError"||(console.error(G),alert((G==null?void 0:G.message)??"Unknown error"))}finally{be.content!==null&&await mn.appendMsg(be,Se)}R(Y,null),_e(ct)},le=async(Y,Se,_e,we,Te)=>{if(F(Y??"")||_e.trim().length===0)return!1;if(Y===null||Y.length===0||Se===null){const ct=await mn.createConversation(_e.substring(0,256));Y=ct.id,Se=ct.currNode,n(`/chat/${Y}`)}const Re=Date.now()+fl.timercount;fl.timercount=fl.timercount+2;const nt=Re;mn.appendMsg({id:nt,timestamp:Re,type:"text",convId:Y,role:"user",content:_e,extra:we,parent:Se,children:[]},Se),Te(nt);try{return await ae(Y,nt,Te),!0}catch{}return!1},V=Y=>{var Se;R(Y,null),(Se=p[Y])==null||Se.abort()},ce=async(Y,Se,_e,we,Te)=>{if(!F(Y)){if(_e!==null){const Re=Date.now(),nt=Re;mn.appendMsg({id:nt,timestamp:Re,type:"text",convId:Y,role:"user",content:_e,extra:we,parent:Se,children:[]},Se),Se=nt}Te(Se),await ae(Y,Se,Te)}},Ne=Y=>{mn.setConfig(Y),k(Y)};return q.jsx(x2.Provider,{value:{isGenerating:F,viewingChat:l,pendingMessages:c,sendMessage:le,stopGenerating:V,replaceMessageAndGenerate:ce,canvasData:x,setCanvasData:C,config:g,saveConfig:Ne,showSettings:N,setShowSettings:D},children:e})},Ha=()=>ee.useContext(x2);function G6(){const e=p0(),[t,n]=ee.useState(mn.getTheme()),{setShowSettings:i}=Ha(),o=y=>{mn.setTheme(y),n(y)};ee.useEffect(()=>{var y;document.body.setAttribute("data-theme",t),document.body.setAttribute("data-color-scheme",((y=y2[t])==null?void 0:y["color-scheme"])??"auto")},[t]);const{isGenerating:l,viewingChat:s}=Ha(),c=l((s==null?void 0:s.conv.id)??""),d=()=>{if(c||!s)return;const y=s==null?void 0:s.conv.id;window.confirm("Are you sure to delete this conversation?")&&(mn.remove(y),e("/"))},p=()=>{if(c||!s)return;const y=s==null?void 0:s.conv.id,g=JSON.stringify(s,null,2),k=new Blob([g],{type:"application/json"}),x=URL.createObjectURL(k),C=document.createElement("a");C.href=x,C.download=`conversation_${y}.json`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(x)};return q.jsxs("div",{className:"flex flex-row items-center pt-6 pb-6 sticky top-0 z-10 bg-base-100",children:[q.jsx("label",{htmlFor:"toggle-drawer",className:"btn btn-ghost lg:hidden",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-list",viewBox:"0 0 16 16",children:q.jsx("path",{fillRule:"evenodd",d:"M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5"})})}),q.jsx("div",{className:"grow text-2xl font-bold ml-2",children:"llama.cpp"}),q.jsxs("div",{className:"flex items-center",children:[s&&q.jsxs("div",{className:"dropdown dropdown-end",children:[q.jsx("button",{tabIndex:0,role:"button",className:"btn m-1",disabled:c,children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-three-dots-vertical",viewBox:"0 0 16 16",children:q.jsx("path",{d:"M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"})})}),q.jsxs("ul",{tabIndex:0,className:"dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow",children:[q.jsx("li",{onClick:p,children:q.jsx("a",{children:"Download"})}),q.jsx("li",{className:"text-error",onClick:d,children:q.jsx("a",{children:"Delete"})})]})]}),q.jsx("div",{className:"tooltip tooltip-bottom","data-tip":"Settings",children:q.jsx("button",{className:"btn",onClick:()=>i(!0),children:q.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-gear",viewBox:"0 0 16 16",children:[q.jsx("path",{d:"M8 4.754a3.246 3.246 0 1 0 0 6.492 3.246 3.246 0 0 0 0-6.492M5.754 8a2.246 2.246 0 1 1 4.492 0 2.246 2.246 0 0 1-4.492 0"}),q.jsx("path",{d:"M9.796 1.343c-.527-1.79-3.065-1.79-3.592 0l-.094.319a.873.873 0 0 1-1.255.52l-.292-.16c-1.64-.892-3.433.902-2.54 2.541l.159.292a.873.873 0 0 1-.52 1.255l-.319.094c-1.79.527-1.79 3.065 0 3.592l.319.094a.873.873 0 0 1 .52 1.255l-.16.292c-.892 1.64.901 3.434 2.541 2.54l.292-.159a.873.873 0 0 1 1.255.52l.094.319c.527 1.79 3.065 1.79 3.592 0l.094-.319a.873.873 0 0 1 1.255-.52l.292.16c1.64.893 3.434-.902 2.54-2.541l-.159-.292a.873.873 0 0 1 .52-1.255l.319-.094c1.79-.527 1.79-3.065 0-3.592l-.319-.094a.873.873 0 0 1-.52-1.255l.16-.292c.893-1.64-.902-3.433-2.541-2.54l-.292.159a.873.873 0 0 1-1.255-.52zm-2.633.283c.246-.835 1.428-.835 1.674 0l.094.319a1.873 1.873 0 0 0 2.693 1.115l.291-.16c.764-.415 1.6.42 1.184 1.185l-.159.292a1.873 1.873 0 0 0 1.116 2.692l.318.094c.835.246.835 1.428 0 1.674l-.319.094a1.873 1.873 0 0 0-1.115 2.693l.16.291c.415.764-.42 1.6-1.185 1.184l-.291-.159a1.873 1.873 0 0 0-2.693 1.116l-.094.318c-.246.835-1.428.835-1.674 0l-.094-.319a1.873 1.873 0 0 0-2.692-1.115l-.292.16c-.764.415-1.6-.42-1.184-1.185l.159-.291A1.873 1.873 0 0 0 1.945 8.93l-.319-.094c-.835-.246-.835-1.428 0-1.674l.319-.094A1.873 1.873 0 0 0 3.06 4.377l-.16-.292c-.415-.764.42-1.6 1.185-1.184l.292.159a1.873 1.873 0 0 0 2.692-1.115z"})]})})}),q.jsx("div",{className:"tooltip tooltip-bottom","data-tip":"Themes",children:q.jsxs("div",{className:"dropdown dropdown-end dropdown-bottom",children:[q.jsx("div",{tabIndex:0,role:"button",className:"btn m-1",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-palette2",viewBox:"0 0 16 16",children:q.jsx("path",{d:"M0 .5A.5.5 0 0 1 .5 0h5a.5.5 0 0 1 .5.5v5.277l4.147-4.131a.5.5 0 0 1 .707 0l3.535 3.536a.5.5 0 0 1 0 .708L10.261 10H15.5a.5.5 0 0 1 .5.5v5a.5.5 0 0 1-.5.5H3a3 3 0 0 1-2.121-.879A3 3 0 0 1 0 13.044m6-.21 7.328-7.3-2.829-2.828L6 7.188zM4.5 13a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0M15 15v-4H9.258l-4.015 4zM0 .5v12.495zm0 12.495V13z"})})}),q.jsxs("ul",{tabIndex:0,className:"dropdown-content bg-base-300 rounded-box z-[1] w-52 p-2 shadow-2xl h-80 overflow-y-auto",children:[q.jsx("li",{children:q.jsx("button",{className:Dr({"btn btn-sm btn-block btn-ghost justify-start":!0,"btn-active":t==="auto"}),onClick:()=>o("auto"),children:"auto"})}),$6.map(y=>q.jsx("li",{children:q.jsx("input",{type:"radio",name:"theme-dropdown",className:"theme-controller btn btn-sm btn-block btn-ghost justify-start","aria-label":y,value:y,checked:t===y,onChange:g=>g.target.checked&&o(y)})},y))]})]})})]})]})}function W6(){const e=R3(),t=p0(),[n,i]=ee.useState([]),[o,l]=ee.useState(null);return ee.useEffect(()=>{mn.getOneConversation(e.convId??"").then(l)},[e.convId]),ee.useEffect(()=>{const s=async()=>{i(await mn.getAllConversations())};return mn.onConversationChanged(s),s(),()=>{mn.offConversationChanged(s)}},[]),q.jsxs(q.Fragment,{children:[q.jsx("input",{id:"toggle-drawer",type:"checkbox",className:"drawer-toggle",defaultChecked:!0}),q.jsxs("div",{className:"drawer-side h-screen lg:h-screen z-50 lg:max-w-64",children:[q.jsx("label",{htmlFor:"toggle-drawer","aria-label":"close sidebar",className:"drawer-overlay"}),q.jsxs("div",{className:"flex flex-col bg-base-200 min-h-full max-w-64 py-4 px-4",children:[q.jsxs("div",{className:"flex flex-row items-center justify-between mb-4 mt-4",children:[q.jsx("h2",{className:"font-bold ml-4",children:"Conversations"}),q.jsx("label",{htmlFor:"toggle-drawer",className:"btn btn-ghost lg:hidden",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-arrow-bar-left",viewBox:"0 0 16 16",children:q.jsx("path",{fillRule:"evenodd",d:"M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5M10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5"})})})]}),q.jsx("div",{className:Dr({"btn btn-ghost justify-start":!0,"btn-active":!o}),onClick:()=>t("/"),children:"+ New conversation"}),n.map(s=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal":!0,"btn-active":s.id===(o==null?void 0:o.id)}),onClick:()=>t(`/chat/${s.id}`),dir:"auto",children:q.jsx("span",{className:"truncate",children:s.name})},s.id)),q.jsx("div",{className:"text-center text-xs opacity-40 mt-auto mx-4",children:"Conversations are saved to browser's IndexedDB"})]})]})]})}function c1(e){const t=[],n=String(e||"");let i=n.indexOf(","),o=0,l=!1;for(;!l;){i===-1&&(i=n.length,l=!0);const s=n.slice(o,i).trim();(s||!l)&&t.push(s),o=i+1,i=n.indexOf(",",o)}return t}function Y6(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const X6=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Z6=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Q6={};function d1(e,t){return(Q6.jsx?Z6:X6).test(e)}const J6=/[ \t\n\f\r]/g;function ev(e){return typeof e=="object"?e.type==="text"?f1(e.value):!1:f1(e)}function f1(e){return e.replace(J6,"")===""}class mu{constructor(t,n,i){this.property=t,this.normal=n,i&&(this.space=i)}}mu.prototype.property={};mu.prototype.normal={};mu.prototype.space=null;function E2(e,t){const n={},i={};let o=-1;for(;++o4&&n.slice(0,4)==="data"&&av.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(p1,sv);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!p1.test(l)){let s=l.replace(ov,lv);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}o=Eh}return new o(i,t)}function lv(e){return"-"+e.toLowerCase()}function sv(e){return e.charAt(1).toUpperCase()}const uv={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"},O2=E2([C2,_2,A2,M2,rv],"html"),g0=E2([C2,_2,A2,M2,iv],"svg");function m1(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function cv(e){return e.join(" ").trim()}var Xl={},of,g1;function dv(){if(g1)return of;g1=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,c=/^\s+|\s+$/g,d=` + `+O:""),this.inner=O||null):typeof T=="object"&&(this.message="".concat(T.name," ").concat(T.message),this.inner=T):(this.message=me[m]||w,this.inner=null)}return N(_).from(kt),f[m]=_,f},{});Be.Syntax=SyntaxError,Be.Type=TypeError,Be.Range=RangeError;var Xt=Qr.reduce(function(f,m){return f[m+"Error"]=Be[m],f},{}),$n=$r.reduce(function(f,m){return["Syntax","Type","Range"].indexOf(m)===-1&&(f[m+"Error"]=Be[m]),f},{});function Ht(){}function tr(f){return f}function Er(f,m){return f==null||f===tr?m:function(w){return m(f(w))}}function qn(f,m){return function(){f.apply(this,arguments),m.apply(this,arguments)}}function jt(f,m){return f===Ht?m:function(){var w=f.apply(this,arguments);w!==void 0&&(arguments[0]=w);var _=this.onsuccess,T=this.onerror;this.onsuccess=null,this.onerror=null;var O=m.apply(this,arguments);return _&&(this.onsuccess=this.onsuccess?qn(_,this.onsuccess):_),T&&(this.onerror=this.onerror?qn(T,this.onerror):T),O!==void 0?O:w}}function Vn(f,m){return f===Ht?m:function(){f.apply(this,arguments);var w=this.onsuccess,_=this.onerror;this.onsuccess=this.onerror=null,m.apply(this,arguments),w&&(this.onsuccess=this.onsuccess?qn(w,this.onsuccess):w),_&&(this.onerror=this.onerror?qn(_,this.onerror):_)}}function Gn(f,m){return f===Ht?m:function(w){var _=f.apply(this,arguments);d(w,_);var T=this.onsuccess,O=this.onerror;return this.onsuccess=null,this.onerror=null,w=m.apply(this,arguments),T&&(this.onsuccess=this.onsuccess?qn(T,this.onsuccess):T),O&&(this.onerror=this.onerror?qn(O,this.onerror):O),_===void 0?w===void 0?void 0:w:d(_,w)}}function dr(f,m){return f===Ht?m:function(){return m.apply(this,arguments)!==!1&&f.apply(this,arguments)}}function Sr(f,m){return f===Ht?m:function(){var w=f.apply(this,arguments);if(w&&typeof w.then=="function"){for(var _=this,T=arguments.length,O=new Array(T);T--;)O[T]=arguments[T];return w.then(function(){return m.apply(_,O)})}return m.apply(this,arguments)}}$n.ModifyError=ft,$n.DexieError=B,$n.BulkError=lt;var zn=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Qi(f){zn=f}var Zr={},_r=100,ke=typeof Promise>"u"?[]:function(){var f=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[f,p(f),f];var m=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[m,p(m),f]}(),Qr=ke[0],$r=ke[1],ke=ke[2],$r=$r&&$r.then,Ie=Qr&&Qr.constructor,xt=!!ke,Ot=function(f,m){rr.push([f,m]),wn&&(queueMicrotask(At),wn=!1)},Kt=!0,wn=!0,Wn=[],Yn=[],Cr=tr,nr={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ht,pgp:!1,env:{},finalize:Ht},Je=nr,rr=[],yn=0,Pi=[];function Ze(f){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var m=this._PSD=Je;if(typeof f!="function"){if(f!==Zr)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Jr(this,this._value))}this._state=null,this._value=null,++m.ref,function w(_,T){try{T(function(O){if(_._state===null){if(O===_)throw new TypeError("A promise cannot be resolved with itself.");var P=_._lib&&tn();O&&typeof O.then=="function"?w(_,function(H,Z){O instanceof Ze?O._then(H,Z):O.then(H,Z)}):(_._state=!0,_._value=O,W(_)),P&&rn()}},Jr.bind(null,_))}catch(O){Jr(_,O)}}(this,f)}var gi={get:function(){var f=Je,m=vi;function w(_,T){var O=this,P=!f.global&&(f!==Je||m!==vi),H=P&&!ir(),Z=new Ze(function(te,oe){Ce(O,new yi(Ro(_,f,P,H),Ro(T,f,P,H),te,oe,f))});return this._consoleTask&&(Z._consoleTask=this._consoleTask),Z}return w.prototype=Zr,w},set:function(f){C(this,"then",f&&f.prototype===Zr?gi:{get:function(){return f},set:gi.set})}};function yi(f,m,w,_,T){this.onFulfilled=typeof f=="function"?f:null,this.onRejected=typeof m=="function"?m:null,this.resolve=w,this.reject=_,this.psd=T}function Jr(f,m){var w,_;Yn.push(m),f._state===null&&(w=f._lib&&tn(),m=Cr(m),f._state=!1,f._value=m,_=f,Wn.some(function(T){return T._value===_._value})||Wn.push(_),W(f),w&&rn())}function W(f){var m=f._listeners;f._listeners=[];for(var w=0,_=m.length;w<_;++w)Ce(f,m[w]);var T=f._PSD;--T.ref||T.finalize(),yn===0&&(++yn,Ot(function(){--yn==0&&at()},[]))}function Ce(f,m){if(f._state!==null){var w=f._state?m.onFulfilled:m.onRejected;if(w===null)return(f._state?m.resolve:m.reject)(f._value);++m.psd.ref,++yn,Ot(Xe,[w,f,m])}else f._listeners.push(m)}function Xe(f,m,w){try{var _,T=m._value;!m._state&&Yn.length&&(Yn=[]),_=zn&&m._consoleTask?m._consoleTask.run(function(){return f(T)}):f(T),m._state||Yn.indexOf(T)!==-1||function(O){for(var P=Wn.length;P;)if(Wn[--P]._value===O._value)return Wn.splice(P,1)}(m),w.resolve(_)}catch(O){w.reject(O)}finally{--yn==0&&at(),--w.psd.ref||w.psd.finalize()}}function At(){bi(nr,function(){tn()&&rn()})}function tn(){var f=Kt;return wn=Kt=!1,f}function rn(){var f,m,w;do for(;0.",wl="String expected.",ki=[],xi="__dbnames",ea="readonly",Fe="readwrite";function pt(f,m){return f?m?function(){return f.apply(this,arguments)&&m.apply(this,arguments)}:f:m}var zt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Bt(f){return typeof f!="string"||/\./.test(f)?function(m){return m}:function(m){return m[f]===void 0&&f in m&&delete(m=we(m))[f],m}}function kn(){throw Be.Type()}function bt(f,m){try{var w=ti(f),_=ti(m);if(w!==_)return w==="Array"?1:_==="Array"?-1:w==="binary"?1:_==="binary"?-1:w==="string"?1:_==="string"?-1:w==="Date"?1:_!=="Date"?NaN:-1;switch(w){case"number":case"Date":case"string":return mve+Ee&&he(ve+oe)})})}var ye=Ur(w)&&w.limit===1/0&&(typeof f!="function"||f===ka)&&{index:w.index,range:w.range};return he(0).then(function(){if(0=se})).length!==0?(oe.forEach(function(he){ue.push(function(){var ye=re,ve=he._cfg.dbschema;lr(K,ye,ie),lr(K,ve,ie),re=K._dbSchema=ve;var Ee=Qa(ye,ve);Ee.add.forEach(function(Ye){El(ie,Ye[0],Ye[1].primKey,Ye[1].indexes)}),Ee.change.forEach(function(Ye){if(Ye.recreate)throw new Be.Upgrade("Not yet support for changing primary key");var je=ie.objectStore(Ye.name);Ye.add.forEach(function(it){return Sa(je,it)}),Ye.change.forEach(function(it){je.deleteIndex(it.name),Sa(je,it)}),Ye.del.forEach(function(it){return je.deleteIndex(it)})});var ze=he._cfg.contentUpgrade;if(ze&&he._cfg.version>se){Za(K,ie),Q._memoizedTables={};var Ve=Ne(ve);Ee.del.forEach(function(Ye){Ve[Ye]=ye[Ye]}),Fo(K,[K.Transaction.prototype]),Ea(K,[K.Transaction.prototype],s(Ve),Ve),Q.schema=Ve;var Pe,He=G(ze);return He&&Ji(),Ee=Ze.follow(function(){var Ye;(Pe=ze(Q))&&He&&(Ye=ir.bind(null,null),Pe.then(Ye,Ye))}),Pe&&typeof Pe.then=="function"?Ze.resolve(Pe):Ee.then(function(){return Pe})}}),ue.push(function(ye){var ve,Ee,ze=he._cfg.dbschema;ve=ze,Ee=ye,[].slice.call(Ee.db.objectStoreNames).forEach(function(Ve){return ve[Ve]==null&&Ee.db.deleteObjectStore(Ve)}),Fo(K,[K.Transaction.prototype]),Ea(K,[K.Transaction.prototype],K._storeNames,K._dbSchema),Q.schema=K._dbSchema}),ue.push(function(ye){K.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(K.idbdb.version/10)===he._cfg.version?(K.idbdb.deleteObjectStore("$meta"),delete K._dbSchema.$meta,K._storeNames=K._storeNames.filter(function(ve){return ve!=="$meta"})):ye.objectStore("$meta").put(he._cfg.version,"version"))})}),function he(){return ue.length?Ze.resolve(ue.shift()(Q.idbtrans)).then(he):Ze.resolve()}().then(function(){Uo(re,ie)})):Ze.resolve();var K,se,Q,ie,ue,re}).catch(P)):(s(T).forEach(function(oe){El(w,oe,T[oe].primKey,T[oe].indexes)}),Za(f,w),void Ze.follow(function(){return f.on.populate.fire(O)}).catch(P));var Z,te})}function ms(f,m){Uo(f._dbSchema,m),m.db.version%10!=0||m.objectStoreNames.contains("$meta")||m.db.createObjectStore("$meta").add(Math.ceil(m.db.version/10-1),"version");var w=$o(0,f.idbdb,m);lr(f,f._dbSchema,m);for(var _=0,T=Qa(w,f._dbSchema).change;_Math.pow(2,62)?0:re.oldVersion,K=re<1,f.idbdb=ue.result,O&&ms(f,oe),ra(f,re/10,oe,Q))},Q),ue.onsuccess=et(function(){oe=null;var re,he,ye,ve,Ee,ze=f.idbdb=ue.result,Ve=L(ze.objectStoreNames);if(0"u"?Ze.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(se){function Q(){return indexedDB.databases().finally(se)}Z=setInterval(Q,100),Q()}).finally(function(){return clearInterval(Z)}):Promise.resolve()).then(H)]).then(function(){return P(),m.onReadyBeingFired=[],Ze.resolve(Ho(function(){return f.on.ready.fire(f.vip)})).then(function se(){if(0m.limit?se.length=m.limit:f.length===m.limit&&se.length=he.limit&&(!he.values||ze.req.values)&&Ru(ze.req.query.range,he.query.range)}),!1,ye,ve];case"count":return Ee=ve.find(function(ze){return Mu(ze.req.query.range,he.query.range)}),[Ee,!!Ee,ye,ve]}}(m,w,"query",O),oe=te[0],K=te[1],se=te[2],Q=te[3];return oe&&K?oe.obsSet=O.obsSet:(K=_.query(O).then(function(ie){var ue=ie.result;if(oe&&(oe.res=ue),P){for(var re=0,he=ue.length;re{Xf.dispatchEvent(new CustomEvent("conversationChange",{detail:{convId:e}}))},_n=new Jc("LlamacppWebui");_n.version(1).stores({conversations:"&id, lastModified",messages:"&id, convId, [convId+id], timestamp"});const mn={async getAllConversations(){return await K6().catch(console.error),(await _n.conversations.toArray()).sort((e,t)=>t.lastModified-e.lastModified)},async getOneConversation(e){return await _n.conversations.where("id").equals(e).first()??null},async getMessages(e){return await _n.messages.where({convId:e}).toArray()},filterByLeafNodeId(e,t,n){const i=[],o=new Map;for(const c of e)o.set(c.id,c);let l=o.get(t);if(!l){let c=-1;for(const d of e)d.timestamp>c&&(l=d,c=d.timestamp)}let s=l;for(;s;)(s.type!=="root"||s.type==="root"&&n)&&i.push(s),s=o.get(s.parent??-1);return i.sort((c,d)=>c.timestamp-d.timestamp),i},async createConversation(e){const t=Date.now(),n=t,i={id:`conv-${t}`,lastModified:t,currNode:n,name:e};return await _n.conversations.add(i),await _n.messages.add({id:n,convId:i.id,type:"root",timestamp:t,role:"system",content:"",parent:-1,children:[]}),i},async appendMsg(e,t){if(e.content===null)return;const{convId:n}=e;await _n.transaction("rw",_n.conversations,_n.messages,async()=>{const i=await mn.getOneConversation(n),o=await _n.messages.where({convId:n,id:t}).first();if(!i)throw new Error(`Conversation ${n} does not exist`);if(!o)throw new Error(`Parent message ID ${t} does not exist in conversation ${n}`);await _n.conversations.update(n,{lastModified:Date.now(),currNode:e.id}),await _n.messages.update(t,{children:[...o.children,e.id]}),await _n.messages.add({...e,parent:t,children:[]})}),s1(n)},async remove(e){await _n.transaction("rw",_n.conversations,_n.messages,async()=>{await _n.conversations.delete(e),await _n.messages.where({convId:e}).delete()}),s1(e)},onConversationChanged(e){const t=n=>e(n.detail.convId);rf.push([e,t]),Xf.addEventListener("conversationChange",t)},offConversationChanged(e){const t=rf.find(([n,i])=>n===e);t&&Xf.removeEventListener("conversationChange",t[1]),rf=[]},getConfig(){const e=JSON.parse(localStorage.getItem("config")||"{}");return{...wo,...e}},setConfig(e){localStorage.setItem("config",JSON.stringify(e))},getTheme(){return localStorage.getItem("theme")||"auto"},setTheme(e){e==="auto"?localStorage.removeItem("theme"):localStorage.setItem("theme",e)}};async function K6(){if(localStorage.getItem("migratedToIDB"))return;const e=[];for(const t in localStorage)t.startsWith("conv-")&&e.push(JSON.parse(localStorage.getItem(t)??"{}"));e.length!==0&&await _n.transaction("rw",_n.conversations,_n.messages,async()=>{let t=0;for(const n of e){const{id:i,lastModified:o,messages:l}=n,s=l[0],c=l.at(-1);if(l.length<2||!s||!c){console.log(`Skipping conversation ${i} with ${l.length} messages`);continue}const d=s.content??"(no messages)";await _n.conversations.add({id:i,lastModified:o,currNode:c.id,name:d});const p=l[0].id-2;await _n.messages.add({id:p,convId:i,type:"root",timestamp:p,role:"system",content:"",parent:-1,children:[s.id]});for(let y=0;y{const t=await mn.getOneConversation(e);return t?{conv:t,messages:await mn.getMessages(e)}:null},V6=({children:e})=>{var xe;const{pathname:t}=Co(),n=p0(),i=nu("/chat/:convId",t),o=(xe=i==null?void 0:i.params)==null?void 0:xe.convId,[l,s]=ee.useState(null),[c,d]=ee.useState({}),[p,y]=ee.useState({}),[g,k]=ee.useState(mn.getConfig()),[x,C]=ee.useState(null),[N,D]=ee.useState(!1);ee.useEffect(()=>{C(null);const Y=async Se=>{Se===o&&s(await u1(Se))};return mn.onConversationChanged(Y),u1(o??"").then(s),()=>{mn.offConversationChanged(Y)}},[o]);const R=(Y,Se)=>{d(Se?_e=>({..._e,[Y]:Se}):_e=>{const we={..._e};return delete we[Y],we})},L=(Y,Se)=>{y(Se?_e=>({..._e,[Y]:Se}):_e=>{const we={..._e};return delete we[Y],we})},F=Y=>!!c[Y],ae=async(Y,Se,_e)=>{var Ue,z;if(F(Y))return;const we=mn.getConfig();if(!await mn.getOneConversation(Y))throw new Error("Current conversation is not found");const Re=mn.filterByLeafNodeId(await mn.getMessages(Y),Se,!1),nt=new AbortController;if(L(Y,nt),!Re)throw new Error("Current messages are not found");const ct=Date.now()+fl.timercount+1;fl.timercount=fl.timercount+2;let be={id:ct,convId:Y,type:"text",timestamp:ct,role:"assistant",content:null,parent:Se,children:[]};R(Y,be);try{let G=[...we.systemMessage.length===0?[]:[{role:"system",content:we.systemMessage}],...D6(Re)];we.excludeThoughtOnReq&&(G=L6(G));const me={messages:G,stream:!0,cache_prompt:!0,samplers:we.samplers,temperature:we.temperature,dynatemp_range:we.dynatemp_range,dynatemp_exponent:we.dynatemp_exponent,top_k:we.top_k,top_p:we.top_p,min_p:we.min_p,typical_p:we.typical_p,xtc_probability:we.xtc_probability,xtc_threshold:we.xtc_threshold,top_n_sigma:we.top_n_sigma,repeat_last_n:we.repeat_last_n,repeat_penalty:we.repeat_penalty,presence_penalty:we.presence_penalty,frequency_penalty:we.frequency_penalty,dry_multiplier:we.dry_multiplier,dry_base:we.dry_base,dry_allowed_length:we.dry_allowed_length,dry_penalty_last_n:we.dry_penalty_last_n,max_tokens:we.max_tokens,timings_per_token:!!we.showTokensPerSecond,...we.custom.length?JSON.parse(we.custom):{}},B=await fetch(`${F6}/v1/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",...we.apiKey?{Authorization:`Bearer ${we.apiKey}`}:{}},body:JSON.stringify(me),signal:nt.signal});if(B.status!==200){const ft=await B.json();throw new Error(((Ue=ft==null?void 0:ft.error)==null?void 0:Ue.message)||"Unknown error")}const gt=O6(B);for await(const ft of gt){if(ft.error)throw new Error(((z=ft.error)==null?void 0:z.message)||"Unknown error");const lt=ft.choices[0].delta.content,Nt=be.content||"";lt&&(be={...be,content:Nt+lt});const kt=ft.timings;kt&&we.showTokensPerSecond&&(be.timings={prompt_n:kt.prompt_n,prompt_ms:kt.prompt_ms,predicted_n:kt.predicted_n,predicted_ms:kt.predicted_ms}),R(Y,be),_e()}}catch(G){R(Y,null),G.name==="AbortError"||(console.error(G),alert((G==null?void 0:G.message)??"Unknown error"))}finally{be.content!==null&&await mn.appendMsg(be,Se)}R(Y,null),_e(ct)},le=async(Y,Se,_e,we,Te)=>{if(F(Y??"")||_e.trim().length===0)return!1;if(Y===null||Y.length===0||Se===null){const ct=await mn.createConversation(_e.substring(0,256));Y=ct.id,Se=ct.currNode,n(`/chat/${Y}`)}const Re=Date.now()+fl.timercount;fl.timercount=fl.timercount+2;const nt=Re;mn.appendMsg({id:nt,timestamp:Re,type:"text",convId:Y,role:"user",content:_e,extra:we,parent:Se,children:[]},Se),Te(nt);try{return await ae(Y,nt,Te),!0}catch{}return!1},V=Y=>{var Se;R(Y,null),(Se=p[Y])==null||Se.abort()},ce=async(Y,Se,_e,we,Te)=>{if(!F(Y)){if(_e!==null){const Re=Date.now(),nt=Re;mn.appendMsg({id:nt,timestamp:Re,type:"text",convId:Y,role:"user",content:_e,extra:we,parent:Se,children:[]},Se),Se=nt}Te(Se),await ae(Y,Se,Te)}},Ne=Y=>{mn.setConfig(Y),k(Y)};return q.jsx(x2.Provider,{value:{isGenerating:F,viewingChat:l,pendingMessages:c,sendMessage:le,stopGenerating:V,replaceMessageAndGenerate:ce,canvasData:x,setCanvasData:C,config:g,saveConfig:Ne,showSettings:N,setShowSettings:D},children:e})},Ha=()=>ee.useContext(x2);function G6(){const e=p0(),[t,n]=ee.useState(mn.getTheme()),{setShowSettings:i}=Ha(),o=y=>{mn.setTheme(y),n(y)};ee.useEffect(()=>{var y;document.body.setAttribute("data-theme",t),document.body.setAttribute("data-color-scheme",((y=y2[t])==null?void 0:y["color-scheme"])??"auto")},[t]);const{isGenerating:l,viewingChat:s}=Ha(),c=l((s==null?void 0:s.conv.id)??""),d=()=>{if(c||!s)return;const y=s==null?void 0:s.conv.id;window.confirm("Are you sure to delete this conversation?")&&(mn.remove(y),e("/"))},p=()=>{if(c||!s)return;const y=s==null?void 0:s.conv.id,g=JSON.stringify(s,null,2),k=new Blob([g],{type:"application/json"}),x=URL.createObjectURL(k),C=document.createElement("a");C.href=x,C.download=`conversation_${y}.json`,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(x)};return q.jsxs("div",{className:"flex flex-row items-center pt-6 pb-6 sticky top-0 z-10 bg-base-100",children:[q.jsx("label",{htmlFor:"toggle-drawer",className:"btn btn-ghost lg:hidden",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-list",viewBox:"0 0 16 16",children:q.jsx("path",{fillRule:"evenodd",d:"M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5"})})}),q.jsx("div",{className:"grow text-2xl font-bold ml-2",children:"ik_llama.cpp"}),q.jsxs("div",{className:"flex items-center",children:[s&&q.jsxs("div",{className:"dropdown dropdown-end",children:[q.jsx("button",{tabIndex:0,role:"button",className:"btn m-1",disabled:c,children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-three-dots-vertical",viewBox:"0 0 16 16",children:q.jsx("path",{d:"M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"})})}),q.jsxs("ul",{tabIndex:0,className:"dropdown-content menu bg-base-100 rounded-box z-[1] w-52 p-2 shadow",children:[q.jsx("li",{onClick:p,children:q.jsx("a",{children:"Download"})}),q.jsx("li",{className:"text-error",onClick:d,children:q.jsx("a",{children:"Delete"})})]})]}),q.jsx("div",{className:"tooltip tooltip-bottom","data-tip":"Settings",children:q.jsx("button",{className:"btn",onClick:()=>i(!0),children:q.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-gear",viewBox:"0 0 16 16",children:[q.jsx("path",{d:"M8 4.754a3.246 3.246 0 1 0 0 6.492 3.246 3.246 0 0 0 0-6.492M5.754 8a2.246 2.246 0 1 1 4.492 0 2.246 2.246 0 0 1-4.492 0"}),q.jsx("path",{d:"M9.796 1.343c-.527-1.79-3.065-1.79-3.592 0l-.094.319a.873.873 0 0 1-1.255.52l-.292-.16c-1.64-.892-3.433.902-2.54 2.541l.159.292a.873.873 0 0 1-.52 1.255l-.319.094c-1.79.527-1.79 3.065 0 3.592l.319.094a.873.873 0 0 1 .52 1.255l-.16.292c-.892 1.64.901 3.434 2.541 2.54l.292-.159a.873.873 0 0 1 1.255.52l.094.319c.527 1.79 3.065 1.79 3.592 0l.094-.319a.873.873 0 0 1 1.255-.52l.292.16c1.64.893 3.434-.902 2.54-2.541l-.159-.292a.873.873 0 0 1 .52-1.255l.319-.094c1.79-.527 1.79-3.065 0-3.592l-.319-.094a.873.873 0 0 1-.52-1.255l.16-.292c.893-1.64-.902-3.433-2.541-2.54l-.292.159a.873.873 0 0 1-1.255-.52zm-2.633.283c.246-.835 1.428-.835 1.674 0l.094.319a1.873 1.873 0 0 0 2.693 1.115l.291-.16c.764-.415 1.6.42 1.184 1.185l-.159.292a1.873 1.873 0 0 0 1.116 2.692l.318.094c.835.246.835 1.428 0 1.674l-.319.094a1.873 1.873 0 0 0-1.115 2.693l.16.291c.415.764-.42 1.6-1.185 1.184l-.291-.159a1.873 1.873 0 0 0-2.693 1.116l-.094.318c-.246.835-1.428.835-1.674 0l-.094-.319a1.873 1.873 0 0 0-2.692-1.115l-.292.16c-.764.415-1.6-.42-1.184-1.185l.159-.291A1.873 1.873 0 0 0 1.945 8.93l-.319-.094c-.835-.246-.835-1.428 0-1.674l.319-.094A1.873 1.873 0 0 0 3.06 4.377l-.16-.292c-.415-.764.42-1.6 1.185-1.184l.292.159a1.873 1.873 0 0 0 2.692-1.115z"})]})})}),q.jsx("div",{className:"tooltip tooltip-bottom","data-tip":"Themes",children:q.jsxs("div",{className:"dropdown dropdown-end dropdown-bottom",children:[q.jsx("div",{tabIndex:0,role:"button",className:"btn m-1",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-palette2",viewBox:"0 0 16 16",children:q.jsx("path",{d:"M0 .5A.5.5 0 0 1 .5 0h5a.5.5 0 0 1 .5.5v5.277l4.147-4.131a.5.5 0 0 1 .707 0l3.535 3.536a.5.5 0 0 1 0 .708L10.261 10H15.5a.5.5 0 0 1 .5.5v5a.5.5 0 0 1-.5.5H3a3 3 0 0 1-2.121-.879A3 3 0 0 1 0 13.044m6-.21 7.328-7.3-2.829-2.828L6 7.188zM4.5 13a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0M15 15v-4H9.258l-4.015 4zM0 .5v12.495zm0 12.495V13z"})})}),q.jsxs("ul",{tabIndex:0,className:"dropdown-content bg-base-300 rounded-box z-[1] w-52 p-2 shadow-2xl h-80 overflow-y-auto",children:[q.jsx("li",{children:q.jsx("button",{className:Dr({"btn btn-sm btn-block btn-ghost justify-start":!0,"btn-active":t==="auto"}),onClick:()=>o("auto"),children:"auto"})}),$6.map(y=>q.jsx("li",{children:q.jsx("input",{type:"radio",name:"theme-dropdown",className:"theme-controller btn btn-sm btn-block btn-ghost justify-start","aria-label":y,value:y,checked:t===y,onChange:g=>g.target.checked&&o(y)})},y))]})]})})]})]})}function W6(){const e=R3(),t=p0(),[n,i]=ee.useState([]),[o,l]=ee.useState(null);return ee.useEffect(()=>{mn.getOneConversation(e.convId??"").then(l)},[e.convId]),ee.useEffect(()=>{const s=async()=>{i(await mn.getAllConversations())};return mn.onConversationChanged(s),s(),()=>{mn.offConversationChanged(s)}},[]),q.jsxs(q.Fragment,{children:[q.jsx("input",{id:"toggle-drawer",type:"checkbox",className:"drawer-toggle",defaultChecked:!0}),q.jsxs("div",{className:"drawer-side h-screen lg:h-screen z-50 lg:max-w-64",children:[q.jsx("label",{htmlFor:"toggle-drawer","aria-label":"close sidebar",className:"drawer-overlay"}),q.jsxs("div",{className:"flex flex-col bg-base-200 min-h-full max-w-64 py-4 px-4",children:[q.jsxs("div",{className:"flex flex-row items-center justify-between mb-4 mt-4",children:[q.jsx("h2",{className:"font-bold ml-4",children:"Conversations"}),q.jsx("label",{htmlFor:"toggle-drawer",className:"btn btn-ghost lg:hidden",children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"currentColor",className:"bi bi-arrow-bar-left",viewBox:"0 0 16 16",children:q.jsx("path",{fillRule:"evenodd",d:"M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5M10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5"})})})]}),q.jsx("div",{className:Dr({"btn btn-ghost justify-start":!0,"btn-active":!o}),onClick:()=>t("/"),children:"+ New conversation"}),n.map(s=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal":!0,"btn-active":s.id===(o==null?void 0:o.id)}),onClick:()=>t(`/chat/${s.id}`),dir:"auto",children:q.jsx("span",{className:"truncate",children:s.name})},s.id)),q.jsx("div",{className:"text-center text-xs opacity-40 mt-auto mx-4",children:"Conversations are saved to browser's IndexedDB"})]})]})]})}function c1(e){const t=[],n=String(e||"");let i=n.indexOf(","),o=0,l=!1;for(;!l;){i===-1&&(i=n.length,l=!0);const s=n.slice(o,i).trim();(s||!l)&&t.push(s),o=i+1,i=n.indexOf(",",o)}return t}function Y6(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const X6=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Z6=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Q6={};function d1(e,t){return(Q6.jsx?Z6:X6).test(e)}const J6=/[ \t\n\f\r]/g;function ev(e){return typeof e=="object"?e.type==="text"?f1(e.value):!1:f1(e)}function f1(e){return e.replace(J6,"")===""}class mu{constructor(t,n,i){this.property=t,this.normal=n,i&&(this.space=i)}}mu.prototype.property={};mu.prototype.normal={};mu.prototype.space=null;function E2(e,t){const n={},i={};let o=-1;for(;++o4&&n.slice(0,4)==="data"&&av.test(t)){if(t.charAt(4)==="-"){const l=t.slice(5).replace(p1,sv);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=t.slice(4);if(!p1.test(l)){let s=l.replace(ov,lv);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}o=Eh}return new o(i,t)}function lv(e){return"-"+e.toLowerCase()}function sv(e){return e.charAt(1).toUpperCase()}const uv={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"},O2=E2([C2,_2,A2,M2,rv],"html"),g0=E2([C2,_2,A2,M2,iv],"svg");function m1(e){const t=String(e||"").trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function cv(e){return e.join(" ").trim()}var Xl={},of,g1;function dv(){if(g1)return of;g1=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,c=/^\s+|\s+$/g,d=` `,p="/",y="*",g="",k="comment",x="declaration";of=function(N,D){if(typeof N!="string")throw new TypeError("First argument must be a string");if(!N)return[];D=D||{};var R=1,L=1;function F(we){var Te=we.match(t);Te&&(R+=Te.length);var Re=we.lastIndexOf(d);L=~Re?we.length-Re:L+we.length}function ae(){var we={line:R,column:L};return function(Te){return Te.position=new le(we),Ne(),Te}}function le(we){this.start=we,this.end={line:R,column:L},this.source=D.source}le.prototype.content=N;function V(we){var Te=new Error(D.source+":"+R+":"+L+": "+we);if(Te.reason=we,Te.filename=D.source,Te.line=R,Te.column=L,Te.source=N,!D.silent)throw Te}function ce(we){var Te=we.exec(N);if(Te){var Re=Te[0];return F(Re),N=N.slice(Re.length),Te}}function Ne(){ce(n)}function xe(we){var Te;for(we=we||[];Te=Y();)Te!==!1&&we.push(Te);return we}function Y(){var we=ae();if(!(p!=N.charAt(0)||y!=N.charAt(1))){for(var Te=2;g!=N.charAt(Te)&&(y!=N.charAt(Te)||p!=N.charAt(Te+1));)++Te;if(Te+=2,g===N.charAt(Te-1))return V("End of comment missing");var Re=N.slice(2,Te-2);return L+=2,F(Re),N=N.slice(Te),L+=2,we({type:k,comment:Re})}}function Se(){var we=ae(),Te=ce(i);if(Te){if(Y(),!ce(o))return V("property missing ':'");var Re=ce(l),nt=we({type:x,property:C(Te[0].replace(e,g)),value:Re?C(Re[0].replace(e,g)):g});return ce(s),nt}}function _e(){var we=[];xe(we);for(var Te;Te=Se();)Te!==!1&&(we.push(Te),xe(we));return we}return Ne(),_e()};function C(N){return N?N.replace(c,g):g}return of}var y1;function fv(){if(y1)return Xl;y1=1;var e=Xl&&Xl.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Xl,"__esModule",{value:!0}),Xl.default=n;var t=e(dv());function n(i,o){var l=null;if(!i||typeof i!="string")return l;var s=(0,t.default)(i),c=typeof o=="function";return s.forEach(function(d){if(d.type==="declaration"){var p=d.property,y=d.value;c?o(p,y,d):y&&(l=l||{},l[p]=y)}}),l}return Xl}var hv=fv();const v1=f0(hv),pv=v1.default||v1,I2=D2("end"),Sh=D2("start");function D2(e){return t;function t(n){const i=n&&n.position&&n.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function mv(e){const t=Sh(e),n=I2(e);if(t&&n)return{start:t,end:n}}function Zs(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?b1(e.position):"start"in e||"end"in e?b1(e):"line"in e||"column"in e?Qf(e):""}function Qf(e){return w1(e&&e.line)+":"+w1(e&&e.column)}function b1(e){return Qf(e&&e.start)+"-"+Qf(e&&e.end)}function w1(e){return e&&typeof e=="number"?e:1}class xr extends Error{constructor(t,n,i){super(),typeof n=="string"&&(i=n,n=void 0);let o="",l={},s=!1;if(n&&("line"in n&&"column"in n?l={place:n}:"start"in n&&"end"in n?l={place:n}:"type"in n?l={ancestors:[n],place:n.position}:l={...n}),typeof t=="string"?o=t:!l.cause&&t&&(s=!0,o=t.message,l.cause=t),!l.ruleId&&!l.source&&typeof i=="string"){const d=i.indexOf(":");d===-1?l.ruleId=i:(l.source=i.slice(0,d),l.ruleId=i.slice(d+1))}if(!l.place&&l.ancestors&&l.ancestors){const d=l.ancestors[l.ancestors.length-1];d&&(l.place=d.position)}const c=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file,this.message=o,this.line=c?c.line:void 0,this.name=Zs(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=s&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual,this.expected,this.note,this.url}}xr.prototype.file="";xr.prototype.name="";xr.prototype.reason="";xr.prototype.message="";xr.prototype.stack="";xr.prototype.column=void 0;xr.prototype.line=void 0;xr.prototype.ancestors=void 0;xr.prototype.cause=void 0;xr.prototype.fatal=void 0;xr.prototype.place=void 0;xr.prototype.ruleId=void 0;xr.prototype.source=void 0;const _h={}.hasOwnProperty,gv=new Map,yv=/[A-Z]/g,vv=/-([a-z])/g,bv=new Set(["table","tbody","thead","tfoot","tr"]),wv=new Set(["td","th"]),L2="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function kv(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let i;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=Av(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");i=Nv(n,t.jsx,t.jsxs)}const o={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:i,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"?g0:O2,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},l=z2(o,e,void 0);return l&&typeof l!="string"?l:o.create(e,o.Fragment,{children:l||void 0},void 0)}function z2(e,t,n){if(t.type==="element")return xv(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Ev(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return _v(e,t,n);if(t.type==="mdxjsEsm")return Sv(e,t);if(t.type==="root")return Cv(e,t,n);if(t.type==="text")return Tv(e,t)}function xv(e,t,n){const i=e.schema;let o=i;t.tagName.toLowerCase()==="svg"&&i.space==="html"&&(o=g0,e.schema=o),e.ancestors.push(t);const l=B2(e,t.tagName,!1),s=Mv(e,t);let c=Th(e,t);return bv.has(t.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!ev(d):!0})),P2(e,s,l,t),Ch(s,c),e.ancestors.pop(),e.schema=i,e.create(t,l,s,n)}function Ev(e,t){if(t.data&&t.data.estree&&e.evaluater){const i=t.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}iu(e,t.position)}function Sv(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);iu(e,t.position)}function _v(e,t,n){const i=e.schema;let o=i;t.name==="svg"&&i.space==="html"&&(o=g0,e.schema=o),e.ancestors.push(t);const l=t.name===null?e.Fragment:B2(e,t.name,!0),s=Rv(e,t),c=Th(e,t);return P2(e,s,l,t),Ch(s,c),e.ancestors.pop(),e.schema=i,e.create(t,l,s,n)}function Cv(e,t,n){const i={};return Ch(i,Th(e,t)),e.create(t,e.Fragment,i,n)}function Tv(e,t){return t.value}function P2(e,t,n,i){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=i)}function Ch(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Nv(e,t,n){return i;function i(o,l,s,c){const p=Array.isArray(s.children)?n:t;return c?p(l,s,c):p(l,s)}}function Av(e,t){return n;function n(i,o,l,s){const c=Array.isArray(l.children),d=Sh(i);return t(o,l,s,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function Mv(e,t){const n={};let i,o;for(o in t.properties)if(o!=="children"&&_h.call(t.properties,o)){const l=Ov(e,o,t.properties[o]);if(l){const[s,c]=l;e.tableCellAlignToStyle&&s==="align"&&typeof c=="string"&&wv.has(t.tagName)?i=c:n[s]=c}}if(i){const l=n.style||(n.style={});l[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return n}function Rv(e,t){const n={};for(const i of t.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const l=i.data.estree.body[0];l.type;const s=l.expression;s.type;const c=s.properties[0];c.type,Object.assign(n,e.evaluater.evaluateExpression(c.argument))}else iu(e,t.position);else{const o=i.name;let l;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,l=e.evaluater.evaluateExpression(c.expression)}else iu(e,t.position);else l=i.value===null?!0:i.value;n[o]=l}return n}function Th(e,t){const n=[];let i=-1;const o=e.passKeys?new Map:gv;for(;++io?0:o+t:t=t>o?o:t,n=n>0?n:0,i.length<1e4)s=Array.from(i),s.unshift(t,n),e.splice(...s);else for(n&&e.splice(t,n);l0?(pi(e,e.length,0,t),e):t}const E1={}.hasOwnProperty;function U2(e){const t={};let n=-1;for(;++n13&&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 Wi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Lr=To(/[A-Za-z]/),kr=To(/[\dA-Za-z]/),qv=To(/[#-'*+\--9=?A-Z^-~]/);function e0(e){return e!==null&&(e<32||e===127)}const Jf=To(/\d/),Hv=To(/[\dA-Fa-f]/),jv=To(/[!-/:-@[-`{-~]/);function wt(e){return e!==null&&e<-2}function cn(e){return e!==null&&(e<0||e===32)}function Yt(e){return e===-2||e===-1||e===32}const y0=To(new RegExp("\\p{P}|\\p{S}","u")),pl=To(/\s/);function To(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function ds(e){const t=[];let n=-1,i=0,o=0;for(;++n55295&&l<57344){const c=e.charCodeAt(n+1);l<56320&&c>56319&&c<57344?(s=String.fromCharCode(l,c),o=1):s="�"}else s=String.fromCharCode(l);s&&(t.push(e.slice(i,n),encodeURIComponent(s)),i=n+o+1,s=""),o&&(n+=o,o=0)}return t.join("")+e.slice(i)}function Wt(e,t,n,i){const o=i?i-1:Number.POSITIVE_INFINITY;let l=0;return s;function s(d){return Yt(d)?(e.enter(n),c(d)):t(d)}function c(d){return Yt(d)&&l++s))return;const ce=t.events.length;let Ne=ce,xe,Y;for(;Ne--;)if(t.events[Ne][0]==="exit"&&t.events[Ne][1].type==="chunkFlow"){if(xe){Y=t.events[Ne][1].end;break}xe=!0}for(R(i),V=ce;VF;){const le=n[ae];t.containerState=le[1],le[0].exit.call(t,e)}n.length=F}function L(){o.write([null]),l=void 0,o=void 0,t.containerState._closeFlow=void 0}}function Yv(e,t,n){return Wt(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function os(e){if(e===null||cn(e)||pl(e))return 1;if(y0(e))return 2}function v0(e,t,n){const i=[];let o=-1;for(;++o1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const g={...e[i][1].end},k={...e[n][1].start};_1(g,-d),_1(k,d),s={type:d>1?"strongSequence":"emphasisSequence",start:g,end:{...e[i][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:k},l={type:d>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[n][1].start}},o={type:d>1?"strong":"emphasis",start:{...s.start},end:{...c.end}},e[i][1].end={...s.start},e[n][1].start={...c.end},p=[],e[i][1].end.offset-e[i][1].start.offset&&(p=Oi(p,[["enter",e[i][1],t],["exit",e[i][1],t]])),p=Oi(p,[["enter",o,t],["enter",s,t],["exit",s,t],["enter",l,t]]),p=Oi(p,v0(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),p=Oi(p,[["exit",l,t],["enter",c,t],["exit",c,t],["exit",o,t]]),e[n][1].end.offset-e[n][1].start.offset?(y=2,p=Oi(p,[["enter",e[n][1],t],["exit",e[n][1],t]])):y=0,pi(e,i-1,n-i+3,p),n=i+p.length-y-2;break}}for(n=-1;++n0&&Yt(V)?Wt(e,L,"linePrefix",l+1)(V):L(V)}function L(V){return V===null||wt(V)?e.check(C1,N,ae)(V):(e.enter("codeFlowValue"),F(V))}function F(V){return V===null||wt(V)?(e.exit("codeFlowValue"),L(V)):(e.consume(V),F)}function ae(V){return e.exit("codeFenced"),t(V)}function le(V,ce,Ne){let xe=0;return Y;function Y(Re){return V.enter("lineEnding"),V.consume(Re),V.exit("lineEnding"),Se}function Se(Re){return V.enter("codeFencedFence"),Yt(Re)?Wt(V,_e,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(Re):_e(Re)}function _e(Re){return Re===c?(V.enter("codeFencedFenceSequence"),we(Re)):Ne(Re)}function we(Re){return Re===c?(xe++,V.consume(Re),we):xe>=s?(V.exit("codeFencedFenceSequence"),Yt(Re)?Wt(V,Te,"whitespace")(Re):Te(Re)):Ne(Re)}function Te(Re){return Re===null||wt(Re)?(V.exit("codeFencedFence"),ce(Re)):Ne(Re)}}}function lb(e,t,n){const i=this;return o;function o(s){return s===null?n(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),l)}function l(s){return i.parser.lazy[i.now().line]?n(s):t(s)}}const sf={name:"codeIndented",tokenize:ub},sb={partial:!0,tokenize:cb};function ub(e,t,n){const i=this;return o;function o(p){return e.enter("codeIndented"),Wt(e,l,"linePrefix",5)(p)}function l(p){const y=i.events[i.events.length-1];return y&&y[1].type==="linePrefix"&&y[2].sliceSerialize(y[1],!0).length>=4?s(p):n(p)}function s(p){return p===null?d(p):wt(p)?e.attempt(sb,s,d)(p):(e.enter("codeFlowValue"),c(p))}function c(p){return p===null||wt(p)?(e.exit("codeFlowValue"),s(p)):(e.consume(p),c)}function d(p){return e.exit("codeIndented"),t(p)}}function cb(e,t,n){const i=this;return o;function o(s){return i.parser.lazy[i.now().line]?n(s):wt(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),o):Wt(e,l,"linePrefix",5)(s)}function l(s){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?t(s):wt(s)?o(s):n(s)}}const db={name:"codeText",previous:hb,resolve:fb,tokenize:pb};function fb(e){let t=e.length-4,n=3,i,o;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(i=n;++i=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 tthis.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(t,n,i){const o=n||0;this.setCursor(Math.trunc(t));const l=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return i&&Vs(this.left,i),l.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),Vs(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Vs(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=4?t(s):e.interrupt(i.parser.constructs.flow,n,t)(s)}}function V2(e,t,n,i,o,l,s,c,d){const p=d||Number.POSITIVE_INFINITY;let y=0;return g;function g(R){return R===60?(e.enter(i),e.enter(o),e.enter(l),e.consume(R),e.exit(l),k):R===null||R===32||R===41||e0(R)?n(R):(e.enter(i),e.enter(s),e.enter(c),e.enter("chunkString",{contentType:"string"}),N(R))}function k(R){return R===62?(e.enter(l),e.consume(R),e.exit(l),e.exit(o),e.exit(i),t):(e.enter(c),e.enter("chunkString",{contentType:"string"}),x(R))}function x(R){return R===62?(e.exit("chunkString"),e.exit(c),k(R)):R===null||R===60||wt(R)?n(R):(e.consume(R),R===92?C:x)}function C(R){return R===60||R===62||R===92?(e.consume(R),x):x(R)}function N(R){return!y&&(R===null||R===41||cn(R))?(e.exit("chunkString"),e.exit(c),e.exit(s),e.exit(i),t(R)):y999||x===null||x===91||x===93&&!d||x===94&&!c&&"_hiddenFootnoteSupport"in s.parser.constructs?n(x):x===93?(e.exit(l),e.enter(o),e.consume(x),e.exit(o),e.exit(i),t):wt(x)?(e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),y):(e.enter("chunkString",{contentType:"string"}),g(x))}function g(x){return x===null||x===91||x===93||wt(x)||c++>999?(e.exit("chunkString"),y(x)):(e.consume(x),d||(d=!Yt(x)),x===92?k:g)}function k(x){return x===91||x===92||x===93?(e.consume(x),c++,g):g(x)}}function W2(e,t,n,i,o,l){let s;return c;function c(k){return k===34||k===39||k===40?(e.enter(i),e.enter(o),e.consume(k),e.exit(o),s=k===40?41:k,d):n(k)}function d(k){return k===s?(e.enter(o),e.consume(k),e.exit(o),e.exit(i),t):(e.enter(l),p(k))}function p(k){return k===s?(e.exit(l),d(s)):k===null?n(k):wt(k)?(e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),Wt(e,p,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),y(k))}function y(k){return k===s||k===null||wt(k)?(e.exit("chunkString"),p(k)):(e.consume(k),k===92?g:y)}function g(k){return k===s||k===92?(e.consume(k),y):y(k)}}function Qs(e,t){let n;return i;function i(o){return wt(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n=!0,i):Yt(o)?Wt(e,i,n?"linePrefix":"lineSuffix")(o):t(o)}}const xb={name:"definition",tokenize:Sb},Eb={partial:!0,tokenize:_b};function Sb(e,t,n){const i=this;let o;return l;function l(x){return e.enter("definition"),s(x)}function s(x){return G2.call(i,e,c,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(x)}function c(x){return o=Wi(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),d):n(x)}function d(x){return cn(x)?Qs(e,p)(x):p(x)}function p(x){return V2(e,y,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(x)}function y(x){return e.attempt(Eb,g,g)(x)}function g(x){return Yt(x)?Wt(e,k,"whitespace")(x):k(x)}function k(x){return x===null||wt(x)?(e.exit("definition"),i.parser.defined.push(o),t(x)):n(x)}}function _b(e,t,n){return i;function i(c){return cn(c)?Qs(e,o)(c):n(c)}function o(c){return W2(e,l,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function l(c){return Yt(c)?Wt(e,s,"whitespace")(c):s(c)}function s(c){return c===null||wt(c)?t(c):n(c)}}const Cb={name:"hardBreakEscape",tokenize:Tb};function Tb(e,t,n){return i;function i(l){return e.enter("hardBreakEscape"),e.consume(l),o}function o(l){return wt(l)?(e.exit("hardBreakEscape"),t(l)):n(l)}}const Nb={name:"headingAtx",resolve:Ab,tokenize:Mb};function Ab(e,t){let n=e.length-2,i=3,o,l;return e[i][1].type==="whitespace"&&(i+=2),n-2>i&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(i===n-1||n-4>i&&e[n-2][1].type==="whitespace")&&(n-=i+1===n?2:4),n>i&&(o={type:"atxHeadingText",start:e[i][1].start,end:e[n][1].end},l={type:"chunkText",start:e[i][1].start,end:e[n][1].end,contentType:"text"},pi(e,i,n-i+1,[["enter",o,t],["enter",l,t],["exit",l,t],["exit",o,t]])),e}function Mb(e,t,n){let i=0;return o;function o(y){return e.enter("atxHeading"),l(y)}function l(y){return e.enter("atxHeadingSequence"),s(y)}function s(y){return y===35&&i++<6?(e.consume(y),s):y===null||cn(y)?(e.exit("atxHeadingSequence"),c(y)):n(y)}function c(y){return y===35?(e.enter("atxHeadingSequence"),d(y)):y===null||wt(y)?(e.exit("atxHeading"),t(y)):Yt(y)?Wt(e,c,"whitespace")(y):(e.enter("atxHeadingText"),p(y))}function d(y){return y===35?(e.consume(y),d):(e.exit("atxHeadingSequence"),c(y))}function p(y){return y===null||y===35||cn(y)?(e.exit("atxHeadingText"),c(y)):(e.consume(y),p)}}const Rb=["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"],N1=["pre","script","style","textarea"],Ob={concrete:!0,name:"htmlFlow",resolveTo:Lb,tokenize:zb},Ib={partial:!0,tokenize:Bb},Db={partial:!0,tokenize:Pb};function Lb(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 zb(e,t,n){const i=this;let o,l,s,c,d;return p;function p(B){return y(B)}function y(B){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(B),g}function g(B){return B===33?(e.consume(B),k):B===47?(e.consume(B),l=!0,N):B===63?(e.consume(B),o=3,i.interrupt?t:z):Lr(B)?(e.consume(B),s=String.fromCharCode(B),D):n(B)}function k(B){return B===45?(e.consume(B),o=2,x):B===91?(e.consume(B),o=5,c=0,C):Lr(B)?(e.consume(B),o=4,i.interrupt?t:z):n(B)}function x(B){return B===45?(e.consume(B),i.interrupt?t:z):n(B)}function C(B){const gt="CDATA[";return B===gt.charCodeAt(c++)?(e.consume(B),c===gt.length?i.interrupt?t:_e:C):n(B)}function N(B){return Lr(B)?(e.consume(B),s=String.fromCharCode(B),D):n(B)}function D(B){if(B===null||B===47||B===62||cn(B)){const gt=B===47,ft=s.toLowerCase();return!gt&&!l&&N1.includes(ft)?(o=1,i.interrupt?t(B):_e(B)):Rb.includes(s.toLowerCase())?(o=6,gt?(e.consume(B),R):i.interrupt?t(B):_e(B)):(o=7,i.interrupt&&!i.parser.lazy[i.now().line]?n(B):l?L(B):F(B))}return B===45||kr(B)?(e.consume(B),s+=String.fromCharCode(B),D):n(B)}function R(B){return B===62?(e.consume(B),i.interrupt?t:_e):n(B)}function L(B){return Yt(B)?(e.consume(B),L):Y(B)}function F(B){return B===47?(e.consume(B),Y):B===58||B===95||Lr(B)?(e.consume(B),ae):Yt(B)?(e.consume(B),F):Y(B)}function ae(B){return B===45||B===46||B===58||B===95||kr(B)?(e.consume(B),ae):le(B)}function le(B){return B===61?(e.consume(B),V):Yt(B)?(e.consume(B),le):F(B)}function V(B){return B===null||B===60||B===61||B===62||B===96?n(B):B===34||B===39?(e.consume(B),d=B,ce):Yt(B)?(e.consume(B),V):Ne(B)}function ce(B){return B===d?(e.consume(B),d=null,xe):B===null||wt(B)?n(B):(e.consume(B),ce)}function Ne(B){return B===null||B===34||B===39||B===47||B===60||B===61||B===62||B===96||cn(B)?le(B):(e.consume(B),Ne)}function xe(B){return B===47||B===62||Yt(B)?F(B):n(B)}function Y(B){return B===62?(e.consume(B),Se):n(B)}function Se(B){return B===null||wt(B)?_e(B):Yt(B)?(e.consume(B),Se):n(B)}function _e(B){return B===45&&o===2?(e.consume(B),nt):B===60&&o===1?(e.consume(B),ct):B===62&&o===4?(e.consume(B),G):B===63&&o===3?(e.consume(B),z):B===93&&o===5?(e.consume(B),Ue):wt(B)&&(o===6||o===7)?(e.exit("htmlFlowData"),e.check(Ib,me,we)(B)):B===null||wt(B)?(e.exit("htmlFlowData"),we(B)):(e.consume(B),_e)}function we(B){return e.check(Db,Te,me)(B)}function Te(B){return e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),Re}function Re(B){return B===null||wt(B)?we(B):(e.enter("htmlFlowData"),_e(B))}function nt(B){return B===45?(e.consume(B),z):_e(B)}function ct(B){return B===47?(e.consume(B),s="",be):_e(B)}function be(B){if(B===62){const gt=s.toLowerCase();return N1.includes(gt)?(e.consume(B),G):_e(B)}return Lr(B)&&s.length<8?(e.consume(B),s+=String.fromCharCode(B),be):_e(B)}function Ue(B){return B===93?(e.consume(B),z):_e(B)}function z(B){return B===62?(e.consume(B),G):B===45&&o===2?(e.consume(B),z):_e(B)}function G(B){return B===null||wt(B)?(e.exit("htmlFlowData"),me(B)):(e.consume(B),G)}function me(B){return e.exit("htmlFlow"),t(B)}}function Pb(e,t,n){const i=this;return o;function o(s){return wt(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),l):n(s)}function l(s){return i.parser.lazy[i.now().line]?n(s):t(s)}}function Bb(e,t,n){return i;function i(o){return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),e.attempt(gu,t,n)}}const Fb={name:"htmlText",tokenize:Ub};function Ub(e,t,n){const i=this;let o,l,s;return c;function c(z){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(z),d}function d(z){return z===33?(e.consume(z),p):z===47?(e.consume(z),le):z===63?(e.consume(z),F):Lr(z)?(e.consume(z),Ne):n(z)}function p(z){return z===45?(e.consume(z),y):z===91?(e.consume(z),l=0,C):Lr(z)?(e.consume(z),L):n(z)}function y(z){return z===45?(e.consume(z),x):n(z)}function g(z){return z===null?n(z):z===45?(e.consume(z),k):wt(z)?(s=g,ct(z)):(e.consume(z),g)}function k(z){return z===45?(e.consume(z),x):g(z)}function x(z){return z===62?nt(z):z===45?k(z):g(z)}function C(z){const G="CDATA[";return z===G.charCodeAt(l++)?(e.consume(z),l===G.length?N:C):n(z)}function N(z){return z===null?n(z):z===93?(e.consume(z),D):wt(z)?(s=N,ct(z)):(e.consume(z),N)}function D(z){return z===93?(e.consume(z),R):N(z)}function R(z){return z===62?nt(z):z===93?(e.consume(z),R):N(z)}function L(z){return z===null||z===62?nt(z):wt(z)?(s=L,ct(z)):(e.consume(z),L)}function F(z){return z===null?n(z):z===63?(e.consume(z),ae):wt(z)?(s=F,ct(z)):(e.consume(z),F)}function ae(z){return z===62?nt(z):F(z)}function le(z){return Lr(z)?(e.consume(z),V):n(z)}function V(z){return z===45||kr(z)?(e.consume(z),V):ce(z)}function ce(z){return wt(z)?(s=ce,ct(z)):Yt(z)?(e.consume(z),ce):nt(z)}function Ne(z){return z===45||kr(z)?(e.consume(z),Ne):z===47||z===62||cn(z)?xe(z):n(z)}function xe(z){return z===47?(e.consume(z),nt):z===58||z===95||Lr(z)?(e.consume(z),Y):wt(z)?(s=xe,ct(z)):Yt(z)?(e.consume(z),xe):nt(z)}function Y(z){return z===45||z===46||z===58||z===95||kr(z)?(e.consume(z),Y):Se(z)}function Se(z){return z===61?(e.consume(z),_e):wt(z)?(s=Se,ct(z)):Yt(z)?(e.consume(z),Se):xe(z)}function _e(z){return z===null||z===60||z===61||z===62||z===96?n(z):z===34||z===39?(e.consume(z),o=z,we):wt(z)?(s=_e,ct(z)):Yt(z)?(e.consume(z),_e):(e.consume(z),Te)}function we(z){return z===o?(e.consume(z),o=void 0,Re):z===null?n(z):wt(z)?(s=we,ct(z)):(e.consume(z),we)}function Te(z){return z===null||z===34||z===39||z===60||z===61||z===96?n(z):z===47||z===62||cn(z)?xe(z):(e.consume(z),Te)}function Re(z){return z===47||z===62||cn(z)?xe(z):n(z)}function nt(z){return z===62?(e.consume(z),e.exit("htmlTextData"),e.exit("htmlText"),t):n(z)}function ct(z){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(z),e.exit("lineEnding"),be}function be(z){return Yt(z)?Wt(e,Ue,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(z):Ue(z)}function Ue(z){return e.enter("htmlTextData"),s(z)}}const Mh={name:"labelEnd",resolveAll:jb,resolveTo:Kb,tokenize:Vb},$b={tokenize:Gb},qb={tokenize:Wb},Hb={tokenize:Yb};function jb(e){let t=-1;const n=[];for(;++t=3&&(p===null||wt(p))?(e.exit("thematicBreak"),t(p)):n(p)}function d(p){return p===o?(e.consume(p),i++,d):(e.exit("thematicBreakSequence"),Yt(p)?Wt(e,c,"whitespace")(p):c(p))}}const Wr={continuation:{tokenize:a7},exit:l7,name:"list",tokenize:i7},n7={partial:!0,tokenize:s7},r7={partial:!0,tokenize:o7};function i7(e,t,n){const i=this,o=i.events[i.events.length-1];let l=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,s=0;return c;function c(x){const C=i.containerState.type||(x===42||x===43||x===45?"listUnordered":"listOrdered");if(C==="listUnordered"?!i.containerState.marker||x===i.containerState.marker:Jf(x)){if(i.containerState.type||(i.containerState.type=C,e.enter(C,{_container:!0})),C==="listUnordered")return e.enter("listItemPrefix"),x===42||x===45?e.check(Xc,n,p)(x):p(x);if(!i.interrupt||x===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(x)}return n(x)}function d(x){return Jf(x)&&++s<10?(e.consume(x),d):(!i.interrupt||s<2)&&(i.containerState.marker?x===i.containerState.marker:x===41||x===46)?(e.exit("listItemValue"),p(x)):n(x)}function p(x){return e.enter("listItemMarker"),e.consume(x),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||x,e.check(gu,i.interrupt?n:y,e.attempt(n7,k,g))}function y(x){return i.containerState.initialBlankLine=!0,l++,k(x)}function g(x){return Yt(x)?(e.enter("listItemPrefixWhitespace"),e.consume(x),e.exit("listItemPrefixWhitespace"),k):n(x)}function k(x){return i.containerState.size=l+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(x)}}function a7(e,t,n){const i=this;return i.containerState._closeFlow=void 0,e.check(gu,o,l);function o(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Wt(e,t,"listItemIndent",i.containerState.size+1)(c)}function l(c){return i.containerState.furtherBlankLines||!Yt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,s(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(r7,t,s)(c))}function s(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Wt(e,e.attempt(Wr,t,n),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function o7(e,t,n){const i=this;return Wt(e,o,"listItemIndent",i.containerState.size+1);function o(l){const s=i.events[i.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===i.containerState.size?t(l):n(l)}}function l7(e){e.exit(this.containerState.type)}function s7(e,t,n){const i=this;return Wt(e,o,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(l){const s=i.events[i.events.length-1];return!Yt(l)&&s&&s[1].type==="listItemPrefixWhitespace"?t(l):n(l)}}const A1={name:"setextUnderline",resolveTo:u7,tokenize:c7};function u7(e,t){let n=e.length,i,o,l;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){i=n;break}e[n][1].type==="paragraph"&&(o=n)}else e[n][1].type==="content"&&e.splice(n,1),!l&&e[n][1].type==="definition"&&(l=n);const s={type:"setextHeading",start:{...e[o][1].start},end:{...e[e.length-1][1].end}};return e[o][1].type="setextHeadingText",l?(e.splice(o,0,["enter",s,t]),e.splice(l+1,0,["exit",e[i][1],t]),e[i][1].end={...e[l][1].end}):e[i][1]=s,e.push(["exit",s,t]),e}function c7(e,t,n){const i=this;let o;return l;function l(p){let y=i.events.length,g;for(;y--;)if(i.events[y][1].type!=="lineEnding"&&i.events[y][1].type!=="linePrefix"&&i.events[y][1].type!=="content"){g=i.events[y][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||g)?(e.enter("setextHeadingLine"),o=p,s(p)):n(p)}function s(p){return e.enter("setextHeadingLineSequence"),c(p)}function c(p){return p===o?(e.consume(p),c):(e.exit("setextHeadingLineSequence"),Yt(p)?Wt(e,d,"lineSuffix")(p):d(p))}function d(p){return p===null||wt(p)?(e.exit("setextHeadingLine"),t(p)):n(p)}}const d7={tokenize:f7};function f7(e){const t=this,n=e.attempt(gu,i,e.attempt(this.parser.constructs.flowInitial,o,Wt(e,e.attempt(this.parser.constructs.flow,o,e.attempt(yb,o)),"linePrefix")));return n;function i(l){if(l===null){e.consume(l);return}return e.enter("lineEndingBlank"),e.consume(l),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function o(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const h7={resolveAll:X2()},p7=Y2("string"),m7=Y2("text");function Y2(e){return{resolveAll:X2(e==="text"?g7:void 0),tokenize:t};function t(n){const i=this,o=this.parser.constructs[e],l=n.attempt(o,s,c);return s;function s(y){return p(y)?l(y):c(y)}function c(y){if(y===null){n.consume(y);return}return n.enter("data"),n.consume(y),d}function d(y){return p(y)?(n.exit("data"),l(y)):(n.consume(y),d)}function p(y){if(y===null)return!0;const g=o[y];let k=-1;if(g)for(;++k-1){const c=s[0];typeof c=="string"?s[0]=c.slice(i):s.shift()}l>0&&s.push(e[o].slice(0,l))}return s}function A7(e,t){let n=-1;const i=[];let o;for(;++n0){const wn=xt.tokenStack[xt.tokenStack.length-1];(wn[1]||R1).call(xt,void 0,wn[0])}for(Ie.position={start:go(ke.length>0?ke[0][1].start:{line:1,column:1,offset:0}),end:go(ke.length>0?ke[ke.length-2][1].end:{line:1,column:1,offset:0})},Kt=-1;++Kt { interruptBuffer[0] = 0; }; `;let d0;const Ys=Yy?new Uint8Array(new SharedArrayBuffer(1)):null,Xy=()=>{d0||(d0=new Worker(URL.createObjectURL(new Blob([sC],{type:"text/javascript"}))))};mn.getConfig().pyIntepreterEnabled&&Xy();const uC=(e,t)=>{Xy();const n=Math.random()*1e8,i={};return Ys&&(Ys[0]=0),{donePromise:new Promise(s=>{d0.onmessage=c=>{const{error:d,stdOutAndErr:p,running:y}=c.data;if(n===c.data.id)if(y){t();return}else s(d?d.toString():p.join(` -`))},d0.postMessage({id:n,python:e,context:i,interruptBuffer:Ys})}),interrupt:()=>{console.log("Interrupting..."),console.trace(),Ys&&(Ys[0]=2)}}};function cC(){const{canvasData:e,setCanvasData:t}=Ha(),[n,i]=ee.useState((e==null?void 0:e.content)??""),[o,l]=ee.useState(!1),[s,c]=ee.useState(""),[d,p]=ee.useState(),[y,g]=ee.useState(!1),k=async x=>{d==null||d(),l(!0),c("Loading Pyodide...");const{donePromise:C,interrupt:N}=uC(x,()=>{c("Running..."),g(Yy)});p(()=>N);const D=await C;c(D),l(!1),g(!1)};return ee.useEffect(()=>{i((e==null?void 0:e.content)??""),k((e==null?void 0:e.content)??"")},[e==null?void 0:e.content]),(e==null?void 0:e.type)!==A0.PY_INTERPRETER?null:q.jsx("div",{className:"card bg-base-200 w-full h-full shadow-xl",children:q.jsxs("div",{className:"card-body",children:[q.jsxs("div",{className:"flex justify-between items-center mb-4",children:[q.jsx("span",{className:"text-lg font-bold",children:"Python Interpreter"}),q.jsx(lC,{className:"bg-base-100",onClick:()=>t(null)})]}),q.jsxs("div",{className:"grid grid-rows-3 gap-4 h-full",children:[q.jsx("textarea",{className:"textarea textarea-bordered w-full h-full font-mono",value:n,onChange:x=>i(x.target.value)}),q.jsxs("div",{className:"font-mono flex flex-col row-span-2",children:[q.jsxs("div",{className:"flex items-center mb-2",children:[q.jsxs("button",{className:"btn btn-sm bg-base-100",onClick:()=>k(n),disabled:o,children:[q.jsx(tC,{className:"h-6 w-6"})," Run"]}),y&&q.jsxs("button",{className:"btn btn-sm bg-base-100 ml-2",onClick:()=>d==null?void 0:d(),children:[q.jsx(aC,{className:"h-6 w-6"})," Stop"]}),q.jsx("span",{className:"grow text-right text-xs",children:q.jsx(Qc,{href:"https://github.com/ggerganov/llama.cpp/issues/11762",children:"Report a bug"})})]}),q.jsx("textarea",{className:"textarea textarea-bordered h-full dark-color",value:s,readOnly:!0})]})]})]})})}const dC=e=>{const[t,n]=ee.useState(null);return ee.useEffect(()=>{const i=o=>{var l;if(((l=o.data)==null?void 0:l.command)==="setText"){const s=o.data;e.setValue(s==null?void 0:s.text),s!=null&&s.context&&s.context.length>0&&n({type:"context",content:s.context}),e.focus()}};return window.addEventListener("message",i),()=>window.removeEventListener("message",i)},[e]),ee.useEffect(()=>{const i=o=>{o.key==="Escape"&&window.parent.postMessage({command:"escapePressed"},"*")};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[]),{extraContext:t,clearExtraContext:()=>n(null)}},fC="(min-width: 1024px)",jc=e=>{if(!e)return;if(!window.matchMedia(fC).matches){e.style.height="",e.style.maxHeight="";return}const n=window.getComputedStyle(e).maxHeight;e.style.maxHeight="none",e.style.height="auto",e.style.height=`${e.scrollHeight}px`,e.style.maxHeight=n};function hC(e){const[t,n]=ee.useState(e),i=ee.useRef(null);ee.useEffect(()=>{const l=i.current;l&&(typeof t=="string"&&t.length>0?(l.value=t,setTimeout(()=>jc(l),0),n("")):setTimeout(()=>jc(l),0))},[i,t]);const o=ee.useCallback(l=>{jc(l.currentTarget)},[]);return{value:()=>{var l;return((l=i.current)==null?void 0:l.value)??""},setValue:l=>{const s=i.current;s&&(s.value=l,setTimeout(()=>jc(s),0))},focus:()=>{i.current&&i.current.focus()},ref:i,onInput:o}}const qf={content(){const e=new URL(window.location.href);return e.searchParams.get("m")??e.searchParams.get("q")??""},shouldSend(){return new URL(window.location.href).searchParams.has("q")},clear(){P6(["m","q"])}};function pC(e,t){const n=mn.filterByLeafNodeId(e,t,!0),i=[],o=new Map;for(const s of e)o.set(s.id,s);const l=s=>{let c=o.get(s);for(;c&&c.children.length!==0;)c=o.get(c.children.at(-1)??-1);return(c==null?void 0:c.id)??-1};for(const s of n){const c=o.get(s.parent??-1);if(!c)continue;const d=c.children;s.type!=="root"&&i.push({msg:s,siblingLeafNodeIds:d.map(l),siblingCurrIdx:d.indexOf(s.id)})}return i}const dl=z6((e,t=80)=>{const n=document.getElementById("main-scroll");if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;(!e||i<50)&&setTimeout(()=>n.scrollTo({top:n.scrollHeight}),t)},80);function e2(){var V;const{viewingChat:e,sendMessage:t,isGenerating:n,stopGenerating:i,pendingMessages:o,canvasData:l,replaceMessageAndGenerate:s}=Ha(),c=hC(qf.content()),{extraContext:d,clearExtraContext:p}=dC(c),y=d?[d]:void 0,[g,k]=ee.useState(-1),x=ee.useMemo(()=>e?pC(e.messages,g):[],[g,e]),C=(e==null?void 0:e.conv.id)??null,N=o[C??""];ee.useEffect(()=>{k(-1),dl(!1,1)},[C]);const D=ce=>{ce&&k(ce),dl(!0)},R=async()=>{var xe;const ce=c.value();if(ce.trim().length===0||n(C??""))return;c.setValue(""),dl(!1),k(-1);const Ne=((xe=x.at(-1))==null?void 0:xe.msg.id)??null;await t(C,Ne,ce,y,D)||c.setValue(ce),p()},L=async(ce,Ne)=>{e&&(k(ce.id),dl(!1),await s(e.conv.id,ce.parent,Ne,ce.extra,D),k(-1),dl(!1))},F=async ce=>{e&&(k(ce.parent),dl(!1),await s(e.conv.id,ce.parent,null,ce.extra,D),k(-1),dl(!1))},ae=!!l;ee.useEffect(()=>{qf.shouldSend()?R():c.focus(),qf.clear()},[c.ref]);const le=N&&((V=x.at(-1))==null?void 0:V.msg.id)!==N.id?[{msg:N,siblingLeafNodeIds:[],siblingCurrIdx:0,isPending:!0}]:[];return q.jsxs("div",{className:Dr({"grid lg:gap-8 grow transition-[300ms]":!0,"grid-cols-[1fr_0fr] lg:grid-cols-[1fr_1fr]":ae,"grid-cols-[1fr_0fr]":!ae}),children:[q.jsxs("div",{className:Dr({"flex flex-col w-full max-w-[900px] mx-auto":!0,"hidden lg:flex":ae,flex:!ae}),children:[q.jsxs("div",{id:"messages-list",className:"grow",children:[q.jsx("div",{className:"mt-auto flex justify-center",children:e?"":"Send a message to start"}),[...x,...le].map(ce=>q.jsx(oC,{msg:ce.msg,siblingLeafNodeIds:ce.siblingLeafNodeIds,siblingCurrIdx:ce.siblingCurrIdx,onRegenerateMessage:F,onEditMessage:L,onChangeSibling:k},ce.msg.id))]}),q.jsxs("div",{className:"flex flex-row items-end pt-8 pb-6 sticky bottom-0 bg-base-100",children:[q.jsx("textarea",{className:"textarea textarea-bordered w-full resize-vertical lg:resize-none lg:max-h-48 lg:overflow-y-auto",placeholder:"Type a message (Shift+Enter to add a new line)",ref:c.ref,onInput:c.onInput,onKeyDown:ce=>{ce.nativeEvent.isComposing||ce.keyCode===229||ce.key==="Enter"&&!ce.shiftKey&&(ce.preventDefault(),R())},id:"msg-input",dir:"auto",rows:2}),n(C??"")?q.jsx("button",{className:"btn btn-neutral ml-2",onClick:()=>i(C??""),children:"Stop"}):q.jsx("button",{className:"btn btn-primary ml-2",onClick:R,children:"Send"})]})]}),q.jsx("div",{className:"w-full sticky top-[7em] h-[calc(100vh-9em)]",children:(l==null?void 0:l.type)===A0.PY_INTERPRETER&&q.jsx(cC,{})})]})}const mC=["temperature","top_k","top_p","min_p","max_tokens"],gC=["dynatemp_range","dynatemp_exponent","typical_p","xtc_probability","xtc_threshold"],yC=["repeat_last_n","repeat_penalty","presence_penalty","frequency_penalty","dry_multiplier","dry_base","dry_allowed_length","dry_penalty_last_n"],Jl="w-4 h-4 mr-1 inline",Kc=[{title:q.jsxs(q.Fragment,{children:[q.jsx(Y_,{className:Jl}),"General"]}),fields:[{type:0,label:"API Key",key:"apiKey"},{type:1,label:"System Message (will be disabled if left empty)",key:"systemMessage"},...mC.map(e=>({type:0,label:e,key:e}))]},{title:q.jsxs(q.Fragment,{children:[q.jsx(Z_,{className:Jl}),"Samplers"]}),fields:[{type:0,label:"Samplers queue",key:"samplers"},...gC.map(e=>({type:0,label:e,key:e}))]},{title:q.jsxs(q.Fragment,{children:[q.jsx(J_,{className:Jl}),"Penalties"]}),fields:yC.map(e=>({type:0,label:e,key:e}))},{title:q.jsxs(q.Fragment,{children:[q.jsx(H_,{className:Jl}),"Reasoning"]}),fields:[{type:2,label:"Expand thought process by default when generating messages",key:"showThoughtInProgress"},{type:2,label:"Exclude thought process when sending requests to API (Recommended for DeepSeek-R1)",key:"excludeThoughtOnReq"}]},{title:q.jsxs(q.Fragment,{children:[q.jsx(rC,{className:Jl}),"Advanced"]}),fields:[{type:3,key:"custom",component:()=>{const e=async()=>{const n=await(await fetch("/demo-conversation.json")).json();mn.remove(n.id);for(const i of n.messages)mn.appendMsg(n.id,i)};return q.jsx("button",{className:"btn",onClick:e,children:"(debug) Import demo conversation"})}},{type:2,label:"Show tokens per second",key:"showTokensPerSecond"},{type:1,label:q.jsxs(q.Fragment,{children:["Custom JSON config (For more info, refer to"," ",q.jsx(Qc,{href:"https://github.com/ggerganov/llama.cpp/blob/master/examples/server/README.md",children:"server documentation"}),")"]}),key:"custom"}]},{title:q.jsxs(q.Fragment,{children:[q.jsx($_,{className:Jl}),"Experimental"]}),fields:[{type:3,key:"custom",component:()=>q.jsx(q.Fragment,{children:q.jsxs("p",{className:"mb-8",children:["Experimental features are not guaranteed to work correctly.",q.jsx("br",{}),q.jsx("br",{}),"If you encounter any problems, create a"," ",q.jsx(Qc,{href:"https://github.com/ggerganov/llama.cpp/issues/new?template=019-bug-misc.yml",children:"Bug (misc.)"})," ","report on Github. Please also specify ",q.jsx("b",{children:"webui/experimental"})," on the report title and include screenshots.",q.jsx("br",{}),q.jsx("br",{}),"Some features may require packages downloaded from CDN, so they need internet connection."]})})},{type:2,label:q.jsxs(q.Fragment,{children:[q.jsx("b",{children:"Enable Python interpreter"}),q.jsx("br",{}),q.jsxs("small",{className:"text-xs",children:["This feature uses"," ",q.jsx(Qc,{href:"https://pyodide.org",children:"pyodide"}),', downloaded from CDN. To use this feature, ask the LLM to generate Python code inside a Markdown code block. You will see a "Run" button on the code block, near the "Copy" button.']})]}),key:"pyIntepreterEnabled"}]}];function vC({show:e,onClose:t}){const{config:n,saveConfig:i}=Ha(),[o,l]=ee.useState(0),[s,c]=ee.useState(JSON.parse(JSON.stringify(n))),d=()=>{window.confirm("Are you sure you want to reset all settings?")&&c(wo)},p=()=>{const g=JSON.parse(JSON.stringify(s));for(const k in g){const x=g[k],C=Gf(wo[k]),N=Vf(wo[k]),D=Wf(wo[k]);if(N){if(!Vf(x)){alert(`Value for ${k} must be string`);return}}else if(D){const R=x.toString().trim(),L=Number(R);if(isNaN(L)||!Wf(L)||R.length===0){alert(`Value for ${k} must be numeric`);return}g[k]=L}else if(C){if(!Gf(x)){alert(`Value for ${k} must be boolean`);return}}else console.error(`Unknown default type for key ${k}`)}i(g),t()},y=g=>k=>{c({...s,[g]:k})};return q.jsx("dialog",{className:Dr({modal:!0,"modal-open":e}),children:q.jsxs("div",{className:"modal-box w-11/12 max-w-3xl",children:[q.jsx("h3",{className:"text-lg font-bold mb-6",children:"Settings"}),q.jsxs("div",{className:"flex flex-col md:flex-row h-[calc(90vh-12rem)]",children:[q.jsx("div",{className:"hidden md:flex flex-col items-stretch pr-4 mr-4 border-r-2 border-base-200",children:Kc.map((g,k)=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal w-44 mb-1":!0,"btn-active":o===k}),onClick:()=>l(k),dir:"auto",children:g.title},k))}),q.jsx("div",{className:"md:hidden flex flex-row gap-2 mb-4",children:q.jsxs("details",{className:"dropdown",children:[q.jsx("summary",{className:"btn bt-sm w-full m-1",children:Kc[o].title}),q.jsx("ul",{className:"menu dropdown-content bg-base-100 rounded-box z-[1] w-52 p-2 shadow",children:Kc.map((g,k)=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal":!0,"btn-active":o===k}),onClick:()=>l(k),dir:"auto",children:g.title},k))})]})}),q.jsxs("div",{className:"grow overflow-y-auto px-4",children:[Kc[o].fields.map((g,k)=>{const x=`${o}-${k}`;if(g.type===0)return q.jsx(wC,{configKey:g.key,value:s[g.key],onChange:y(g.key),label:g.label},x);if(g.type===1)return q.jsx(bC,{configKey:g.key,value:s[g.key].toString(),onChange:y(g.key),label:g.label},x);if(g.type===2)return q.jsx(kC,{configKey:g.key,value:!!s[g.key],onChange:y(g.key),label:g.label},x);if(g.type===3)return q.jsx("div",{className:"mb-2",children:typeof g.component=="string"?g.component:g.component({value:s[g.key],onChange:y(g.key)})},x)}),q.jsx("p",{className:"opacity-40 mb-6 text-sm mt-8",children:"Settings are saved in browser's localStorage"})]})]}),q.jsxs("div",{className:"modal-action",children:[q.jsx("button",{className:"btn",onClick:d,children:"Reset to default"}),q.jsx("button",{className:"btn",onClick:t,children:"Close"}),q.jsx("button",{className:"btn btn-primary",onClick:p,children:"Save"})]})]})})}function bC({configKey:e,value:t,onChange:n,label:i}){return q.jsxs("label",{className:"form-control mb-2",children:[q.jsx("div",{className:"label inline",children:i||e}),q.jsx("textarea",{className:"textarea textarea-bordered h-24",placeholder:`Default: ${wo[e]||"none"}`,value:t,onChange:o=>n(o.target.value)})]})}function wC({configKey:e,value:t,onChange:n,label:i}){const o=U6[e];return q.jsxs(q.Fragment,{children:[o&&q.jsxs("div",{className:"block md:hidden mb-1",children:[q.jsx("b",{children:i||e}),q.jsx("br",{}),q.jsx("p",{className:"text-xs",children:o})]}),q.jsxs("label",{className:"input input-bordered join-item grow flex items-center gap-2 mb-2",children:[q.jsxs("div",{className:"dropdown dropdown-hover",children:[q.jsx("div",{tabIndex:0,role:"button",className:"font-bold hidden md:block",children:i||e}),o&&q.jsx("div",{className:"dropdown-content menu bg-base-100 rounded-box z-10 w-64 p-2 shadow mt-4",children:o})]}),q.jsx("input",{type:"text",className:"grow",placeholder:`Default: ${wo[e]||"none"}`,value:t,onChange:l=>n(l.target.value)})]})]})}function kC({configKey:e,value:t,onChange:n,label:i}){return q.jsxs("div",{className:"flex flex-row items-center mb-2",children:[q.jsx("input",{type:"checkbox",className:"toggle",checked:t,onChange:o=>n(o.target.checked)}),q.jsx("span",{className:"ml-4",children:i||e})]})}function xC(){return q.jsx(y6,{children:q.jsx("div",{className:"flex flex-row drawer lg:drawer-open",children:q.jsx(V6,{children:q.jsx(G3,{children:q.jsxs(Vc,{element:q.jsx(EC,{}),children:[q.jsx(Vc,{path:"/chat/:convId",element:q.jsx(e2,{})}),q.jsx(Vc,{path:"*",element:q.jsx(e2,{})})]})})})})})}function EC(){const{showSettings:e,setShowSettings:t}=Ha();return q.jsxs(q.Fragment,{children:[q.jsx(W6,{}),q.jsxs("div",{className:"drawer-content grow flex flex-col h-screen w-screen mx-auto px-4 overflow-auto bg-base-100",id:"main-scroll",children:[q.jsx(G6,{}),q.jsx(K3,{})]}),q.jsx(vC,{show:e,onClose:()=>t(!1)})]})}J5.createRoot(document.getElementById("root")).render(q.jsx(ee.StrictMode,{children:q.jsx(xC,{})})); - +`))},d0.postMessage({id:n,python:e,context:i,interruptBuffer:Ys})}),interrupt:()=>{console.log("Interrupting..."),console.trace(),Ys&&(Ys[0]=2)}}};function cC(){const{canvasData:e,setCanvasData:t}=Ha(),[n,i]=ee.useState((e==null?void 0:e.content)??""),[o,l]=ee.useState(!1),[s,c]=ee.useState(""),[d,p]=ee.useState(),[y,g]=ee.useState(!1),k=async x=>{d==null||d(),l(!0),c("Loading Pyodide...");const{donePromise:C,interrupt:N}=uC(x,()=>{c("Running..."),g(Yy)});p(()=>N);const D=await C;c(D),l(!1),g(!1)};return ee.useEffect(()=>{i((e==null?void 0:e.content)??""),k((e==null?void 0:e.content)??"")},[e==null?void 0:e.content]),(e==null?void 0:e.type)!==A0.PY_INTERPRETER?null:q.jsx("div",{className:"card bg-base-200 w-full h-full shadow-xl",children:q.jsxs("div",{className:"card-body",children:[q.jsxs("div",{className:"flex justify-between items-center mb-4",children:[q.jsx("span",{className:"text-lg font-bold",children:"Python Interpreter"}),q.jsx(lC,{className:"bg-base-100",onClick:()=>t(null)})]}),q.jsxs("div",{className:"grid grid-rows-3 gap-4 h-full",children:[q.jsx("textarea",{className:"textarea textarea-bordered w-full h-full font-mono",value:n,onChange:x=>i(x.target.value)}),q.jsxs("div",{className:"font-mono flex flex-col row-span-2",children:[q.jsxs("div",{className:"flex items-center mb-2",children:[q.jsxs("button",{className:"btn btn-sm bg-base-100",onClick:()=>k(n),disabled:o,children:[q.jsx(tC,{className:"h-6 w-6"})," Run"]}),y&&q.jsxs("button",{className:"btn btn-sm bg-base-100 ml-2",onClick:()=>d==null?void 0:d(),children:[q.jsx(aC,{className:"h-6 w-6"})," Stop"]}),q.jsx("span",{className:"grow text-right text-xs",children:q.jsx(Qc,{href:"https://github.com/ggerganov/llama.cpp/issues/11762",children:"Report a bug"})})]}),q.jsx("textarea",{className:"textarea textarea-bordered h-full dark-color",value:s,readOnly:!0})]})]})]})})}const dC=e=>{const[t,n]=ee.useState(null);return ee.useEffect(()=>{const i=o=>{var l;if(((l=o.data)==null?void 0:l.command)==="setText"){const s=o.data;e.setValue(s==null?void 0:s.text),s!=null&&s.context&&s.context.length>0&&n({type:"context",content:s.context}),e.focus()}};return window.addEventListener("message",i),()=>window.removeEventListener("message",i)},[e]),ee.useEffect(()=>{const i=o=>{o.key==="Escape"&&window.parent.postMessage({command:"escapePressed"},"*")};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[]),{extraContext:t,clearExtraContext:()=>n(null)}},fC="(min-width: 1024px)",jc=e=>{if(!e)return;if(!window.matchMedia(fC).matches){e.style.height="",e.style.maxHeight="";return}const n=window.getComputedStyle(e).maxHeight;e.style.maxHeight="none",e.style.height="auto",e.style.height=`${e.scrollHeight}px`,e.style.maxHeight=n};function hC(e){const[t,n]=ee.useState(e),i=ee.useRef(null);ee.useEffect(()=>{const l=i.current;l&&(typeof t=="string"&&t.length>0?(l.value=t,setTimeout(()=>jc(l),0),n("")):setTimeout(()=>jc(l),0))},[i,t]);const o=ee.useCallback(l=>{jc(l.currentTarget)},[]);return{value:()=>{var l;return((l=i.current)==null?void 0:l.value)??""},setValue:l=>{const s=i.current;s&&(s.value=l,setTimeout(()=>jc(s),0))},focus:()=>{i.current&&i.current.focus()},ref:i,onInput:o}}const qf={content(){const e=new URL(window.location.href);return e.searchParams.get("m")??e.searchParams.get("q")??""},shouldSend(){return new URL(window.location.href).searchParams.has("q")},clear(){P6(["m","q"])}};function pC(e,t){const n=mn.filterByLeafNodeId(e,t,!0),i=[],o=new Map;for(const s of e)o.set(s.id,s);const l=s=>{let c=o.get(s);for(;c&&c.children.length!==0;)c=o.get(c.children.at(-1)??-1);return(c==null?void 0:c.id)??-1};for(const s of n){const c=o.get(s.parent??-1);if(!c)continue;const d=c.children;s.type!=="root"&&i.push({msg:s,siblingLeafNodeIds:d.map(l),siblingCurrIdx:d.indexOf(s.id)})}return i}const dl=z6((e,t=80)=>{const n=document.getElementById("main-scroll");if(!n)return;const i=n.scrollHeight-n.scrollTop-n.clientHeight;(!e||i<50)&&setTimeout(()=>n.scrollTo({top:n.scrollHeight}),t)},80);function e2(){var V;const{viewingChat:e,sendMessage:t,isGenerating:n,stopGenerating:i,pendingMessages:o,canvasData:l,replaceMessageAndGenerate:s}=Ha(),c=hC(qf.content()),{extraContext:d,clearExtraContext:p}=dC(c),y=d?[d]:void 0,[g,k]=ee.useState(-1),x=ee.useMemo(()=>e?pC(e.messages,g):[],[g,e]),C=(e==null?void 0:e.conv.id)??null,N=o[C??""];ee.useEffect(()=>{k(-1),dl(!1,1)},[C]);const D=ce=>{ce&&k(ce),dl(!0)},R=async()=>{var xe;const ce=c.value();if(ce.trim().length===0||n(C??""))return;c.setValue(""),dl(!1),k(-1);const Ne=((xe=x.at(-1))==null?void 0:xe.msg.id)??null;await t(C,Ne,ce,y,D)||c.setValue(ce),p()},L=async(ce,Ne)=>{e&&(k(ce.id),dl(!1),await s(e.conv.id,ce.parent,Ne,ce.extra,D),k(-1),dl(!1))},F=async ce=>{e&&(k(ce.parent),dl(!1),await s(e.conv.id,ce.parent,null,ce.extra,D),k(-1),dl(!1))},ae=!!l;ee.useEffect(()=>{qf.shouldSend()?R():c.focus(),qf.clear()},[c.ref]);const le=N&&((V=x.at(-1))==null?void 0:V.msg.id)!==N.id?[{msg:N,siblingLeafNodeIds:[],siblingCurrIdx:0,isPending:!0}]:[];return q.jsxs("div",{className:Dr({"grid lg:gap-8 grow transition-[300ms]":!0,"grid-cols-[1fr_0fr] lg:grid-cols-[1fr_1fr]":ae,"grid-cols-[1fr_0fr]":!ae}),children:[q.jsxs("div",{className:Dr({"flex flex-col w-full max-w-[900px] mx-auto":!0,"hidden lg:flex":ae,flex:!ae}),children:[q.jsxs("div",{id:"messages-list",className:"grow",children:[q.jsx("div",{className:"mt-auto flex justify-center",children:e?"":"Send a message to start"}),[...x,...le].map(ce=>q.jsx(oC,{msg:ce.msg,siblingLeafNodeIds:ce.siblingLeafNodeIds,siblingCurrIdx:ce.siblingCurrIdx,onRegenerateMessage:F,onEditMessage:L,onChangeSibling:k},ce.msg.id))]}),q.jsxs("div",{className:"flex flex-row items-end pt-8 pb-6 sticky bottom-0 bg-base-100",children:[q.jsx("textarea",{className:"textarea textarea-bordered w-full resize-vertical lg:resize-none lg:max-h-48 lg:overflow-y-auto",placeholder:"Type a message (Shift+Enter to add a new line)",ref:c.ref,onInput:c.onInput,onKeyDown:ce=>{ce.nativeEvent.isComposing||ce.keyCode===229||ce.key==="Enter"&&!ce.shiftKey&&(ce.preventDefault(),R())},id:"msg-input",dir:"auto",rows:2}),n(C??"")?q.jsx("button",{className:"btn btn-neutral ml-2",onClick:()=>i(C??""),children:"Stop"}):q.jsx("button",{className:"btn btn-primary ml-2",onClick:R,children:"Send"})]})]}),q.jsx("div",{className:"w-full sticky top-[7em] h-[calc(100vh-9em)]",children:(l==null?void 0:l.type)===A0.PY_INTERPRETER&&q.jsx(cC,{})})]})}const mC=["temperature","top_k","top_p","min_p","max_tokens"],gC=["dynatemp_range","dynatemp_exponent","typical_p","xtc_probability","xtc_threshold","top_n_sigma"],yC=["repeat_last_n","repeat_penalty","presence_penalty","frequency_penalty","dry_multiplier","dry_base","dry_allowed_length","dry_penalty_last_n"],Jl="w-4 h-4 mr-1 inline",Kc=[{title:q.jsxs(q.Fragment,{children:[q.jsx(Y_,{className:Jl}),"General"]}),fields:[{type:0,label:"API Key",key:"apiKey"},{type:1,label:"System Message (will be disabled if left empty)",key:"systemMessage"},...mC.map(e=>({type:0,label:e,key:e}))]},{title:q.jsxs(q.Fragment,{children:[q.jsx(Z_,{className:Jl}),"Samplers"]}),fields:[{type:0,label:"Samplers queue",key:"samplers"},...gC.map(e=>({type:0,label:e,key:e}))]},{title:q.jsxs(q.Fragment,{children:[q.jsx(J_,{className:Jl}),"Penalties"]}),fields:yC.map(e=>({type:0,label:e,key:e}))},{title:q.jsxs(q.Fragment,{children:[q.jsx(H_,{className:Jl}),"Reasoning"]}),fields:[{type:2,label:"Expand thought process by default when generating messages",key:"showThoughtInProgress"},{type:2,label:"Exclude thought process when sending requests to API (Recommended for DeepSeek-R1)",key:"excludeThoughtOnReq"}]},{title:q.jsxs(q.Fragment,{children:[q.jsx(rC,{className:Jl}),"Advanced"]}),fields:[{type:3,key:"custom",component:()=>{const e=async()=>{const n=await(await fetch("/demo-conversation.json")).json();mn.remove(n.id);for(const i of n.messages)mn.appendMsg(n.id,i)};return q.jsx("button",{className:"btn",onClick:e,children:"(debug) Import demo conversation"})}},{type:2,label:"Show tokens per second",key:"showTokensPerSecond"},{type:1,label:q.jsxs(q.Fragment,{children:["Custom JSON config (For more info, refer to"," ",q.jsx(Qc,{href:"https://github.com/ikawrakow/ik_llama.cpp/tree/main/examples/server/README.md",children:"server documentation"}),")"]}),key:"custom"}]},{title:q.jsxs(q.Fragment,{children:[q.jsx($_,{className:Jl}),"Experimental"]}),fields:[{type:3,key:"custom",component:()=>q.jsx(q.Fragment,{children:q.jsxs("p",{className:"mb-8",children:["Experimental features are not guaranteed to work correctly.",q.jsx("br",{}),q.jsx("br",{}),"If you encounter any problems, create a"," ",q.jsx(Qc,{href:"https://github.com/ikawrakow/ik_llama.cpp/issues/new?template=019-bug-misc.yml",children:"Bug (misc.)"})," ","report on Github. Please also specify ",q.jsx("b",{children:"webui/experimental"})," on the report title and include screenshots.",q.jsx("br",{}),q.jsx("br",{}),"Some features may require packages downloaded from CDN, so they need internet connection."]})})},{type:2,label:q.jsxs(q.Fragment,{children:[q.jsx("b",{children:"Enable Python interpreter"}),q.jsx("br",{}),q.jsxs("small",{className:"text-xs",children:["This feature uses"," ",q.jsx(Qc,{href:"https://pyodide.org",children:"pyodide"}),', downloaded from CDN. To use this feature, ask the LLM to generate Python code inside a Markdown code block. You will see a "Run" button on the code block, near the "Copy" button.']})]}),key:"pyIntepreterEnabled"}]}];function vC({show:e,onClose:t}){const{config:n,saveConfig:i}=Ha(),[o,l]=ee.useState(0),[s,c]=ee.useState(JSON.parse(JSON.stringify(n))),d=()=>{window.confirm("Are you sure you want to reset all settings?")&&c(wo)},p=()=>{const g=JSON.parse(JSON.stringify(s));for(const k in g){const x=g[k],C=Gf(wo[k]),N=Vf(wo[k]),D=Wf(wo[k]);if(N){if(!Vf(x)){alert(`Value for ${k} must be string`);return}}else if(D){const R=x.toString().trim(),L=Number(R);if(isNaN(L)||!Wf(L)||R.length===0){alert(`Value for ${k} must be numeric`);return}g[k]=L}else if(C){if(!Gf(x)){alert(`Value for ${k} must be boolean`);return}}else console.error(`Unknown default type for key ${k}`)}i(g),t()},y=g=>k=>{c({...s,[g]:k})};return q.jsx("dialog",{className:Dr({modal:!0,"modal-open":e}),children:q.jsxs("div",{className:"modal-box w-11/12 max-w-3xl",children:[q.jsx("h3",{className:"text-lg font-bold mb-6",children:"Settings"}),q.jsxs("div",{className:"flex flex-col md:flex-row h-[calc(90vh-12rem)]",children:[q.jsx("div",{className:"hidden md:flex flex-col items-stretch pr-4 mr-4 border-r-2 border-base-200",children:Kc.map((g,k)=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal w-44 mb-1":!0,"btn-active":o===k}),onClick:()=>l(k),dir:"auto",children:g.title},k))}),q.jsx("div",{className:"md:hidden flex flex-row gap-2 mb-4",children:q.jsxs("details",{className:"dropdown",children:[q.jsx("summary",{className:"btn bt-sm w-full m-1",children:Kc[o].title}),q.jsx("ul",{className:"menu dropdown-content bg-base-100 rounded-box z-[1] w-52 p-2 shadow",children:Kc.map((g,k)=>q.jsx("div",{className:Dr({"btn btn-ghost justify-start font-normal":!0,"btn-active":o===k}),onClick:()=>l(k),dir:"auto",children:g.title},k))})]})}),q.jsxs("div",{className:"grow overflow-y-auto px-4",children:[Kc[o].fields.map((g,k)=>{const x=`${o}-${k}`;if(g.type===0)return q.jsx(wC,{configKey:g.key,value:s[g.key],onChange:y(g.key),label:g.label},x);if(g.type===1)return q.jsx(bC,{configKey:g.key,value:s[g.key].toString(),onChange:y(g.key),label:g.label},x);if(g.type===2)return q.jsx(kC,{configKey:g.key,value:!!s[g.key],onChange:y(g.key),label:g.label},x);if(g.type===3)return q.jsx("div",{className:"mb-2",children:typeof g.component=="string"?g.component:g.component({value:s[g.key],onChange:y(g.key)})},x)}),q.jsx("p",{className:"opacity-40 mb-6 text-sm mt-8",children:"Settings are saved in browser's localStorage"})]})]}),q.jsxs("div",{className:"modal-action",children:[q.jsx("button",{className:"btn",onClick:d,children:"Reset to default"}),q.jsx("button",{className:"btn",onClick:t,children:"Close"}),q.jsx("button",{className:"btn btn-primary",onClick:p,children:"Save"})]})]})})}function bC({configKey:e,value:t,onChange:n,label:i}){return q.jsxs("label",{className:"form-control mb-2",children:[q.jsx("div",{className:"label inline",children:i||e}),q.jsx("textarea",{className:"textarea textarea-bordered h-24",placeholder:`Default: ${wo[e]||"none"}`,value:t,onChange:o=>n(o.target.value)})]})}function wC({configKey:e,value:t,onChange:n,label:i}){const o=U6[e];return q.jsxs(q.Fragment,{children:[o&&q.jsxs("div",{className:"block md:hidden mb-1",children:[q.jsx("b",{children:i||e}),q.jsx("br",{}),q.jsx("p",{className:"text-xs whitespace-normal",children:o})]}),q.jsxs("label",{className:"input input-bordered join-item grow flex items-center gap-2 mb-2",children:[q.jsxs("div",{className:"dropdown dropdown-hover",children:[q.jsx("div",{tabIndex:0,role:"button",className:"font-bold hidden md:block",children:i||e}),o&&q.jsx("div",{className:"dropdown-content menu bg-base-100 rounded-box z-10 w-64 p-2 shadow mt-4 whitespace-normal break-words",children:o})]}),q.jsx("input",{type:"text",className:"grow",placeholder:`Default: ${wo[e]||"none"}`,value:t,onChange:l=>n(l.target.value)})]})]})}function kC({configKey:e,value:t,onChange:n,label:i}){return q.jsxs("div",{className:"flex flex-row items-center mb-2",children:[q.jsx("input",{type:"checkbox",className:"toggle",checked:t,onChange:o=>n(o.target.checked)}),q.jsx("span",{className:"ml-4",children:i||e})]})}function xC(){return q.jsx(y6,{children:q.jsx("div",{className:"flex flex-row drawer lg:drawer-open",children:q.jsx(V6,{children:q.jsx(G3,{children:q.jsxs(Vc,{element:q.jsx(EC,{}),children:[q.jsx(Vc,{path:"/chat/:convId",element:q.jsx(e2,{})}),q.jsx(Vc,{path:"*",element:q.jsx(e2,{})})]})})})})})}function EC(){const{showSettings:e,setShowSettings:t}=Ha();return q.jsxs(q.Fragment,{children:[q.jsx(W6,{}),q.jsxs("div",{className:"drawer-content grow flex flex-col h-screen w-screen mx-auto px-4 overflow-auto bg-base-100",id:"main-scroll",children:[q.jsx(G6,{}),q.jsx(K3,{})]}),q.jsx(vC,{show:e,onClose:()=>t(!1)})]})}J5.createRoot(document.getElementById("root")).render(q.jsx(ee.StrictMode,{children:q.jsx(xC,{})})); +
diff --git a/examples/server/webui/src/Config.ts b/examples/server/webui/src/Config.ts index f40ed30c..35411def 100644 --- a/examples/server/webui/src/Config.ts +++ b/examples/server/webui/src/Config.ts @@ -17,7 +17,7 @@ export const CONFIG_DEFAULT = { showThoughtInProgress: false, excludeThoughtOnReq: true, // make sure these default values are in sync with `common.h` - samplers: 'dkypmxt', + samplers: 'dkypmxnt', temperature: 0.8, dynatemp_range: 0.0, dynatemp_exponent: 1.0, @@ -26,6 +26,7 @@ export const CONFIG_DEFAULT = { min_p: 0.05, xtc_probability: 0.0, xtc_threshold: 0.1, + top_n_sigma: 0.0, typical_p: 1.0, repeat_last_n: 64, repeat_penalty: 1.0, @@ -44,7 +45,7 @@ export const CONFIG_INFO: Record = { apiKey: 'Set the API Key if you are using --api-key option for the server.', systemMessage: 'The starting message that defines how model should behave.', samplers: - 'The order at which samplers are applied, in simplified way. Default is "dkypmxt": dry->top_k->typ_p->top_p->min_p->xtc->temperature', + 'The order at which samplers are applied, in simplified way. Default is "dkypmxt": dry->top_k->typ_p->top_p->min_p->xtc->top_sigma->temperature', temperature: 'Controls the randomness of the generated text by affecting the probability distribution of the output tokens. Higher = more random, lower = more focused.', dynatemp_range: @@ -60,6 +61,8 @@ export const CONFIG_INFO: Record = { 'XTC sampler cuts out top tokens; this parameter controls the chance of cutting tokens at all. 0 disables XTC.', xtc_threshold: 'XTC sampler cuts out top tokens; this parameter controls the token probability that is required to cut that token.', + top_n_sigma: + 'Top-n-sigma sampling filters out low-value tokens by discarding tokens that fall more than n standard deviations below the maximum probability', typical_p: 'Sorts and limits tokens based on the difference between log-probability and entropy.', repeat_last_n: 'Last n tokens to consider for penalizing repetition', diff --git a/examples/server/webui/src/components/Header.tsx b/examples/server/webui/src/components/Header.tsx index 4c6b291e..84fea191 100644 --- a/examples/server/webui/src/components/Header.tsx +++ b/examples/server/webui/src/components/Header.tsx @@ -70,7 +70,7 @@ export default function Header() { -
llama.cpp
+
ik_llama.cpp
{/* action buttons (top right) */}
diff --git a/examples/server/webui/src/components/SettingDialog.tsx b/examples/server/webui/src/components/SettingDialog.tsx index b65e73ae..cd091a55 100644 --- a/examples/server/webui/src/components/SettingDialog.tsx +++ b/examples/server/webui/src/components/SettingDialog.tsx @@ -29,6 +29,7 @@ const SAMPLER_KEYS: SettKey[] = [ 'typical_p', 'xtc_probability', 'xtc_threshold', + 'top_n_sigma' ]; const PENALTY_KEYS: SettKey[] = [ 'repeat_last_n', @@ -196,7 +197,7 @@ const SETTING_SECTIONS: SettingSection[] = [ label: ( <> Custom JSON config (For more info, refer to{' '} - + server documentation ) @@ -224,7 +225,7 @@ const SETTING_SECTIONS: SettingSection[] = [

If you encounter any problems, create a{' '} - + Bug (misc.) {' '} report on Github. Please also specify webui/experimental on @@ -456,11 +457,11 @@ function SettingsModalLongInput({
{label || configKey}