0&&(p+=y,le)))for(r=0;r=a)continue;(o>0||e.hskipBeforeAndAfter)&&(i=l.deflt(c.pregap,u),0!==i&&(z=Ve.makeSpan(["arraycolsep"],[]),z.style.width=F(i),M.push(z)));let d=[];for(r=0;r0){const e=Ve.makeLineSpan("hline",t,m),r=Ve.makeLineSpan("hdashline",t,m),n=[{type:"elem",elem:h,shift:0}];for(;c.length>0;){const t=c.pop(),o=t.pos-k;t.isDashed?n.push({type:"elem",elem:r,shift:o}):n.push({type:"elem",elem:e,shift:o})}h=Ve.makeVList({positionType:"individualShift",children:n},t)}if(0===T.length)return Ve.makeSpan(["mord"],[h],t);{let e=Ve.makeVList({positionType:"individualShift",children:T},t);return e=Ve.makeSpan(["tag"],[e],t),Ve.makeFragment([h,e])}},Lr={c:"center ",l:"left ",r:"right "},Dr=function(e,t){const r=[],n=new gt.MathNode("mtd",[],["mtr-glue"]),o=new gt.MathNode("mtd",[],["mml-eqn-num"]);for(let s=0;s0){const t=e.cols;let r="",n=!1,o=0,i=t.length;"separator"===t[0].type&&(a+="top ",o=1),"separator"===t[t.length-1].type&&(a+="bottom ",i-=1);for(let e=o;e0?"left ":"",a+=c[c.length-1].length>0?"right ":"";for(let e=1;e-1?"alignat":"align",s="split"===e.envName,i=Hr(e.parser,{cols:r,addJot:!0,autoTag:s?void 0:Rr(e.envName),emptySingleRow:!0,colSeparationType:o,maxNumCols:s?2:void 0,leqno:e.parser.settings.leqno},"display");let a,l=0;const h={type:"ordgroup",mode:e.mode,body:[]};if(t[0]&&"ordgroup"===t[0].type){let e="";for(let r=0;r0&&c&&(n=1),r[e]={type:"align",align:t,pregap:n,postgap:0}}return i.colSeparationType=c?"align":"alignat",i};Ar({type:"array",names:["array","darray"],props:{numArgs:1},handler(e,t){const r=(Rt(t[0])?[t[0]]:qt(t[0],"ordgroup").body).map((function(e){const t=It(e).text;if(-1!=="lcr".indexOf(t))return{type:"align",align:t};if("|"===t)return{type:"separator",separator:"|"};if(":"===t)return{type:"separator",separator:":"};throw new n("Unknown column alignment: "+t,e)})),o={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return Hr(e.parser,o,Or(e.envName))},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(e){const t={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[e.envName.replace("*","")];let r="c";const o={hskipBeforeAndAfter:!1,cols:[{type:"align",align:r}]};if("*"===e.envName.charAt(e.envName.length-1)){const t=e.parser;if(t.consumeSpaces(),"["===t.fetch().text){if(t.consume(),t.consumeSpaces(),r=t.fetch().text,-1==="lcr".indexOf(r))throw new n("Expected l or c or r",t.nextToken);t.consume(),t.consumeSpaces(),t.expect("]"),t.consume(),o.cols=[{type:"align",align:r}]}}const s=Hr(e.parser,o,Or(e.envName)),i=Math.max(0,...s.body.map((e=>e.length)));return s.cols=new Array(i).fill({type:"align",align:r}),t?{type:"leftright",mode:e.mode,body:[s],left:t[0],right:t[1],rightColor:void 0}:s},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(e){const t=Hr(e.parser,{arraystretch:.5},"script");return t.colSeparationType="small",t},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["subarray"],props:{numArgs:1},handler(e,t){const r=(Rt(t[0])?[t[0]]:qt(t[0],"ordgroup").body).map((function(e){const t=It(e).text;if(-1!=="lc".indexOf(t))return{type:"align",align:t};throw new n("Unknown column alignment: "+t,e)}));if(r.length>1)throw new n("{subarray} can contain only one column");let o={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5};if(o=Hr(e.parser,o,"script"),o.body.length>0&&o.body[0].length>1)throw new n("{subarray} can contain only one column");return o},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(e){const t=Hr(e.parser,{arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},Or(e.envName));return{type:"leftright",mode:e.mode,body:[t],left:e.envName.indexOf("r")>-1?".":"\\{",right:e.envName.indexOf("r")>-1?"\\}":".",rightColor:void 0}},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:Vr,htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(e){l.contains(["gather","gather*"],e.envName)&&Ir(e);const t={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:Rr(e.envName),emptySingleRow:!0,leqno:e.parser.settings.leqno};return Hr(e.parser,t,"display")},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:Vr,htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(e){Ir(e);const t={autoTag:Rr(e.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:e.parser.settings.leqno};return Hr(e.parser,t,"display")},htmlBuilder:Er,mathmlBuilder:Dr}),Ar({type:"array",names:["CD"],props:{numArgs:0},handler(e){return Ir(e),function(e){const t=[];for(e.gullet.beginGroup(),e.gullet.macros.set("\\cr","\\\\\\relax"),e.gullet.beginGroup();;){t.push(e.parseExpression(!1,"\\\\")),e.gullet.endGroup(),e.gullet.beginGroup();const r=e.fetch().text;if("&"!==r&&"\\\\"!==r){if("\\end"===r){0===t[t.length-1].length&&t.pop();break}throw new n("Expected \\\\ or \\cr or \\end",e.nextToken)}e.consume()}let r=[];const o=[r];for(let a=0;a-1);else{if(!("<>AV".indexOf(o)>-1))throw new n('Expected one of "<>AV=|." after @',l[t]);for(let e=0;e<2;e++){let r=!0;for(let h=t+1;h{const r=e.font,n=t.withFont(r);return ht(e.body,n)},Gr=(e,t)=>{const r=e.font,n=t.withFont(r);return vt(e.body,n)},Ur={"\\Bbb":"\\mathbb","\\bold":"\\mathbf","\\frak":"\\mathfrak","\\bm":"\\boldsymbol"};je({type:"font",names:["\\mathrm","\\mathit","\\mathbf","\\mathnormal","\\mathbb","\\mathcal","\\mathfrak","\\mathscr","\\mathsf","\\mathtt","\\Bbb","\\bold","\\frak"],props:{numArgs:1,allowedInArgument:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=Ze(t[0]);let s=n;return s in Ur&&(s=Ur[s]),{type:"font",mode:r.mode,font:s.slice(1),body:o}},htmlBuilder:Fr,mathmlBuilder:Gr}),je({type:"mclass",names:["\\boldsymbol","\\bm"],props:{numArgs:1},handler:(e,t)=>{let{parser:r}=e;const n=t[0],o=l.isCharacterBox(n);return{type:"mclass",mode:r.mode,mclass:Ft(n),body:[{type:"font",mode:r.mode,font:"boldsymbol",body:n}],isCharacterBox:o}}}),je({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{let{parser:r,funcName:n,breakOnTokenText:o}=e;const{mode:s}=r,i=r.parseExpression(!0,o);return{type:"font",mode:s,font:"math"+n.slice(1),body:{type:"ordgroup",mode:r.mode,body:i}}},htmlBuilder:Fr,mathmlBuilder:Gr});const Yr=(e,t)=>{let r=t;return"display"===e?r=r.id>=w.SCRIPT.id?r.text():w.DISPLAY:"text"===e&&r.size===w.DISPLAY.size?r=w.TEXT:"script"===e?r=w.SCRIPT:"scriptscript"===e&&(r=w.SCRIPTSCRIPT),r},Xr=(e,t)=>{const r=Yr(e.size,t.style),n=r.fracNum(),o=r.fracDen();let s;s=t.havingStyle(n);const i=ht(e.numer,s,t);if(e.continued){const e=8.5/t.fontMetrics().ptPerEm,r=3.5/t.fontMetrics().ptPerEm;i.height=i.height0?3*c:7*c,u=t.fontMetrics().denom1):(h>0?(m=t.fontMetrics().num2,p=c):(m=t.fontMetrics().num3,p=3*c),u=t.fontMetrics().denom2),l){const e=t.fontMetrics().axisHeight;m-i.depth-(e+.5*h){let r=new gt.MathNode("mfrac",[vt(e.numer,t),vt(e.denom,t)]);if(e.hasBarLine){if(e.barSize){const n=P(e.barSize,t);r.setAttribute("linethickness",F(n))}}else r.setAttribute("linethickness","0px");const n=Yr(e.size,t.style);if(n.size!==t.style.size){r=new gt.MathNode("mstyle",[r]);const e=n.size===w.DISPLAY.size?"true":"false";r.setAttribute("displaystyle",e),r.setAttribute("scriptlevel","0")}if(null!=e.leftDelim||null!=e.rightDelim){const t=[];if(null!=e.leftDelim){const r=new gt.MathNode("mo",[new gt.TextNode(e.leftDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}if(t.push(r),null!=e.rightDelim){const r=new gt.MathNode("mo",[new gt.TextNode(e.rightDelim.replace("\\",""))]);r.setAttribute("fence","true"),t.push(r)}return bt(t)}return r};je({type:"genfrac",names:["\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],props:{numArgs:2,allowedInArgument:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=t[1];let i,a=null,l=null,h="auto";switch(n){case"\\dfrac":case"\\frac":case"\\tfrac":i=!0;break;case"\\\\atopfrac":i=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":i=!1,a="(",l=")";break;case"\\\\bracefrac":i=!1,a="\\{",l="\\}";break;case"\\\\brackfrac":i=!1,a="[",l="]";break;default:throw new Error("Unrecognized genfrac command")}switch(n){case"\\dfrac":case"\\dbinom":h="display";break;case"\\tfrac":case"\\tbinom":h="text"}return{type:"genfrac",mode:r.mode,continued:!1,numer:o,denom:s,hasBarLine:i,leftDelim:a,rightDelim:l,size:h,barSize:null}},htmlBuilder:Xr,mathmlBuilder:Wr}),je({type:"genfrac",names:["\\cfrac"],props:{numArgs:2},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=t[1];return{type:"genfrac",mode:r.mode,continued:!0,numer:o,denom:s,hasBarLine:!0,leftDelim:null,rightDelim:null,size:"display",barSize:null}}}),je({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],props:{numArgs:0,infix:!0},handler(e){let t,{parser:r,funcName:n,token:o}=e;switch(n){case"\\over":t="\\frac";break;case"\\choose":t="\\binom";break;case"\\atop":t="\\\\atopfrac";break;case"\\brace":t="\\\\bracefrac";break;case"\\brack":t="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:r.mode,replaceWith:t,token:o}}});const _r=["display","text","script","scriptscript"],jr=function(e){let t=null;return e.length>0&&(t=e,t="."===t?null:t),t};je({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"]},handler(e,t){let{parser:r}=e;const n=t[4],o=t[5],s=Ze(t[0]),i="atom"===s.type&&"open"===s.family?jr(s.text):null,a=Ze(t[1]),l="atom"===a.type&&"close"===a.family?jr(a.text):null,h=qt(t[2],"size");let c,m=null;h.isBlank?c=!0:(m=h.value,c=m.number>0);let p="auto",u=t[3];if("ordgroup"===u.type){if(u.body.length>0){const e=qt(u.body[0],"textord");p=_r[Number(e.text)]}}else u=qt(u,"textord"),p=_r[Number(u.text)];return{type:"genfrac",mode:r.mode,numer:n,denom:o,continued:!1,hasBarLine:c,barSize:m,leftDelim:i,rightDelim:l,size:p}},htmlBuilder:Xr,mathmlBuilder:Wr}),je({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler(e,t){let{parser:r,funcName:n,token:o}=e;return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:qt(t[0],"size").value,token:o}}}),je({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0],s=function(e){if(!e)throw new Error("Expected non-null, but got "+String(e));return e}(qt(t[1],"infix").size),i=t[2],a=s.number>0;return{type:"genfrac",mode:r.mode,numer:o,denom:i,continued:!1,hasBarLine:a,barSize:s,leftDelim:null,rightDelim:null,size:"auto"}},htmlBuilder:Xr,mathmlBuilder:Wr});const $r=(e,t)=>{const r=t.style;let n,o;"supsub"===e.type?(n=e.sup?ht(e.sup,t.havingStyle(r.sup()),t):ht(e.sub,t.havingStyle(r.sub()),t),o=qt(e.base,"horizBrace")):o=qt(e,"horizBrace");const s=ht(o.base,t.havingBaseStyle(w.DISPLAY)),i=Nt(o,t);let a;if(o.isOver?(a=Ve.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:i}]},t),a.children[0].children[0].children[1].classes.push("svg-align")):(a=Ve.makeVList({positionType:"bottom",positionData:s.depth+.1+i.height,children:[{type:"elem",elem:i},{type:"kern",size:.1},{type:"elem",elem:s}]},t),a.children[0].children[0].children[0].classes.push("svg-align")),n){const e=Ve.makeSpan(["mord",o.isOver?"mover":"munder"],[a],t);a=o.isOver?Ve.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:e},{type:"kern",size:.2},{type:"elem",elem:n}]},t):Ve.makeVList({positionType:"bottom",positionData:e.depth+.2+n.height+n.depth,children:[{type:"elem",elem:n},{type:"kern",size:.2},{type:"elem",elem:e}]},t)}return Ve.makeSpan(["mord",o.isOver?"mover":"munder"],[a],t)};je({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler(e,t){let{parser:r,funcName:n}=e;return{type:"horizBrace",mode:r.mode,label:n,isOver:/^\\over/.test(n),base:t[0]}},htmlBuilder:$r,mathmlBuilder:(e,t)=>{const r=Ct(e.label);return new gt.MathNode(e.isOver?"mover":"munder",[vt(e.base,t),r])}}),je({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[1],o=qt(t[0],"url").url;return r.settings.isTrusted({command:"\\href",url:o})?{type:"href",mode:r.mode,href:o,body:Ke(n)}:r.formatUnsupportedCmd("\\href")},htmlBuilder:(e,t)=>{const r=nt(e.body,t,!1);return Ve.makeAnchor(e.href,[],r,t)},mathmlBuilder:(e,t)=>{let r=wt(e.body,t);return r instanceof ut||(r=new ut("mrow",[r])),r.setAttribute("href",e.href),r}}),je({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=qt(t[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:n}))return r.formatUnsupportedCmd("\\url");const o=[];for(let e=0;e{let{parser:r,funcName:o,token:s}=e;const i=qt(t[0],"raw").string,a=t[1];let l;r.settings.strict&&r.settings.reportNonstrict("htmlExtension","HTML extension is disabled on strict mode");const h={};switch(o){case"\\htmlClass":h.class=i,l={command:"\\htmlClass",class:i};break;case"\\htmlId":h.id=i,l={command:"\\htmlId",id:i};break;case"\\htmlStyle":h.style=i,l={command:"\\htmlStyle",style:i};break;case"\\htmlData":{const e=i.split(",");for(let t=0;t{const r=nt(e.body,t,!1),n=["enclosing"];e.attributes.class&&n.push(...e.attributes.class.trim().split(/\s+/));const o=Ve.makeSpan(n,r,t);for(const t in e.attributes)"class"!==t&&e.attributes.hasOwnProperty(t)&&o.setAttribute(t,e.attributes[t]);return o},mathmlBuilder:(e,t)=>wt(e.body,t)}),je({type:"htmlmathml",names:["\\html@mathml"],props:{numArgs:2,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;return{type:"htmlmathml",mode:r.mode,html:Ke(t[0]),mathml:Ke(t[1])}},htmlBuilder:(e,t)=>{const r=nt(e.html,t,!1);return Ve.makeFragment(r)},mathmlBuilder:(e,t)=>wt(e.mathml,t)});const Zr=function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};{const t=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!t)throw new n("Invalid size: '"+e+"' in \\includegraphics");const r={number:+(t[1]+t[2]),unit:t[3]};if(!V(r))throw new n("Invalid unit: '"+r.unit+"' in \\includegraphics.");return r}};je({type:"includegraphics",names:["\\includegraphics"],props:{numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1},handler:(e,t,r)=>{let{parser:o}=e,s={number:0,unit:"em"},i={number:.9,unit:"em"},a={number:0,unit:"em"},l="";if(r[0]){const e=qt(r[0],"raw").string.split(",");for(let t=0;t{const r=P(e.height,t);let n=0;e.totalheight.number>0&&(n=P(e.totalheight,t)-r);let o=0;e.width.number>0&&(o=P(e.width,t));const s={height:F(r+n)};o>0&&(s.width=F(o)),n>0&&(s.verticalAlign=F(-n));const i=new j(e.src,e.alt,s);return i.height=r,i.depth=n,i},mathmlBuilder:(e,t)=>{const r=new gt.MathNode("mglyph",[]);r.setAttribute("alt",e.alt);const n=P(e.height,t);let o=0;if(e.totalheight.number>0&&(o=P(e.totalheight,t)-n,r.setAttribute("valign",F(-o))),r.setAttribute("height",F(n+o)),e.width.number>0){const n=P(e.width,t);r.setAttribute("width",F(n))}return r.setAttribute("src",e.src),r}}),je({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0},handler(e,t){let{parser:r,funcName:n}=e;const o=qt(t[0],"size");if(r.settings.strict){const e="m"===n[1],t="mu"===o.value.unit;e?(t||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" supports only mu units, not "+o.value.unit+" units"),"math"!==r.mode&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" works only in math mode")):t&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+n+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:o.value}},htmlBuilder(e,t){return Ve.makeGlue(e.dimension,t)},mathmlBuilder(e,t){const r=P(e.dimension,t);return new gt.SpaceNode(r)}}),je({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r,funcName:n}=e;const o=t[0];return{type:"lap",mode:r.mode,alignment:n.slice(5),body:o}},htmlBuilder:(e,t)=>{let r;"clap"===e.alignment?(r=Ve.makeSpan([],[ht(e.body,t)]),r=Ve.makeSpan(["inner"],[r],t)):r=Ve.makeSpan(["inner"],[ht(e.body,t)]);const n=Ve.makeSpan(["fix"],[]);let o=Ve.makeSpan([e.alignment],[r,n],t);const s=Ve.makeSpan(["strut"]);return s.style.height=F(o.height+o.depth),o.depth&&(s.style.verticalAlign=F(-o.depth)),o.children.unshift(s),o=Ve.makeSpan(["thinbox"],[o],t),Ve.makeSpan(["mord","vbox"],[o],t)},mathmlBuilder:(e,t)=>{const r=new gt.MathNode("mpadded",[vt(e.body,t)]);if("rlap"!==e.alignment){const t="llap"===e.alignment?"-1":"-0.5";r.setAttribute("lspace",t+"width")}return r.setAttribute("width","0px"),r}}),je({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){let{funcName:r,parser:n}=e;const o=n.mode;n.switchMode("math");const s="\\("===r?"\\)":"$",i=n.parseExpression(!1,s);return n.expect(s),n.switchMode(o),{type:"styling",mode:n.mode,style:"text",body:i}}}),je({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){throw new n("Mismatched "+e.funcName)}});const Kr=(e,t)=>{switch(t.style.size){case w.DISPLAY.size:return e.display;case w.TEXT.size:return e.text;case w.SCRIPT.size:return e.script;case w.SCRIPTSCRIPT.size:return e.scriptscript;default:return e.text}};je({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4,primitive:!0},handler:(e,t)=>{let{parser:r}=e;return{type:"mathchoice",mode:r.mode,display:Ke(t[0]),text:Ke(t[1]),script:Ke(t[2]),scriptscript:Ke(t[3])}},htmlBuilder:(e,t)=>{const r=Kr(e,t),n=nt(r,t,!1);return Ve.makeFragment(n)},mathmlBuilder:(e,t)=>{const r=Kr(e,t);return wt(r,t)}});const Jr=(e,t,r,n,o,s,i)=>{e=Ve.makeSpan([],[e]);const a=r&&l.isCharacterBox(r);let h,c,m;if(t){const e=ht(t,n.havingStyle(o.sup()),n);c={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing1,n.fontMetrics().bigOpSpacing3-e.depth)}}if(r){const e=ht(r,n.havingStyle(o.sub()),n);h={elem:e,kern:Math.max(n.fontMetrics().bigOpSpacing2,n.fontMetrics().bigOpSpacing4-e.height)}}if(c&&h){const t=n.fontMetrics().bigOpSpacing5+h.elem.height+h.elem.depth+h.kern+e.depth+i;m=Ve.makeVList({positionType:"bottom",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:h.elem,marginLeft:F(-s)},{type:"kern",size:h.kern},{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:F(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}else if(h){const t=e.height-i;m=Ve.makeVList({positionType:"top",positionData:t,children:[{type:"kern",size:n.fontMetrics().bigOpSpacing5},{type:"elem",elem:h.elem,marginLeft:F(-s)},{type:"kern",size:h.kern},{type:"elem",elem:e}]},n)}else{if(!c)return e;{const t=e.depth+i;m=Ve.makeVList({positionType:"bottom",positionData:t,children:[{type:"elem",elem:e},{type:"kern",size:c.kern},{type:"elem",elem:c.elem,marginLeft:F(s)},{type:"kern",size:n.fontMetrics().bigOpSpacing5}]},n)}}const p=[m];if(h&&0!==s&&!a){const e=Ve.makeSpan(["mspace"],[],n);e.style.marginRight=F(s),p.unshift(e)}return Ve.makeSpan(["mop","op-limits"],p,n)},Qr=["\\smallint"],en=(e,t)=>{let r,n,o,s=!1;"supsub"===e.type?(r=e.sup,n=e.sub,o=qt(e.base,"op"),s=!0):o=qt(e,"op");const i=t.style;let a,h=!1;if(i.size===w.DISPLAY.size&&o.symbol&&!l.contains(Qr,o.name)&&(h=!0),o.symbol){const e=h?"Size2-Regular":"Size1-Regular";let r="";if("\\oiint"!==o.name&&"\\oiiint"!==o.name||(r=o.name.slice(1),o.name="oiint"===r?"\\iint":"\\iiint"),a=Ve.makeSymbol(o.name,e,"math",t,["mop","op-symbol",h?"large-op":"small-op"]),r.length>0){const e=a.italic,n=Ve.staticSvg(r+"Size"+(h?"2":"1"),t);a=Ve.makeVList({positionType:"individualShift",children:[{type:"elem",elem:a,shift:0},{type:"elem",elem:n,shift:h?.08:0}]},t),o.name="\\"+r,a.classes.unshift("mop"),a.italic=e}}else if(o.body){const e=nt(o.body,t,!0);1===e.length&&e[0]instanceof Z?(a=e[0],a.classes[0]="mop"):a=Ve.makeSpan(["mop"],e,t)}else{const e=[];for(let r=1;r{let r;if(e.symbol)r=new ut("mo",[ft(e.name,e.mode)]),l.contains(Qr,e.name)&&r.setAttribute("largeop","false");else if(e.body)r=new ut("mo",xt(e.body,t));else{r=new ut("mi",[new dt(e.name.slice(1))]);const t=new ut("mo",[ft("\u2061","text")]);r=e.parentIsSupSub?new ut("mrow",[r,t]):pt([r,t])}return r},rn={"\u220f":"\\prod","\u2210":"\\coprod","\u2211":"\\sum","\u22c0":"\\bigwedge","\u22c1":"\\bigvee","\u22c2":"\\bigcap","\u22c3":"\\bigcup","\u2a00":"\\bigodot","\u2a01":"\\bigoplus","\u2a02":"\\bigotimes","\u2a04":"\\biguplus","\u2a06":"\\bigsqcup"};je({type:"op",names:["\\coprod","\\bigvee","\\bigwedge","\\biguplus","\\bigcap","\\bigcup","\\intop","\\prod","\\sum","\\bigotimes","\\bigoplus","\\bigodot","\\bigsqcup","\\smallint","\u220f","\u2210","\u2211","\u22c0","\u22c1","\u22c2","\u22c3","\u2a00","\u2a01","\u2a02","\u2a04","\u2a06"],props:{numArgs:0},handler:(e,t)=>{let{parser:r,funcName:n}=e,o=n;return 1===o.length&&(o=rn[o]),{type:"op",mode:r.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:o}},htmlBuilder:en,mathmlBuilder:tn}),je({type:"op",names:["\\mathop"],props:{numArgs:1,primitive:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"op",mode:r.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:Ke(n)}},htmlBuilder:en,mathmlBuilder:tn});const nn={"\u222b":"\\int","\u222c":"\\iint","\u222d":"\\iiint","\u222e":"\\oint","\u222f":"\\oiint","\u2230":"\\oiiint"};je({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:en,mathmlBuilder:tn}),je({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e;return{type:"op",mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:en,mathmlBuilder:tn}),je({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","\u222b","\u222c","\u222d","\u222e","\u222f","\u2230"],props:{numArgs:0},handler(e){let{parser:t,funcName:r}=e,n=r;return 1===n.length&&(n=nn[n]),{type:"op",mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:n}},htmlBuilder:en,mathmlBuilder:tn});const on=(e,t)=>{let r,n,o,s,i=!1;if("supsub"===e.type?(r=e.sup,n=e.sub,o=qt(e.base,"operatorname"),i=!0):o=qt(e,"operatorname"),o.body.length>0){const e=o.body.map((e=>{const t=e.text;return"string"==typeof t?{type:"textord",mode:e.mode,text:t}:e})),r=nt(e,t.withFont("mathrm"),!0);for(let e=0;e{let{parser:r,funcName:n}=e;const o=t[0];return{type:"operatorname",mode:r.mode,body:Ke(o),alwaysHandleSupSub:"\\operatornamewithlimits"===n,limits:!1,parentIsSupSub:!1}},htmlBuilder:on,mathmlBuilder:(e,t)=>{let r=xt(e.body,t.withFont("mathrm")),n=!0;for(let e=0;ee.toText())).join("");r=[new gt.TextNode(e)]}const o=new gt.MathNode("mi",r);o.setAttribute("mathvariant","normal");const s=new gt.MathNode("mo",[ft("\u2061","text")]);return e.parentIsSupSub?new gt.MathNode("mrow",[o,s]):gt.newDocumentFragment([o,s])}}),Br("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@"),$e({type:"ordgroup",htmlBuilder(e,t){return e.semisimple?Ve.makeFragment(nt(e.body,t,!1)):Ve.makeSpan(["mord"],nt(e.body,t,!0),t)},mathmlBuilder(e,t){return wt(e.body,t,!0)}}),je({type:"overline",names:["\\overline"],props:{numArgs:1},handler(e,t){let{parser:r}=e;const n=t[0];return{type:"overline",mode:r.mode,body:n}},htmlBuilder(e,t){const r=ht(e.body,t.havingCrampedStyle()),n=Ve.makeLineSpan("overline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Ve.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r},{type:"kern",size:3*o},{type:"elem",elem:n},{type:"kern",size:o}]},t);return Ve.makeSpan(["mord","overline"],[s],t)},mathmlBuilder(e,t){const r=new gt.MathNode("mo",[new gt.TextNode("\u203e")]);r.setAttribute("stretchy","true");const n=new gt.MathNode("mover",[vt(e.body,t),r]);return n.setAttribute("accent","true"),n}}),je({type:"phantom",names:["\\phantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"phantom",mode:r.mode,body:Ke(n)}},htmlBuilder:(e,t)=>{const r=nt(e.body,t.withPhantom(),!1);return Ve.makeFragment(r)},mathmlBuilder:(e,t)=>{const r=xt(e.body,t);return new gt.MathNode("mphantom",r)}}),je({type:"hphantom",names:["\\hphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"hphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{let r=Ve.makeSpan([],[ht(e.body,t.withPhantom())]);if(r.height=0,r.depth=0,r.children)for(let e=0;e{const r=xt(Ke(e.body),t),n=new gt.MathNode("mphantom",r),o=new gt.MathNode("mpadded",[n]);return o.setAttribute("height","0px"),o.setAttribute("depth","0px"),o}}),je({type:"vphantom",names:["\\vphantom"],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{let{parser:r}=e;const n=t[0];return{type:"vphantom",mode:r.mode,body:n}},htmlBuilder:(e,t)=>{const r=Ve.makeSpan(["inner"],[ht(e.body,t.withPhantom())]),n=Ve.makeSpan(["fix"],[]);return Ve.makeSpan(["mord","rlap"],[r,n],t)},mathmlBuilder:(e,t)=>{const r=xt(Ke(e.body),t),n=new gt.MathNode("mphantom",r),o=new gt.MathNode("mpadded",[n]);return o.setAttribute("width","0px"),o}}),je({type:"raisebox",names:["\\raisebox"],props:{numArgs:2,argTypes:["size","hbox"],allowedInText:!0},handler(e,t){let{parser:r}=e;const n=qt(t[0],"size").value,o=t[1];return{type:"raisebox",mode:r.mode,dy:n,body:o}},htmlBuilder(e,t){const r=ht(e.body,t),n=P(e.dy,t);return Ve.makeVList({positionType:"shift",positionData:-n,children:[{type:"elem",elem:r}]},t)},mathmlBuilder(e,t){const r=new gt.MathNode("mpadded",[vt(e.body,t)]),n=e.dy.number+e.dy.unit;return r.setAttribute("voffset",n),r}}),je({type:"internal",names:["\\relax"],props:{numArgs:0,allowedInText:!0},handler(e){let{parser:t}=e;return{type:"internal",mode:t.mode}}}),je({type:"rule",names:["\\rule"],props:{numArgs:2,numOptionalArgs:1,argTypes:["size","size","size"]},handler(e,t,r){let{parser:n}=e;const o=r[0],s=qt(t[0],"size"),i=qt(t[1],"size");return{type:"rule",mode:n.mode,shift:o&&qt(o,"size").value,width:s.value,height:i.value}},htmlBuilder(e,t){const r=Ve.makeSpan(["mord","rule"],[],t),n=P(e.width,t),o=P(e.height,t),s=e.shift?P(e.shift,t):0;return r.style.borderRightWidth=F(n),r.style.borderTopWidth=F(o),r.style.bottom=F(s),r.width=n,r.height=o+s,r.depth=-s,r.maxFontSize=1.125*o*t.sizeMultiplier,r},mathmlBuilder(e,t){const r=P(e.width,t),n=P(e.height,t),o=e.shift?P(e.shift,t):0,s=t.color&&t.getColor()||"black",i=new gt.MathNode("mspace");i.setAttribute("mathbackground",s),i.setAttribute("width",F(r)),i.setAttribute("height",F(n));const a=new gt.MathNode("mpadded",[i]);return o>=0?a.setAttribute("height",F(o)):(a.setAttribute("height",F(o)),a.setAttribute("depth",F(-o))),a.setAttribute("voffset",F(o)),a}});const an=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"];je({type:"sizing",names:an,props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{let{breakOnTokenText:r,funcName:n,parser:o}=e;const s=o.parseExpression(!1,r);return{type:"sizing",mode:o.mode,size:an.indexOf(n)+1,body:s}},htmlBuilder:(e,t)=>{const r=t.havingSize(e.size);return sn(e.body,r,t)},mathmlBuilder:(e,t)=>{const r=t.havingSize(e.size),n=xt(e.body,r),o=new gt.MathNode("mstyle",n);return o.setAttribute("mathsize",F(r.sizeMultiplier)),o}}),je({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:(e,t,r)=>{let{parser:n}=e,o=!1,s=!1;const i=r[0]&&qt(r[0],"ordgroup");if(i){let e="";for(let t=0;t{const r=Ve.makeSpan([],[ht(e.body,t)]);if(!e.smashHeight&&!e.smashDepth)return r;if(e.smashHeight&&(r.height=0,r.children))for(let e=0;e{const r=new gt.MathNode("mpadded",[vt(e.body,t)]);return e.smashHeight&&r.setAttribute("height","0px"),e.smashDepth&&r.setAttribute("depth","0px"),r}}),je({type:"sqrt",names:["\\sqrt"],props:{numArgs:1,numOptionalArgs:1},handler(e,t,r){let{parser:n}=e;const o=r[0],s=t[0];return{type:"sqrt",mode:n.mode,body:s,index:o}},htmlBuilder(e,t){let r=ht(e.body,t.havingCrampedStyle());0===r.height&&(r.height=t.fontMetrics().xHeight),r=Ve.wrapFragment(r,t);const n=t.fontMetrics().defaultRuleThickness;let o=n;t.style.idr.height+r.depth+s&&(s=(s+c-r.height-r.depth)/2);const m=a.height-r.height-s-l;r.style.paddingLeft=F(h);const p=Ve.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+m)},{type:"elem",elem:a},{type:"kern",size:l}]},t);if(e.index){const r=t.havingStyle(w.SCRIPTSCRIPT),n=ht(e.index,r,t),o=.6*(p.height-p.depth),s=Ve.makeVList({positionType:"shift",positionData:-o,children:[{type:"elem",elem:n}]},t),i=Ve.makeSpan(["root"],[s]);return Ve.makeSpan(["mord","sqrt"],[i,p],t)}return Ve.makeSpan(["mord","sqrt"],[p],t)},mathmlBuilder(e,t){const{body:r,index:n}=e;return n?new gt.MathNode("mroot",[vt(r,t),vt(n,t)]):new gt.MathNode("msqrt",[vt(r,t)])}});const ln={display:w.DISPLAY,text:w.TEXT,script:w.SCRIPT,scriptscript:w.SCRIPTSCRIPT};je({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e,t){let{breakOnTokenText:r,funcName:n,parser:o}=e;const s=o.parseExpression(!0,r),i=n.slice(1,n.length-5);return{type:"styling",mode:o.mode,style:i,body:s}},htmlBuilder(e,t){const r=ln[e.style],n=t.havingStyle(r).withFont("");return sn(e.body,n,t)},mathmlBuilder(e,t){const r=ln[e.style],n=t.havingStyle(r),o=xt(e.body,n),s=new gt.MathNode("mstyle",o),i={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]}[e.style];return s.setAttribute("scriptlevel",i[0]),s.setAttribute("displaystyle",i[1]),s}});$e({type:"supsub",htmlBuilder(e,t){const r=function(e,t){const r=e.base;if(r)return"op"===r.type?r.limits&&(t.style.size===w.DISPLAY.size||r.alwaysHandleSupSub)?en:null:"operatorname"===r.type?r.alwaysHandleSupSub&&(t.style.size===w.DISPLAY.size||r.limits)?on:null:"accent"===r.type?l.isCharacterBox(r.base)?Ht:null:"horizBrace"===r.type&&!e.sub===r.isOver?$r:null;return null}(e,t);if(r)return r(e,t);const{base:n,sup:o,sub:s}=e,i=ht(n,t);let a,h;const c=t.fontMetrics();let m=0,p=0;const u=n&&l.isCharacterBox(n);if(o){const e=t.havingStyle(t.style.sup());a=ht(o,e,t),u||(m=i.height-e.fontMetrics().supDrop*e.sizeMultiplier/t.sizeMultiplier)}if(s){const e=t.havingStyle(t.style.sub());h=ht(s,e,t),u||(p=i.depth+e.fontMetrics().subDrop*e.sizeMultiplier/t.sizeMultiplier)}let d;d=t.style===w.DISPLAY?c.sup1:t.style.cramped?c.sup3:c.sup2;const g=t.sizeMultiplier,f=F(.5/c.ptPerEm/g);let b,y=null;if(h){const t=e.base&&"op"===e.base.type&&e.base.name&&("\\oiint"===e.base.name||"\\oiiint"===e.base.name);(i instanceof Z||t)&&(y=F(-i.italic))}if(a&&h){m=Math.max(m,d,a.depth+.25*c.xHeight),p=Math.max(p,c.sub2);const e=4*c.defaultRuleThickness;if(m-a.depth-(h.height-p)0&&(m+=t,p-=t)}const r=[{type:"elem",elem:h,shift:p,marginRight:f,marginLeft:y},{type:"elem",elem:a,shift:-m,marginRight:f}];b=Ve.makeVList({positionType:"individualShift",children:r},t)}else if(h){p=Math.max(p,c.sub1,h.height-.8*c.xHeight);const e=[{type:"elem",elem:h,marginLeft:y,marginRight:f}];b=Ve.makeVList({positionType:"shift",positionData:p,children:e},t)}else{if(!a)throw new Error("supsub must have either sup or sub.");m=Math.max(m,d,a.depth+.25*c.xHeight),b=Ve.makeVList({positionType:"shift",positionData:-m,children:[{type:"elem",elem:a,marginRight:f}]},t)}const x=at(i,"right")||"mord";return Ve.makeSpan([x],[i,Ve.makeSpan(["msupsub"],[b])],t)},mathmlBuilder(e,t){let r,n,o=!1;e.base&&"horizBrace"===e.base.type&&(n=!!e.sup,n===e.base.isOver&&(o=!0,r=e.base.isOver)),!e.base||"op"!==e.base.type&&"operatorname"!==e.base.type||(e.base.parentIsSupSub=!0);const s=[vt(e.base,t)];let i;if(e.sub&&s.push(vt(e.sub,t)),e.sup&&s.push(vt(e.sup,t)),o)i=r?"mover":"munder";else if(e.sub)if(e.sup){const r=e.base;i=r&&"op"===r.type&&r.limits&&t.style===w.DISPLAY||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(t.style===w.DISPLAY||r.limits)?"munderover":"msubsup"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===w.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===w.DISPLAY)?"munder":"msub"}else{const r=e.base;i=r&&"op"===r.type&&r.limits&&(t.style===w.DISPLAY||r.alwaysHandleSupSub)||r&&"operatorname"===r.type&&r.alwaysHandleSupSub&&(r.limits||t.style===w.DISPLAY)?"mover":"msup"}return new gt.MathNode(i,s)}}),$e({type:"atom",htmlBuilder(e,t){return Ve.mathsym(e.text,e.mode,t,["m"+e.family])},mathmlBuilder(e,t){const r=new gt.MathNode("mo",[ft(e.text,e.mode)]);if("bin"===e.family){const n=yt(e,t);"bold-italic"===n&&r.setAttribute("mathvariant",n)}else"punct"===e.family?r.setAttribute("separator","true"):"open"!==e.family&&"close"!==e.family||r.setAttribute("stretchy","false");return r}});const hn={mi:"italic",mn:"normal",mtext:"normal"};$e({type:"mathord",htmlBuilder(e,t){return Ve.makeOrd(e,t,"mathord")},mathmlBuilder(e,t){const r=new gt.MathNode("mi",[ft(e.text,e.mode,t)]),n=yt(e,t)||"italic";return n!==hn[r.type]&&r.setAttribute("mathvariant",n),r}}),$e({type:"textord",htmlBuilder(e,t){return Ve.makeOrd(e,t,"textord")},mathmlBuilder(e,t){const r=ft(e.text,e.mode,t),n=yt(e,t)||"normal";let o;return o="text"===e.mode?new gt.MathNode("mtext",[r]):/[0-9]/.test(e.text)?new gt.MathNode("mn",[r]):"\\prime"===e.text?new gt.MathNode("mo",[r]):new gt.MathNode("mi",[r]),n!==hn[o.type]&&o.setAttribute("mathvariant",n),o}});const cn={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},mn={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};$e({type:"spacing",htmlBuilder(e,t){if(mn.hasOwnProperty(e.text)){const r=mn[e.text].className||"";if("text"===e.mode){const n=Ve.makeOrd(e,t,"textord");return n.classes.push(r),n}return Ve.makeSpan(["mspace",r],[Ve.mathsym(e.text,e.mode,t)],t)}if(cn.hasOwnProperty(e.text))return Ve.makeSpan(["mspace",cn[e.text]],[],t);throw new n('Unknown type of space "'+e.text+'"')},mathmlBuilder(e,t){let r;if(!mn.hasOwnProperty(e.text)){if(cn.hasOwnProperty(e.text))return new gt.MathNode("mspace");throw new n('Unknown type of space "'+e.text+'"')}return r=new gt.MathNode("mtext",[new gt.TextNode("\xa0")]),r}});const pn=()=>{const e=new gt.MathNode("mtd",[]);return e.setAttribute("width","50%"),e};$e({type:"tag",mathmlBuilder(e,t){const r=new gt.MathNode("mtable",[new gt.MathNode("mtr",[pn(),new gt.MathNode("mtd",[wt(e.body,t)]),pn(),new gt.MathNode("mtd",[wt(e.tag,t)])])]);return r.setAttribute("width","100%"),r}});const un={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},dn={"\\textbf":"textbf","\\textmd":"textmd"},gn={"\\textit":"textit","\\textup":"textup"},fn=(e,t)=>{const r=e.font;return r?un[r]?t.withTextFontFamily(un[r]):dn[r]?t.withTextFontWeight(dn[r]):"\\emph"===r?"textit"===t.fontShape?t.withTextFontShape("textup"):t.withTextFontShape("textit"):t.withTextFontShape(gn[r]):t};je({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],props:{numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0},handler(e,t){let{parser:r,funcName:n}=e;const o=t[0];return{type:"text",mode:r.mode,body:Ke(o),font:n}},htmlBuilder(e,t){const r=fn(e,t),n=nt(e.body,r,!0);return Ve.makeSpan(["mord","text"],n,r)},mathmlBuilder(e,t){const r=fn(e,t);return wt(e.body,r)}}),je({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler(e,t){let{parser:r}=e;return{type:"underline",mode:r.mode,body:t[0]}},htmlBuilder(e,t){const r=ht(e.body,t),n=Ve.makeLineSpan("underline-line",t),o=t.fontMetrics().defaultRuleThickness,s=Ve.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:o},{type:"elem",elem:n},{type:"kern",size:3*o},{type:"elem",elem:r}]},t);return Ve.makeSpan(["mord","underline"],[s],t)},mathmlBuilder(e,t){const r=new gt.MathNode("mo",[new gt.TextNode("\u203e")]);r.setAttribute("stretchy","true");const n=new gt.MathNode("munder",[vt(e.body,t),r]);return n.setAttribute("accentunder","true"),n}}),je({type:"vcenter",names:["\\vcenter"],props:{numArgs:1,argTypes:["original"],allowedInText:!1},handler(e,t){let{parser:r}=e;return{type:"vcenter",mode:r.mode,body:t[0]}},htmlBuilder(e,t){const r=ht(e.body,t),n=t.fontMetrics().axisHeight,o=.5*(r.height-n-(r.depth+n));return Ve.makeVList({positionType:"shift",positionData:o,children:[{type:"elem",elem:r}]},t)},mathmlBuilder(e,t){return new gt.MathNode("mpadded",[vt(e.body,t)],["vcenter"])}}),je({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler(e,t,r){throw new n("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(e,t){const r=bn(e),n=[],o=t.havingStyle(t.style.text());for(let t=0;te.body.replace(/ /g,e.star?"\u2423":"\xa0");var yn=Xe;const xn="[ \r\n\t]",wn="(\\\\[a-zA-Z@]+)"+xn+"*",vn="[\u0300-\u036f]",kn=new RegExp(vn+"+$"),Sn="("+xn+"+)|\\\\(\n|[ \r\t]+\n?)[ \r\t]*|([!-\\[\\]-\u2027\u202a-\ud7ff\uf900-\uffff]"+vn+"*|[\ud800-\udbff][\udc00-\udfff]"+vn+"*|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5|"+wn+"|\\\\[^\ud800-\udfff])";class Mn{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(Sn,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){const e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new Nr("EOF",new Cr(this,t,t));const r=this.tokenRegex.exec(e);if(null===r||r.index!==t)throw new n("Unexpected character: '"+e[t]+"'",new Nr(e[t],new Cr(this,t,t+1)));const o=r[6]||r[3]||(r[2]?"\\ ":" ");if(14===this.catcodes[o]){const t=e.indexOf("\n",this.tokenRegex.lastIndex);return-1===t?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=t+1,this.lex()}return new Nr(o,new Cr(this,t,this.tokenRegex.lastIndex))}}class zn{constructor(e,t){void 0===e&&(e={}),void 0===t&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(0===this.undefStack.length)throw new n("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");const e=this.undefStack.pop();for(const t in e)e.hasOwnProperty(t)&&(null==e[t]?delete this.current[t]:this.current[t]=e[t])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,t,r){if(void 0===r&&(r=!1),r){for(let t=0;t0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{const t=this.undefStack[this.undefStack.length-1];t&&!t.hasOwnProperty(e)&&(t[e]=this.current[e])}null==t?delete this.current[e]:this.current[e]=t}}var An=Tr;Br("\\noexpand",(function(e){const t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}})),Br("\\expandafter",(function(e){const t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}})),Br("\\@firstoftwo",(function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}})),Br("\\@secondoftwo",(function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}})),Br("\\@ifnextchar",(function(e){const t=e.consumeArgs(3);e.consumeSpaces();const r=e.future();return 1===t[0].length&&t[0][0].text===r.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}})),Br("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),Br("\\TextOrMath",(function(e){const t=e.consumeArgs(2);return"text"===e.mode?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}}));const Tn={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};Br("\\char",(function(e){let t,r=e.popToken(),o="";if("'"===r.text)t=8,r=e.popToken();else if('"'===r.text)t=16,r=e.popToken();else if("`"===r.text)if(r=e.popToken(),"\\"===r.text[0])o=r.text.charCodeAt(1);else{if("EOF"===r.text)throw new n("\\char` missing argument");o=r.text.charCodeAt(0)}else t=10;if(t){if(o=Tn[r.text],null==o||o>=t)throw new n("Invalid base-"+t+" digit "+r.text);let s;for(;null!=(s=Tn[e.future().text])&&s{let o=e.consumeArg().tokens;if(1!==o.length)throw new n("\\newcommand's first argument must be a macro name");const s=o[0].text,i=e.isDefined(s);if(i&&!t)throw new n("\\newcommand{"+s+"} attempting to redefine "+s+"; use \\renewcommand");if(!i&&!r)throw new n("\\renewcommand{"+s+"} when command "+s+" does not yet exist; use \\newcommand");let a=0;if(o=e.consumeArg().tokens,1===o.length&&"["===o[0].text){let t="",r=e.expandNextToken();for(;"]"!==r.text&&"EOF"!==r.text;)t+=r.text,r=e.expandNextToken();if(!t.match(/^\s*[0-9]+\s*$/))throw new n("Invalid number of arguments: "+t);a=parseInt(t),o=e.consumeArg().tokens}return e.macros.set(s,{tokens:o,numArgs:a}),""};Br("\\newcommand",(e=>Bn(e,!1,!0))),Br("\\renewcommand",(e=>Bn(e,!0,!1))),Br("\\providecommand",(e=>Bn(e,!0,!0))),Br("\\message",(e=>{const t=e.consumeArgs(1)[0];return console.log(t.reverse().map((e=>e.text)).join("")),""})),Br("\\errmessage",(e=>{const t=e.consumeArgs(1)[0];return console.error(t.reverse().map((e=>e.text)).join("")),""})),Br("\\show",(e=>{const t=e.popToken(),r=t.text;return console.log(t,e.macros.get(r),yn[r],oe.math[r],oe.text[r]),""})),Br("\\bgroup","{"),Br("\\egroup","}"),Br("~","\\nobreakspace"),Br("\\lq","`"),Br("\\rq","'"),Br("\\aa","\\r a"),Br("\\AA","\\r A"),Br("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`\xa9}"),Br("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"),Br("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xae}"),Br("\u212c","\\mathscr{B}"),Br("\u2130","\\mathscr{E}"),Br("\u2131","\\mathscr{F}"),Br("\u210b","\\mathscr{H}"),Br("\u2110","\\mathscr{I}"),Br("\u2112","\\mathscr{L}"),Br("\u2133","\\mathscr{M}"),Br("\u211b","\\mathscr{R}"),Br("\u212d","\\mathfrak{C}"),Br("\u210c","\\mathfrak{H}"),Br("\u2128","\\mathfrak{Z}"),Br("\\Bbbk","\\Bbb{k}"),Br("\xb7","\\cdotp"),Br("\\llap","\\mathllap{\\textrm{#1}}"),Br("\\rlap","\\mathrlap{\\textrm{#1}}"),Br("\\clap","\\mathclap{\\textrm{#1}}"),Br("\\mathstrut","\\vphantom{(}"),Br("\\underbar","\\underline{\\text{#1}}"),Br("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}'),Br("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}"),Br("\\ne","\\neq"),Br("\u2260","\\neq"),Br("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}"),Br("\u2209","\\notin"),Br("\u2258","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}"),Br("\u2259","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}"),Br("\u225a","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225a}}"),Br("\u225b","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225b}}"),Br("\u225d","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225d}}"),Br("\u225e","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225e}}"),Br("\u225f","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225f}}"),Br("\u27c2","\\perp"),Br("\u203c","\\mathclose{!\\mkern-0.8mu!}"),Br("\u220c","\\notni"),Br("\u231c","\\ulcorner"),Br("\u231d","\\urcorner"),Br("\u231e","\\llcorner"),Br("\u231f","\\lrcorner"),Br("\xa9","\\copyright"),Br("\xae","\\textregistered"),Br("\ufe0f","\\textregistered"),Br("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}'),Br("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}'),Br("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}'),Br("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}'),Br("\\vdots","\\mathord{\\varvdots\\rule{0pt}{15pt}}"),Br("\u22ee","\\vdots"),Br("\\varGamma","\\mathit{\\Gamma}"),Br("\\varDelta","\\mathit{\\Delta}"),Br("\\varTheta","\\mathit{\\Theta}"),Br("\\varLambda","\\mathit{\\Lambda}"),Br("\\varXi","\\mathit{\\Xi}"),Br("\\varPi","\\mathit{\\Pi}"),Br("\\varSigma","\\mathit{\\Sigma}"),Br("\\varUpsilon","\\mathit{\\Upsilon}"),Br("\\varPhi","\\mathit{\\Phi}"),Br("\\varPsi","\\mathit{\\Psi}"),Br("\\varOmega","\\mathit{\\Omega}"),Br("\\substack","\\begin{subarray}{c}#1\\end{subarray}"),Br("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax"),Br("\\boxed","\\fbox{$\\displaystyle{#1}$}"),Br("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;"),Br("\\implies","\\DOTSB\\;\\Longrightarrow\\;"),Br("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;");const Cn={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};Br("\\dots",(function(e){let t="\\dotso";const r=e.expandAfterFuture().text;return r in Cn?t=Cn[r]:("\\not"===r.slice(0,4)||r in oe.math&&l.contains(["bin","rel"],oe.math[r].group))&&(t="\\dotsb"),t}));const Nn={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};Br("\\dotso",(function(e){return e.future().text in Nn?"\\ldots\\,":"\\ldots"})),Br("\\dotsc",(function(e){const t=e.future().text;return t in Nn&&","!==t?"\\ldots\\,":"\\ldots"})),Br("\\cdots",(function(e){return e.future().text in Nn?"\\@cdots\\,":"\\@cdots"})),Br("\\dotsb","\\cdots"),Br("\\dotsm","\\cdots"),Br("\\dotsi","\\!\\cdots"),Br("\\dotsx","\\ldots\\,"),Br("\\DOTSI","\\relax"),Br("\\DOTSB","\\relax"),Br("\\DOTSX","\\relax"),Br("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"),Br("\\,","\\tmspace+{3mu}{.1667em}"),Br("\\thinspace","\\,"),Br("\\>","\\mskip{4mu}"),Br("\\:","\\tmspace+{4mu}{.2222em}"),Br("\\medspace","\\:"),Br("\\;","\\tmspace+{5mu}{.2777em}"),Br("\\thickspace","\\;"),Br("\\!","\\tmspace-{3mu}{.1667em}"),Br("\\negthinspace","\\!"),Br("\\negmedspace","\\tmspace-{4mu}{.2222em}"),Br("\\negthickspace","\\tmspace-{5mu}{.277em}"),Br("\\enspace","\\kern.5em "),Br("\\enskip","\\hskip.5em\\relax"),Br("\\quad","\\hskip1em\\relax"),Br("\\qquad","\\hskip2em\\relax"),Br("\\tag","\\@ifstar\\tag@literal\\tag@paren"),Br("\\tag@paren","\\tag@literal{({#1})}"),Br("\\tag@literal",(e=>{if(e.macros.get("\\df@tag"))throw new n("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"})),Br("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"),Br("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"),Br("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}"),Br("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"),Br("\\newline","\\\\\\relax"),Br("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");const qn=F(T["Main-Regular"]["T".charCodeAt(0)][1]-.7*T["Main-Regular"]["A".charCodeAt(0)][1]);Br("\\LaTeX","\\textrm{\\html@mathml{L\\kern-.36em\\raisebox{"+qn+"}{\\scriptstyle A}\\kern-.15em\\TeX}{LaTeX}}"),Br("\\KaTeX","\\textrm{\\html@mathml{K\\kern-.17em\\raisebox{"+qn+"}{\\scriptstyle A}\\kern-.15em\\TeX}{KaTeX}}"),Br("\\hspace","\\@ifstar\\@hspacer\\@hspace"),Br("\\@hspace","\\hskip #1\\relax"),Br("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax"),Br("\\ordinarycolon",":"),Br("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}"),Br("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}'),Br("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}'),Br("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}'),Br("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}'),Br("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}'),Br("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}'),Br("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}'),Br("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}'),Br("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}'),Br("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}'),Br("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}'),Br("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}'),Br("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}'),Br("\u2237","\\dblcolon"),Br("\u2239","\\eqcolon"),Br("\u2254","\\coloneqq"),Br("\u2255","\\eqqcolon"),Br("\u2a74","\\Coloneqq"),Br("\\ratio","\\vcentcolon"),Br("\\coloncolon","\\dblcolon"),Br("\\colonequals","\\coloneqq"),Br("\\coloncolonequals","\\Coloneqq"),Br("\\equalscolon","\\eqqcolon"),Br("\\equalscoloncolon","\\Eqqcolon"),Br("\\colonminus","\\coloneq"),Br("\\coloncolonminus","\\Coloneq"),Br("\\minuscolon","\\eqcolon"),Br("\\minuscoloncolon","\\Eqcolon"),Br("\\coloncolonapprox","\\Colonapprox"),Br("\\coloncolonsim","\\Colonsim"),Br("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),Br("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"),Br("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"),Br("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"),Br("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220c}}"),Br("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}"),Br("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}"),Br("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}"),Br("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}"),Br("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}"),Br("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}"),Br("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}"),Br("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}"),Br("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}"),Br("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}"),Br("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}"),Br("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}"),Br("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}"),Br("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}"),Br("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}"),Br("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}"),Br("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}"),Br("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}"),Br("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228a}"),Br("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2acb}"),Br("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228b}"),Br("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2acc}"),Br("\\imath","\\html@mathml{\\@imath}{\u0131}"),Br("\\jmath","\\html@mathml{\\@jmath}{\u0237}"),Br("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27e6}}"),Br("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27e7}}"),Br("\u27e6","\\llbracket"),Br("\u27e7","\\rrbracket"),Br("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}"),Br("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}"),Br("\u2983","\\lBrace"),Br("\u2984","\\rBrace"),Br("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29b5}}"),Br("\u29b5","\\minuso"),Br("\\darr","\\downarrow"),Br("\\dArr","\\Downarrow"),Br("\\Darr","\\Downarrow"),Br("\\lang","\\langle"),Br("\\rang","\\rangle"),Br("\\uarr","\\uparrow"),Br("\\uArr","\\Uparrow"),Br("\\Uarr","\\Uparrow"),Br("\\N","\\mathbb{N}"),Br("\\R","\\mathbb{R}"),Br("\\Z","\\mathbb{Z}"),Br("\\alef","\\aleph"),Br("\\alefsym","\\aleph"),Br("\\Alpha","\\mathrm{A}"),Br("\\Beta","\\mathrm{B}"),Br("\\bull","\\bullet"),Br("\\Chi","\\mathrm{X}"),Br("\\clubs","\\clubsuit"),Br("\\cnums","\\mathbb{C}"),Br("\\Complex","\\mathbb{C}"),Br("\\Dagger","\\ddagger"),Br("\\diamonds","\\diamondsuit"),Br("\\empty","\\emptyset"),Br("\\Epsilon","\\mathrm{E}"),Br("\\Eta","\\mathrm{H}"),Br("\\exist","\\exists"),Br("\\harr","\\leftrightarrow"),Br("\\hArr","\\Leftrightarrow"),Br("\\Harr","\\Leftrightarrow"),Br("\\hearts","\\heartsuit"),Br("\\image","\\Im"),Br("\\infin","\\infty"),Br("\\Iota","\\mathrm{I}"),Br("\\isin","\\in"),Br("\\Kappa","\\mathrm{K}"),Br("\\larr","\\leftarrow"),Br("\\lArr","\\Leftarrow"),Br("\\Larr","\\Leftarrow"),Br("\\lrarr","\\leftrightarrow"),Br("\\lrArr","\\Leftrightarrow"),Br("\\Lrarr","\\Leftrightarrow"),Br("\\Mu","\\mathrm{M}"),Br("\\natnums","\\mathbb{N}"),Br("\\Nu","\\mathrm{N}"),Br("\\Omicron","\\mathrm{O}"),Br("\\plusmn","\\pm"),Br("\\rarr","\\rightarrow"),Br("\\rArr","\\Rightarrow"),Br("\\Rarr","\\Rightarrow"),Br("\\real","\\Re"),Br("\\reals","\\mathbb{R}"),Br("\\Reals","\\mathbb{R}"),Br("\\Rho","\\mathrm{P}"),Br("\\sdot","\\cdot"),Br("\\sect","\\S"),Br("\\spades","\\spadesuit"),Br("\\sub","\\subset"),Br("\\sube","\\subseteq"),Br("\\supe","\\supseteq"),Br("\\Tau","\\mathrm{T}"),Br("\\thetasym","\\vartheta"),Br("\\weierp","\\wp"),Br("\\Zeta","\\mathrm{Z}"),Br("\\argmin","\\DOTSB\\operatorname*{arg\\,min}"),Br("\\argmax","\\DOTSB\\operatorname*{arg\\,max}"),Br("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits"),Br("\\bra","\\mathinner{\\langle{#1}|}"),Br("\\ket","\\mathinner{|{#1}\\rangle}"),Br("\\braket","\\mathinner{\\langle{#1}\\rangle}"),Br("\\Bra","\\left\\langle#1\\right|"),Br("\\Ket","\\left|#1\\right\\rangle");const In=e=>t=>{const r=t.consumeArg().tokens,n=t.consumeArg().tokens,o=t.consumeArg().tokens,s=t.consumeArg().tokens,i=t.macros.get("|"),a=t.macros.get("\\|");t.macros.beginGroup();const l=t=>r=>{e&&(r.macros.set("|",i),o.length&&r.macros.set("\\|",a));let s=t;if(!t&&o.length){"|"===r.future().text&&(r.popToken(),s=!0)}return{tokens:s?o:n,numArgs:0}};t.macros.set("|",l(!1)),o.length&&t.macros.set("\\|",l(!0));const h=t.consumeArg().tokens,c=t.expandTokens([...s,...h,...r]);return t.macros.endGroup(),{tokens:c.reverse(),numArgs:0}};Br("\\bra@ket",In(!1)),Br("\\bra@set",In(!0)),Br("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}"),Br("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}"),Br("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}"),Br("\\angln","{\\angl n}"),Br("\\blue","\\textcolor{##6495ed}{#1}"),Br("\\orange","\\textcolor{##ffa500}{#1}"),Br("\\pink","\\textcolor{##ff00af}{#1}"),Br("\\red","\\textcolor{##df0030}{#1}"),Br("\\green","\\textcolor{##28ae7b}{#1}"),Br("\\gray","\\textcolor{gray}{#1}"),Br("\\purple","\\textcolor{##9d38bd}{#1}"),Br("\\blueA","\\textcolor{##ccfaff}{#1}"),Br("\\blueB","\\textcolor{##80f6ff}{#1}"),Br("\\blueC","\\textcolor{##63d9ea}{#1}"),Br("\\blueD","\\textcolor{##11accd}{#1}"),Br("\\blueE","\\textcolor{##0c7f99}{#1}"),Br("\\tealA","\\textcolor{##94fff5}{#1}"),Br("\\tealB","\\textcolor{##26edd5}{#1}"),Br("\\tealC","\\textcolor{##01d1c1}{#1}"),Br("\\tealD","\\textcolor{##01a995}{#1}"),Br("\\tealE","\\textcolor{##208170}{#1}"),Br("\\greenA","\\textcolor{##b6ffb0}{#1}"),Br("\\greenB","\\textcolor{##8af281}{#1}"),Br("\\greenC","\\textcolor{##74cf70}{#1}"),Br("\\greenD","\\textcolor{##1fab54}{#1}"),Br("\\greenE","\\textcolor{##0d923f}{#1}"),Br("\\goldA","\\textcolor{##ffd0a9}{#1}"),Br("\\goldB","\\textcolor{##ffbb71}{#1}"),Br("\\goldC","\\textcolor{##ff9c39}{#1}"),Br("\\goldD","\\textcolor{##e07d10}{#1}"),Br("\\goldE","\\textcolor{##a75a05}{#1}"),Br("\\redA","\\textcolor{##fca9a9}{#1}"),Br("\\redB","\\textcolor{##ff8482}{#1}"),Br("\\redC","\\textcolor{##f9685d}{#1}"),Br("\\redD","\\textcolor{##e84d39}{#1}"),Br("\\redE","\\textcolor{##bc2612}{#1}"),Br("\\maroonA","\\textcolor{##ffbde0}{#1}"),Br("\\maroonB","\\textcolor{##ff92c6}{#1}"),Br("\\maroonC","\\textcolor{##ed5fa6}{#1}"),Br("\\maroonD","\\textcolor{##ca337c}{#1}"),Br("\\maroonE","\\textcolor{##9e034e}{#1}"),Br("\\purpleA","\\textcolor{##ddd7ff}{#1}"),Br("\\purpleB","\\textcolor{##c6b9fc}{#1}"),Br("\\purpleC","\\textcolor{##aa87ff}{#1}"),Br("\\purpleD","\\textcolor{##7854ab}{#1}"),Br("\\purpleE","\\textcolor{##543b78}{#1}"),Br("\\mintA","\\textcolor{##f5f9e8}{#1}"),Br("\\mintB","\\textcolor{##edf2df}{#1}"),Br("\\mintC","\\textcolor{##e0e5cc}{#1}"),Br("\\grayA","\\textcolor{##f6f7f7}{#1}"),Br("\\grayB","\\textcolor{##f0f1f2}{#1}"),Br("\\grayC","\\textcolor{##e3e5e6}{#1}"),Br("\\grayD","\\textcolor{##d6d8da}{#1}"),Br("\\grayE","\\textcolor{##babec2}{#1}"),Br("\\grayF","\\textcolor{##888d93}{#1}"),Br("\\grayG","\\textcolor{##626569}{#1}"),Br("\\grayH","\\textcolor{##3b3e40}{#1}"),Br("\\grayI","\\textcolor{##21242c}{#1}"),Br("\\kaBlue","\\textcolor{##314453}{#1}"),Br("\\kaGreen","\\textcolor{##71B307}{#1}");const Rn={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class Hn{constructor(e,t,r){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new zn(An,t.macros),this.mode=r,this.stack=[]}feed(e){this.lexer=new Mn(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return 0===this.stack.length&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){let t,r,n;if(e){if(this.consumeSpaces(),"["!==this.future().text)return null;t=this.popToken(),({tokens:n,end:r}=this.consumeArg(["]"]))}else({tokens:n,start:t,end:r}=this.consumeArg());return this.pushToken(new Nr("EOF",r.loc)),this.pushTokens(n),t.range(r,"")}consumeSpaces(){for(;;){if(" "!==this.future().text)break;this.stack.pop()}}consumeArg(e){const t=[],r=e&&e.length>0;r||this.consumeSpaces();const o=this.future();let s,i=0,a=0;do{if(s=this.popToken(),t.push(s),"{"===s.text)++i;else if("}"===s.text){if(--i,-1===i)throw new n("Extra }",s)}else if("EOF"===s.text)throw new n("Unexpected end of input in a macro argument, expected '"+(e&&r?e[a]:"}")+"'",s);if(e&&r)if((0===i||1===i&&"{"===e[a])&&s.text===e[a]){if(++a,a===e.length){t.splice(-a,a);break}}else a=0}while(0!==i||r);return"{"===o.text&&"}"===t[t.length-1].text&&(t.pop(),t.shift()),t.reverse(),{tokens:t,start:o,end:s}}consumeArgs(e,t){if(t){if(t.length!==e+1)throw new n("The length of delimiters doesn't match the number of args!");const r=t[0];for(let e=0;ethis.settings.maxExpand)throw new n("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){const t=this.popToken(),r=t.text,o=t.noexpand?null:this._getExpansion(r);if(null==o||e&&o.unexpandable){if(e&&null==o&&"\\"===r[0]&&!this.isDefined(r))throw new n("Undefined control sequence: "+r);return this.pushToken(t),!1}this.countExpansion(1);let s=o.tokens;const i=this.consumeArgs(o.numArgs,o.delimiters);if(o.numArgs){s=s.slice();for(let e=s.length-1;e>=0;--e){let t=s[e];if("#"===t.text){if(0===e)throw new n("Incomplete placeholder at end of macro body",t);if(t=s[--e],"#"===t.text)s.splice(e+1,1);else{if(!/^[1-9]$/.test(t.text))throw new n("Not a valid argument number",t);s.splice(e,2,...i[+t.text-1])}}}}return this.pushTokens(s),s.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(!1===this.expandOnce()){const e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}throw new Error}expandMacro(e){return this.macros.has(e)?this.expandTokens([new Nr(e)]):void 0}expandTokens(e){const t=[],r=this.stack.length;for(this.pushTokens(e);this.stack.length>r;)if(!1===this.expandOnce(!0)){const e=this.stack.pop();e.treatAsRelax&&(e.noexpand=!1,e.treatAsRelax=!1),t.push(e)}return this.countExpansion(t.length),t}expandMacroAsText(e){const t=this.expandMacro(e);return t?t.map((e=>e.text)).join(""):t}_getExpansion(e){const t=this.macros.get(e);if(null==t)return t;if(1===e.length){const t=this.lexer.catcodes[e];if(null!=t&&13!==t)return}const r="function"==typeof t?t(this):t;if("string"==typeof r){let e=0;if(-1!==r.indexOf("#")){const t=r.replace(/##/g,"");for(;-1!==t.indexOf("#"+(e+1));)++e}const t=new Mn(r,this.settings),n=[];let o=t.lex();for(;"EOF"!==o.text;)n.push(o),o=t.lex();n.reverse();return{tokens:n,numArgs:e}}return r}isDefined(e){return this.macros.has(e)||yn.hasOwnProperty(e)||oe.math.hasOwnProperty(e)||oe.text.hasOwnProperty(e)||Rn.hasOwnProperty(e)}isExpandable(e){const t=this.macros.get(e);return null!=t?"string"==typeof t||"function"==typeof t||!t.unexpandable:yn.hasOwnProperty(e)&&!yn[e].primitive}}const On=/^[\u208a\u208b\u208c\u208d\u208e\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u2090\u2091\u2095\u1d62\u2c7c\u2096\u2097\u2098\u2099\u2092\u209a\u1d63\u209b\u209c\u1d64\u1d65\u2093\u1d66\u1d67\u1d68\u1d69\u1d6a]/,En=Object.freeze({"\u208a":"+","\u208b":"-","\u208c":"=","\u208d":"(","\u208e":")","\u2080":"0","\u2081":"1","\u2082":"2","\u2083":"3","\u2084":"4","\u2085":"5","\u2086":"6","\u2087":"7","\u2088":"8","\u2089":"9","\u2090":"a","\u2091":"e","\u2095":"h","\u1d62":"i","\u2c7c":"j","\u2096":"k","\u2097":"l","\u2098":"m","\u2099":"n","\u2092":"o","\u209a":"p","\u1d63":"r","\u209b":"s","\u209c":"t","\u1d64":"u","\u1d65":"v","\u2093":"x","\u1d66":"\u03b2","\u1d67":"\u03b3","\u1d68":"\u03c1","\u1d69":"\u03d5","\u1d6a":"\u03c7","\u207a":"+","\u207b":"-","\u207c":"=","\u207d":"(","\u207e":")","\u2070":"0","\xb9":"1","\xb2":"2","\xb3":"3","\u2074":"4","\u2075":"5","\u2076":"6","\u2077":"7","\u2078":"8","\u2079":"9","\u1d2c":"A","\u1d2e":"B","\u1d30":"D","\u1d31":"E","\u1d33":"G","\u1d34":"H","\u1d35":"I","\u1d36":"J","\u1d37":"K","\u1d38":"L","\u1d39":"M","\u1d3a":"N","\u1d3c":"O","\u1d3e":"P","\u1d3f":"R","\u1d40":"T","\u1d41":"U","\u2c7d":"V","\u1d42":"W","\u1d43":"a","\u1d47":"b","\u1d9c":"c","\u1d48":"d","\u1d49":"e","\u1da0":"f","\u1d4d":"g","\u02b0":"h","\u2071":"i","\u02b2":"j","\u1d4f":"k","\u02e1":"l","\u1d50":"m","\u207f":"n","\u1d52":"o","\u1d56":"p","\u02b3":"r","\u02e2":"s","\u1d57":"t","\u1d58":"u","\u1d5b":"v","\u02b7":"w","\u02e3":"x","\u02b8":"y","\u1dbb":"z","\u1d5d":"\u03b2","\u1d5e":"\u03b3","\u1d5f":"\u03b4","\u1d60":"\u03d5","\u1d61":"\u03c7","\u1dbf":"\u03b8"}),Ln={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030c":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030a":{text:"\\r",math:"\\mathring"},"\u030b":{text:"\\H"},"\u0327":{text:"\\c"}},Dn={"\xe1":"a\u0301","\xe0":"a\u0300","\xe4":"a\u0308","\u01df":"a\u0308\u0304","\xe3":"a\u0303","\u0101":"a\u0304","\u0103":"a\u0306","\u1eaf":"a\u0306\u0301","\u1eb1":"a\u0306\u0300","\u1eb5":"a\u0306\u0303","\u01ce":"a\u030c","\xe2":"a\u0302","\u1ea5":"a\u0302\u0301","\u1ea7":"a\u0302\u0300","\u1eab":"a\u0302\u0303","\u0227":"a\u0307","\u01e1":"a\u0307\u0304","\xe5":"a\u030a","\u01fb":"a\u030a\u0301","\u1e03":"b\u0307","\u0107":"c\u0301","\u1e09":"c\u0327\u0301","\u010d":"c\u030c","\u0109":"c\u0302","\u010b":"c\u0307","\xe7":"c\u0327","\u010f":"d\u030c","\u1e0b":"d\u0307","\u1e11":"d\u0327","\xe9":"e\u0301","\xe8":"e\u0300","\xeb":"e\u0308","\u1ebd":"e\u0303","\u0113":"e\u0304","\u1e17":"e\u0304\u0301","\u1e15":"e\u0304\u0300","\u0115":"e\u0306","\u1e1d":"e\u0327\u0306","\u011b":"e\u030c","\xea":"e\u0302","\u1ebf":"e\u0302\u0301","\u1ec1":"e\u0302\u0300","\u1ec5":"e\u0302\u0303","\u0117":"e\u0307","\u0229":"e\u0327","\u1e1f":"f\u0307","\u01f5":"g\u0301","\u1e21":"g\u0304","\u011f":"g\u0306","\u01e7":"g\u030c","\u011d":"g\u0302","\u0121":"g\u0307","\u0123":"g\u0327","\u1e27":"h\u0308","\u021f":"h\u030c","\u0125":"h\u0302","\u1e23":"h\u0307","\u1e29":"h\u0327","\xed":"i\u0301","\xec":"i\u0300","\xef":"i\u0308","\u1e2f":"i\u0308\u0301","\u0129":"i\u0303","\u012b":"i\u0304","\u012d":"i\u0306","\u01d0":"i\u030c","\xee":"i\u0302","\u01f0":"j\u030c","\u0135":"j\u0302","\u1e31":"k\u0301","\u01e9":"k\u030c","\u0137":"k\u0327","\u013a":"l\u0301","\u013e":"l\u030c","\u013c":"l\u0327","\u1e3f":"m\u0301","\u1e41":"m\u0307","\u0144":"n\u0301","\u01f9":"n\u0300","\xf1":"n\u0303","\u0148":"n\u030c","\u1e45":"n\u0307","\u0146":"n\u0327","\xf3":"o\u0301","\xf2":"o\u0300","\xf6":"o\u0308","\u022b":"o\u0308\u0304","\xf5":"o\u0303","\u1e4d":"o\u0303\u0301","\u1e4f":"o\u0303\u0308","\u022d":"o\u0303\u0304","\u014d":"o\u0304","\u1e53":"o\u0304\u0301","\u1e51":"o\u0304\u0300","\u014f":"o\u0306","\u01d2":"o\u030c","\xf4":"o\u0302","\u1ed1":"o\u0302\u0301","\u1ed3":"o\u0302\u0300","\u1ed7":"o\u0302\u0303","\u022f":"o\u0307","\u0231":"o\u0307\u0304","\u0151":"o\u030b","\u1e55":"p\u0301","\u1e57":"p\u0307","\u0155":"r\u0301","\u0159":"r\u030c","\u1e59":"r\u0307","\u0157":"r\u0327","\u015b":"s\u0301","\u1e65":"s\u0301\u0307","\u0161":"s\u030c","\u1e67":"s\u030c\u0307","\u015d":"s\u0302","\u1e61":"s\u0307","\u015f":"s\u0327","\u1e97":"t\u0308","\u0165":"t\u030c","\u1e6b":"t\u0307","\u0163":"t\u0327","\xfa":"u\u0301","\xf9":"u\u0300","\xfc":"u\u0308","\u01d8":"u\u0308\u0301","\u01dc":"u\u0308\u0300","\u01d6":"u\u0308\u0304","\u01da":"u\u0308\u030c","\u0169":"u\u0303","\u1e79":"u\u0303\u0301","\u016b":"u\u0304","\u1e7b":"u\u0304\u0308","\u016d":"u\u0306","\u01d4":"u\u030c","\xfb":"u\u0302","\u016f":"u\u030a","\u0171":"u\u030b","\u1e7d":"v\u0303","\u1e83":"w\u0301","\u1e81":"w\u0300","\u1e85":"w\u0308","\u0175":"w\u0302","\u1e87":"w\u0307","\u1e98":"w\u030a","\u1e8d":"x\u0308","\u1e8b":"x\u0307","\xfd":"y\u0301","\u1ef3":"y\u0300","\xff":"y\u0308","\u1ef9":"y\u0303","\u0233":"y\u0304","\u0177":"y\u0302","\u1e8f":"y\u0307","\u1e99":"y\u030a","\u017a":"z\u0301","\u017e":"z\u030c","\u1e91":"z\u0302","\u017c":"z\u0307","\xc1":"A\u0301","\xc0":"A\u0300","\xc4":"A\u0308","\u01de":"A\u0308\u0304","\xc3":"A\u0303","\u0100":"A\u0304","\u0102":"A\u0306","\u1eae":"A\u0306\u0301","\u1eb0":"A\u0306\u0300","\u1eb4":"A\u0306\u0303","\u01cd":"A\u030c","\xc2":"A\u0302","\u1ea4":"A\u0302\u0301","\u1ea6":"A\u0302\u0300","\u1eaa":"A\u0302\u0303","\u0226":"A\u0307","\u01e0":"A\u0307\u0304","\xc5":"A\u030a","\u01fa":"A\u030a\u0301","\u1e02":"B\u0307","\u0106":"C\u0301","\u1e08":"C\u0327\u0301","\u010c":"C\u030c","\u0108":"C\u0302","\u010a":"C\u0307","\xc7":"C\u0327","\u010e":"D\u030c","\u1e0a":"D\u0307","\u1e10":"D\u0327","\xc9":"E\u0301","\xc8":"E\u0300","\xcb":"E\u0308","\u1ebc":"E\u0303","\u0112":"E\u0304","\u1e16":"E\u0304\u0301","\u1e14":"E\u0304\u0300","\u0114":"E\u0306","\u1e1c":"E\u0327\u0306","\u011a":"E\u030c","\xca":"E\u0302","\u1ebe":"E\u0302\u0301","\u1ec0":"E\u0302\u0300","\u1ec4":"E\u0302\u0303","\u0116":"E\u0307","\u0228":"E\u0327","\u1e1e":"F\u0307","\u01f4":"G\u0301","\u1e20":"G\u0304","\u011e":"G\u0306","\u01e6":"G\u030c","\u011c":"G\u0302","\u0120":"G\u0307","\u0122":"G\u0327","\u1e26":"H\u0308","\u021e":"H\u030c","\u0124":"H\u0302","\u1e22":"H\u0307","\u1e28":"H\u0327","\xcd":"I\u0301","\xcc":"I\u0300","\xcf":"I\u0308","\u1e2e":"I\u0308\u0301","\u0128":"I\u0303","\u012a":"I\u0304","\u012c":"I\u0306","\u01cf":"I\u030c","\xce":"I\u0302","\u0130":"I\u0307","\u0134":"J\u0302","\u1e30":"K\u0301","\u01e8":"K\u030c","\u0136":"K\u0327","\u0139":"L\u0301","\u013d":"L\u030c","\u013b":"L\u0327","\u1e3e":"M\u0301","\u1e40":"M\u0307","\u0143":"N\u0301","\u01f8":"N\u0300","\xd1":"N\u0303","\u0147":"N\u030c","\u1e44":"N\u0307","\u0145":"N\u0327","\xd3":"O\u0301","\xd2":"O\u0300","\xd6":"O\u0308","\u022a":"O\u0308\u0304","\xd5":"O\u0303","\u1e4c":"O\u0303\u0301","\u1e4e":"O\u0303\u0308","\u022c":"O\u0303\u0304","\u014c":"O\u0304","\u1e52":"O\u0304\u0301","\u1e50":"O\u0304\u0300","\u014e":"O\u0306","\u01d1":"O\u030c","\xd4":"O\u0302","\u1ed0":"O\u0302\u0301","\u1ed2":"O\u0302\u0300","\u1ed6":"O\u0302\u0303","\u022e":"O\u0307","\u0230":"O\u0307\u0304","\u0150":"O\u030b","\u1e54":"P\u0301","\u1e56":"P\u0307","\u0154":"R\u0301","\u0158":"R\u030c","\u1e58":"R\u0307","\u0156":"R\u0327","\u015a":"S\u0301","\u1e64":"S\u0301\u0307","\u0160":"S\u030c","\u1e66":"S\u030c\u0307","\u015c":"S\u0302","\u1e60":"S\u0307","\u015e":"S\u0327","\u0164":"T\u030c","\u1e6a":"T\u0307","\u0162":"T\u0327","\xda":"U\u0301","\xd9":"U\u0300","\xdc":"U\u0308","\u01d7":"U\u0308\u0301","\u01db":"U\u0308\u0300","\u01d5":"U\u0308\u0304","\u01d9":"U\u0308\u030c","\u0168":"U\u0303","\u1e78":"U\u0303\u0301","\u016a":"U\u0304","\u1e7a":"U\u0304\u0308","\u016c":"U\u0306","\u01d3":"U\u030c","\xdb":"U\u0302","\u016e":"U\u030a","\u0170":"U\u030b","\u1e7c":"V\u0303","\u1e82":"W\u0301","\u1e80":"W\u0300","\u1e84":"W\u0308","\u0174":"W\u0302","\u1e86":"W\u0307","\u1e8c":"X\u0308","\u1e8a":"X\u0307","\xdd":"Y\u0301","\u1ef2":"Y\u0300","\u0178":"Y\u0308","\u1ef8":"Y\u0303","\u0232":"Y\u0304","\u0176":"Y\u0302","\u1e8e":"Y\u0307","\u0179":"Z\u0301","\u017d":"Z\u030c","\u1e90":"Z\u0302","\u017b":"Z\u0307","\u03ac":"\u03b1\u0301","\u1f70":"\u03b1\u0300","\u1fb1":"\u03b1\u0304","\u1fb0":"\u03b1\u0306","\u03ad":"\u03b5\u0301","\u1f72":"\u03b5\u0300","\u03ae":"\u03b7\u0301","\u1f74":"\u03b7\u0300","\u03af":"\u03b9\u0301","\u1f76":"\u03b9\u0300","\u03ca":"\u03b9\u0308","\u0390":"\u03b9\u0308\u0301","\u1fd2":"\u03b9\u0308\u0300","\u1fd1":"\u03b9\u0304","\u1fd0":"\u03b9\u0306","\u03cc":"\u03bf\u0301","\u1f78":"\u03bf\u0300","\u03cd":"\u03c5\u0301","\u1f7a":"\u03c5\u0300","\u03cb":"\u03c5\u0308","\u03b0":"\u03c5\u0308\u0301","\u1fe2":"\u03c5\u0308\u0300","\u1fe1":"\u03c5\u0304","\u1fe0":"\u03c5\u0306","\u03ce":"\u03c9\u0301","\u1f7c":"\u03c9\u0300","\u038e":"\u03a5\u0301","\u1fea":"\u03a5\u0300","\u03ab":"\u03a5\u0308","\u1fe9":"\u03a5\u0304","\u1fe8":"\u03a5\u0306","\u038f":"\u03a9\u0301","\u1ffa":"\u03a9\u0300"};class Vn{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new Hn(e,t,this.mode),this.settings=t,this.leftrightDepth=0}expect(e,t){if(void 0===t&&(t=!0),this.fetch().text!==e)throw new n("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());t&&this.consume()}consume(){this.nextToken=null}fetch(){return null==this.nextToken&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{const e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){const t=this.nextToken;this.consume(),this.gullet.pushToken(new Nr("}")),this.gullet.pushTokens(e);const r=this.parseExpression(!1);return this.expect("}"),this.nextToken=t,r}parseExpression(e,t){const r=[];for(;;){"math"===this.mode&&this.consumeSpaces();const n=this.fetch();if(-1!==Vn.endOfExpression.indexOf(n.text))break;if(t&&n.text===t)break;if(e&&yn[n.text]&&yn[n.text].infix)break;const o=this.parseAtom(t);if(!o)break;"internal"!==o.type&&r.push(o)}return"text"===this.mode&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(e){let t,r=-1;for(let o=0;o=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+t[0]+'" used in math mode',e);const r=oe[this.mode][t].group,n=Cr.range(e);let s;if(te.hasOwnProperty(r)){const e=r;s={type:"atom",mode:this.mode,family:e,loc:n,text:t}}else s={type:r,mode:this.mode,loc:n,text:t};o=s}else{if(!(t.charCodeAt(0)>=128))return null;this.settings.strict&&(S(t.charCodeAt(0))?"math"===this.mode&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+t[0]+'" used in math mode',e):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+t[0]+'" ('+t.charCodeAt(0)+")",e)),o={type:"textord",mode:"text",loc:Cr.range(e),text:t}}if(this.consume(),r)for(let t=0;t {
+ console.log(`[page-chat] listening on http://127.0.0.1:${info.port}`);
+ return info;
+ })
+ .catch((err) => {
+ console.error("[page-chat] could not start:", err?.message || err);
+ return null;
+ });
+
+// magpie 会把每个导出的函数当成一个插件调用;用 OpenCode v1 的形式只导出服务器。
+export default {
+ id: "magpie-chat",
+ server: async (input, options) => {
+ // 插件被重新启用时,宿主是新的进程;这里无事可做,服务已在加载时起来。
+ if (options && typeof options === "object") {
+ await started.catch(() => null);
+ }
+ return {};
+ },
+};
diff --git a/packages/chat/install-autostart.cmd b/packages/chat/install-autostart.cmd
new file mode 100644
index 0000000..0773195
--- /dev/null
+++ b/packages/chat/install-autostart.cmd
@@ -0,0 +1,11 @@
+@echo off
+chcp 65001 >nul
+title 安装 magpie-chat 开机自启
+cd /d "%~dp0"
+echo.
+echo 在「启动」文件夹里放一个快捷方式,
+echo 以后开机会自动在后台起对话服务(不弹窗口)。
+echo.
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install-autostart.ps1"
+echo.
+pause >nul
diff --git a/packages/chat/install-autostart.ps1 b/packages/chat/install-autostart.ps1
new file mode 100644
index 0000000..3d96c0e
--- /dev/null
+++ b/packages/chat/install-autostart.ps1
@@ -0,0 +1,20 @@
+# 在「启动」文件夹里放一个指向 start-server.vbs 的快捷方式
+$root = Split-Path -Parent $MyInvocation.MyCommand.Path
+$vbs = Join-Path $root 'start-server.vbs'
+if (-not (Test-Path $vbs)) { Write-Host '找不到 start-server.vbs'; exit 1 }
+$startup = [Environment]::GetFolderPath('Startup')
+$lnk = Join-Path $startup 'magpie-chat 对话服务.lnk'
+$sh = New-Object -ComObject WScript.Shell
+$s = $sh.CreateShortcut($lnk)
+$s.TargetPath = $vbs
+$s.WorkingDirectory = $root
+$s.Description = 'magpie 对话页面的本地服务'
+$s.Save()
+if (Test-Path $lnk) {
+ Write-Host ''
+ Write-Host ' 已安装开机自启:' -ForegroundColor Green
+ Write-Host " $lnk"
+ Write-Host ' 下次开机会自动在后台启动。想立刻测试就双击 start-server.vbs。'
+} else {
+ Write-Host ' 安装失败,请手动把 start-server.vbs 的快捷方式放进 shell:startup' -ForegroundColor Yellow
+}
diff --git a/packages/chat/lib/gateway.mjs b/packages/chat/lib/gateway.mjs
new file mode 100644
index 0000000..eb3682f
--- /dev/null
+++ b/packages/chat/lib/gateway.mjs
@@ -0,0 +1,148 @@
+// 和 magpie 自己的网关说话:列模型、发 chat completions(流式),带工具循环。
+// 网关是 OpenAI 兼容的,所以这里就是标准的 chat completions 客户端。
+
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+const DEFAULT_GATEWAY = "http://127.0.0.1:3425";
+
+// 候选地址:显式指定的 → 本次 magpie 的 MAGPIE_ADDR → magpie 的老端口
+function candidates(opts = {}) {
+ const out = [];
+ const push = (u) => {
+ if (!u) return;
+ const s = String(u).trim().replace(/\/+$/, "");
+ if (!/^https?:\/\//.test(s) || out.includes(s)) return;
+ out.push(s);
+ };
+ push(opts.gateway || process.env.MAGPIE_CHAT_GATEWAY);
+ const addr = process.env.MAGPIE_ADDR;
+ if (addr && /^[\w.-]+:\d+$/.test(addr)) push("http://" + addr);
+ push(DEFAULT_GATEWAY);
+ return out;
+}
+
+// 第一个真的答得上 /v1/models 的地址;都没答上就用默认的,让错误原样露出来
+let picked = { at: 0, url: "" };
+export async function resolveGateway(opts = {}) {
+ if (picked.url && Date.now() - picked.at < 60e3) return picked.url;
+ for (const url of candidates(opts)) {
+ try {
+ const res = await fetch(url + "/v1/models", {
+ headers: headers(),
+ signal: AbortSignal.timeout(2500),
+ });
+ if (res.ok) {
+ picked = { at: Date.now(), url };
+ return url;
+ }
+ } catch {
+ /* 换下一个 */
+ }
+ }
+ return candidates(opts)[0] || DEFAULT_GATEWAY;
+}
+
+export function gatewayURL(opts = {}) {
+ return picked.url || candidates(opts)[0] || DEFAULT_GATEWAY;
+}
+
+// 显式给的 key;没有就问 magpie 自己的 caller-keys.json 要一把
+// (magpie web 的网关要 key,桌面版的不要,带着也无害)
+let keyCache;
+function callerKey() {
+ if (keyCache !== undefined) return keyCache;
+ keyCache = process.env.MAGPIE_API_KEY || process.env.MAGPIE_GATEWAY_KEY || "";
+ if (keyCache) return keyCache;
+ try {
+ const dir = process.env.XDG_CONFIG_HOME
+ ? join(process.env.XDG_CONFIG_HOME, "magpie")
+ : join(homedir(), ".config", "magpie");
+ const list = JSON.parse(readFileSync(join(dir, "caller-keys.json"), "utf8"));
+ const hit = Array.isArray(list) ? (list.find((k) => k?.secret && k.name) || list.find((k) => k?.secret)) : null;
+ if (hit?.secret) keyCache = String(hit.secret);
+ } catch {
+ /* 没有这把 key 就算了 */
+ }
+ return keyCache;
+}
+
+function headers(extra = {}) {
+ const h = { "content-type": "application/json", ...extra };
+ const key = callerKey();
+ if (key) h.authorization = "Bearer " + key;
+ return h;
+}
+
+// 归一化成界面要用的形状:名字、思考档位、上下文、能不能看图
+export function normalizeModel(m) {
+ const id = String(m.id || "");
+ const efforts = Array.isArray(m.reasoning_levels) && m.reasoning_levels.length
+ ? m.reasoning_levels
+ : (m.supported_reasoning_levels || []).map((x) => x.effort).filter(Boolean);
+ const input = m.modalities?.input || m.input_modalities || [];
+ return {
+ id,
+ name: String(m.display_name || m.magpie_label || m.name || id),
+ provider: id.includes("/") ? id.slice(0, id.indexOf("/")) : "",
+ // 真正接住请求的供应商:路由组模型的 provider 是 "group",看 owned_by 才对
+ owner: String(m.owned_by || m.provider_source_id || ""),
+ reasoning: Boolean(m.reasoning) && efforts.length > 0,
+ efforts,
+ context: Number(m.max_input_tokens || m.context_length || m.context_window || 0) || 0,
+ output: Number(m.max_output_tokens || 0) || 0,
+ images: Array.isArray(input) ? input.includes("image") : false,
+ };
+}
+
+export async function listModels(opts = {}) {
+ const url = await resolveGateway(opts) + "/v1/models";
+ const res = await fetch(url, { headers: headers() });
+ if (!res.ok) throw new Error(`magpie ${res.status} · ${(await res.text()).slice(0, 300)}`);
+ const body = await res.json();
+ const list = Array.isArray(body?.data) ? body.data : Array.isArray(body) ? body : [];
+ return list.map(normalizeModel).filter((m) => m.id);
+}
+
+// 发一次 chat completions(stream 时返回原始 Response,由调用方读 SSE)
+export async function chatCompletions(body, { signal, stream = true } = {}, opts = {}) {
+ const base = await resolveGateway(opts);
+ return fetch(base + "/v1/chat/completions", {
+ method: "POST",
+ headers: headers(),
+ body: JSON.stringify({ ...body, stream }),
+ signal,
+ });
+}
+
+// 解析 SSE:逐行 data:,回调每个 JSON
+export async function* sseChunks(res) {
+ if (!res.body) return;
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ try {
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let i;
+ while ((i = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, i).replace(/\r$/, "");
+ buffer = buffer.slice(i + 1);
+ if (!line || line.startsWith(":")) continue; // 心跳
+ if (!line.startsWith("data:")) continue;
+ const data = line.slice(5).trim();
+ if (!data || data === "[DONE]") continue;
+ try {
+ yield JSON.parse(data);
+ } catch {
+ /* 半行,丢掉 */
+ }
+ }
+ }
+ } finally {
+ try { reader.releaseLock(); } catch { /* 已关闭 */ }
+ }
+}
diff --git a/packages/chat/lib/library.mjs b/packages/chat/lib/library.mjs
new file mode 100644
index 0000000..f28a8ce
--- /dev/null
+++ b/packages/chat/lib/library.mjs
@@ -0,0 +1,204 @@
+// 读 magpie 自己的资源库:指令、技能、MCP 服务器。
+// 这些是用户在 magpie 里配好的东西,插件只是照着用,不改它们。
+
+import { readFile, readdir, stat } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+export function configDir() {
+ const xdg = process.env.XDG_CONFIG_HOME;
+ if (xdg) return join(xdg, "magpie");
+ return join(homedir(), ".config", "magpie");
+}
+
+export function libraryDir(dir = configDir()) {
+ return join(dir, "library");
+}
+
+async function readJson(path, fallback) {
+ try {
+ return JSON.parse(await readFile(path, "utf8"));
+ } catch {
+ return fallback;
+ }
+}
+
+// SKILL.md 的 frontmatter:name 与 description,够用即可
+function frontmatter(text) {
+ const out = { name: "", description: "" };
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
+ if (!m) return out;
+ for (const line of m[1].split(/\r?\n/)) {
+ const i = line.indexOf(":");
+ if (i < 0) continue;
+ const k = line.slice(0, i).trim();
+ const v = line.slice(i + 1).trim().replace(/^["']|["']$/g, "");
+ if (k === "name") out.name = v;
+ else if (k === "description") out.description = v;
+ }
+ return out;
+}
+
+export async function readInstructions(dir = configDir()) {
+ const root = join(libraryDir(dir), "instructions");
+ if (!existsSync(root)) return [];
+ const names = await readdir(root).catch(() => []);
+ const out = [];
+ for (const file of names) {
+ if (!/\.(md|markdown|txt)$/i.test(file)) continue;
+ const path = join(root, file);
+ const st = await stat(path).catch(() => null);
+ if (!st?.isFile()) continue;
+ out.push({ id: file.replace(/\.(md|markdown|txt)$/i, ""), name: file, size: st.size, path });
+ }
+ return out.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export async function readSkills(dir = configDir()) {
+ const root = join(libraryDir(dir), "skills");
+ if (!existsSync(root)) return [];
+ const names = await readdir(root).catch(() => []);
+ const out = [];
+ for (const name of names) {
+ const path = join(root, name, "SKILL.md");
+ if (!existsSync(path)) continue;
+ const text = await readFile(path, "utf8").catch(() => "");
+ const fm = frontmatter(text);
+ out.push({
+ name: fm.name || name,
+ description: fm.description,
+ path,
+ body: text.replace(/^---[\s\S]*?---\r?\n/, "").trim(),
+ });
+ }
+ return out.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export async function readMcp(dir = configDir()) {
+ // magpie 的 MCP 列表在配置目录的 library.json(library/ 里放的是指令和技能的正文)
+ const lib = await readJson(join(dir, "library.json"), {});
+ const list = Array.isArray(lib.mcp) ? lib.mcp : [];
+ return list.map((m) => ({
+ name: m.name || m.url || m.command || "mcp",
+ transport: m.transport === "stdio" ? "stdio" : "http",
+ url: m.url,
+ headers: m.headers && typeof m.headers === "object" ? m.headers : undefined,
+ command: m.command,
+ args: Array.isArray(m.args) ? m.args : undefined,
+ env: m.env && typeof m.env === "object" ? m.env : undefined,
+ detail: m.url || [m.command, ...(m.args || [])].join(" "),
+ }));
+}
+
+// 给前端的精简视图(不带正文,免得 bootstrap 太重)
+export async function libraryView(dir = configDir()) {
+ const [instructions, skills, mcp] = await Promise.all([readInstructions(dir), readSkills(dir), readMcp(dir)]);
+ return {
+ instructions: instructions.map(({ id, name, size }) => ({ id, name, size })),
+ skills: skills.map(({ name, description }) => ({ name, description })),
+ mcp: mcp.map(({ name, transport, detail }) => ({ name, transport, detail })),
+ };
+}
+
+// 组装 system prompt:用户自己写的 + 勾选的指令 + 勾选的技能
+export async function composeSystem(settings, dir = configDir()) {
+ const parts = [];
+ const mine = String(settings.system || "").trim();
+ if (mine) parts.push(mine);
+ const [instructions, skills] = await Promise.all([readInstructions(dir), readSkills(dir)]);
+ for (const id of settings.instructions || []) {
+ const hit = instructions.find((x) => x.id === id || x.name === id);
+ if (!hit) continue;
+ const text = await readFile(hit.path, "utf8").catch(() => "");
+ if (text.trim()) parts.push(`# ${hit.id}\n\n${text.trim()}`);
+ }
+ for (const name of settings.skills || []) {
+ const hit = skills.find((x) => x.name === name);
+ if (!hit) continue;
+ parts.push(`# Skill: ${hit.name}\n\n${hit.description ? hit.description + "\n\n" : ""}${hit.body}`);
+ }
+ return parts.join("\n\n---\n\n");
+}
+
+// 供应商图标:magpie 的 providers.json 里每个供应商有 icon,
+// 可能是内置图标名(deepseek-color)、file: 本地文件,或 http 地址。
+// 这里统一变成服务端能直接给的 URL(/api/icon/),取不到就不给。
+export async function providerIcons(dir = configDir()) {
+ const out = new Map();
+ const providers = await readJson(join(dir, "providers.json"), null);
+ const list = Array.isArray(providers) ? providers : Array.isArray(providers?.providers) ? providers.providers : [];
+ for (const p of list) {
+ if (!p || typeof p !== "object") continue;
+ const id = p.id || p.name;
+ const icon = p.icon || p.logo || "";
+ if (!id || typeof icon !== "string" || !icon) continue;
+ out.set(String(id), "/api/icon/" + encodeURIComponent(String(id)));
+ }
+ return out;
+}
+
+// 路由组(group/)本身没有图标:用组里第一个成员模型的供应商图标顶上。
+export async function groupIcons(dir = configDir()) {
+ const out = new Map();
+ const groups = await readJson(join(dir, "providers.json"), null).catch(() => null);
+ const routing = await readJson(join(dir, "routing.json"), null).catch(() => null);
+ const list = Array.isArray(routing) ? routing : Array.isArray(routing?.groups) ? routing.groups : [];
+ for (const g of list) {
+ if (!g || typeof g !== "object") continue;
+ const id = g.id || g.name;
+ const members = Array.isArray(g.models) ? g.models : Array.isArray(g.members) ? g.members : [];
+ const first = members.find((m) => typeof m === "string" && m.includes("/"));
+ if (id && first) out.set(String(id), first.slice(0, first.indexOf("/")));
+ }
+ void groups;
+ return out;
+}
+
+// 真去磁盘/网络拿那个图标,回给页面
+export async function readProviderIcon(providerId, dir = configDir()) {
+ const providers = await readJson(join(dir, "providers.json"), null);
+ const list = Array.isArray(providers) ? providers : Array.isArray(providers?.providers) ? providers.providers : [];
+ const p = list.find((x) => x && String(x.id || x.name) === String(providerId));
+ const icon = p && (p.icon || p.logo);
+ if (!icon || typeof icon !== "string") return null;
+
+ // 1) file:xxx → 配置目录 icons/ 下的文件
+ if (icon.startsWith("file:")) {
+ const name = icon.slice(5).replace(/[^\w.-]/g, "");
+ if (!name) return null;
+ for (const base of [join(dir, "icons"), dir]) {
+ const data = await readFile(join(base, name)).catch(() => null);
+ if (data) return { data, type: mimeOf(name) };
+ }
+ return null;
+ }
+
+ // 2) 内置图标名(deepseek-color 之类):magpie 把它们编在自己身上,
+ // 只在可执行文件旁边有解包目录时才找得到;找不到就当没有图标。
+ if (!/^(https?:|data:)/.test(icon)) {
+ const name = icon.replace(/[^\w.-]/g, "");
+ const roots = [
+ join(dir, "icons"),
+ join(dir, "..", "assets", "icons"),
+ join(dir, "..", "..", "assets", "icons"),
+ ];
+ for (const root of roots) {
+ for (const ext of [".svg", ".png", ".webp", ".ico"]) {
+ const data = await readFile(join(root, name + ext)).catch(() => null);
+ if (data) return { data, type: mimeOf(name + ext) };
+ }
+ }
+ return null;
+ }
+
+ // 3) http(s) 图标:不代拉(页面本身没有网络),直接用远程地址
+ return { url: icon };
+}
+
+function mimeOf(name) {
+ const ext = String(name).toLowerCase().split(".").pop();
+ return { svg: "image/svg+xml", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", ico: "image/x-icon" }[ext] || "application/octet-stream";
+}
+
+export { readJson };
diff --git a/packages/chat/lib/mcp.mjs b/packages/chat/lib/mcp.mjs
new file mode 100644
index 0000000..89be219
--- /dev/null
+++ b/packages/chat/lib/mcp.mjs
@@ -0,0 +1,469 @@
+// magpie MCP 客户端:Streamable HTTP + stdio。只依赖 Node/Bun 内置模块与全局 fetch。
+// 契约见 CONTRACT.md「lib/mcp.mjs 必需导出」。
+import { readFileSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { homedir } from "node:os";
+import path from "node:path";
+
+const PROTOCOL_VERSION = "2024-11-05";
+const CLIENT_INFO = { name: "magpie", version: "0.1.0" };
+const TIMEOUT_MS = 60_000;
+
+const httpSessions = new Map(); // key -> { id, ready }
+const stdioSessions = new Map(); // key -> { proc, buf, err, pending, seq, closed, ready }
+let seq = 0;
+
+/* ---------------- 配置 ---------------- */
+
+// 与 lib/library.mjs 的 configDir 保持一致:支持 XDG_CONFIG_HOME 覆盖
+function configDir() {
+ const xdg = process.env.XDG_CONFIG_HOME;
+ return xdg ? path.join(xdg, "magpie") : path.join(homedir(), ".config", "magpie");
+}
+
+export function loadServers() {
+ const file =
+ process.env.MAGPIE_LIBRARY || path.join(configDir(), "library.json");
+ let raw;
+ try {
+ raw = readFileSync(file, "utf8");
+ } catch (e) {
+ if (e.code === "ENOENT") return []; // 没装过 magpie 配置就当没有服务器
+ throw new Error(`读取 magpie 配置失败:${file}(${e.message})`);
+ }
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch (e) {
+ throw new Error(`magpie 配置不是合法 JSON:${file}(${e.message})`);
+ }
+ const list = Array.isArray(data?.mcp) ? data.mcp : [];
+ const out = [];
+ for (const item of list) {
+ if (!item || typeof item !== "object" || !item.name) continue;
+ const transport =
+ item.transport === "stdio" || item.transport === "http"
+ ? item.transport
+ : item.command
+ ? "stdio"
+ : "http";
+ const server = { name: String(item.name), transport };
+ // library.mjs 会带 detail 字段,这里也保留,方便前端展示
+ if (typeof item.detail === "string") server.detail = item.detail;
+ if (item.env && typeof item.env === "object") server.env = { ...item.env };
+ if (transport === "http") {
+ server.url = typeof item.url === "string" ? item.url : "";
+ if (item.headers && typeof item.headers === "object") server.headers = { ...item.headers };
+ } else {
+ server.command = typeof item.command === "string" ? item.command : "";
+ server.args = Array.isArray(item.args) ? item.args.map(String) : [];
+ }
+ out.push(server);
+ }
+ return out;
+}
+
+/* ---------------- 对外 API ---------------- */
+
+export async function listTools(server) {
+ const target = targetOf(server);
+ const result = await rpc(target, "tools/list", {});
+ const tools = Array.isArray(result?.tools) ? result.tools : [];
+ return tools.map((t) => ({
+ name: String(t?.name ?? ""),
+ description: typeof t?.description === "string" ? t.description : "",
+ inputSchema: t?.inputSchema ?? { type: "object", properties: {} },
+ server: target.name,
+ }));
+}
+
+export async function callTool(server, name, args) {
+ if (!name) throw new Error("调用 MCP 工具时缺少工具名");
+ const target = targetOf(server);
+ const result = await rpc(target, "tools/call", {
+ name: String(name),
+ arguments: args && typeof args === "object" ? args : {},
+ });
+ const parts = [];
+ for (const c of Array.isArray(result?.content) ? result.content : []) {
+ if (c?.type === "text") parts.push(String(c.text ?? ""));
+ else if (c?.type === "image") parts.push(`[图片 ${c.mimeType ?? "unknown"},已省略]`);
+ else if (c?.type === "resource") parts.push(String(c.resource?.text ?? `[资源 ${c.resource?.uri ?? ""}]`));
+ else if (c?.type === "audio") parts.push(`[音频 ${c.mimeType ?? "unknown"},已省略]`);
+ else parts.push(JSON.stringify(c));
+ }
+ let text = parts.join("\n").trim();
+ if (!text && result?.structuredContent) text = JSON.stringify(result.structuredContent, null, 2);
+ if (!text && result != null) text = JSON.stringify(result);
+ return { text, isError: Boolean(result?.isError) };
+}
+
+export async function closeAll() {
+ for (const session of stdioSessions.values()) killStdio(session);
+ stdioSessions.clear();
+ httpSessions.clear();
+}
+
+/* ---------------- 公共 ---------------- */
+
+function targetOf(server) {
+ if (typeof server === "string") {
+ const found = loadServers().find((s) => s.name === server);
+ if (!found) throw new Error(`未在 magpie 配置里找到 MCP 服务器「${server}」`);
+ server = found;
+ }
+ if (!server || typeof server !== "object" || !server.name) {
+ throw new Error("MCP 服务器配置无效:缺少 name");
+ }
+ const transport = server.transport === "stdio" ? "stdio" : "http";
+ const target = { name: String(server.name), transport };
+ if (transport === "http") {
+ if (!server.url) throw new Error(`MCP 服务器「${target.name}」缺少 url,无法连接`);
+ target.url = server.url;
+ target.headers =
+ server.headers && typeof server.headers === "object" ? { ...server.headers } : {};
+ } else {
+ if (!server.command) throw new Error(`MCP 服务器「${target.name}」缺少 command,无法启动`);
+ target.command = server.command;
+ target.args = Array.isArray(server.args) ? server.args.map(String) : [];
+ target.env = server.env && typeof server.env === "object" ? { ...server.env } : null;
+ }
+ target.key = `${target.name}\u0000${transport === "http" ? target.url : target.command}`;
+ return target;
+}
+
+function rpc(target, method, params) {
+ return target.transport === "http"
+ ? httpRpc(target, method, params)
+ : stdioRpc(target, method, params);
+}
+
+/* ---------------- HTTP (Streamable MCP) ---------------- */
+
+async function ensureHttp(target) {
+ let session = httpSessions.get(target.key);
+ if (session) {
+ await session.ready;
+ return session;
+ }
+ session = { id: null, ready: null };
+ session.ready = (async () => {
+ const id = ++seq;
+ const res = await httpPost(
+ target,
+ {
+ jsonrpc: "2.0",
+ id,
+ method: "initialize",
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO },
+ },
+ session,
+ );
+ session.id = res.headers.get("mcp-session-id") || null;
+ const msg = await readRpc(target, res, id);
+ if (!msg) throw new Error(`MCP 服务器「${target.name}」的 initialize 没有返回结果`);
+ if (msg.error) {
+ throw new Error(
+ `MCP 服务器「${target.name}」拒绝初始化:${msg.error.message || JSON.stringify(msg.error)}`,
+ );
+ }
+ // initialized 通知:部分实现不回 202,出错也不阻断后续调用
+ try {
+ const note = await httpPost(target, { jsonrpc: "2.0", method: "notifications/initialized" }, session);
+ const sid = note.headers.get("mcp-session-id");
+ if (sid) session.id = sid;
+ await note.text().catch(() => "");
+ } catch {
+ /* ignore */
+ }
+ })().catch((e) => {
+ httpSessions.delete(target.key);
+ throw e;
+ });
+ session.ready.catch(() => {});
+ httpSessions.set(target.key, session);
+ await session.ready;
+ return session;
+}
+
+async function httpRpc(target, method, params) {
+ let session = await ensureHttp(target);
+ const attempt = async () => {
+ const id = ++seq;
+ const res = await httpPost(target, { jsonrpc: "2.0", id, method, params }, session);
+ const sid = res.headers.get("mcp-session-id");
+ if (sid) session.id = sid;
+ if (res.status === 404 && session.id) {
+ await res.text().catch(() => "");
+ const err = new Error("MCP 会话已过期");
+ err.expired = true;
+ throw err;
+ }
+ const msg = await readRpc(target, res, id);
+ if (!msg) throw new Error(`MCP 服务器「${target.name}」没有返回 ${method} 的结果`);
+ if (msg.error) {
+ throw new Error(
+ `MCP 服务器「${target.name}」执行 ${method} 出错:${msg.error.message || JSON.stringify(msg.error)}`,
+ );
+ }
+ return msg.result;
+ };
+ try {
+ return await attempt();
+ } catch (e) {
+ if (!e.expired) throw e;
+ httpSessions.delete(target.key);
+ session = await ensureHttp(target);
+ return await attempt();
+ }
+}
+
+async function httpPost(target, body, session) {
+ const headers = {
+ "content-type": "application/json",
+ accept: "application/json, text/event-stream",
+ ...target.headers,
+ };
+ if (session?.id) headers["mcp-session-id"] = session.id;
+ try {
+ return await fetch(target.url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (e) {
+ const reason =
+ e?.name === "TimeoutError"
+ ? `超过 ${TIMEOUT_MS / 1000}s 未响应`
+ : e?.cause?.message || e?.message || String(e);
+ throw new Error(`连接 MCP 服务器「${target.name}」失败(${target.url}):${reason}`);
+ }
+}
+
+async function readRpc(target, res, id) {
+ if (!res.ok) {
+ const body = await res.text().catch(() => "");
+ const hint =
+ res.status === 401 || res.status === 403
+ ? ",请检查 headers 里的 Authorization"
+ : res.status === 404
+ ? ",地址或会话不存在"
+ : "";
+ throw new Error(
+ `MCP 服务器「${target.name}」返回 HTTP ${res.status}${hint}${body ? `:${body.slice(0, 300)}` : ""}`,
+ );
+ }
+ if (res.status === 202 || res.status === 204) return null;
+ const ct = (res.headers.get("content-type") || "").toLowerCase();
+ const text = await res.text();
+ if (!text.trim()) return null;
+ const messages = ct.includes("text/event-stream") || text.startsWith("data:")
+ ? parseSse(text)
+ : parseJson(text);
+ return pick(messages, id);
+}
+
+function parseJson(text) {
+ try {
+ const data = JSON.parse(text);
+ return Array.isArray(data) ? data : [data];
+ } catch {
+ throw new Error(`MCP 服务器返回了无法解析的响应:${text.slice(0, 200)}`);
+ }
+}
+
+function parseSse(text) {
+ const out = [];
+ for (const block of text.split(/\r?\n\r?\n/)) {
+ const data = block
+ .split(/\r?\n/)
+ .filter((line) => line.startsWith("data:"))
+ .map((line) => line.slice(5).replace(/^ /, ""))
+ .join("\n")
+ .trim();
+ if (!data) continue;
+ try {
+ const msg = JSON.parse(data);
+ if (Array.isArray(msg)) out.push(...msg);
+ else out.push(msg);
+ } catch {
+ /* 心跳或非 JSON 事件,忽略 */
+ }
+ }
+ return out;
+}
+
+function pick(messages, id) {
+ if (!messages.length) return null;
+ const same = (m) => m && String(m.id) === String(id);
+ return messages.find(same) || messages.find((m) => m && m.id !== undefined && m.id !== null) || null;
+}
+
+/* ---------------- stdio ---------------- */
+
+function ensureStdio(target) {
+ const existing = stdioSessions.get(target.key);
+ if (existing) return existing;
+ const session = { proc: null, buf: "", err: "", pending: new Map(), seq: 0, closed: false };
+ session.ready = (async () => {
+ const proc = spawn(target.command, target.args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ env: target.env ? { ...process.env, ...target.env } : process.env,
+ });
+ session.proc = proc;
+ proc.stdin.on("error", () => {});
+ proc.stdout.setEncoding("utf8");
+ proc.stdout.on("data", (chunk) => onStdout(session, target, chunk));
+ proc.stderr.setEncoding("utf8");
+ proc.stderr.on("data", (chunk) => {
+ session.err = (session.err + chunk).slice(-4000);
+ });
+ proc.on("error", (e) => {
+ const hint = e?.code === "ENOENT" ? "(命令不存在,检查是否已安装或不在 PATH)" : "";
+ fail(session, `无法启动 MCP 服务器「${target.name}」:${target.command}${hint}(${e.message})`);
+ });
+ proc.on("exit", (code, signal) => {
+ if (session.closed) return;
+ const tail = session.err.trim().slice(-600);
+ fail(
+ session,
+ `MCP 服务器「${target.name}」(${target.command})已退出(code=${code}${signal ? `, signal=${signal}` : ""})${tail ? `:${tail}` : ""}`,
+ );
+ stdioSessions.delete(target.key);
+ });
+ await stdioCall(session, target, "initialize", {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: CLIENT_INFO,
+ });
+ send(session, { jsonrpc: "2.0", method: "notifications/initialized" });
+ })().catch((e) => {
+ killStdio(session);
+ stdioSessions.delete(target.key);
+ throw e;
+ });
+ session.ready.catch(() => {});
+ stdioSessions.set(target.key, session);
+ return session;
+}
+
+async function stdioRpc(target, method, params) {
+ const session = ensureStdio(target);
+ await session.ready;
+ return stdioCall(session, target, method, params);
+}
+
+function stdioCall(session, target, method, params) {
+ if (session.closed) return Promise.reject(new Error(`MCP 服务器「${target.name}」已停止`));
+ const id = ++session.seq;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ session.pending.delete(id);
+ const tail = session.err.trim().slice(-400);
+ reject(
+ new Error(
+ `MCP 服务器「${target.name}」在 ${TIMEOUT_MS / 1000}s 内没有响应 ${method}${tail ? `:${tail}` : ""}`,
+ ),
+ );
+ }, TIMEOUT_MS);
+ timer.unref?.();
+ session.pending.set(id, { resolve, reject, timer, method });
+ if (!send(session, { jsonrpc: "2.0", id, method, params })) {
+ session.pending.delete(id);
+ clearTimeout(timer);
+ const tail = session.err.trim().slice(-400);
+ reject(
+ new Error(
+ `无法向 MCP 服务器「${target.name}」写入请求,进程可能已退出${tail ? `:${tail}` : ""}`,
+ ),
+ );
+ }
+ });
+}
+
+function send(session, msg) {
+ const proc = session.proc;
+ if (!proc || proc.exitCode !== null || !proc.stdin.writable) return false;
+ try {
+ proc.stdin.write(JSON.stringify(msg) + "\n");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function onStdout(session, target, chunk) {
+ session.buf += chunk;
+ let idx;
+ while ((idx = session.buf.indexOf("\n")) >= 0) {
+ const line = session.buf.slice(0, idx).trim();
+ session.buf = session.buf.slice(idx + 1);
+ if (!line) continue;
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ continue; // 非 JSON 行(启动日志等)直接跳过
+ }
+ for (const m of Array.isArray(msg) ? msg : [msg]) handleStdioMessage(session, target, m);
+ }
+}
+
+function handleStdioMessage(session, target, msg) {
+ if (!msg || typeof msg !== "object") return;
+ const pending = msg.id !== undefined && msg.id !== null ? session.pending.get(msg.id) : undefined;
+ if (pending) {
+ session.pending.delete(msg.id);
+ clearTimeout(pending.timer);
+ if (msg.error) {
+ pending.reject(
+ new Error(
+ `MCP 服务器「${target.name}」执行 ${pending.method} 出错:${msg.error.message || JSON.stringify(msg.error)}`,
+ ),
+ );
+ } else {
+ pending.resolve(msg.result);
+ }
+ return;
+ }
+ // 服务器反向请求(ping / roots 等):回空结果,避免对方等待
+ if (msg.id !== undefined && msg.id !== null && msg.method) {
+ send(
+ session,
+ msg.method === "ping"
+ ? { jsonrpc: "2.0", id: msg.id, result: {} }
+ : { jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "method not supported" } },
+ );
+ }
+}
+
+function fail(session, message) {
+ session.closed = true;
+ for (const p of session.pending.values()) {
+ clearTimeout(p.timer);
+ p.reject(new Error(message));
+ }
+ session.pending.clear();
+}
+
+function killStdio(session) {
+ session.closed = true;
+ fail(session, "MCP 客户端已关闭");
+ const proc = session.proc;
+ if (!proc || proc.exitCode !== null) return;
+ try {
+ proc.kill();
+ } catch {
+ /* ignore */
+ }
+ const timer = setTimeout(() => {
+ try {
+ proc.kill("SIGKILL");
+ } catch {
+ /* ignore */
+ }
+ }, 2000);
+ timer.unref?.();
+}
diff --git a/packages/chat/lib/server.mjs b/packages/chat/lib/server.mjs
new file mode 100644
index 0000000..a54f1df
--- /dev/null
+++ b/packages/chat/lib/server.mjs
@@ -0,0 +1,740 @@
+// magpie-chat 的服务:给窗口里的对话页提供 /api/*,并把聊天请求转给 magpie 网关。
+// 只用内置模块,不装依赖。
+
+import { createServer } from "node:http";
+import { readFile, writeFile } from "node:fs/promises";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join, extname, normalize } from "node:path";
+import { fileURLToPath } from "node:url";
+import { composeSystem, configDir, groupIcons, libraryView, providerIcons, readJson, readMcp, readProviderIcon } from "./library.mjs";
+import { chatCompletions, gatewayURL, listModels, resolveGateway, sseChunks } from "./gateway.mjs";
+import { callTool, closeAll, listTools } from "./mcp.mjs";
+
+const here = fileURLToPath(new URL(".", import.meta.url));
+const UI_ROOT = join(here, "..", "chat");
+const MAX_TOOL_ROUNDS = 8;
+
+// 插件版本,从包里的 package.json 读(别在两处写死同一个数字)
+const VERSION = (() => {
+ try {
+ return JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")).version || "";
+ } catch {
+ return "";
+ }
+})();
+
+const MIME = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".mjs": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".json": "application/json; charset=utf-8",
+ ".woff2": "font/woff2",
+};
+
+// ---- 设置与对话:存在 magpie 配置目录下,跟插件自己的数据放一起 ----
+function dataDir(configDirPath) {
+ const dir = join(configDirPath || configDir(), "magpie-chat");
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+// 从 magpie 的 settings.json 读用户设的字体,拼成覆盖 :root 的 CSS。
+// 没设就返回空串,页面用自己的兜底字体栈。
+async function fontCss() {
+ const UI_FALLBACK = '-apple-system, BlinkMacSystemFont, "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "PingFang SC", system-ui, sans-serif';
+ const CODE_FALLBACK = 'ui-monospace, "SF Mono", Menlo, Consolas, monospace';
+ const quote = (s) => '"' + String(s).replace(/["\\\x00-\x1f]/g, "") + '"';
+ const parts = [];
+ try {
+ const s = JSON.parse(await readFile(join(configDir(), "settings.json"), "utf8"));
+ const has = (f) => f && typeof f.family === "string" && f.family.trim();
+ if (has(s.uiFont)) {
+ const f = s.uiFont;
+ // 字体名后面接 magpie 自己的基础栈:找不到那个字体时逐级回落
+ parts.push(`--font: ${quote(f.family)}, ${UI_FALLBACK};`);
+ if (Number.isFinite(f.weight) && f.weight >= 1 && f.weight <= 1000) parts.push(`--font-weight: ${f.weight};`);
+ if (["normal", "italic", "oblique"].includes(f.style)) parts.push(`--font-style: ${f.style};`);
+ if (Number.isFinite(f.stretch) && f.stretch > 0) parts.push(`--font-stretch: ${f.stretch}%;`);
+ }
+ if (has(s.codeFont)) {
+ const c = s.codeFont;
+ parts.push(`--code: ${quote(c.family)}, ${CODE_FALLBACK};`);
+ if (Number.isFinite(c.weight) && c.weight >= 1 && c.weight <= 1000) parts.push(`--code-weight: ${c.weight};`);
+ }
+ } catch {
+ return ""; // 读不到设置就用页面自己的兜底
+ }
+ return parts.length ? `:root { ${parts.join(" ")} }` : "";
+}
+
+const DEFAULTS = {
+ model: "", effort: "", system: "", instructions: [], skills: [], mcp: [],
+ temperature: 0.7, maxTokens: 0, showReasoning: true,
+ pinned: [], // 置顶的对话 id,按置顶顺序排在列表最前
+ sidebar: true, // 左侧栏是否展开
+ settingsOpen: false, // 右侧设置栏是否打开
+ leftWidth: 0, // 左侧栏宽度(0 = 用默认值)
+ rightWidth: 0, // 设置栏宽度(0 = 用默认值)
+ convWidth: 72, // 会话内容列宽度(%),100 = 铺满
+ composerWidth: 70, // 输入框宽度(%)
+};
+
+function cleanSettings(raw) {
+ const s = { ...DEFAULTS, ...(raw && typeof raw === "object" ? raw : {}) };
+ return {
+ model: String(s.model || ""),
+ effort: String(s.effort || ""),
+ system: String(s.system || ""),
+ instructions: Array.isArray(s.instructions) ? s.instructions.map(String) : [],
+ skills: Array.isArray(s.skills) ? s.skills.map(String) : [],
+ mcp: Array.isArray(s.mcp) ? s.mcp.map(String) : [],
+ temperature: Number.isFinite(Number(s.temperature)) ? Number(s.temperature) : 0.7,
+ maxTokens: Number.isFinite(Number(s.maxTokens)) ? Number(s.maxTokens) : 0,
+ showReasoning: s.showReasoning !== false,
+ pinned: Array.isArray(s.pinned) ? s.pinned.map(String).filter(Boolean).slice(0, 200) : [],
+ sidebar: s.sidebar !== false,
+ settingsOpen: s.settingsOpen === true,
+ leftWidth: Number.isFinite(Number(s.leftWidth)) ? Math.max(0, Math.min(420, Number(s.leftWidth))) : 0,
+ rightWidth: Number.isFinite(Number(s.rightWidth)) ? Math.max(0, Math.min(560, Number(s.rightWidth))) : 0,
+ convWidth: Number.isFinite(Number(s.convWidth)) ? Math.max(0, Math.min(100, Number(s.convWidth))) : 72,
+ composerWidth: Number.isFinite(Number(s.composerWidth)) ? Math.max(40, Math.min(100, Number(s.composerWidth))) : 70,
+ };
+}
+
+export function createStore(configDirPath) {
+ const dir = dataDir(configDirPath);
+ const settingsPath = join(dir, "settings.json");
+ const convDir = join(dir, "conversations");
+ if (!existsSync(convDir)) mkdirSync(convDir, { recursive: true });
+
+ const store = {
+ dir,
+ async settings() {
+ return cleanSettings(await readJson(settingsPath, {}));
+ },
+ async saveSettings(patch) {
+ const next = cleanSettings({ ...(await store.settings()), ...(patch || {}) });
+ await writeFile(settingsPath, JSON.stringify(next, null, 2));
+ return next;
+ },
+ convPath(id) {
+ const safe = String(id || "").replace(/[^\w-]/g, "").slice(0, 64);
+ return safe ? join(convDir, safe + ".json") : "";
+ },
+ async getConversation(id) {
+ const p = store.convPath(id);
+ if (!p) return null;
+ return readJson(p, null);
+ },
+ async saveConversation(conv) {
+ const id = conv.id || "c_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
+ const messages = Array.isArray(conv.messages) ? conv.messages.slice(-400) : [];
+ const title = String(conv.title || firstLine(messages) || "新对话").slice(0, 90);
+ const out = { id, title, updated: Date.now(), messages };
+ const p = store.convPath(id);
+ if (!p) throw new Error("bad conversation id");
+ await writeFile(p, JSON.stringify(out));
+ return out;
+ },
+ async listConversations() {
+ const { readdir } = await import("node:fs/promises");
+ const names = await readdir(convDir).catch(() => []);
+ const items = [];
+ for (const n of names) {
+ if (!n.endsWith(".json")) continue;
+ const c = await readJson(join(convDir, n), null);
+ if (!c?.id) continue;
+ const last = [...(c.messages || [])].reverse().find((m) => m.role === "user");
+ items.push({ id: c.id, title: c.title, updated: c.updated || 0, preview: String(last?.content || "").slice(0, 120) });
+ }
+ // 置顶的排在前面(按置顶顺序),其余按最近更新
+ const pinned = (await store.settings()).pinned || [];
+ const rank = new Map(pinned.map((id, i) => [id, i]));
+ return items.sort((a, b) => {
+ const ra = rank.has(a.id) ? rank.get(a.id) : -1;
+ const rb = rank.has(b.id) ? rank.get(b.id) : -1;
+ if (ra >= 0 && rb >= 0) return ra - rb;
+ if (ra >= 0) return -1;
+ if (rb >= 0) return 1;
+ return b.updated - a.updated;
+ }).map((item) => ({ ...item, pinned: rank.has(item.id) }));
+ },
+ async removeConversation(id) {
+ const { rm } = await import("node:fs/promises");
+ const p = store.convPath(id);
+ if (p) await rm(p, { force: true });
+ },
+ };
+ return store;
+}
+
+// 没有图标文件时生成的首字母徽章:颜色按名字散列,同一供应商总是同一色
+function letterIcon(name) {
+ const s = String(name || "?");
+ let hue = 0;
+ for (let i = 0; i < s.length; i++) hue = (hue * 31 + s.charCodeAt(i)) % 360;
+ const ch = s.slice(0, 1).toUpperCase().replace(/[<&>"]/g, "");
+ return ``;
+}
+
+function firstLine(messages) {
+ const u = (messages || []).find((m) => m.role === "user");
+ const text = String(u?.content || "").trim().replace(/\s+/g, " ");
+ return text.slice(0, 60);
+}
+
+// ---- HTTP ----
+// magpie 的插件页面跑在 sandbox="allow-scripts" 的框架里,origin 是 opaque,
+// 浏览器发来的 Origin 就是字面量 "null"。直接在地址栏打开同一个服务时,Origin 是本服务自己。
+// 其他来源一律拒绝:这个服务能替用户烧额度,不能给任意网页用。
+let OWN = new Set();
+
+function originAllowed(req) {
+ const o = req.headers.origin;
+ return o === undefined || o === "null" || OWN.has(o);
+}
+
+function corsHeaders(req) {
+ const o = req.headers?.origin;
+ const allow = o === "null" ? "null" : o && OWN.has(o) ? o : "null";
+ return {
+ "access-control-allow-origin": allow,
+ "access-control-allow-headers": "content-type",
+ "access-control-allow-methods": "GET,POST,DELETE,OPTIONS",
+ vary: "Origin",
+ };
+}
+
+function send(res, status, body, type = "application/json; charset=utf-8") {
+ const data = typeof body === "string" || body instanceof Uint8Array ? body : JSON.stringify(body);
+ res.writeHead(status, {
+ "content-type": type,
+ "cache-control": "no-store",
+ ...corsHeaders(res.req),
+ "x-content-type-options": "nosniff",
+ });
+ res.end(data);
+}
+
+async function readBody(req) {
+ const chunks = [];
+ let size = 0;
+ for await (const c of req) {
+ size += c.length;
+ if (size > 24 * 1024 * 1024) throw new Error("请求太大");
+ chunks.push(c);
+ }
+ if (!chunks.length) return {};
+ try {
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ } catch {
+ throw new Error("请求不是合法的 JSON");
+ }
+}
+
+function sseHead(res) {
+ res.writeHead(200, {
+ "content-type": "text/event-stream; charset=utf-8",
+ "cache-control": "no-store",
+ connection: "keep-alive",
+ ...corsHeaders(res.req),
+ "x-accel-buffering": "no",
+ });
+ res.flushHeaders?.();
+}
+
+function sse(res, type, data) {
+ if (res.writableEnded) return;
+ res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);
+}
+
+// system prompt 之外,把 MCP 工具的用途也告诉模型(工具本身用 function calling 给)
+// 工具清单写在 system 里会和 function 定义重复一遍,所以只给一句交代。
+function toolsHint(tools) {
+ if (!tools.length) return "";
+ return `# 工具\n\n你可以调用用户配置的 MCP 工具(共 ${tools.length} 个)。需要时直接调用,不要臆造结果;用不上就直接回答。`;
+}
+
+// 工具的 schema 是提示词里最大的一块:GitHub 那 46 个工具光描述和参数就有上千万字符。
+// 只留名字、第一行说明,参数表裁到前 8 个字段、每个字段只留类型和一句说明。
+const MAX_PROPS = 8;
+function slimSchema(schema) {
+ if (!schema || typeof schema !== "object") return { type: "object", properties: {} };
+ const out = { type: "object", properties: {} };
+ const props = schema.properties && typeof schema.properties === "object" ? schema.properties : {};
+ for (const [key, val] of Object.entries(props).slice(0, MAX_PROPS)) {
+ if (!val || typeof val !== "object") { out.properties[key] = { type: "string" }; continue; }
+ const slim = { type: val.type || "string" };
+ if (val.description) slim.description = String(val.description).split("\n")[0].slice(0, 120);
+ if (Array.isArray(val.enum)) slim.enum = val.enum.slice(0, 20);
+ if (val.type === "array" && val.items?.type) slim.items = { type: val.items.type };
+ out.properties[key] = slim;
+ }
+ if (Array.isArray(schema.required) && schema.required.length) out.required = schema.required.slice(0, MAX_PROPS);
+ return out;
+}
+
+function toFunctionTools(tools) {
+ return tools.map((t) => ({
+ type: "function",
+ function: {
+ name: t.name,
+ description: (t.description || "").split("\n")[0].slice(0, 200) || t.name,
+ parameters: slimSchema(t.inputSchema),
+ },
+ }));
+}
+
+// 一条消息转成网关认的 content:
+// 没有图片就是字符串;有图片就变成 [{type:"text"},{type:"image_url",image_url:{url}}]
+// (image_url 收 data: URL,magpie 网关会原样转给上游)。
+function toGatewayContent(m) {
+ const text = String(m.content ?? "");
+ const files = Array.isArray(m.files) ? m.files : [];
+ const images = files.filter((f) => f && f.kind === "image" && f.data);
+ if (!images.length) return text;
+ const parts = [];
+ if (text.trim()) parts.push({ type: "text", text });
+ for (const img of images) {
+ parts.push({ type: "image_url", image_url: { url: String(img.data) } });
+ }
+ // 非图片附件以文字交代给模型,避免它不知道用户放了文件
+ const others = files.filter((f) => f && f.kind !== "image");
+ if (others.length) {
+ parts.push({ type: "text", text: others.map((f) => `[附件] ${f.name || "文件"}(${f.size || 0} 字节)`).join("\n") });
+ }
+ return parts;
+}
+
+// 一轮对话:可多次工具调用;把每条增量转成 SSE 发回浏览器
+async function runChat({ res, body, settings, store }, controllers) {
+ const clientId = String(body.clientId || "");
+ const abort = new AbortController();
+ if (clientId) controllers.set(clientId, abort);
+ res.on("close", () => { if (!res.writableEnded) abort.abort(); });
+
+ const started = Date.now();
+ const model = String(body.model || settings.model || "");
+ const effort = String(body.effort ?? settings.effort ?? "");
+ const temperature = Number.isFinite(Number(body.temperature)) ? Number(body.temperature) : settings.temperature;
+ const maxTokens = Number.isFinite(Number(body.maxTokens)) ? Number(body.maxTokens) : settings.maxTokens;
+ const wantTools = body.useTools !== false && (settings.mcp || []).length > 0;
+
+ const history = Array.isArray(body.messages) ? body.messages.filter((m) => m && (m.role === "user" || m.role === "assistant")) : [];
+ // 只挂了图片/文件、没写文字的消息也算有内容
+ const hasContent = history.some((m) => String(m.content ?? "").trim() || (Array.isArray(m.files) && m.files.length));
+ if (!model) { sse(res, "error", { message: "没有选模型:在右下角挑一个 magpie 的模型" }); res.end(); return; }
+ if (!history.length || !hasContent) { sse(res, "error", { message: "没有内容可发送" }); res.end(); return; }
+
+ // 工具:只把跟这轮问题相关的交出去。
+ // GitHub 一个服务器就有 46 个工具,全塞给模型时提示词会涨到上千万 token:
+ // 又慢又贵,模型还会被工具说明淹掉、几乎不产出正文。所以按问题里的词筛,
+ // 没筛出相关的就只留最通用的几个,宁可少给也不要全给。
+ let tools = [];
+ let toolNote = "";
+ if (wantTools) {
+ const servers = await readMcp();
+ const picked = servers.filter((s) => (settings.mcp || []).includes(s.name));
+ const all = [];
+ for (const s of picked) {
+ try {
+ const list = await listTools(s);
+ for (const t of list) all.push({ ...t, server: s.name, name: s.name + "_" + t.name.replace(/[^\w-]/g, "_"), rawName: t.name });
+ } catch (err) {
+ sse(res, "tool", { phase: "error", name: s.name, result: "无法连接 " + s.name + ":" + (err?.message || err) });
+ }
+ }
+ const q = String(history[history.length - 1]?.content || "").toLowerCase();
+ const words = q.split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length >= 3);
+ const scored = all.map((t) => {
+ const hay = (t.name + " " + (t.description || "")).toLowerCase();
+ let score = 0;
+ for (const w of words) if (hay.includes(w)) score += w.length > 4 ? 2 : 1;
+ return { t, score };
+ }).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
+ const MAX_TOOLS = 12;
+ tools = scored.slice(0, MAX_TOOLS).map((x) => x.t);
+ if (tools.length < 3) {
+ // 问得太笼统时给一组最通用的,但仍然封顶
+ const common = /^(get|list|search|read|fetch|query)_|(_search|_list|_get)$/;
+ const extra = all.filter((t) => common.test(t.rawName) && !tools.includes(t)).slice(0, 8);
+ tools = tools.concat(extra).slice(0, MAX_TOOLS);
+ }
+ if (all.length > tools.length) {
+ toolNote = `(这次提供了 ${tools.length}/${all.length} 个工具:按你的问题挑的)`;
+ }
+ }
+
+ const system = [await composeSystem(settings), toolsHint(tools)].filter(Boolean).join("\n\n");
+ if (toolNote) sse(res, "tool", { phase: "note", name: "tools", result: toolNote });
+ const messages = [];
+ if (system) messages.push({ role: "system", content: system });
+ for (const m of history) {
+ const calls = m.role === "assistant" && Array.isArray(m.toolCalls) ? m.toolCalls.filter((c) => c && c.name) : [];
+ if (!calls.length) {
+ messages.push({ role: m.role, content: toGatewayContent(m) });
+ continue;
+ }
+ // 一轮工具调用的完整重放:assistant.tool_calls 后面必须跟每个调用的 tool 结果,
+ // 少一条网关就拒收,所以没有结果的调用不放进历史。
+ const done = calls.filter((c) => String(c.result ?? "") !== "" || c.isError);
+ if (!done.length) {
+ if (m.content) messages.push({ role: "assistant", content: String(m.content) });
+ continue;
+ }
+ messages.push({
+ role: "assistant",
+ content: m.content || "",
+ tool_calls: done.map((c, i) => ({
+ id: String(c.id || `history_${i}`),
+ type: "function",
+ function: { name: String(c.name), arguments: typeof c.args === "string" ? c.args : JSON.stringify(c.args || {}) },
+ })),
+ });
+ for (const [i, c] of done.entries()) {
+ messages.push({
+ role: "tool",
+ tool_call_id: String(c.id || `history_${i}`),
+ content: String(c.result ?? "").slice(0, 20000) || (c.isError ? "error" : "ok"),
+ });
+ }
+ }
+
+ sse(res, "start", { model, tools: tools.map((t) => t.name), gateway: await resolveGateway().catch(() => gatewayURL()) });
+
+ let usageTotal = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
+ try {
+ for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
+ const payload = { model, messages, stream: true };
+ if (effort) payload.reasoning_effort = effort;
+ if (Number.isFinite(temperature)) payload.temperature = temperature;
+ if (maxTokens > 0) payload.max_tokens = maxTokens;
+ if (tools.length) {
+ payload.tools = toFunctionTools(tools);
+ payload.tool_choice = "auto";
+ }
+
+ const upstream = await chatCompletions(payload, { signal: abort.signal });
+ if (!upstream.ok || !upstream.body) {
+ const text = upstream.body ? (await upstream.text()).slice(0, 600) : "";
+ sse(res, "error", { message: `magpie ${upstream.status}${text ? " · " + text : ""}` });
+ res.end();
+ return;
+ }
+
+ let content = "";
+ let reasoning = "";
+ const calls = new Map(); // index -> { id, name, args }
+ let finish = "";
+
+ for await (const chunk of sseChunks(upstream)) {
+ const choice = chunk?.choices?.[0];
+ if (chunk?.usage) {
+ usageTotal = {
+ prompt_tokens: usageTotal.prompt_tokens + (chunk.usage.prompt_tokens || 0),
+ completion_tokens: usageTotal.completion_tokens + (chunk.usage.completion_tokens || 0),
+ total_tokens: usageTotal.total_tokens + (chunk.usage.total_tokens || 0),
+ };
+ }
+ if (!choice) continue;
+ const d = choice.delta || {};
+ if (d.reasoning_content) { reasoning += d.reasoning_content; sse(res, "reasoning", { text: d.reasoning_content }); }
+ if (d.content) { content += d.content; sse(res, "delta", { text: d.content }); }
+ for (const tc of d.tool_calls || []) {
+ const i = tc.index ?? 0;
+ const cur = calls.get(i) || { id: "", name: "", args: "" };
+ if (tc.id) cur.id = tc.id;
+ if (tc.function?.name) cur.name += tc.function.name;
+ if (tc.function?.arguments) cur.args += tc.function.arguments;
+ calls.set(i, cur);
+ }
+ if (choice.finish_reason) finish = choice.finish_reason;
+ }
+
+ if (calls.size && (finish === "tool_calls" || finish === "stop")) {
+ const made = [...calls.values()].filter((c) => c.name);
+ if (!made.length) { sse(res, "done", { ms: Date.now() - started, usage: usageTotal }); res.end(); return; }
+
+ messages.push({
+ role: "assistant",
+ content: content || "",
+ tool_calls: made.map((c, i) => ({ id: c.id || `call_${round}_${i}`, type: "function", function: { name: c.name, arguments: c.args || "{}" } })),
+ });
+ if (content) sse(res, "delta", { text: "" });
+
+ for (const c of made) {
+ const id = c.id || `call_${round}`;
+ let args = {};
+ try { args = JSON.parse(c.args || "{}"); } catch { args = {}; }
+ const tool = tools.find((t) => t.name === c.name) || tools.find((t) => t.rawName === c.name);
+ sse(res, "tool", { phase: "call", id, name: c.name, args });
+ let result = "", isError = false;
+ if (!tool) {
+ result = "没有这个工具:" + c.name; isError = true;
+ } else {
+ const server = (await readMcp()).find((s) => s.name === tool.server);
+ try {
+ const out = await callTool(server, tool.rawName, args);
+ result = out.text; isError = Boolean(out.isError);
+ } catch (err) {
+ result = String(err?.message || err); isError = true;
+ }
+ }
+ sse(res, "tool", { phase: "result", id, name: c.name, args, result: String(result).slice(0, 20000), isError });
+ messages.push({ role: "tool", tool_call_id: id, content: String(result).slice(0, 60000) || (isError ? "error" : "ok") });
+ }
+ continue; // 让模型基于工具结果继续
+ }
+
+ sse(res, "usage", usageTotal);
+ sse(res, "done", { ms: Date.now() - started });
+ res.end();
+ return;
+ }
+ sse(res, "error", { message: `工具调用超过 ${MAX_TOOL_ROUNDS} 轮,已停下` });
+ res.end();
+ } catch (err) {
+ if (abort.signal.aborted) { sse(res, "done", { ms: Date.now() - started, stopped: true }); }
+ else sse(res, "error", { message: String(err?.message || err) });
+ res.end();
+ } finally {
+ if (clientId) controllers.delete(clientId);
+ }
+}
+
+export async function startServer({ configDir: dir, options = {} } = {}) {
+ const store = createStore(dir || configDir());
+ const controllers = new Map();
+ const port = Number(options.port || process.env.MAGPIE_CHAT_PORT || 3477);
+ OWN = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]);
+
+ // 模型列表缓存几十秒,够界面用,又不用每次开页都等网关
+ let cache = { at: 0, models: [] };
+ async function models(opts = {}) {
+ if (Date.now() - cache.at < 30e3 && cache.models.length) return cache.models;
+ const list = await listModels(opts);
+ cache = { at: Date.now(), models: list };
+ return list;
+ }
+
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url || "/", "http://127.0.0.1:" + port);
+ const path = url.pathname;
+ if (!originAllowed(req)) return send(res, 403, { error: "只服务于 magpie 窗口里的对话页" });
+ if (req.method === "OPTIONS") {
+ res.writeHead(204, corsHeaders(req));
+ return res.end();
+ }
+
+ try {
+ if (path.startsWith("/api/")) {
+ if (req.method === "GET" && path === "/api/bootstrap") {
+ const settings = await store.settings();
+ let list = [];
+ let gatewayError = "";
+ await resolveGateway(options).catch(() => "");
+ try { list = await models(options); } catch (err) { gatewayError = String(err?.message || err); }
+ // 模型图标:magpie 的 providers.json 里有各供应商的 logo,能对上就带上
+ try {
+ const icons = await providerIcons(dir);
+ // group/ 这种路由组没有自己的图标,借组里第一个供应商的
+ const groups = await groupIcons(dir).catch(() => new Map());
+ list = list.map((m) => {
+ // 路由组(group/*)的 provider 是 "group",实际供应商在 owner 里
+ const icon = icons.get(m.owner) || icons.get(m.provider)
+ || (m.provider === "group" ? icons.get(groups.get(m.id.replace(/^group\//, "")) || "") : "");
+ return { ...m, icon: icon || "" };
+ });
+ } catch { /* 没有图标就只显示名字 */ }
+ if (!settings.model && list.length) settings.model = list[0].id;
+ const effortOK = list.find((m) => m.id === settings.model)?.efforts?.includes(settings.effort);
+ if (!effortOK) settings.effort = "";
+ return send(res, 200, {
+ port,
+ version: "0.1.0",
+ gateway: gatewayURL(options),
+ settings,
+ models: list,
+ library: await libraryView(dir),
+ error: gatewayError,
+ });
+ }
+ // 供应商图标:模型名字前面那个小图标
+ const iconHit = /^\/api\/icon\/([^/]+)$/.exec(path);
+ if (iconHit && req.method === "GET") {
+ const pid = decodeURIComponent(iconHit[1]);
+ const icon = await readProviderIcon(pid, dir).catch(() => null);
+ if (icon && icon.url) return send(res, 302, "", "text/plain");
+ // 没有图片文件就画一个首字母徽章(magpie 的内置图标编在二进制里,取不到)
+ const body = icon ? icon.data : letterIcon(pid);
+ res.writeHead(200, {
+ "content-type": icon ? icon.type || "application/octet-stream" : "image/svg+xml",
+ "cache-control": "public, max-age=86400",
+ "access-control-allow-origin": "*",
+ });
+ return res.end(body);
+ }
+ // 探活:带路页在跳转前先打这个,确认服务已经起来,
+ // 免得页面直接撞上"127.0.0.1 拒绝连接"。
+ if (path === "/api/ping" && req.method === "GET") {
+ // 版本号从 package.json 读,别再写死(写死会跟实际版本对不上)
+ // 报实际端口(可能不是 3477,被占时会退到 3478…)
+ return send(res, 200, { ok: true, port: actualPort, version: VERSION });
+ }
+
+ // 字体:直接读 magpie 设置里的 uiFont / codeFont,生成一份 CSS 给页面用。
+ //
+ // 为什么从服务端读,而不是让带路页在 magpie 页面里读 CSS 变量:
+ // 带路页能读,但读的时机靠不住 —— magpie 是在设置加载完之后才把
+ // --ui-font 写到 :root 上的,带路页 await 完 magpie.ready 立刻读,
+ // 经常读到空值;页面 CSP 是 connect-src 'none',读不到也没法重试。
+ // 服务是普通 node 进程,直接读 settings.json,什么时候读都准。
+ if (path === "/api/fonts.css" && req.method === "GET") {
+ const css = await fontCss();
+ res.writeHead(200, {
+ "content-type": "text/css; charset=utf-8",
+ "cache-control": "no-store",
+ "access-control-allow-origin": "*",
+ });
+ return res.end(css);
+ }
+
+ if (path === "/api/upload" && req.method === "POST") {
+ const body = await readBody(req);
+ const name = String(body.name || "file").slice(0, 200);
+ const type = String(body.type || "");
+ const data = String(body.data || "");
+ if (!data) return send(res, 400, { error: "没有内容" });
+ // 图片保留 data URL 直接给模型;文本文件转成文本附件
+ const isImage = /^image\//.test(type);
+ if (isImage && data.length > 24 * 1024 * 1024) return send(res, 413, { error: "图片太大(上限约 24MB)" });
+ if (!isImage && data.length > 8 * 1024 * 1024) return send(res, 413, { error: "文件太大(上限约 8MB)" });
+ return send(res, 200, { name, type, kind: isImage ? "image" : "file", size: data.length, data });
+ }
+ if (path === "/api/settings" && req.method === "GET") return send(res, 200, await store.settings());
+ if (path === "/api/settings" && req.method === "POST") {
+ const patch = await readBody(req);
+ return send(res, 200, await store.saveSettings(patch));
+ }
+ if (path === "/api/library" && req.method === "GET") return send(res, 200, await libraryView(dir));
+ if (path === "/api/mcp/tools" && req.method === "GET") {
+ const settings = await store.settings();
+ const servers = (await readMcp(dir)).filter((s) => settings.mcp.includes(s.name));
+ const out = [];
+ for (const s of servers) {
+ try {
+ const tools = await listTools(s);
+ out.push({ name: s.name, ok: true, tools: tools.map((t) => ({ name: t.name, description: t.description, server: s.name })) });
+ } catch (err) {
+ out.push({ name: s.name, ok: false, error: String(err?.message || err), tools: [] });
+ }
+ }
+ return send(res, 200, { servers: out });
+ }
+ if (path === "/api/models" && req.method === "GET") {
+ try { return send(res, 200, { models: await models(options) }); }
+ catch (err) { return send(res, 502, { error: String(err?.message || err), models: [] }); }
+ }
+ if (path === "/api/conversations" && req.method === "GET") return send(res, 200, { items: await store.listConversations() });
+ if (path === "/api/conversations" && req.method === "POST") {
+ const body = await readBody(req);
+ return send(res, 200, await store.saveConversation(body || {}));
+ }
+ const conv = /^\/api\/conversations\/([\w-]+)$/.exec(path);
+ if (conv && req.method === "GET") {
+ const c = await store.getConversation(conv[1]);
+ return c ? send(res, 200, c) : send(res, 404, { error: "没有这个对话" });
+ }
+ if (conv && req.method === "DELETE") {
+ await store.removeConversation(conv[1]);
+ return send(res, 200, { ok: true });
+ }
+ if (path === "/api/chat" && req.method === "POST") {
+ const body = await readBody(req);
+ const settings = await store.settings();
+ sseHead(res);
+ await runChat({ res, body, settings, store }, controllers);
+ return;
+ }
+ if (path === "/api/chat/stop" && req.method === "POST") {
+ const body = await readBody(req).catch(() => ({}));
+ const c = controllers.get(String(body.clientId || ""));
+ if (c) c.abort();
+ return send(res, 200, { ok: Boolean(c) });
+ }
+ return send(res, 404, { error: "没有这个接口:" + path });
+ }
+
+ // 静态:对话页自己的文件
+ const rel = normalize(decodeURIComponent(path)).replace(/^([/\\.]+)/, "");
+ const file = join(UI_ROOT, rel === "" ? "index.html" : rel);
+ if (!file.startsWith(UI_ROOT)) return send(res, 403, { error: "forbidden" });
+ const data = await readFile(file).catch(() => null);
+ if (!data) return send(res, 404, "没有这个文件", "text/plain; charset=utf-8");
+ return send(res, 200, data, MIME[extname(file).toLowerCase()] || "application/octet-stream");
+ } catch (err) {
+ if (res.headersSent) { try { res.end(); } catch { /* 已结束 */ } return; }
+ return send(res, 500, { error: String(err?.message || err) });
+ }
+ });
+
+ // 端口策略:先试指定的(默认 3477),被占就立刻换一个空闲端口 ——
+ // 不再傻等 6 秒。窗口里常常同时有命令行 magpie 和桌面 magpie 两个宿主,
+ // 抢同一个端口是常态;谁抢到谁服务,后来者换一个端口照样能用。
+ const bindOn = (p) => new Promise((resolve, reject) => {
+ const onError = (err) => { server.removeListener("listening", onListening); reject(err); };
+ const onListening = () => { server.removeListener("error", onError); resolve(); };
+ server.once("error", onError);
+ server.once("listening", onListening);
+ server.listen(p, "127.0.0.1");
+ });
+
+ // 从 0 让内核分配一个空闲端口,拿它的实际值
+ const bindEphemeral = () => new Promise((resolve, reject) => {
+ const onError = (err) => { server.removeListener("listening", onListening); reject(err); };
+ const onListening = () => {
+ server.removeListener("error", onError);
+ resolve(server.address().port);
+ };
+ server.once("error", onError);
+ server.once("listening", onListening);
+ server.listen(0, "127.0.0.1");
+ });
+
+ const actualPort = port;
+
+ // 端口固定用 3477 —— 带路页写死了跳这个端口(页面 CSP 是 connect-src 'none',
+ // 没法先探测再决定跳哪,只能盲跳)。所以这里也必须是 3477,换端口页面就连不上了。
+ // 被上一次的宿主占着就等它松手,最多等 6 秒。
+ let bound = false;
+ for (let i = 0; i < 12 && !bound; i++) {
+ try {
+ await bindOn(port);
+ bound = true;
+ } catch (err) {
+ if (err?.code !== "EADDRINUSE") throw err;
+ if (i === 0) console.log(`[page-chat] ${port} 被上一次的宿主占着,等一下再绑`);
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ }
+ if (!bound) throw new Error(`${port} 一直被占用,服务起不来`);
+
+ // 把实际端口写到配置目录,带路页(page/boot.js)会来读 ——
+ // 端口可能是换过的,页面不能假设永远是 3477。
+ try {
+ // dir 可能是空字符串(没传 configDir),交给 dataDir 落到默认配置目录
+ const cfgRoot = dataDir(dir);
+ writeFileSync(join(cfgRoot, "port.json"), JSON.stringify({ port: actualPort, at: Date.now() }));
+ } catch (err) {
+ console.warn("[page-chat] 端口文件写失败:", err?.message || err);
+ }
+
+ return { port: actualPort, server, store, close: async () => { await closeAll(); server.close(); } };
+}
diff --git a/packages/chat/package.json b/packages/chat/package.json
new file mode 100644
index 0000000..da59ee7
--- /dev/null
+++ b/packages/chat/package.json
@@ -0,0 +1,59 @@
+{
+ "name": "@magpie-community/page-chat",
+ "version": "0.1.18",
+ "description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
+ "files": [
+ "index.mjs",
+ "lib",
+ "chat",
+ "page",
+ "assets",
+ "serve.mjs",
+ "start-server.cmd",
+ "start-server.vbs",
+ "install-autostart.cmd",
+ "install-autostart.ps1",
+ "README.md",
+ "SERVE.md",
+ "LICENSE"
+ ],
+ "keywords": [
+ "magpie",
+ "magpie-page",
+ "magpie-plugin",
+ "opencode",
+ "opencode-plugin",
+ "chat",
+ "llm"
+ ],
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Magiczerowxy/magpie-chat.git"
+ },
+ "bugs": {
+ "url": "https://github.com/Magiczerowxy/magpie-chat/issues"
+ },
+ "homepage": "https://github.com/Magiczerowxy/magpie-chat#readme",
+ "engines": {
+ "magpie": ">=0.1.1340"
+ },
+ "magpie": {
+ "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHJlY3Qgd2lkdGg9IjEyOCIgaGVpZ2h0PSIxMjgiIHJ4PSIyOCIgZmlsbD0iIzRmNDZlNSIvPgogIDxwYXRoIGQ9Ik0zMCAzOGg2OGE4IDggMCAwIDEgOCA4djM0YTggOCAwIDAgMS04IDhINjBsLTE2IDE0di0xNGgtMTRhOCA4IDAgMCAxLTgtOFY0NmE4IDggMCAwIDEgOC04eiIgZmlsbD0iI2ZmZiIvPgogIDxnIGZpbGw9IiM0ZjQ2ZTUiPgogICAgPGNpcmNsZSBjeD0iNDYiIGN5PSI1OCIgcj0iNSIvPgogICAgPGNpcmNsZSBjeD0iNjQiIGN5PSI1OCIgcj0iNSIvPgogICAgPGNpcmNsZSBjeD0iODIiIGN5PSI1OCIgcj0iNSIvPgogIDwvZz4KPC9zdmc+Cg==",
+ "page": {
+ "title": "Chat",
+ "titles": {
+ "zh": "对话",
+ "zh-TW": "對話",
+ "ja": "チャット"
+ },
+ "file": "page/index.html",
+ "icon": "assets/icon.svg"
+ }
+ },
+ "scripts": {
+ "start": "node -e \"import('./index.mjs')\""
+ },
+ "main": "./index.mjs",
+ "type": "module"
+}
diff --git a/packages/chat/page/boot.js b/packages/chat/page/boot.js
new file mode 100644
index 0000000..fa61473
--- /dev/null
+++ b/packages/chat/page/boot.js
@@ -0,0 +1,56 @@
+// 带路页:把它自己(也就是 magpie 页面那个框架)导航到插件的服务。
+//
+// 这里必须"直接跳",不能先探测:
+// 页面的 CSP 是 connect-src 'none',fetch/XHR/WebSocket 全被禁止 ——
+// 连 no-cors 的请求都会被直接拒绝。所以「先探一下服务在不在」这条路走不通,
+// alive() 永远返回 false,页面会永远停在等待页。
+// magpie 文档也明说了:这个页面唯一能做的联网动作就是把自己跳转到别处。
+//
+// 端口用固定的 3477。多个 magpie 实例同时在跑时,后来者会退到 3478…,
+// 但页面一律跳 3477 —— 指向先起来的那个,行为反而更一致。
+//
+// 顺手把窗口的主题和设计令牌一起带上(magpie 的 bridge 已经把它们算好了),
+// 这样对话页的配色和字体跟窗口完全一致,连用户的自定义主题也算在内。
+(async () => {
+ const DEFAULT_PORT = 3477;
+ let port = DEFAULT_PORT;
+ let theme = "";
+ let tokens = null;
+
+ try {
+ const t = await window.magpie?.ready; // { dark, lang, tokens }
+ if (t) {
+ if (typeof t.dark === "boolean") theme = t.dark ? "dark" : "light";
+ if (t.tokens && typeof t.tokens === "object") tokens = t.tokens;
+ }
+ } catch { /* 没有 bridge 就退回默认主题 */ }
+
+ try {
+ const o = await window.magpie?.options?.get?.();
+ if (o && Number.isFinite(Number(o.port)) && Number(o.port) > 0) port = Number(o.port);
+ } catch { /* 没有 options 就用默认端口 */ }
+
+ // 字体不在这里传。
+ //
+ // 试过从 magpie 页面的 CSS 变量里读 --ui-font 再带过去,但时机靠不住:
+ // magpie 是设置加载完之后才把 --ui-font 写到 :root 上的,这里 await 完
+ // magpie.ready 立刻读,经常读到空。而且页面 CSP 是 connect-src 'none',
+ // 读不到也没法重试。现在改成服务端直接读 magpie 的 settings.json,
+ // 由 /api/fonts.css 提供给对话页 —— 那边什么时候读都准。
+
+ const q = new URLSearchParams();
+ if (theme) q.set("theme", theme);
+ if (true) {
+ // 只留非空的令牌,压成一个短串;令牌本身就是 magpie 自己的 CSS 变量值。
+ const slim = {};
+ for (const [k, v] of Object.entries(tokens || {})) {
+ const s = String(v ?? "").trim();
+ if (s) slim[k] = s;
+ }
+ if (Object.keys(slim).length) {
+ try { q.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); } catch { /* 编码不了就只带主题 */ }
+ }
+ }
+
+ location.replace("http://127.0.0.1:" + port + "/?" + q.toString());
+})();
diff --git a/packages/chat/page/index.html b/packages/chat/page/index.html
new file mode 100644
index 0000000..9a6fdb6
--- /dev/null
+++ b/packages/chat/page/index.html
@@ -0,0 +1,24 @@
+
+
+
+
+
+对话
+
+
+
+ 对话正在连接到本地对话服务…
+
+
+
+
diff --git a/packages/chat/serve.mjs b/packages/chat/serve.mjs
new file mode 100644
index 0000000..7914526
--- /dev/null
+++ b/packages/chat/serve.mjs
@@ -0,0 +1,48 @@
+// 独立启动对话服务,不依赖 magpie 的插件宿主。
+// 用法:node serve.mjs (或双击 start-server.cmd)
+//
+// 如果 magpie 已经通过插件把服务起起来了,这里就什么都不做直接退出,
+// 避免两个实例抢同一份设置和对话文件。
+import { startServer } from "./lib/server.mjs";
+
+const CANDIDATES = [3477, 3478, 3479, 3480];
+
+async function alreadyRunning() {
+ for (const p of CANDIDATES) {
+ try {
+ const ctl = new AbortController();
+ const timer = setTimeout(() => ctl.abort(), 800);
+ const res = await fetch("http://127.0.0.1:" + p + "/api/ping", { signal: ctl.signal });
+ clearTimeout(timer);
+ if (res.ok) {
+ const j = await res.json().catch(() => null);
+ if (j && j.ok) return { port: p, version: j.version };
+ }
+ } catch { /* 这个端口没有 */ }
+ }
+ return null;
+}
+
+const alive = await alreadyRunning();
+if (alive) {
+ console.log("");
+ console.log(" 对话服务已经在运行了");
+ console.log(" 地址: http://127.0.0.1:" + alive.port + " (版本 " + (alive.version || "?") + ")");
+ console.log(" 不需要再起一个,直接去 magpie 里打开「对话」即可。");
+ console.log("");
+ process.exit(0);
+}
+
+const info = await startServer({ configDir: process.env.MAGPIE_CHAT_CONFIG || "", options: {} })
+ .catch((err) => {
+ console.error("启动失败:", err?.message || err);
+ process.exit(1);
+ });
+
+console.log("");
+console.log(" 对话服务已就绪");
+console.log(" 地址: http://127.0.0.1:" + info.port);
+console.log(" 这个窗口最小化即可,关掉服务就停了");
+console.log("");
+
+process.on("SIGINT", async () => { await info.close(); process.exit(0); });
diff --git a/packages/chat/start-server.cmd b/packages/chat/start-server.cmd
new file mode 100644
index 0000000..d1a4db8
--- /dev/null
+++ b/packages/chat/start-server.cmd
@@ -0,0 +1,11 @@
+@echo off
+chcp 65001 >nul
+title magpie-chat 对话服务
+cd /d "%~dp0"
+echo.
+echo 正在启动 magpie 对话服务...
+echo.
+node serve.mjs
+echo.
+echo 服务已停止。按任意键关闭。
+pause >nul
diff --git a/packages/chat/start-server.vbs b/packages/chat/start-server.vbs
new file mode 100644
index 0000000..f9e67f3
--- /dev/null
+++ b/packages/chat/start-server.vbs
@@ -0,0 +1,7 @@
+' 静默启动 magpie 对话服务(不弹命令行窗口)
+' 双击即可;把它放进「启动」文件夹就能开机自启
+Set fso = CreateObject("Scripting.FileSystemObject")
+Set sh = CreateObject("WScript.Shell")
+here = fso.GetParentFolderName(WScript.ScriptFullName)
+sh.CurrentDirectory = here
+sh.Run "node serve.mjs", 0, False