@vulcan-energy/mcp-helper 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,23 +1,21 @@
1
- var Sn=Object.create;var rr=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var Pn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var An=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Rn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var jn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of En(t))!xn.call(e,a)&&a!==n&&rr(e,a,{get:()=>t[a],enumerable:!(r=kn(t,a))||r.enumerable});return e};var Tn=(e,t,n)=>(n=e!=null?Sn(Pn(e)):{},jn(t||!e||!e.__esModule?rr(n,"default",{value:e,enumerable:!0}):n,e));var dr=Rn((wt,vt)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof vt=="object"&&typeof wt<"u"?vt.exports=t():e.Papa=t()})(wt,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function n(){var c=t.URL||t.webkitURL||null,l=e.toString();return o.BLOB_URL||(o.BLOB_URL=c.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",l,")();"],{type:"text/javascript"})))}var r=!t.document&&!!t.postMessage,a=t.IS_PAPA_WORKER||!1,s={},i=0,o={};if(o.parse=u,o.unparse=d,o.RECORD_SEP="",o.UNIT_SEP="",o.BYTE_ORDER_MARK="\uFEFF",o.BAD_DELIMITERS=["\r",`
2
- `,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!r&&!!t.Worker,o.NODE_STREAM_INPUT=1,o.LocalChunkSize=1024*1024*10,o.RemoteChunkSize=1024*1024*5,o.DefaultDelimiter=",",o.Parser=U,o.ParserHandle=T,o.NetworkStreamer=h,o.FileStreamer=p,o.StringStreamer=C,o.ReadableStreamStreamer=w,typeof PAPA_BROWSER_CONTEXT>"u"&&(o.DuplexStreamStreamer=S),t.jQuery){var m=t.jQuery;m.fn.parse=function(c){var l=c.config||{},_=[];return this.each(function(k){var b=m(this).prop("tagName").toUpperCase()==="INPUT"&&m(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!b||!this.files||this.files.length===0)return!0;for(var L=0;L<this.files.length;L++)_.push({file:this.files[L],inputElem:this,instanceConfig:m.extend({},l)})}),g(),this;function g(){if(_.length===0){j(c.complete)&&c.complete();return}var k=_[0];if(j(c.before)){var b=c.before(k.file,k.inputElem);if(typeof b=="object")if(b.action==="abort"){v("AbortError",k.file,k.inputElem,b.reason);return}else if(b.action==="skip"){M();return}else typeof b.config=="object"&&(k.instanceConfig=m.extend(k.instanceConfig,b.config));else if(b==="skip"){M();return}}var L=k.instanceConfig.complete;k.instanceConfig.complete=function(q){j(L)&&L(q,k.file,k.inputElem),M()},o.parse(k.file,k.instanceConfig)}function v(k,b,L,q){j(c.error)&&c.error({name:k},b,L,q)}function M(){_.splice(0,1),g()}}}a&&(t.onmessage=Ce);function u(c,l){l=l||{};var _=l.dynamicTyping||!1;if(j(_)&&(l.dynamicTypingFunction=_,_={}),l.dynamicTyping=_,l.transform=j(l.transform)?l.transform:!1,l.worker&&o.WORKERS_SUPPORTED){var g=J();g.userStep=l.step,g.userChunk=l.chunk,g.userComplete=l.complete,g.userError=l.error,l.step=j(l.step),l.chunk=j(l.chunk),l.complete=j(l.complete),l.error=j(l.error),delete l.worker,g.postMessage({input:c,config:l,workerId:g.id});return}var v=null;if(c===o.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return v=new S(l),v.getStream();return typeof c=="string"?(c=M(c),l.download?v=new h(l):v=new C(l)):c.readable===!0&&j(c.read)&&j(c.on)?v=new w(l):(t.File&&c instanceof File||c instanceof Object)&&(v=new p(l)),v.stream(c);function M(k){return k.charCodeAt(0)===65279?k.slice(1):k}}function d(c,l){var _=!1,g=!0,v=",",M=`\r
3
- `,k='"',b=k+k,L=!1,q=null,ee=!1;le();var O=new RegExp(F(k),"g");if(typeof c=="string"&&(c=JSON.parse(c)),Array.isArray(c)){if(!c.length||Array.isArray(c[0]))return x(null,c,L);if(typeof c[0]=="object")return x(q||Object.keys(c[0]),c,L)}else if(typeof c=="object")return typeof c.data=="string"&&(c.data=JSON.parse(c.data)),Array.isArray(c.data)&&(c.fields||(c.fields=c.meta&&c.meta.fields||q),c.fields||(c.fields=Array.isArray(c.data[0])?c.fields:typeof c.data[0]=="object"?Object.keys(c.data[0]):[]),!Array.isArray(c.data[0])&&typeof c.data[0]!="object"&&(c.data=[c.data])),x(c.fields||[],c.data||[],L);throw new Error("Unable to serialize unrecognized input");function le(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!o.BAD_DELIMITERS.filter(function(I){return l.delimiter.indexOf(I)!==-1}).length&&(v=l.delimiter),(typeof l.quotes=="boolean"||typeof l.quotes=="function"||Array.isArray(l.quotes))&&(_=l.quotes),(typeof l.skipEmptyLines=="boolean"||typeof l.skipEmptyLines=="string")&&(L=l.skipEmptyLines),typeof l.newline=="string"&&(M=l.newline),typeof l.quoteChar=="string"&&(k=l.quoteChar),typeof l.header=="boolean"&&(g=l.header),Array.isArray(l.columns)){if(l.columns.length===0)throw new Error("Option columns is empty");q=l.columns}l.escapeChar!==void 0&&(b=l.escapeChar+k),l.escapeFormulae instanceof RegExp?ee=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(ee=/^[=+\-@\t\r].*$/)}}function x(I,D,Y){var Z="";typeof I=="string"&&(I=JSON.parse(I)),typeof D=="string"&&(D=JSON.parse(D));var de=Array.isArray(I)&&I.length>0,ae=!Array.isArray(D[0]);if(de&&g){for(var me=0;me<I.length;me++)me>0&&(Z+=v),Z+=$(I[me],me);D.length>0&&(Z+=M)}for(var W=0;W<D.length;W++){var Se=de?I.length:D[W].length,fe=!1,P=de?Object.keys(D[W]).length===0:D[W].length===0;if(Y&&!de&&(fe=Y==="greedy"?D[W].join("").trim()==="":D[W].length===1&&D[W][0].length===0),Y==="greedy"&&de){for(var A=[],N=0;N<Se;N++){var H=ae?I[N]:N;A.push(D[W][H])}fe=A.join("").trim()===""}if(!fe){for(var E=0;E<Se;E++){E>0&&!P&&(Z+=v);var V=de&&ae?I[E]:E;Z+=$(D[W][V],E)}W<D.length-1&&(!Y||Se>0&&!P)&&(Z+=M)}}return Z}function $(I,D){if(typeof I>"u"||I===null)return"";if(I.constructor===Date)return JSON.stringify(I).slice(1,25);var Y=!1;ee&&typeof I=="string"&&ee.test(I)&&(I="'"+I,Y=!0);var Z=I.toString().replace(O,b);return Y=Y||_===!0||typeof _=="function"&&_(I,D)||Array.isArray(_)&&_[D]||Re(Z,o.BAD_DELIMITERS)||Z.indexOf(v)>-1||Z.charAt(0)===" "||Z.charAt(Z.length-1)===" ",Y?k+Z+k:Z}function Re(I,D){for(var Y=0;Y<D.length;Y++)if(I.indexOf(D[Y])>-1)return!0;return!1}}function f(c){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},l.call(this,c),this.parseChunk=function(_,g){let v=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&v>0){let ee=this._config.newline;if(!ee){let le=this._config.quoteChar||'"';ee=this._handle.guessLineEndings(_,le)}_=[..._.split(ee).slice(v)].join(ee)}if(this.isFirstChunk&&j(this._config.beforeFirstChunk)){var M=this._config.beforeFirstChunk(_);M!==void 0&&(_=M)}this.isFirstChunk=!1,this._halted=!1;var k=this._partialLine+_;this._partialLine="";var b=this._handle.parse(k,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var L=b.meta.cursor;this._finished||(this._partialLine=k.substring(L-this._baseIndex),this._baseIndex=L),b&&b.data&&(this._rowCount+=b.data.length);var q=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(a)t.postMessage({results:b,workerId:o.WORKER_ID,finished:q});else if(j(this._config.chunk)&&!g){if(this._config.chunk(b,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}b=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(b.data),this._completeResults.errors=this._completeResults.errors.concat(b.errors),this._completeResults.meta=b.meta),!this._completed&&q&&j(this._config.complete)&&(!b||!b.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!q&&(!b||!b.meta.paused)&&this._nextChunk(),b},this._sendError=function(_){j(this._config.error)?this._config.error(_):a&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:_,finished:!1})};function l(_){var g=re(_);g.chunkSize=parseInt(g.chunkSize),!_.step&&!_.chunk&&(g.chunkSize=null),this._handle=new T(g),this._handle.streamer=this,this._config=g}}function h(c){c=c||{},c.chunkSize||(c.chunkSize=o.RemoteChunkSize),f.call(this,c);var l;r?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(g){this._input=g,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(l=new XMLHttpRequest,this._config.withCredentials&&(l.withCredentials=this._config.withCredentials),r||(l.onload=R(this._chunkLoaded,this),l.onerror=R(this._chunkError,this)),l.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var g=this._config.downloadRequestHeaders;for(var v in g)l.setRequestHeader(v,g[v])}if(this._config.chunkSize){var M=this._start+this._config.chunkSize-1;l.setRequestHeader("Range","bytes="+this._start+"-"+M)}try{l.send(this._config.downloadRequestBody)}catch(k){this._chunkError(k.message)}r&&l.status===0&&this._chunkError()},this._chunkLoaded=function(){if(l.readyState===4){if(l.status<200||l.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:l.responseText.length,this._finished=!this._config.chunkSize||this._start>=_(l),this.parseChunk(l.responseText)}},this._chunkError=function(g){var v=l.statusText||g;this._sendError(new Error(v))};function _(g){var v=g.getResponseHeader("Content-Range");return v===null?-1:parseInt(v.substring(v.lastIndexOf("/")+1))}}h.prototype=Object.create(f.prototype),h.prototype.constructor=h;function p(c){c=c||{},c.chunkSize||(c.chunkSize=o.LocalChunkSize),f.call(this,c);var l,_,g=typeof FileReader<"u";this.stream=function(v){this._input=v,_=v.slice||v.webkitSlice||v.mozSlice,g?(l=new FileReader,l.onload=R(this._chunkLoaded,this),l.onerror=R(this._chunkError,this)):l=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var v=this._input;if(this._config.chunkSize){var M=Math.min(this._start+this._config.chunkSize,this._input.size);v=_.call(v,this._start,M)}var k=l.readAsText(v,this._config.encoding);g||this._chunkLoaded({target:{result:k}})},this._chunkLoaded=function(v){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(v.target.result)},this._chunkError=function(){this._sendError(l.error)}}p.prototype=Object.create(f.prototype),p.prototype.constructor=p;function C(c){c=c||{},f.call(this,c);var l;this.stream=function(_){return l=_,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var _=this._config.chunkSize,g;return _?(g=l.substring(0,_),l=l.substring(_)):(g=l,l=""),this._finished=!l,this.parseChunk(g)}}}C.prototype=Object.create(C.prototype),C.prototype.constructor=C;function w(c){c=c||{},f.call(this,c);var l=[],_=!0,g=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(v){this._input=v,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){g&&l.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),l.length?this.parseChunk(l.shift()):_=!0},this._streamData=R(function(v){try{l.push(typeof v=="string"?v:v.toString(this._config.encoding)),_&&(_=!1,this._checkIsFinished(),this.parseChunk(l.shift()))}catch(M){this._streamError(M)}},this),this._streamError=R(function(v){this._streamCleanUp(),this._sendError(v)},this),this._streamEnd=R(function(){this._streamCleanUp(),g=!0,this._streamData("")},this),this._streamCleanUp=R(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}w.prototype=Object.create(f.prototype),w.prototype.constructor=w;function S(c){var l=An("stream").Duplex,_=re(c),g=!0,v=!1,M=[],k=null;this._onCsvData=function(b){var L=b.data;!k.push(L)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){k.push(null)},_.step=R(this._onCsvData,this),_.complete=R(this._onCsvComplete,this),f.call(this,_),this._nextChunk=function(){v&&M.length===1&&(this._finished=!0),M.length?M.shift()():g=!0},this._addToParseQueue=function(b,L){M.push(R(function(){if(this.parseChunk(typeof b=="string"?b:b.toString(_.encoding)),j(L))return L()},this)),g&&(g=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(b,L,q){this._addToParseQueue(b,q)},this._onWriteComplete=function(){v=!0,this._addToParseQueue("")},this.getStream=function(){return k},k=new l({readableObjectMode:!0,decodeStrings:!1,read:R(this._onRead,this),write:R(this._onWrite,this)}),k.once("finish",R(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(S.prototype=Object.create(f.prototype),S.prototype.constructor=S);function T(c){var l=Math.pow(2,53),_=-l,g=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,v=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,M=this,k=0,b=0,L,q,ee=!1,O=!1,le,x=[],$={data:[],errors:[],meta:{}};if(j(c.step)){var Re=c.step;c.step=function(P){if($=P,Z())Y();else{if(Y(),$.data.length===0)return;k+=P.data.length,c.preview&&k>c.preview?q.abort():($.data=$.data[0],Re($,M))}}}this.parse=function(P,A,N){var H=c.quoteChar||'"';if(c.newline||(c.newline=this.guessLineEndings(P,H)),le=!1,c.delimiter)j(c.delimiter)&&(c.delimiter=c.delimiter(P),$.meta.delimiter=c.delimiter);else{var E=Se(P,c.newline,c.skipEmptyLines,c.comments,c.delimitersToGuess);E.successful?c.delimiter=E.bestDelimiter:(le=!0,c.delimiter=o.DefaultDelimiter),$.meta.delimiter=c.delimiter}var V=re(c);return c.preview&&c.header&&V.preview++,L=P,q=new U(V),$=q.parse(L,A,N),Y(),ee?{meta:{paused:!0}}:$||{meta:{paused:!1}}},this.paused=function(){return ee},this.pause=function(){ee=!0,q.abort(),L=j(c.chunk)?"":L.substring(q.getCharIndex())},this.resume=function(){M.streamer._halted?(ee=!1,M.streamer.parseChunk(L,!0)):setTimeout(M.resume,3)},this.aborted=function(){return O},this.abort=function(){O=!0,q.abort(),$.meta.aborted=!0,j(c.complete)&&c.complete($),L=""},this.guessLineEndings=function(P,A){P=P.substring(0,1024*1024);var N=new RegExp(F(A)+"([^]*?)"+F(A),"gm");P=P.replace(N,"");var H=P.split("\r"),E=P.split(`
4
- `),V=E.length>1&&E[0].length<H[0].length;if(H.length===1||V)return`
5
- `;for(var se=0,te=0;te<H.length;te++)H[te][0]===`
1
+ var mn=Object.create;var Xt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var hn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var yn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var wn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of _n(t))!gn.call(e,a)&&a!==n&&Xt(e,a,{get:()=>t[a],enumerable:!(r=fn(t,a))||r.enumerable});return e};var vn=(e,t,n)=>(n=e!=null?mn(pn(e)):{},wn(t||!e||!e.__esModule?Xt(n,"default",{value:e,enumerable:!0}):n,e));var sr=yn((ft,_t)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof _t=="object"&&typeof ft<"u"?_t.exports=t():e.Papa=t()})(ft,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function n(){var c=t.URL||t.webkitURL||null,l=e.toString();return o.BLOB_URL||(o.BLOB_URL=c.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",l,")();"],{type:"text/javascript"})))}var r=!t.document&&!!t.postMessage,a=t.IS_PAPA_WORKER||!1,s={},i=0,o={};if(o.parse=u,o.unparse=m,o.RECORD_SEP="",o.UNIT_SEP="",o.BYTE_ORDER_MARK="\uFEFF",o.BAD_DELIMITERS=["\r",`
2
+ `,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!r&&!!t.Worker,o.NODE_STREAM_INPUT=1,o.LocalChunkSize=1024*1024*10,o.RemoteChunkSize=1024*1024*5,o.DefaultDelimiter=",",o.Parser=U,o.ParserHandle=T,o.NetworkStreamer=h,o.FileStreamer=p,o.StringStreamer=S,o.ReadableStreamStreamer=x,typeof PAPA_BROWSER_CONTEXT>"u"&&(o.DuplexStreamStreamer=P),t.jQuery){var d=t.jQuery;d.fn.parse=function(c){var l=c.config||{},f=[];return this.each(function(b){var v=d(this).prop("tagName").toUpperCase()==="INPUT"&&d(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!v||!this.files||this.files.length===0)return!0;for(var L=0;L<this.files.length;L++)f.push({file:this.files[L],inputElem:this,instanceConfig:d.extend({},l)})}),g(),this;function g(){if(f.length===0){j(c.complete)&&c.complete();return}var b=f[0];if(j(c.before)){var v=c.before(b.file,b.inputElem);if(typeof v=="object")if(v.action==="abort"){w("AbortError",b.file,b.inputElem,v.reason);return}else if(v.action==="skip"){M();return}else typeof v.config=="object"&&(b.instanceConfig=d.extend(b.instanceConfig,v.config));else if(v==="skip"){M();return}}var L=b.instanceConfig.complete;b.instanceConfig.complete=function(q){j(L)&&L(q,b.file,b.inputElem),M()},o.parse(b.file,b.instanceConfig)}function w(b,v,L,q){j(c.error)&&c.error({name:b},v,L,q)}function M(){f.splice(0,1),g()}}}a&&(t.onmessage=be);function u(c,l){l=l||{};var f=l.dynamicTyping||!1;if(j(f)&&(l.dynamicTypingFunction=f,f={}),l.dynamicTyping=f,l.transform=j(l.transform)?l.transform:!1,l.worker&&o.WORKERS_SUPPORTED){var g=V();g.userStep=l.step,g.userChunk=l.chunk,g.userComplete=l.complete,g.userError=l.error,l.step=j(l.step),l.chunk=j(l.chunk),l.complete=j(l.complete),l.error=j(l.error),delete l.worker,g.postMessage({input:c,config:l,workerId:g.id});return}var w=null;if(c===o.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return w=new P(l),w.getStream();return typeof c=="string"?(c=M(c),l.download?w=new h(l):w=new S(l)):c.readable===!0&&j(c.read)&&j(c.on)?w=new x(l):(t.File&&c instanceof File||c instanceof Object)&&(w=new p(l)),w.stream(c);function M(b){return b.charCodeAt(0)===65279?b.slice(1):b}}function m(c,l){var f=!1,g=!0,w=",",M=`\r
3
+ `,b='"',v=b+b,L=!1,q=null,Q=!1;le();var O=new RegExp(F(b),"g");if(typeof c=="string"&&(c=JSON.parse(c)),Array.isArray(c)){if(!c.length||Array.isArray(c[0]))return k(null,c,L);if(typeof c[0]=="object")return k(q||Object.keys(c[0]),c,L)}else if(typeof c=="object")return typeof c.data=="string"&&(c.data=JSON.parse(c.data)),Array.isArray(c.data)&&(c.fields||(c.fields=c.meta&&c.meta.fields||q),c.fields||(c.fields=Array.isArray(c.data[0])?c.fields:typeof c.data[0]=="object"?Object.keys(c.data[0]):[]),!Array.isArray(c.data[0])&&typeof c.data[0]!="object"&&(c.data=[c.data])),k(c.fields||[],c.data||[],L);throw new Error("Unable to serialize unrecognized input");function le(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!o.BAD_DELIMITERS.filter(function(I){return l.delimiter.indexOf(I)!==-1}).length&&(w=l.delimiter),(typeof l.quotes=="boolean"||typeof l.quotes=="function"||Array.isArray(l.quotes))&&(f=l.quotes),(typeof l.skipEmptyLines=="boolean"||typeof l.skipEmptyLines=="string")&&(L=l.skipEmptyLines),typeof l.newline=="string"&&(M=l.newline),typeof l.quoteChar=="string"&&(b=l.quoteChar),typeof l.header=="boolean"&&(g=l.header),Array.isArray(l.columns)){if(l.columns.length===0)throw new Error("Option columns is empty");q=l.columns}l.escapeChar!==void 0&&(v=l.escapeChar+b),l.escapeFormulae instanceof RegExp?Q=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(Q=/^[=+\-@\t\r].*$/)}}function k(I,W,X){var Y="";typeof I=="string"&&(I=JSON.parse(I)),typeof W=="string"&&(W=JSON.parse(W));var de=Array.isArray(I)&&I.length>0,ae=!Array.isArray(W[0]);if(de&&g){for(var me=0;me<I.length;me++)me>0&&(Y+=w),Y+=$(I[me],me);W.length>0&&(Y+=M)}for(var D=0;D<W.length;D++){var Ce=de?I.length:W[D].length,fe=!1,E=de?Object.keys(W[D]).length===0:W[D].length===0;if(X&&!de&&(fe=X==="greedy"?W[D].join("").trim()==="":W[D].length===1&&W[D][0].length===0),X==="greedy"&&de){for(var A=[],N=0;N<Ce;N++){var H=ae?I[N]:N;A.push(W[D][H])}fe=A.join("").trim()===""}if(!fe){for(var C=0;C<Ce;C++){C>0&&!E&&(Y+=w);var J=de&&ae?I[C]:C;Y+=$(W[D][J],C)}D<W.length-1&&(!X||Ce>0&&!E)&&(Y+=M)}}return Y}function $(I,W){if(typeof I>"u"||I===null)return"";if(I.constructor===Date)return JSON.stringify(I).slice(1,25);var X=!1;Q&&typeof I=="string"&&Q.test(I)&&(I="'"+I,X=!0);var Y=I.toString().replace(O,v);return X=X||f===!0||typeof f=="function"&&f(I,W)||Array.isArray(f)&&f[W]||Pe(Y,o.BAD_DELIMITERS)||Y.indexOf(w)>-1||Y.charAt(0)===" "||Y.charAt(Y.length-1)===" ",X?b+Y+b:Y}function Pe(I,W){for(var X=0;X<W.length;X++)if(I.indexOf(W[X])>-1)return!0;return!1}}function _(c){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},l.call(this,c),this.parseChunk=function(f,g){let w=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&w>0){let Q=this._config.newline;if(!Q){let le=this._config.quoteChar||'"';Q=this._handle.guessLineEndings(f,le)}f=[...f.split(Q).slice(w)].join(Q)}if(this.isFirstChunk&&j(this._config.beforeFirstChunk)){var M=this._config.beforeFirstChunk(f);M!==void 0&&(f=M)}this.isFirstChunk=!1,this._halted=!1;var b=this._partialLine+f;this._partialLine="";var v=this._handle.parse(b,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var L=v.meta.cursor;this._finished||(this._partialLine=b.substring(L-this._baseIndex),this._baseIndex=L),v&&v.data&&(this._rowCount+=v.data.length);var q=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(a)t.postMessage({results:v,workerId:o.WORKER_ID,finished:q});else if(j(this._config.chunk)&&!g){if(this._config.chunk(v,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}v=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(v.data),this._completeResults.errors=this._completeResults.errors.concat(v.errors),this._completeResults.meta=v.meta),!this._completed&&q&&j(this._config.complete)&&(!v||!v.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!q&&(!v||!v.meta.paused)&&this._nextChunk(),v},this._sendError=function(f){j(this._config.error)?this._config.error(f):a&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:f,finished:!1})};function l(f){var g=re(f);g.chunkSize=parseInt(g.chunkSize),!f.step&&!f.chunk&&(g.chunkSize=null),this._handle=new T(g),this._handle.streamer=this,this._config=g}}function h(c){c=c||{},c.chunkSize||(c.chunkSize=o.RemoteChunkSize),_.call(this,c);var l;r?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(g){this._input=g,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(l=new XMLHttpRequest,this._config.withCredentials&&(l.withCredentials=this._config.withCredentials),r||(l.onload=R(this._chunkLoaded,this),l.onerror=R(this._chunkError,this)),l.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var g=this._config.downloadRequestHeaders;for(var w in g)l.setRequestHeader(w,g[w])}if(this._config.chunkSize){var M=this._start+this._config.chunkSize-1;l.setRequestHeader("Range","bytes="+this._start+"-"+M)}try{l.send(this._config.downloadRequestBody)}catch(b){this._chunkError(b.message)}r&&l.status===0&&this._chunkError()},this._chunkLoaded=function(){if(l.readyState===4){if(l.status<200||l.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:l.responseText.length,this._finished=!this._config.chunkSize||this._start>=f(l),this.parseChunk(l.responseText)}},this._chunkError=function(g){var w=l.statusText||g;this._sendError(new Error(w))};function f(g){var w=g.getResponseHeader("Content-Range");return w===null?-1:parseInt(w.substring(w.lastIndexOf("/")+1))}}h.prototype=Object.create(_.prototype),h.prototype.constructor=h;function p(c){c=c||{},c.chunkSize||(c.chunkSize=o.LocalChunkSize),_.call(this,c);var l,f,g=typeof FileReader<"u";this.stream=function(w){this._input=w,f=w.slice||w.webkitSlice||w.mozSlice,g?(l=new FileReader,l.onload=R(this._chunkLoaded,this),l.onerror=R(this._chunkError,this)):l=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var w=this._input;if(this._config.chunkSize){var M=Math.min(this._start+this._config.chunkSize,this._input.size);w=f.call(w,this._start,M)}var b=l.readAsText(w,this._config.encoding);g||this._chunkLoaded({target:{result:b}})},this._chunkLoaded=function(w){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(w.target.result)},this._chunkError=function(){this._sendError(l.error)}}p.prototype=Object.create(_.prototype),p.prototype.constructor=p;function S(c){c=c||{},_.call(this,c);var l;this.stream=function(f){return l=f,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var f=this._config.chunkSize,g;return f?(g=l.substring(0,f),l=l.substring(f)):(g=l,l=""),this._finished=!l,this.parseChunk(g)}}}S.prototype=Object.create(S.prototype),S.prototype.constructor=S;function x(c){c=c||{},_.call(this,c);var l=[],f=!0,g=!1;this.pause=function(){_.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){_.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(w){this._input=w,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){g&&l.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),l.length?this.parseChunk(l.shift()):f=!0},this._streamData=R(function(w){try{l.push(typeof w=="string"?w:w.toString(this._config.encoding)),f&&(f=!1,this._checkIsFinished(),this.parseChunk(l.shift()))}catch(M){this._streamError(M)}},this),this._streamError=R(function(w){this._streamCleanUp(),this._sendError(w)},this),this._streamEnd=R(function(){this._streamCleanUp(),g=!0,this._streamData("")},this),this._streamCleanUp=R(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}x.prototype=Object.create(_.prototype),x.prototype.constructor=x;function P(c){var l=hn("stream").Duplex,f=re(c),g=!0,w=!1,M=[],b=null;this._onCsvData=function(v){var L=v.data;!b.push(L)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){b.push(null)},f.step=R(this._onCsvData,this),f.complete=R(this._onCsvComplete,this),_.call(this,f),this._nextChunk=function(){w&&M.length===1&&(this._finished=!0),M.length?M.shift()():g=!0},this._addToParseQueue=function(v,L){M.push(R(function(){if(this.parseChunk(typeof v=="string"?v:v.toString(f.encoding)),j(L))return L()},this)),g&&(g=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(v,L,q){this._addToParseQueue(v,q)},this._onWriteComplete=function(){w=!0,this._addToParseQueue("")},this.getStream=function(){return b},b=new l({readableObjectMode:!0,decodeStrings:!1,read:R(this._onRead,this),write:R(this._onWrite,this)}),b.once("finish",R(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(P.prototype=Object.create(_.prototype),P.prototype.constructor=P);function T(c){var l=Math.pow(2,53),f=-l,g=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,w=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,M=this,b=0,v=0,L,q,Q=!1,O=!1,le,k=[],$={data:[],errors:[],meta:{}};if(j(c.step)){var Pe=c.step;c.step=function(E){if($=E,Y())X();else{if(X(),$.data.length===0)return;b+=E.data.length,c.preview&&b>c.preview?q.abort():($.data=$.data[0],Pe($,M))}}}this.parse=function(E,A,N){var H=c.quoteChar||'"';if(c.newline||(c.newline=this.guessLineEndings(E,H)),le=!1,c.delimiter)j(c.delimiter)&&(c.delimiter=c.delimiter(E),$.meta.delimiter=c.delimiter);else{var C=Ce(E,c.newline,c.skipEmptyLines,c.comments,c.delimitersToGuess);C.successful?c.delimiter=C.bestDelimiter:(le=!0,c.delimiter=o.DefaultDelimiter),$.meta.delimiter=c.delimiter}var J=re(c);return c.preview&&c.header&&J.preview++,L=E,q=new U(J),$=q.parse(L,A,N),X(),Q?{meta:{paused:!0}}:$||{meta:{paused:!1}}},this.paused=function(){return Q},this.pause=function(){Q=!0,q.abort(),L=j(c.chunk)?"":L.substring(q.getCharIndex())},this.resume=function(){M.streamer._halted?(Q=!1,M.streamer.parseChunk(L,!0)):setTimeout(M.resume,3)},this.aborted=function(){return O},this.abort=function(){O=!0,q.abort(),$.meta.aborted=!0,j(c.complete)&&c.complete($),L=""},this.guessLineEndings=function(E,A){E=E.substring(0,1024*1024);var N=new RegExp(F(A)+"([^]*?)"+F(A),"gm");E=E.replace(N,"");var H=E.split("\r"),C=E.split(`
4
+ `),J=C.length>1&&C[0].length<H[0].length;if(H.length===1||J)return`
5
+ `;for(var se=0,ee=0;ee<H.length;ee++)H[ee][0]===`
6
6
  `&&se++;return se>=H.length/2?`\r
7
- `:"\r"};function I(P){return c.skipEmptyLines==="greedy"?P.join("").trim()==="":P.length===1&&P[0].length===0}function D(P){if(g.test(P)){var A=parseFloat(P);if(A>_&&A<l)return!0}return!1}function Y(){return $&&le&&(fe("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&($.data=$.data.filter(function(P){return!I(P)})),Z()&&de(),W()}function Z(){return c.header&&x.length===0}function de(){if(!$)return;function P(N,H){j(c.transformHeader)&&(N=c.transformHeader(N,H)),x.push(N)}if(Array.isArray($.data[0])){for(var A=0;Z()&&A<$.data.length;A++)$.data[A].forEach(P);$.data.splice(0,1)}else $.data.forEach(P)}function ae(P){return c.dynamicTypingFunction&&c.dynamicTyping[P]===void 0&&(c.dynamicTyping[P]=c.dynamicTypingFunction(P)),(c.dynamicTyping[P]||c.dynamicTyping)===!0}function me(P,A){return ae(P)?A==="true"||A==="TRUE"?!0:A==="false"||A==="FALSE"?!1:D(A)?parseFloat(A):v.test(A)?new Date(A):A===""?null:A:A}function W(){if(!$||!c.header&&!c.dynamicTyping&&!c.transform)return $;function P(N,H){var E=c.header?{}:[],V;for(V=0;V<N.length;V++){var se=V,te=N[V];c.header&&(se=V>=x.length?"__parsed_extra":x[V]),c.transform&&(te=c.transform(te,se)),te=me(se,te),se==="__parsed_extra"?(E[se]=E[se]||[],E[se].push(te)):E[se]=te}return c.header&&(V>x.length?fe("FieldMismatch","TooManyFields","Too many fields: expected "+x.length+" fields but parsed "+V,b+H):V<x.length&&fe("FieldMismatch","TooFewFields","Too few fields: expected "+x.length+" fields but parsed "+V,b+H)),E}var A=1;return!$.data.length||Array.isArray($.data[0])?($.data=$.data.map(P),A=$.data.length):$.data=P($.data,0),c.header&&$.meta&&($.meta.fields=x),b+=A,$}function Se(P,A,N,H,E){var V,se,te,je;E=E||[","," ","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var ke=0;ke<E.length;ke++){var De=E[ke],Te=0,Ee=0,ce=0;te=void 0;for(var ge=new U({comments:H,delimiter:De,newline:A,preview:10}).parse(P),oe=0;oe<ge.data.length;oe++){if(N&&I(ge.data[oe])){ce++;continue}var ue=ge.data[oe].length;if(Ee+=ue,typeof te>"u"){te=ue;continue}else ue>0&&(Te+=Math.abs(ue-te),te=ue)}ge.data.length>0&&(Ee/=ge.data.length-ce),(typeof se>"u"||Te<=se)&&(typeof je>"u"||Ee>je)&&Ee>1.99&&(se=Te,V=De,je=Ee)}return c.delimiter=V,{successful:!!V,bestDelimiter:V}}function fe(P,A,N,H){var E={type:P,code:A,message:N};H!==void 0&&(E.row=H),$.errors.push(E)}}function F(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(c){c=c||{};var l=c.delimiter,_=c.newline,g=c.comments,v=c.step,M=c.preview,k=c.fastMode,b,L=null,q=!1;c.quoteChar===void 0||c.quoteChar===null?b='"':b=c.quoteChar;var ee=b;if(c.escapeChar!==void 0&&(ee=c.escapeChar),(typeof l!="string"||o.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),g===l)throw new Error("Comment character same as delimiter");g===!0?g="#":(typeof g!="string"||o.BAD_DELIMITERS.indexOf(g)>-1)&&(g=!1),_!==`
8
- `&&_!=="\r"&&_!==`\r
9
- `&&(_=`
10
- `);var O=0,le=!1;this.parse=function(x,$,Re){if(typeof x!="string")throw new Error("Input must be a string");var I=x.length,D=l.length,Y=_.length,Z=g.length,de=j(v);O=0;var ae=[],me=[],W=[],Se=0;if(!x)return ce();if(k||k!==!1&&x.indexOf(b)===-1){for(var fe=x.split(_),P=0;P<fe.length;P++){if(W=fe[P],O+=W.length,P!==fe.length-1)O+=_.length;else if(Re)return ce();if(!(g&&W.substring(0,Z)===g)){if(de){if(ae=[],ke(W.split(l)),ge(),le)return ce()}else ke(W.split(l));if(M&&P>=M)return ae=ae.slice(0,M),ce(!0)}}return ce()}for(var A=x.indexOf(l,O),N=x.indexOf(_,O),H=new RegExp(F(ee)+F(b),"g"),E=x.indexOf(b,O);;){if(x[O]===b){for(E=O,O++;;){if(E=x.indexOf(b,E+1),E===-1)return Re||me.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:ae.length,index:O}),Te();if(E===I-1){var V=x.substring(O,E).replace(H,b);return Te(V)}if(b===ee&&x[E+1]===ee){E++;continue}if(!(b!==ee&&E!==0&&x[E-1]===ee)){A!==-1&&A<E+1&&(A=x.indexOf(l,E+1)),N!==-1&&N<E+1&&(N=x.indexOf(_,E+1));var se=N===-1?A:Math.min(A,N),te=De(se);if(x.substr(E+1+te,D)===l){W.push(x.substring(O,E).replace(H,b)),O=E+1+te+D,x[E+1+te+D]!==b&&(E=x.indexOf(b,O)),A=x.indexOf(l,O),N=x.indexOf(_,O);break}var je=De(N);if(x.substring(E+1+je,E+1+je+Y)===_){if(W.push(x.substring(O,E).replace(H,b)),Ee(E+1+je+Y),A=x.indexOf(l,O),E=x.indexOf(b,O),de&&(ge(),le))return ce();if(M&&ae.length>=M)return ce(!0);break}me.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:ae.length,index:O}),E++}}continue}if(g&&W.length===0&&x.substring(O,O+Z)===g){if(N===-1)return ce();O=N+Y,N=x.indexOf(_,O),A=x.indexOf(l,O);continue}if(A!==-1&&(A<N||N===-1)){W.push(x.substring(O,A)),O=A+D,A=x.indexOf(l,O);continue}if(N!==-1){if(W.push(x.substring(O,N)),Ee(N+Y),de&&(ge(),le))return ce();if(M&&ae.length>=M)return ce(!0);continue}break}return Te();function ke(oe){ae.push(oe),Se=O}function De(oe){var ue=0;if(oe!==-1){var Pe=x.substring(E+1,oe);Pe&&Pe.trim()===""&&(ue=Pe.length)}return ue}function Te(oe){return Re||(typeof oe>"u"&&(oe=x.substring(O)),W.push(oe),O=I,ke(W),de&&ge()),ce()}function Ee(oe){O=oe,ke(W),W=[],N=x.indexOf(_,O)}function ce(oe){if(c.header&&!$&&ae.length&&!q){let ue=ae[0],Pe=Object.create(null),ut=new Set(ue),er=!1;for(let $e=0;$e<ue.length;$e++){let ye=ue[$e];if(j(c.transformHeader)&&(ye=c.transformHeader(ye,$e)),!Pe[ye])Pe[ye]=1,ue[$e]=ye;else{let We,tr=Pe[ye];do We=`${ye}_${tr}`,tr++;while(ut.has(We));ut.add(We),ue[$e]=We,Pe[ye]++,er=!0,L===null&&(L={}),L[We]=ye}ut.add(ye)}er&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:ae,errors:me,meta:{delimiter:l,linebreak:_,aborted:le,truncated:!!oe,cursor:Se+($||0),renamedHeaders:L}}}function ge(){v(ce()),ae=[],me=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return O}}function J(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=B,l.id=i++,s[l.id]=l,l}function B(c){var l=c.data,_=s[l.workerId],g=!1;if(l.error)_.userError(l.error,l.file);else if(l.results&&l.results.data){var v=function(){g=!0,X(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},M={abort:v,pause:Q,resume:Q};if(j(_.userStep)){for(var k=0;k<l.results.data.length&&(_.userStep({data:l.results.data[k],errors:l.results.errors,meta:l.results.meta},M),!g);k++);delete l.results}else j(_.userChunk)&&(_.userChunk(l.results,M,l.file),delete l.results)}l.finished&&!g&&X(l.workerId,l.results)}function X(c,l){var _=s[c];j(_.userComplete)&&_.userComplete(l),_.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Ce(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var _=o.parse(l.input,l.config);_&&t.postMessage({workerId:o.WORKER_ID,results:_,finished:!0})}}function re(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var _ in c)l[_]=re(c[_]);return l}function R(c,l){return function(){c.apply(l,arguments)}}function j(c){return typeof c=="function"}return o})});import vn from"express";import bn from"cors";import{Server as ts}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as rs}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as ns,CallToolRequestSchema as as,InitializeRequestSchema as Cn}from"@modelcontextprotocol/sdk/types.js";import gt from"fs/promises";import Ne from"path";var nr=Object.freeze(["mcp","analyst"]);function dt(e){return typeof e=="string"&&nr.includes(e)}var Ge="https://usevulcan.app",mt="vulcan-local-tools",Ke=1,ft=10080*60,_t=300,z=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var ar=Object.freeze([`-----BEGIN PUBLIC KEY-----
7
+ `:"\r"};function I(E){return c.skipEmptyLines==="greedy"?E.join("").trim()==="":E.length===1&&E[0].length===0}function W(E){if(g.test(E)){var A=parseFloat(E);if(A>f&&A<l)return!0}return!1}function X(){return $&&le&&(fe("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&($.data=$.data.filter(function(E){return!I(E)})),Y()&&de(),D()}function Y(){return c.header&&k.length===0}function de(){if(!$)return;function E(N,H){j(c.transformHeader)&&(N=c.transformHeader(N,H)),k.push(N)}if(Array.isArray($.data[0])){for(var A=0;Y()&&A<$.data.length;A++)$.data[A].forEach(E);$.data.splice(0,1)}else $.data.forEach(E)}function ae(E){return c.dynamicTypingFunction&&c.dynamicTyping[E]===void 0&&(c.dynamicTyping[E]=c.dynamicTypingFunction(E)),(c.dynamicTyping[E]||c.dynamicTyping)===!0}function me(E,A){return ae(E)?A==="true"||A==="TRUE"?!0:A==="false"||A==="FALSE"?!1:W(A)?parseFloat(A):w.test(A)?new Date(A):A===""?null:A:A}function D(){if(!$||!c.header&&!c.dynamicTyping&&!c.transform)return $;function E(N,H){var C=c.header?{}:[],J;for(J=0;J<N.length;J++){var se=J,ee=N[J];c.header&&(se=J>=k.length?"__parsed_extra":k[J]),c.transform&&(ee=c.transform(ee,se)),ee=me(se,ee),se==="__parsed_extra"?(C[se]=C[se]||[],C[se].push(ee)):C[se]=ee}return c.header&&(J>k.length?fe("FieldMismatch","TooManyFields","Too many fields: expected "+k.length+" fields but parsed "+J,v+H):J<k.length&&fe("FieldMismatch","TooFewFields","Too few fields: expected "+k.length+" fields but parsed "+J,v+H)),C}var A=1;return!$.data.length||Array.isArray($.data[0])?($.data=$.data.map(E),A=$.data.length):$.data=E($.data,0),c.header&&$.meta&&($.meta.fields=k),v+=A,$}function Ce(E,A,N,H,C){var J,se,ee,Re;C=C||[","," ","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var Se=0;Se<C.length;Se++){var Le=C[Se],je=0,Ee=0,ce=0;ee=void 0;for(var he=new U({comments:H,delimiter:Le,newline:A,preview:10}).parse(E),oe=0;oe<he.data.length;oe++){if(N&&I(he.data[oe])){ce++;continue}var ue=he.data[oe].length;if(Ee+=ue,typeof ee>"u"){ee=ue;continue}else ue>0&&(je+=Math.abs(ue-ee),ee=ue)}he.data.length>0&&(Ee/=he.data.length-ce),(typeof se>"u"||je<=se)&&(typeof Re>"u"||Ee>Re)&&Ee>1.99&&(se=je,J=Le,Re=Ee)}return c.delimiter=J,{successful:!!J,bestDelimiter:J}}function fe(E,A,N,H){var C={type:E,code:A,message:N};H!==void 0&&(C.row=H),$.errors.push(C)}}function F(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(c){c=c||{};var l=c.delimiter,f=c.newline,g=c.comments,w=c.step,M=c.preview,b=c.fastMode,v,L=null,q=!1;c.quoteChar===void 0||c.quoteChar===null?v='"':v=c.quoteChar;var Q=v;if(c.escapeChar!==void 0&&(Q=c.escapeChar),(typeof l!="string"||o.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),g===l)throw new Error("Comment character same as delimiter");g===!0?g="#":(typeof g!="string"||o.BAD_DELIMITERS.indexOf(g)>-1)&&(g=!1),f!==`
8
+ `&&f!=="\r"&&f!==`\r
9
+ `&&(f=`
10
+ `);var O=0,le=!1;this.parse=function(k,$,Pe){if(typeof k!="string")throw new Error("Input must be a string");var I=k.length,W=l.length,X=f.length,Y=g.length,de=j(w);O=0;var ae=[],me=[],D=[],Ce=0;if(!k)return ce();if(b||b!==!1&&k.indexOf(v)===-1){for(var fe=k.split(f),E=0;E<fe.length;E++){if(D=fe[E],O+=D.length,E!==fe.length-1)O+=f.length;else if(Pe)return ce();if(!(g&&D.substring(0,Y)===g)){if(de){if(ae=[],Se(D.split(l)),he(),le)return ce()}else Se(D.split(l));if(M&&E>=M)return ae=ae.slice(0,M),ce(!0)}}return ce()}for(var A=k.indexOf(l,O),N=k.indexOf(f,O),H=new RegExp(F(Q)+F(v),"g"),C=k.indexOf(v,O);;){if(k[O]===v){for(C=O,O++;;){if(C=k.indexOf(v,C+1),C===-1)return Pe||me.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:ae.length,index:O}),je();if(C===I-1){var J=k.substring(O,C).replace(H,v);return je(J)}if(v===Q&&k[C+1]===Q){C++;continue}if(!(v!==Q&&C!==0&&k[C-1]===Q)){A!==-1&&A<C+1&&(A=k.indexOf(l,C+1)),N!==-1&&N<C+1&&(N=k.indexOf(f,C+1));var se=N===-1?A:Math.min(A,N),ee=Le(se);if(k.substr(C+1+ee,W)===l){D.push(k.substring(O,C).replace(H,v)),O=C+1+ee+W,k[C+1+ee+W]!==v&&(C=k.indexOf(v,O)),A=k.indexOf(l,O),N=k.indexOf(f,O);break}var Re=Le(N);if(k.substring(C+1+Re,C+1+Re+X)===f){if(D.push(k.substring(O,C).replace(H,v)),Ee(C+1+Re+X),A=k.indexOf(l,O),C=k.indexOf(v,O),de&&(he(),le))return ce();if(M&&ae.length>=M)return ce(!0);break}me.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:ae.length,index:O}),C++}}continue}if(g&&D.length===0&&k.substring(O,O+Y)===g){if(N===-1)return ce();O=N+X,N=k.indexOf(f,O),A=k.indexOf(l,O);continue}if(A!==-1&&(A<N||N===-1)){D.push(k.substring(O,A)),O=A+W,A=k.indexOf(l,O);continue}if(N!==-1){if(D.push(k.substring(O,N)),Ee(N+X),de&&(he(),le))return ce();if(M&&ae.length>=M)return ce(!0);continue}break}return je();function Se(oe){ae.push(oe),Ce=O}function Le(oe){var ue=0;if(oe!==-1){var ke=k.substring(C+1,oe);ke&&ke.trim()===""&&(ue=ke.length)}return ue}function je(oe){return Pe||(typeof oe>"u"&&(oe=k.substring(O)),D.push(oe),O=I,Se(D),de&&he()),ce()}function Ee(oe){O=oe,Se(D),D=[],N=k.indexOf(f,O)}function ce(oe){if(c.header&&!$&&ae.length&&!q){let ue=ae[0],ke=Object.create(null),at=new Set(ue),Gt=!1;for(let Fe=0;Fe<ue.length;Fe++){let ye=ue[Fe];if(j(c.transformHeader)&&(ye=c.transformHeader(ye,Fe)),!ke[ye])ke[ye]=1,ue[Fe]=ye;else{let Ie,Kt=ke[ye];do Ie=`${ye}_${Kt}`,Kt++;while(at.has(Ie));at.add(Ie),ue[Fe]=Ie,ke[ye]++,Gt=!0,L===null&&(L={}),L[Ie]=ye}at.add(ye)}Gt&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:ae,errors:me,meta:{delimiter:l,linebreak:f,aborted:le,truncated:!!oe,cursor:Ce+($||0),renamedHeaders:L}}}function he(){w(ce()),ae=[],me=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return O}}function V(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=B,l.id=i++,s[l.id]=l,l}function B(c){var l=c.data,f=s[l.workerId],g=!1;if(l.error)f.userError(l.error,l.file);else if(l.results&&l.results.data){var w=function(){g=!0,K(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},M={abort:w,pause:Z,resume:Z};if(j(f.userStep)){for(var b=0;b<l.results.data.length&&(f.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},M),!g);b++);delete l.results}else j(f.userChunk)&&(f.userChunk(l.results,M,l.file),delete l.results)}l.finished&&!g&&K(l.workerId,l.results)}function K(c,l){var f=s[c];j(f.userComplete)&&f.userComplete(l),f.terminate(),delete s[c]}function Z(){throw new Error("Not implemented.")}function be(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var f=o.parse(l.input,l.config);f&&t.postMessage({workerId:o.WORKER_ID,results:f,finished:!0})}}function re(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var f in c)l[f]=re(c[f]);return l}function R(c,l){return function(){c.apply(l,arguments)}}function j(c){return typeof c=="function"}return o})});import ln from"express";import un from"cors";import{Server as Na}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Ba}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as La,CallToolRequestSchema as Ia,InitializeRequestSchema as dn}from"@modelcontextprotocol/sdk/types.js";import dt from"fs/promises";import $e from"path";var Yt=Object.freeze(["mcp","analyst"]);function st(e){return typeof e=="string"&&Yt.includes(e)}var He="https://usevulcan.app",ot="vulcan-local-tools",ze=1,it=10080*60,ct=300,z=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var Zt=Object.freeze([`-----BEGIN PUBLIC KEY-----
11
11
  MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
12
- -----END PUBLIC KEY-----`]);import{compactVerify as Mn,importSPKI as On}from"jose";var sr="EdDSA";async function ht(e,t){let n=e.trim();if(!n)throw new z("empty","Vulcan access token is empty.");let r=t.publicKeys??ar,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),i=await Fn(n,r),o=$n(i);if(o.iss!==Ge)throw new z("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${Ge}.`);if(o.aud!==mt)throw new z("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==Ke)throw new z("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${Ke}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new z("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>ft)throw new z("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(s<o.iat-_t)throw new z("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let m=s>o.exp;if(m&&!t.allowExpired)throw new z("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:o,expired:m,expiresAt:new Date(o.exp*1e3),expiresInSeconds:o.exp-s}}async function Fn(e,t){for(let n of t)try{let r=await On(n,sr),{payload:a}=await Mn(e,r,{algorithms:[sr]});return a}catch{}throw new z("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function $n(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new z("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new z("malformed","Vulcan access token payload is not an object.");let n=t,r=Je(n,"iss"),a=Je(n,"aud"),s=Je(n,"sub"),i=Je(n,"org"),o=Je(n,"jti"),m=pt(n,"iat"),u=pt(n,"exp"),d=pt(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new z("malformed","Vulcan access token must include a capabilities array.");let f=[];for(let h of n.capabilities){if(!dt(h))throw new z("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(h)}.`);f.push(h)}if(f.length===0)throw new z("malformed","Vulcan access token grants no capabilities.");if(u<=m)throw new z("malformed","Vulcan access token expires no later than it was issued.");return{iss:r,aud:a,sub:s,org:i,jti:o,capabilities:Object.freeze(f),entitlement_schema_version:d,iat:m,exp:u}}function Je(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new z("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function pt(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new z("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return n}var Nn="mcp",Bn=2880*60;async function or(e){let t=e;if(!t){let u=process.env.VULCAN_WORKSPACE;u?t=Ne.join(u,"vulcan-mcp-config.json"):t=Ne.join(process.cwd(),"vulcan-mcp-config.json")}t=Ne.resolve(t);let n;try{n=await gt.readFile(t,"utf-8")}catch(u){let d=u;throw new Error(`Config file not found: ${t}. Please generate it from Vulcan \u2192 Integrations \u2192 MCP.`)}let r;try{r=JSON.parse(n)}catch(u){let d=u;throw new Error(`Invalid JSON in config file: ${d.message}`)}if(!r.workspace)throw new Error("Config file missing required field: workspace");if(!r.license_token||typeof r.license_token!="string")throw new Error('Your Vulcan MCP token is missing. Open Vulcan \u2192 Integrations \u2192 MCP and click "Generate config".');let a=Ne.resolve(Ne.dirname(t),r.workspace);try{await gt.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}let s=Ne.join(a,"input","batch_parameters");try{await gt.access(s)}catch{throw new Error(`Workspace missing required directory: ${s}. MCP only supports folder (FSA) workspaces backed by the real filesystem.`)}let{payload:i}=await yt(r.license_token),o=Math.floor(Date.now()/1e3),m=i.exp-o;if(m<Bn){let u=Math.max(1,Math.round(m/3600));console.error(`[MCP Helper] Warning: your Vulcan access config expires in about ${u} hour(s). Open Vulcan -> Profile -> Integrations and click "Generate Config File" to avoid interruption.`)}return{workspace:a,license_token:r.license_token,configPath:t}}async function yt(e,t={}){try{let{claims:n}=await ht(e,{capability:Nn,now:t.now,publicKeys:t.publicKeys});return{payload:n}}catch(n){throw new Error(Ln(n))}}function Ln(e){if(!(e instanceof z))return e instanceof Error?e.message:String(e);switch(e.code){case"missing_capability":return"This Vulcan access config does not include MCP. MCP requires a Vulcan Pro seat; open Vulcan -> Profile -> Integrations and generate a new config.";case"expired":return'Your Vulcan access config has expired. Open Vulcan -> Profile -> Integrations and click "Generate Config File" to continue.';case"unsupported_schema_version":return'This Vulcan access config was issued for a newer version of the Vulcan tools. Update the helper with "npm install -g @vulcan-energy/mcp-helper@latest".';case"lifetime_exceeded":return"This Vulcan access config declares a longer lifetime than Vulcan issues and was refused. Generate a new config.";case"clock_behind":return"This system clock is too far behind the access config issue time. Correct the clock, then restart the helper.";case"wrong_audience":case"wrong_issuer":return'This access config was not issued for local Vulcan tools. Open Vulcan -> Profile -> Integrations and click "Generate Config File".';default:return'Your Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and click "Generate Config File".'}}import{timingSafeEqual as In}from"crypto";function Dn(e){if(typeof e!="string")throw new Error("MCP request Bearer token is required");let t=/^Bearer[\t ]+([^\t ]+)$/i.exec(e.trim());if(!t?.[1])throw new Error("MCP request Bearer token is required");return t[1]}function Wn(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&In(n,r)}async function ir(e,t,n=yt){let r=Dn(e);if(!Wn(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as y}from"zod";import Jn from"fs/promises";import Vn from"path";function cr(e,t={}){let n=[],r=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&n.push("Config must have at least one scenario");for(let[s,i]of Object.entries(e)){if(!i||typeof i!="object"){n.push(`Scenario '${s}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&n.push(`Scenario '${s}' must have exactly one base_json (found ${o.base_json.length})`):n.push(`Scenario '${s}' is missing required 'base_json' field (must be array)`);let m=!!(o.weather_file||o.weather_files),u=!!o.external_conditions;if(m){let d=o.weather_file||o.weather_files;Array.isArray(d)?d.length>1&&n.push(`Scenario '${s}' must have at most one weather_file (found ${d.length})`):n.push(`Scenario '${s}' weather_file/weather_files must be an array`)}u&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!m&&!u&&n.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),m&&u&&r.push(`Scenario '${s}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[d,f]of Object.entries(o))Array.isArray(f)||n.push(`Scenario '${s}': '${d}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function lr(e){try{if(!e||typeof e!="object")return null;let t=0;for(let n of Object.values(e)){if(!n||typeof n!="object")continue;let r=n,a=1;for(let s of Object.values(r))Array.isArray(s)&&(a*=s.length);t+=a}return t}catch{return null}}async function ur(e,t){let n=[],r=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:r};for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let i=s;for(let[o,m]of Object.entries(i))if(Array.isArray(m)&&!(o==="weather_file"||o==="weather_files"))for(let u of m){let d=Vn.join(e,"input","batch_parameters",o,`${String(u)}.json`);try{await Jn.access(d)}catch{r.push({scenario:a,category:o,parameter:String(u),path:d}),n.push(`Scenario '${a}': Parameter '${String(u)}' in category '${o}' not found at ${d}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{readFile as jr}from"fs/promises";import{join as Tr}from"path";var Un=Tn(dr(),1),qn=Object.defineProperty,Hn=Object.getOwnPropertyNames,zn=(e,t)=>function(){return e&&(t=(0,e[Hn(e)[0]])(e=0)),t},Gn=(e,t)=>{for(var n in t)qn(e,n,{get:t[n],enumerable:!0})},Kn={};Gn(Kn,{configureWasm:()=>Xn,getRuntimeApiUrl:()=>aa,getRuntimeWasmVariant:()=>ta,getVersionedWasmAssetPaths:()=>St,getVersionedWasmJsUrl:()=>gr,getWasmAssetPaths:()=>hr,getWasmBaseUrl:()=>Ct,getWasmBinaryUrl:()=>yr,getWasmJsUrl:()=>br,getWasmRayonThreadCount:()=>fr,getWasmVariant:()=>pr,getWasmVersionInfo:()=>Xe,getWasmVersionJsonUrl:()=>_r,getWasmWasmUrl:()=>Cr,initializeWasmRayonThreadPool:()=>ea});function Xn(e={}){e.baseUrl&&(wr=Yn(e.baseUrl)),typeof e.preferHashed=="boolean"&&(vr=e.preferHashed)}function mr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Yn(e){return e.replace(/\/+$/,"")||"/"}function Zn(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Qn(){let e=mr();if(e){if(Zn(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Ct(){return wr||Qn()}function fr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function ea(e){let t=e,n=Ve.get(t);if(n)return n;let r=e.initialize_rayon_thread_pool;if(typeof r!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>r(fr())).then(()=>{});return Ve.set(t,a),a.catch(()=>{Ve.get(t)===a&&Ve.delete(t)}),a}function _r(){return`${Ct()}/wasm_version.json`}async function Xe(){try{let e=await fetch(_r(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function pr(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function ta(){return pr(await Xe())}function ra(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function na(e){let t=ra(),r=!!((vr??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(r?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(r?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function hr(e){let t=Ct(),n=e===void 0?await Xe():e,{jsFilename:r,wasmFilename:a}=na(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${a}`}}async function St(){let e=await Xe(),{jsPath:t,wasmPath:n}=await hr(e),r=e?.build_id||e?.sha256||e?.timestamp;if(!r)return{jsPath:t,wasmPath:n,versionInfo:e};let a=`v=${encodeURIComponent(String(r))}`;return{jsPath:`${t}?${a}`,wasmPath:`${n}?${a}`,versionInfo:e}}async function gr(){let{jsPath:e}=await St();return e}async function yr(){let{wasmPath:e}=await St();return e}function aa(e){let t=mr();return t?new URL(e,t.origin).toString():e}var Ve,wr,vr,br,Cr,Sr=zn({"src/wasmPath.ts"(){Ve=new WeakMap,br=gr,Cr=yr}});async function kr(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return null;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(r.files)||!r.files.length||r.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(r.files)}async function Er(e,t){let n=await kr(e,t),r=await e.listFiles(t,{withKind:!0});return n===null?r:r.filter(a=>n.has(typeof a=="string"?a:a.name))}async function Pr(e,t){let n=t.lastIndexOf("/"),r=await kr(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}function kt(e){let t=new Map;for(let{run:i,startedAt:o,fileTime:m}of e){if(o!==void 0&&Number.isNaN(Date.parse(o)))throw new Error(`Run ${i} records an invalid start time: ${o}`);let u=t.get(i);t.set(i,{run:i,startedAt:u?.startedAt??o,fileTime:Math.max(u?.fileTime??m,m)})}let n=(i,o)=>{let m=`Runs ${i.run} and ${o.run} have the same time, so the helper cannot tell which run is newest. Run the config again.`;if(i.startedAt!==void 0&&o.startedAt!==void 0)return Date.parse(i.startedAt)-Date.parse(o.startedAt)||m;if(i.startedAt===void 0&&o.startedAt===void 0)return i.fileTime-o.fileTime||m;let[u,d]=i.startedAt===void 0?[o,i]:[i,o];return d.fileTime<Date.parse(u.startedAt)?u===i?1:-1:`The workspace holds a run recorded by an older version of Vulcan, which did not record when a run started (${d.run}). Its files are dated after run ${u.run} started, so they may have been copied, and the helper cannot tell which run is newest. Run the config again.`},r=[...t.values()],a=r.map(i=>r.filter(o=>o!==i).map(o=>n(i,o))),s=r.find((i,o)=>a[o].every(m=>typeof m=="number"&&m>0));return s||!r.length?s:{unknown:a.flat().find(i=>typeof i=="string")}}function Et(e,t){let n=e.map(r=>typeof r=="string"?r:r.name).filter(r=>r.endsWith(".csv")?t==="results_heat_source_wet"?r.includes("__results_heat_source_wet__"):t==="results_emitters"?r.includes("__results_emitters_"):r.endsWith(`__${t}.csv`):!1).sort((r,a)=>r.localeCompare(a));return n.find(r=>/(?:^|__)FHS__/.test(r))??n.find(r=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(r))}Sr();function sa(e){return e.startsWith("__")}function Ye(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!sa(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function oa(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function ia(e){let t=oa(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function Ze(e,t){let n=[];for(let r of Ye(t)){let a=ia(r.value);for(let s=0;s<a;s+=1)n.push(`result_${e}_${r.name}_${s}`)}return n}function Pt(e){return Math.floor(e/1e3)}function ca(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function la(e){return e==="failure_context.json"}function xr(e){return ca(e)||la(e)}function ua(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&bt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&bt(r))return r;let s=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(s&&bt(s))return s}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function bt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var Es=ua();Sr();import Ar from"fs/promises";import xt from"path";var At="input/defaults/defaults_template.json",Rt="input/batch_parameters/base_json/defaults_template.json",da="batch_parameters/base_json/defaults_template.json",ma="defaults/defaults_template.json";function fa(e){let n=e.split(`
13
- `).slice(0,50).find(s=>/^DefaultsPath,/i.test(s.trim()));return n&&(Qe(n)[1]||"").trim()||null}function _a(e){let t=e.trim().replace(/\\/g,"/");return t===Rt||t.endsWith("/batch_parameters/base_json/defaults_template.json")}function pa(e){let t=e.trim();if(!t)return[];if(!_a(t))return[t];let n=t.replace(/\\/g,"/"),r=n.lastIndexOf(da);return[r>=0?`${n.slice(0,r)}${ma}`:At,t]}async function Rr(e){let t=(e.explicitDefaultsPath??"").trim(),n=t||fa(e.csvContent);if(n){let r=pa(n),a;for(let i of r){let o=xt.isAbsolute(i)?i:xt.join(e.workspace,i);try{return{defaultsJson:await Ar.readFile(o,"utf8"),source:t?`custom: ${i}`:`CSV metadata: ${i}`,path:o}}catch(m){a=m}}let s=a instanceof Error?a.message:String(a);throw new Error(`Could not read defaults file "${n}". Conversion was aborted instead of silently substituting the standard defaults template. ${s}`)}for(let r of[At,Rt,"defaults_template.json"]){let a=xt.join(e.workspace,r);try{return{defaultsJson:await Ar.readFile(a,"utf8"),source:"legacy fallback: standard defaults template",path:a}}catch{}}throw new Error(`Defaults file not found. Tried ${At}, ${Rt}, defaults_template.json`)}function Qe(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}function jt(e,t=!1){let n="",r=1,a,s=[];for(let i of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!i.trim())continue;let o=Qe(i).map(u=>u.trim());if(o[0]=o[0]?.replace(/^#\s*/,"")??"",o[0]&&o.slice(1).every(u=>!u)){n=o[0],a=void 0;continue}if(n==="Metadata"){if(o[0]==="TargetBundleId"&&o[1]&&!t)return`CSV pins TargetBundleId '${o[1]}'. Merge it with vulcan_merge_csv_to_json, which prepares it with its pinned target; the installed legacy converter cannot substitute that bundle.`;o[0]==="VulcanCsvVersion"&&(r=Number(o[1]));continue}if(n!=="Non-Exposed Elements")continue;if(!a){a=o;continue}let m=Object.fromEntries(a.map((u,d)=>[u,o[d]??""]));m.Type==="BuildingElementPartyWall"&&s.push(m)}if(!Number.isInteger(r)||r<1||r>3)return`Unsupported or invalid VulcanCsvVersion '${r}'; supported versions are 1, 2 and 3.`;for(let i of s){let o={};if(i.extra_json)try{o=JSON.parse(i.extra_json)}catch{return`Invalid extra_json for party wall '${i.Name||"unnamed"}'; resolve it before finalizing CSV version 3.`}let m=!!i.u_value||o&&Object.hasOwn(o,"u_value"),u=i.u_value?Number(i.u_value):o?.u_value,d=r<3&&typeof o?.u_value_interpreted_value=="number"&&o.u_value_interpreted_value!==u,f=r>=3&&o?.u_value_interpretation!=="whole_wall"&&o?.u_value_interpretation!=="half_construction";if(m&&(f||d))return`E_CSV_MIGRATION: Party wall '${i.Name||"unnamed"}' has unresolved legacy U-value meaning. Explicitly select whole_wall or half_construction before finalizing CSV version 3.`}}function Be(e){let t=!1,n;for(let r of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!r.trim())continue;let a=Qe(r).map(s=>s.trim());if(a[0]=a[0]?.replace(/^#\s*/,"")??"",a[0]&&a.slice(1).every(s=>!s)){t=a[0]==="Metadata";continue}if(t&&a[0]==="TargetBundleId"&&a[1]){if(n)throw new Error("CSV contains conflicting TargetBundleId metadata");n=a[1]}}return n}async function et(e,t){let n=new Set;for(let{value:r}of Ye(t))if(Array.isArray(r.base_json))for(let a of r.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");n.add(await ha(e,a))}if(n.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...n][0]}async function ha(e,t){try{let n=Be(await jr(Tr(e,"input/base_models",`${t}.csv`),"utf8"));if(n)return n}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await jr(Tr(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof n.targetBundleId!="string"||!n.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return n.targetBundleId}catch(n){if(n.code==="ENOENT")return;throw n}}async function Tt(e,t){if(Ye(t).some(({value:r})=>Array.isArray(r.heating_profiles)&&r.heating_profiles.length))return"Heating profiles require a saved, pinned HEM target batch; the legacy runner cannot apply post-FHS controls.";let n;try{n=await et(e,t)}catch(r){return r.message}if(n)return`This batch's base models pin HEM target '${n}'. Create the batch with vulcan_create_batch_config to capture its exact __hem source/snippet snapshot; a legacy batch cannot substitute the installed Rust runner.`}import{fork as ga}from"child_process";import{resolve as ya}from"path";import{access as wa}from"fs/promises";import{fileURLToPath as Mr}from"url";var Ue=async e=>{let t=!!(e.targetManifestPath||e.targetManifestSha256);if(t&&(!e.targetManifestPath||!/^[a-f0-9]{64}$/.test(e.targetManifestSha256??"")))throw new Error("Supply both target_manifest and target_manifest_sha256 for an offline bundle, or neither to download the verified pinned target.");if(!t&&!e.targetBundleId)throw new Error("No HEM target identified. Save the source CSV with its TargetBundleId pin; installed legacy WASM cannot substitute it.");for(let n of["./hem-target-runtime/browser-adapter.mjs","../hem-target-runtime/browser-adapter.mjs"]){let r=new URL(n,import.meta.url);try{await wa(Mr(r))}catch{continue}let a=t?{...e,manifestPath:ya(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{...e};if(e.operation==="batch")return va(Mr(r),a);let{runTargetBrowser:s}=await import(r.href);return s(a)}throw new Error("Target browser assets are not installed. Build the local target CLI assets or install a helper release including them.")};function va(e,t){return new Promise((n,r)=>{let a=ga(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),s=setTimeout(()=>{a.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",i=>{clearTimeout(s),r(i)}),a.once("exit",i=>{clearTimeout(s),r(new Error(`Target batch stopped before startup (${i})`))}),a.once("message",i=>{clearTimeout(s),i.started?(a.unref(),n({status:"started"})):(a.kill(),r(new Error(i.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as ba}from"crypto";import ne from"fs/promises";import G from"path";async function Ot(e,t,n={},r={}){let{config_name:a,base_model:s,weather_file:i,wrapper:o,parameters:m}=t;if(!a)throw new Error("config_name is required");if(!s)throw new Error("base_model is required");if(!m||typeof m!="object"||Array.isArray(m))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let u=Ca(m),d={base_json:[s],...o?{model_wrappers:[o]}:{},...u},f=await et(e,{scenario_1:d}),h=!!(t.targetManifestPath||t.targetManifestSha256||f);if(!i&&!h)throw new Error("weather_file is required");if(h&&(!/^[a-zA-Z0-9_. -]+$/.test(a)||a===".."))throw new Error("Invalid target config name");i&&(d.weather_files=[h&&!i.endsWith(".epw")?`${i}.epw`:i]);let p={scenario_1:d},C=cr(p,{requireWeather:!h});if(!C.valid)return{success:!1,valid:!1,errors:C.errors,warnings:C.warnings,message:`Config validation failed: ${C.errors.join("; ")}`};let w=lr(p);if(w===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let S=n.maxPermutations??500;if(!Number.isSafeInteger(S)||S<1)throw new Error("maxPermutations must be a positive integer");if(w>S)return{success:!1,valid:!1,errors:[`Total permutations (${w}) exceeds maximum of ${S}`],message:`Config would generate ${w} permutations, which exceeds the limit of ${S}`};let T=p;if(h){let B=await(r.runTarget??Ue)({workspace:e,operation:"snapshot",config:p,targetBundleId:f,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});T={...p,__hem:B}}else{let B=await ur(e,p);if(!B.valid)return{success:!1,valid:!1,errors:B.errors,missingFiles:B.missingFiles,message:`Some parameter files are missing: ${B.errors.slice(0,3).join("; ")}${B.errors.length>3?"...":""}`};let X=G.join(e,"input","batch_parameters","base_json",`${s}.json`);try{await ne.access(X)}catch{return{success:!1,valid:!1,errors:[`Base model '${s}' not found at ${X}`],message:`Base model file not found: ${s}`}}let Q=G.join(e,"input","batch_parameters","weather_files",i.endsWith(".epw")?i:`${i}.epw`);try{await ne.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Q}`],message:`Weather file not found: ${i}`}}}let F=G.join(e,"input","batch_configs");if(h){let B=await ne.realpath(e);for(let X of["input","batch_configs"])if(B=G.join(B,X),await ne.mkdir(B).catch(Q=>{if(Q.code!=="EEXIST")throw Q}),await ne.realpath(B)!==B)throw new Error("Target config directory is a symlink")}else await ne.mkdir(F,{recursive:!0});let U=a.endsWith(".json")?a:`${a}.json`,J=G.join(F,U);try{return await ne.access(J),{success:!1,valid:!1,errors:[`Config file '${U}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await ne.writeFile(J,JSON.stringify(T,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:J,permutations:w,structure:p}}async function rt(e,t,n){let{config_name:r,job_id:a}=t;if(!r)throw new Error("config_name is required");let s=a||n.generateJobId?.()||`mcp_${ba()}`,i=r.endsWith(".json")?r:`${r}.json`,o=G.join(e,"input","batch_configs",i),m;try{m=await ne.readFile(o,"utf8")}catch(h){let p=h;throw p.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${p.message}`)}let u=JSON.parse(m);if(u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let h=u.__hem;if(!h){let p="This batch names a HEM target but has no saved __hem source snapshot. Re-save the batch in the app (or create it with vulcan_create_batch_config).";return{job_id:s,status:"error",message:p,error:p}}try{return await(n.runTarget??Ue)({workspace:e,operation:"batch",config:u,targetBundleId:h.targetBundleId,configName:r.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:r,output_dir:G.join(e,"output"),message:"Exact target batch started. Read progress with vulcan_get_batch_status; runtime provenance is stored with outputs."}}catch(p){let C=p.message;return{job_id:s,status:"error",message:C,error:C}}}let d=await Tt(e,u);if(d)return{job_id:s,status:"error",message:d,error:d};if(t.targetManifestPath||t.targetManifestSha256){let h="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:s,status:"error",message:h,error:h}}let f=G.join(e,"output");await ne.mkdir(f,{recursive:!0});try{let h=await n.processBatchConfig(m,e,f,r.replace(/\.json$/,""),s),p=JSON.parse(h);return p.error?{job_id:s,status:"error",message:`Batch execution failed: ${p.error}`,error:p.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:f}}catch(h){let p=h;return{job_id:s,status:"error",message:`Failed to start batch execution: ${p.message}`,error:p.message}}}async function Ft(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,""),a=G.join(e,"output"),s;if(r&&!n){if(s=await tt(e,r),!s.jobId){let F=s.error!==void 0?"error":s.unknown?"unknown":"not_run",U=s.error??s.unknown??s.changed??`Batch config '${r}' has no recorded run. A legacy engine run records its config only in its result folders: pass the job_id from vulcan_run_batch instead.`;return{config_name:r,status:F,progress:0,passes:0,failures:0,output_dir:a,error:U,...$r(s.warnings)}}n=s.jobId}if(!n)throw new Error("Either job_id or config_name is required");if(/[\\/]/.test(n)||n==="."||n==="..")throw new Error(`Invalid job_id '${n}': a job id is a plain name, as vulcan_run_batch returns it`);let i=s?.warnings??[],o=G.join(a,`progress_${n}.json`),m=G.join(a,`sim_progress_${n}.json`),u=await Me(o,i),d=await Me(m,i),f=await Br(a,n,i);if(!s&&f.config){let F=await tt(e,f.config);i.push(...F.warnings),F.jobId===n&&(s=F),r??=f.config}let h=f.records>0||typeof u?.targetBundleId=="string",p="queued",C=0,w=0,S=0,T=null;if(u?(Nr(u.status)?p=u.status:typeof u.percentage=="number"?(C=u.percentage,p=C>=100?"completed":"running"):typeof u.current_combination=="number"&&typeof u.total_combinations=="number"&&(C=Math.round(u.current_combination/u.total_combinations*100),p=C>=100?"completed":"running"),typeof u.percentage=="number"&&(C=u.percentage),typeof u.error=="string"&&(T=u.error,p="error")):f.records&&(f.stopped?(p="error",T=f.stopped):s?.expected!==void 0&&f.passes===s.expected?(p="completed",C=100):(p="unknown",T=`Job ${n} has finished ${f.passes} of ${s?.expected??"an unknown number of"} scenarios and recorded no failure. The app writes no progress file, so the helper cannot tell whether the run is still going or has stopped; check the app.`)),f.records&&({passes:w,failures:S}=f),s?.error!==void 0&&(T=s.error,p="error"),d&&!h&&(Nr(d.status)&&(p=d.status),typeof d.passes=="number"&&(w=d.passes),typeof d.failures=="number"&&(S=d.failures),typeof d.error=="string"&&(T=d.error,p="error")),!u&&!d&&!f.records){let F=G.join(a,n);try{let U=await ne.readdir(F);p=U.length>0?"completed":"queued",C=U.length>0?100:0}catch(U){throw U.code!=="ENOENT"?U:new Error(`Job ${n} does not exist in this workspace: ${a} holds no progress file, run record or folder for it.`)}}return{job_id:n,...r?{config_name:r}:{},status:p,progress:C,passes:w,failures:S,output_dir:a,error:T,batch_progress:u??null,sim_progress:h?null:d??null,...$r(i)}}async function tt(e,t){let n=G.join(e,"output"),r=[],a=[],s=async R=>(await ne.stat(R)).mtimeMs,i=R=>typeof R.startedAt=="string"?R.startedAt:void 0;for(let R of await ne.readdir(n).catch(Mt)??[]){if(!R.startsWith("progress_")||!R.endsWith(".json"))continue;let j=await Me(G.join(n,R),r),c=R.slice(9,-5);j?.config_name===t&&a.push({run:c,jobId:c,startedAt:i(j),fileTime:await s(G.join(n,R))})}let o=G.join(e,"input","batch_configs",`${t}.json`),m=await Me(o,r),u=m?Ze(t,m):[],d,f=[];for(let R of u){let j=G.join(n,R),c=await ne.readdir(j,{withFileTypes:!0}).catch(Mt);if(!c)continue;if(!c.some(_=>_.name==="target-run.json")){let _=c.filter(g=>g.isFile()&&xr(g.name)).map(g=>G.join(j,g.name));if(!_.length)continue;d??=`Batch config '${t}' has results in output/${R} from the legacy engine, which does not record the job that wrote them. Pass the job_id from vulcan_run_batch.`,a.push({run:Or,fileTime:Math.max(...await Promise.all(_.map(s)))});continue}let l=R.slice(`result_${t}_`.length);for(let _ of c.filter(g=>g.isDirectory()))for(let g of await ne.readdir(G.join(j,_.name),{withFileTypes:!0})){if(!g.isDirectory())continue;let v=G.join(j,_.name,g.name,"target-run.json"),M=r.length,k=await Me(v,r);if(!k){r.length>M&&f.push({warning:r.at(-1),fileTime:await s(v)});continue}k.name===l&&a.push({run:g.name,jobId:g.name,startedAt:i(k),fileTime:await s(v)})}}let h=G.join(n,`batch_status_${t}.json`),p=await Me(h,r),C=p?.status==="error"||p?.status==="running",w=C?i(p):void 0,S=w===void 0?void 0:a.find(R=>R.jobId&&R.startedAt===w)?.jobId;C&&!S&&a.push({run:Fr,startedAt:w,fileTime:await s(h)});let T=m?u.length:void 0,F=a.flatMap(R=>R.startedAt===void 0?[]:[Date.parse(R.startedAt)]),U=f.find(R=>!F.length||R.fileTime>=Math.max(...F));if(U)return{unknown:`The helper cannot read a run record of batch config '${t}', so it cannot tell which run is latest. ${U.warning}`,expected:T,warnings:r};if(!a.length)return{legacyCurrent:!0,expected:T,warnings:r};if(m&&Pt(await s(o))>Pt(Math.max(...a.map(R=>R.fileTime))))return{changed:`Batch config '${t}' was saved after its last run. Results from that run are earlier-run results. Run the config again.`,expected:T,warnings:r};let J=kt(a);if("unknown"in J)return{unknown:J.unknown,expected:T,warnings:r};if(J.run===Or)return{unknown:d,legacyCurrent:!0,expected:T,warnings:r};let B=p?.error_message,X=p?.status!=="error"?void 0:typeof B=="string"&&B?B:`The app recorded the run of batch config '${t}' as failed, with no reason.`;if(J.run!==Fr)return{jobId:J.run,...J.run===S?{error:X}:{},expected:T,warnings:r};if(p?.status==="running")return{unknown:`The app started a run of batch config '${t}' at ${w} and has written no scenario yet. It may still be preparing, or it stopped without recording why; check the app.`,expected:T,warnings:r};if(w!==void 0)return{error:X,expected:T,warnings:r};let Q=kt(a.filter(R=>R.jobId)),Ce=Q&&"run"in Q?Q.run:void 0;return{...Ce&&(await Br(n,Ce,r)).stopped?{jobId:Ce}:{},error:X,expected:T,warnings:r}}var Or="legacy engine results",Fr="the app's run status";async function Br(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let a of await ne.readdir(e,{withFileTypes:!0}).catch(Mt)??[])if(!(!a.isDirectory()||!a.name.startsWith("result_")))for(let s of await ne.readdir(G.join(e,a.name),{withFileTypes:!0})){if(!s.isDirectory())continue;let i=await Me(G.join(e,a.name,s.name,t,"target-run.json"),n);if(!i)continue;r.records+=1;let o=`_${String(i.name)}`;a.name.endsWith(o)&&(r.config??=a.name.slice(7,-o.length)),i.status==="complete"?r.passes+=1:i.status==="failed"&&(r.failures+=1),(i.status==="failed"||i.status==="cancelled")&&(r.stopped??=`Scenario ${String(i.name)} ${i.status}${typeof i.error=="string"?`: ${i.error}`:""}`)}return r}async function Me(e,t){let n;try{n=await ne.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}try{return JSON.parse(n)}catch(r){t.push(`Skipped ${e}: ${r.message}`);return}}function Mt(e){if(e.code!=="ENOENT")throw e}function $r(e){return e.length?{warnings:e}:{}}function Ca(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function Nr(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import io from"crypto";import ve from"fs/promises";import K from"path";import qe from"fs";import xe from"path";import{fileURLToPath as Sa}from"url";function nt(e=process.cwd()){let t=xe.resolve(e);for(qe.existsSync(t)&&qe.statSync(t).isFile()&&(t=xe.dirname(t));;){if(qe.existsSync(xe.join(t,"package.json"))&&qe.existsSync(xe.join(t,"hem-batch-core"))&&qe.existsSync(xe.join(t,"web")))return t;let r=xe.dirname(t);if(r===t)break;t=r}let n=xe.dirname(Sa(import.meta.url));return xe.resolve(n,"..","..","..")}import Lr from"fs/promises";import at from"path";function ka(e){let t=!1,n=null;for(let r of e.split(`
14
- `).slice(0,80)){let a=r.trim();if(/^ComplianceValidationEnabled,/i.test(a)){t=Ir(a)[1]?.trim().toUpperCase()==="TRUE";continue}if(/^SchemaProfile,/i.test(a)){let s=Ir(a)[1]?.trim().toLowerCase();s==="ecaas_input_fhs"&&(n="ecaas_input_fhs"),s==="input_fhs"&&(n="input_fhs"),s==="input_core"&&(n="input_core")}}return n||(t?"input_fhs":"input_core")}async function Dr(e){let t=ka(e.csvContent);if(e.explicitSchemaPath){let a=at.isAbsolute(e.explicitSchemaPath)?e.explicitSchemaPath:at.resolve(e.workspace??process.cwd(),e.explicitSchemaPath);return{mode:t,source:a,schemaJson:await Lr.readFile(a,"utf8")}}let n=Ea({mode:t,repoRoot:e.repoRoot,workspace:e.workspace}),r=[];for(let a of n){r.push(a);try{return{mode:t,source:a,schemaJson:await Lr.readFile(a,"utf8")}}catch{}}throw new Error(`Schema file not found for ${t}. Tried: ${r.join(", ")}`)}function Ea(e){let t=[];if(e.repoRoot&&t.push(at.join(e.repoRoot,...Pa(e.mode))),e.workspace){let n=xa(e.mode);t.push(...n.map(r=>at.join(e.workspace,...r)))}return[...new Set(t)]}function Pa(e){switch(e){case"input_core":return["hem_engine_upstream","schemas","core-input.schema.json"];case"input_fhs":return["hem_fhs_upstream","schema","input_fhs.schema.json"];case"ecaas_input_fhs":return["schemas","ecaas_input_fhs.schema.json"]}}function xa(e){switch(e){case"input_core":return[["input_core.schema.json"],["hem_engine_upstream","schemas","core-input.schema.json"],["core-input.schema.json"],["schemas","core-input.schema.json"],["input.schema.json"]];case"input_fhs":return[["input_fhs.schema.json"],["hem_fhs_upstream","schema","input_fhs.schema.json"],["schema","input_fhs.schema.json"],["schemas","input_fhs.schema.json"]];case"ecaas_input_fhs":return[["ecaas_input_fhs.schema.json"],["schemas","ecaas_input_fhs.schema.json"]]}}function Ir(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}import we from"fs";import _e from"path";import{pathToFileURL as Aa}from"url";var Wr=new Map,Jr=!1,$t=process.cwd(),Ur=!1;async function Nt(e){let t=Wr.get(e);if(t)return t;Ra();let n=_e.join(e,"wasm_wrapper.js"),r=_e.join(e,"wasm_wrapper_bg.wasm"),a=_e.join(e,"wasm_version.json");if(!we.existsSync(n)||!we.existsSync(r))throw new Error(`Browser WASM artifact not found in ${e}`);let s=await import(Aa(n).href);if(typeof s.initSync!="function")throw new Error("WASM module is missing initSync");if(s.initSync({module:we.readFileSync(r)}),s.setup_panic_hook?.(),typeof s.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let i={convertGeometryCsvToJson:s.convert_geometry_csv_to_json.bind(s),validateSnippetJs:s.validate_snippet_js?.bind(s),processBatchConfig:s.process_batch_config?.bind(s),calculateMetricsFromParsedData:s.calculate_metrics_from_parsed_data?.bind(s),setWorkspace:Le,metadata:{source:n,wasm_path:r,wasm_version:Ma(a),build_stamp:ze(s.build_stamp),build_info:Oa(s.get_build_info),runtime_origin_descriptor:ze(s.runtime_origin_descriptor),hem_core_version:ze(s.metadata_hem_core_version),fhs_wrapper_version:ze(s.metadata_fhs_wrapper_version)}};return Wr.set(e,i),i}function Le(e,t={}){$t=_e.resolve(e),Ur=t.confineToWorkspace===!0}function Ra(){ja(),Ta();let e=globalThis;e.self||(e.self=globalThis),e.window||(e.window=globalThis),typeof e.addEventListener!="function"&&(e.addEventListener=()=>{}),typeof e.postMessage!="function"&&(e.postMessage=()=>{});let t=e.self;typeof t.addEventListener!="function"&&(t.addEventListener=()=>{}),typeof t.postMessage!="function"&&(t.postMessage=()=>{}),typeof e.Worker!="function"&&(e.Worker=class{addEventListener(){}postMessage(){}terminate(){}}),e.write_file=(n,r)=>{let a=He(n);try{return we.mkdirSync(_e.dirname(a),{recursive:!0}),we.writeFileSync(a,r),!0}catch(s){return console.error(`[FS Bridge] write_file failed for ${a}:`,s.message),!1}},e.read_file=n=>{let r=He(n);return we.readFileSync(r,"utf8")},e.file_exists=n=>{let r=He(n);return we.existsSync(r)},e.create_dir_all=n=>{let r=He(n);try{return we.mkdirSync(r,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${r}:`,a.message),!1}},e.list_dir=n=>{let r=He(n);try{return we.readdirSync(r)}catch{return[]}}}function He(e){let t=_e.isAbsolute(e)?_e.resolve(e):_e.resolve($t,e);if(Ur){let n=_e.relative($t,t);if(n===".."||n.startsWith(`..${_e.sep}`)||_e.isAbsolute(n))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function ja(){if(Jr)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},Jr=!0}var Vr=!1;function Ta(){if(Vr)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,n)=>{let r=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(r.startsWith("file:")&&r.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,n)}),Vr=!0}function Ma(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function ze(e){return typeof e!="function"?void 0:e()||void 0}function Oa(e){let t=ze(e);if(t)try{return JSON.parse(t)}catch{return t}}async function zr(e){let{workspace:t,csvContent:n,schemaJson:r,defaultsPath:a,deps:s}=e,i=jt(n);if(i)return{ok:!1,error:i};let o=await Rr({workspace:t,csvContent:n,explicitDefaultsPath:a}),m;try{m=await s.convertGeometryCsvToJson(n,r,o.defaultsJson)}catch(d){return{ok:!1,error:`WASM conversion failed: ${d.message}`,defaults_source:o.source,defaults_path:o.path}}if(!m||typeof m!="string")return{ok:!1,error:"WASM returned empty or invalid result",defaults_source:o.source,defaults_path:o.path};let u=Fa(m);return!u.ok||u.json===void 0||u.json===null?{ok:!1,validation:u.validation,error:u.error||"WASM conversion returned invalid result",defaults_source:o.source,defaults_path:o.path}:{ok:!0,json:u.json,validation:u.validation,defaults_source:o.source,defaults_path:o.path}}async function st(e){let{workspace:t,csvPath:n,outputPath:r,schemaPath:a,defaultsPath:s,repoRoot:i,deps:o}=e,m=K.isAbsolute(n)?n:K.join(t,n),u;try{u=await ve.readFile(m,"utf8")}catch(w){let S=w;throw S.code==="ENOENT"?new Error(`CSV file not found at ${m}`):new Error(`Failed to read CSV file: ${S.message}`)}let d=Be(u),f=jt(u,!!d);if(f)return{ok:!1,error:f};if(d){if(a||s)return{ok:!1,error:"Pinned target preparation uses its matching schema/defaults. Keep authored DefaultsPath in the CSV; custom schema/default overrides cannot replace bundle artifacts."};try{let w=await(o.runTarget??Ue)({workspace:t,operation:"prepare",csv:u,targetBundleId:d,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),S=r?K.resolve(t,r):qr(t,m);if(K.extname(S)!==".json")throw new Error("Prepared target output must have a .json extension");return await Gr(t,S),await Hr(t,K.join(t,"input/base_models",K.basename(S,".json")+".target.json"),JSON.stringify({targetBundleId:d,validation:w.validation,schema_omissions:w.schema_omissions,readiness:"wrapper_input"})),await Hr(t,S,JSON.stringify(w.model,null,2)),{ok:!0,json_path:K.relative(t,S),validation:w.validation,...w.schema_omissions?.length?{schema_omissions:w.schema_omissions}:{},schema_source:`target:${d}`,defaults_source:`target:${d}`}}catch(w){return{ok:!1,error:w.message}}}if(e.targetManifestPath||e.targetManifestSha256)return{ok:!1,error:"CSV has no TargetBundleId. Select and save an exact target before supplying its bundle."};let h=await Dr({repoRoot:i??nt(t),workspace:t,csvContent:u,explicitSchemaPath:a}),p=await zr({workspace:t,csvContent:u,schemaJson:h.schemaJson,defaultsPath:s,deps:o});if(!p.ok||p.json===void 0||p.json===null)return{ok:!1,validation:p.validation,error:p.error||"WASM conversion returned invalid result",defaults_source:p.defaults_source,schema_source:h.source};let C=r?K.isAbsolute(r)?r:K.join(t,r):qr(t,m);await ve.mkdir(K.dirname(C),{recursive:!0});try{await ve.writeFile(C,JSON.stringify(p.json,null,2),"utf8")}catch(w){let S=w;return{ok:!1,validation:p.validation,error:`Failed to write JSON file: ${S.message}`,defaults_source:p.defaults_source,schema_source:h.source}}return{ok:!0,json_path:K.relative(t,C),validation:p.validation,defaults_source:p.defaults_source,schema_source:h.source}}function Fa(e){try{return JSON.parse(e)}catch(t){return{ok:!1,error:`WASM returned invalid JSON: ${t.message}`}}}function qr(e,t){let n=K.basename(t,K.extname(t));return K.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function Gr(e,t){let n=await ve.realpath(e),r=K.relative(K.resolve(e),t);if(!r||r===".."||r.startsWith(`..${K.sep}`)||K.isAbsolute(r))throw new Error("Target preparation output must stay within the workspace");let a=K.join(n,r),s=n;for(let i of K.relative(n,K.dirname(a)).split(K.sep).filter(Boolean))if(s=K.join(s,i),await ve.mkdir(s).catch(o=>{if(o.code!=="EEXIST")throw o}),await ve.realpath(s)!==s)throw new Error("Target preparation output directory is a symlink");try{if(await ve.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(i){if(i.code!=="ENOENT")throw i}return a}async function Hr(e,t,n){let r=await Gr(e,t),a=await ve.open(r,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await ve.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return ve.open(r,"w")});try{await a.writeFile(n)}finally{await a.close()}}import pe from"fs/promises";import ie from"path";async function Bt(e,t={}){let{category:n}=t,r=ie.join(e,"input","batch_parameters"),a=await pe.readdir(r,{withFileTypes:!0}),s={};for(let i of a){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let m=ie.join(r,o),u=await pe.readdir(m),d=[];for(let f of u){if(!f.endsWith(".json"))continue;let h=f.replace(/\.json$/,""),p=ie.join(m,f);try{let C=await pe.readFile(p,"utf8"),w=JSON.parse(C);d.push({id:h,name:typeof w.name=="string"?w.name:h,description:typeof w.description=="string"?w.description:"",category:o})}catch(C){console.error(`Failed to parse ${p}: ${C.message}`)}}d.length>0&&(s[o]={category:o,parameters:d.sort((f,h)=>f.name.localeCompare(h.name))})}return{catalog:s,total_categories:Object.keys(s).length,total_parameters:Object.values(s).reduce((i,o)=>i+o.parameters.length,0)}}async function Lt(e,t){let{category:n,parameter_id:r}=t;if(!n)throw new Error("category is required");if(!r)throw new Error("parameter_id is required");let a=ie.join(e,"input","batch_parameters",n),s=ie.join(a,`${r}.json`),i=ie.join(a,`${r}.md`),o;try{let u=await pe.readFile(s,"utf8");o=JSON.parse(u)}catch(u){let d=u;throw d.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${d.message}`)}let m=null;try{m=await pe.readFile(i,"utf8")}catch(u){let d=u;d.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${d.message}`)}return{category:n,parameter_id:r,json:o,markdown:m,has_markdown:m!==null}}async function It(e,t,n){let{category:r,parameter_id:a,content:s,markdown_content:i}=t;if(!r)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(s==null||s==="")throw new Error("content is required");let o=$a(s),[m,u,d]=await Promise.all([Na(e),Ba(e),La(e,r)]),f=n.validateSnippetJs(r,JSON.stringify(o),JSON.stringify(m),JSON.stringify(u),d?JSON.stringify(d):null),h=JSON.parse(f);if(!h.ok){let S=(h.errors??[]).map(T=>typeof T=="string"?T:T.message||String(T));return{success:!1,valid:!1,errors:S,message:`Validation failed: ${S.join("; ")}`}}let p=ie.join(e,"input","batch_parameters",r);await pe.mkdir(p,{recursive:!0});let C=ie.join(p,`${a}.json`);await pe.writeFile(C,JSON.stringify(o,null,2),"utf8");let w=null;return i&&(w=ie.join(p,`${a}.md`),await pe.writeFile(w,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${r}'`,paths:{json:C,markdown:w}}}function $a(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}async function Na(e){let t=[ie.join(e,"input_core.schema.json"),ie.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),ie.join(e,"core-input.schema.json"),ie.join(e,"schemas","core-input.schema.json"),ie.join(e,"input.schema.json")];for(let n of t)try{return JSON.parse(await pe.readFile(n,"utf8"))}catch{}throw new Error(`Schema file not found. Tried: ${t.join(", ")}`)}async function Ba(e){let t=ie.join(e,"input","batch_parameters","base_json","demo_hp_annual.json");try{return JSON.parse(await pe.readFile(t,"utf8"))}catch(n){let r=n;throw new Error(`Baseline model not found at ${t}: ${r.message}`)}}async function La(e,t){if(t!=="simplified_fabric")return null;let n=[ie.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),ie.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let r of n)try{return JSON.parse(await pe.readFile(r,"utf8"))}catch{}return null}import Ut from"fs/promises";import ot from"path";import Fe from"fs/promises";import Oe from"path";async function Ie(e,t){let n=Oe.join(e,"output"),r=Yr(t.config_name),a=[],s=new Set,i=[],o=[];try{let m=Oe.join(n,r),u=await Dt(m);u&&await Kr(m,a,s);let d;try{d=JSON.parse(await Fe.readFile(Oe.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(S){if(S.code!=="ENOENT")throw S;if(!u)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let S of d===void 0?[]:Ze(r,d)){let T=Oe.join(n,S);if(!await Dt(T))continue;let F=S.slice(`result_${r}_`.length);try{await Kr(T,a,s,F)}catch(U){let J=await Fe.readFile(Oe.join(T,"target-run.json"),"utf8").then(JSON.parse,()=>{});J?.status==="failed"||J?.status==="cancelled"?i.push({name:F,...typeof J.jobId=="string"?{job_id:J.jobId}:{},error:typeof J.error=="string"?J.error:`The scenario's run is recorded as ${J.status}, with no reason.`}):J?.status==="running"?o.push(`Scenario ${F} has no results yet: its run${typeof J.jobId=="string"?` (job ${J.jobId})`:""} is recorded as running.`):o.push(`Failed to read result directory ${S}: ${U.message}`)}}a.sort((S,T)=>S.name.localeCompare(T.name));let f=d===void 0?void 0:await tt(e,r),h=f?.jobId;o.push(...f?.warnings??[]),h&&f?.error!==void 0&&!i.some(S=>S.job_id===h)&&o.push(`The app recorded run ${h} of batch config '${r}' as failed after these scenarios finished: ${f.error}`);let p=f===void 0?[]:a.filter(S=>S.job_id===void 0?!f.legacyCurrent:S.job_id!==h),C=h||f?.legacyCurrent?void 0:f?.changed??f?.unknown??(f?.error!==void 0?`The latest run of batch config '${r}' failed before it wrote any scenario: ${f.error}`:void 0),w=a.filter(S=>!p.includes(S));return{config_name:r,models:w,total_models:w.length,output_dir:n,...h?{latest_job_id:h}:{},...p.length?{earlier_run_models:p}:{},...C?{latest_run_unknown:C}:{},...i.length?{failed_models:i}:{},...o.length?{warnings:o}:{}}}catch(m){return{config_name:r,models:[],total_models:0,output_dir:n,error:`Failed to list models: ${m.message}`}}}async function Wt(e,t){let n=Yr(t.config_name),r=await Ie(e,{config_name:n}),a=r.models.find(d=>d.name===t.model_name)?.csv_path;if(!a)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,error:Jt(r,t.model_name)};let i=(await Fe.readFile(a,"utf8")).split(`
15
- `).filter(d=>d.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let o=Xr(i[0]??"").map(d=>d.trim()),m=Xr(i[1]??"").map(d=>d.trim()),u=[];for(let d=1;d<o.length;d+=1){let f=o[d],h=d<m.length?m[d]:"";f&&u.push({name:f,unit:h||"",index:d-1})}return{config_name:n,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:a}}function Jt(e,t){let n=e.earlier_run_models?.find(r=>r.name===t);if(n){let r=e.latest_job_id?`The config's latest run is job ${e.latest_job_id}. `:e.latest_run_unknown?`${e.latest_run_unknown} `:"";return`Model ${t} has results only from ${n.job_id?`job ${n.job_id}`:"the legacy engine"}, an earlier run. ${r}They do not reflect the latest inputs: re-run the config.`}return e.error??`No completed actual-dwelling CSV found for model ${t}`}var Vt={fileExists:Dt,readFile:e=>Fe.readFile(e,"utf8"),listFiles:e=>Fe.readdir(e)};async function Kr(e,t,n,r){let s=(await Er(Vt,e)).map(u=>typeof u=="string"?u:u.name),i=await Fe.readFile(Oe.join(e,"target-run.json"),"utf8").then(JSON.parse,()=>{}),o=typeof i?.jobId=="string"?i.jobId:void 0,m=(u,d)=>{n.has(u)||(n.add(u),t.push({name:u,csv_path:Oe.join(e,d),has_results:!0,...o?{job_id:o}:{}}))};if(r){let u=Et(s,"results");u&&m(r,u);return}for(let u of s){if(!Et([u],"results"))continue;let d=u.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);d?.[1]&&m(d[1],u)}}function Yr(e){return e.replace(/\.json$/,"")}async function Dt(e){try{return await Fe.access(e),!0}catch{return!1}}function Xr(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}var Ia=new Set(["sumif","averageif","countif"]),Zr=new Set([">=","<=",">","<","="]);async function qt(e,t,n){let{config_name:r,model_names:a,metric_definitions:s,time_range:i,tariff_file_path:o,tariff_column_index:m}=t;if(!r)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!s||!Array.isArray(s)||s.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=r.replace(/\.json$/,""),{encodedMetrics:d,metadata:f}=Ja(s);if(f.some(F=>F.function.toLowerCase()==="cost")&&(!o||m===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let p;if(o&&m!==void 0){let F=await Va(o,m,e);p=JSON.stringify(F)}let C=[],w=await Ie(e,{config_name:u}),S=[],T=[];for(let F of a){let U=w.models.find(B=>B.name===F)?.csv_path;if(!U){let B=w.earlier_run_models?.find(Q=>Q.name===F),X=w.failed_models?.find(Q=>Q.name===F);if(X)T.push({model_name:F,...X.job_id?{job_id:X.job_id}:{},error:X.error});else if(B)S.push({model_name:F,...B.job_id?{job_id:B.job_id}:{}});else throw new Error(Jt(w,F));continue}let J=await Ut.readFile(U,"utf8");try{let B=Da(J,F,r);if(f.some(re=>re.isCompliance)){let re=ot.join(ot.dirname(U),"fhs_compliance_report.json");if(!await Pr(Vt,re))throw new Error("Completed FHS compliance report is unavailable");let R=JSON.parse(await Ut.readFile(re,"utf8")),j=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let c of j){let l=R[c];B[c]=typeof l=="number"&&Number.isFinite(l)?l:null}for(let c of f.filter(l=>l.isCompliance)){let l=j.find(_=>_===c.column);if(!l||B[l]===null)throw new Error(`Completed FHS compliance rate '${c.column}' is unavailable`)}}if(B.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${F}`);if(Object.keys(B.columns).length===0)throw new Error(`No columns found in CSV for model ${F}`);let X=Ua(B,d,f);if(X.length>0){let re=Object.keys(B.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${X.join(", ")}. Available columns: ${re.join(", ")}...`)}let Q=n.calculateMetricsFromParsedData(JSON.stringify(B),JSON.stringify(d),i?JSON.stringify(i):void 0,p);if(!Q||typeof Q!="string")throw new Error(`WASM returned invalid result: ${typeof Q}`);let Ce=JSON.parse(Q);if(!Array.isArray(Ce))throw new Error(`WASM returned non-array result: ${typeof Ce}`);Ce.forEach((re,R)=>{let j=f[R],[c=re.name,l="sum"]=re.name.split("|");C.push({id:j?.id||re.name,name:j?.name||re.name,column:j?.column||c,function:j?.function||l,comparator:j?.comparator,threshold:j?.threshold,value:re.value,model_name:F})})}catch(B){let X=B;if(X.code==="ENOENT"){console.warn(`CSV file not found for model ${F}: ${U}`);continue}throw new Error(`Failed to process model ${F}: ${X.message}`)}}return{metrics:C,total_models:a.length-S.length-T.length,total_metrics:C.length,...S.length?{earlier_run_models:S}:{},...T.length?{failed_models:T}:{},...w.latest_run_unknown?{latest_run_unknown:w.latest_run_unknown}:{},...w.warnings?{warnings:w.warnings}:{}}}function Da(e,t,n){let r=e.split(`
16
- `).filter(d=>d.trim());if(r.length<2)throw new Error("CSV must have at least headers and units rows");let a=(r[0]??"").split(",").map(d=>d.trim()),s=(r[1]??"").split(",").map(d=>d.trim()),i=[],o={},m=[],u=[];for(let d=1;d<a.length;d+=1){let f=a[d];f&&(o[f]=[],m.push(f),u.push(d<s.length&&s[d]||""))}for(let d=2;d<r.length;d+=1){let f=(r[d]??"").split(",").map(C=>C.trim());if(f.length===0||f.length===1&&!f[0])continue;let h=f[0];if(!h)continue;let p=Number.parseInt(h,10);if(!(Number.isNaN(p)||p<0)){i.push(p);for(let C=1;C<a.length&&C<f.length;C+=1){let w=a[C];if(!w||!o[w])continue;let S=f[C];if(S===void 0)continue;let T=Number.parseFloat(S);o[w].push(Number.isNaN(T)?0:T)}}}return{timestamps:i,columns:o,column_order:m,column_units:u,metadata:{model_name:t,config_name:n.replace(/\.json$/,""),total_points:i.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function Wa(e){let t=(e.function||e.type||"sum").toString(),n=t.toLowerCase();if(n==="cost")return"cost";if(!Ia.has(n))return n;let r=e.comparator||">=";if(!Zr.has(r))throw new Error(`Invalid comparator "${r}" for ${t}. Use one of ${Array.from(Zr).join(", ")}`);if(e.threshold===void 0||e.threshold===null||Number.isNaN(Number(e.threshold)))throw new Error(`threshold is required for ${t} metrics`);return`${n}${r}${e.threshold}`}function Ja(e){let t=[],n=[];return e.forEach((r,a)=>{if(typeof r=="string"){let m=r.includes("|")?r:`${r}|sum`,[u=r,d="sum"]=m.split("|");t.push({name:m}),n.push({id:r,name:r,column:u,function:d,isCompliance:d.toLowerCase()==="compliance"});return}let s=r.column||(r.name?.includes("|")?r.name.split("|")[0]:r.name);if(!s)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(r)}`);let i=r.name?.includes("|")&&!r.function?r.name.split("|")[1]||"sum":Wa(r),o=`${s}|${i}`;t.push({name:o}),n.push({id:r.id||r.metric_id||`${s}_${i}`,name:r.name||r.id||s,column:s,function:i,comparator:r.comparator,threshold:r.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:n}}async function Va(e,t,n){let r=ot.isAbsolute(e)?e:ot.resolve(n,e),s=(await Ut.readFile(r,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${r}. Error: ${o.message}`)})).split(`
17
- `).filter(o=>o.trim());if(s.length===0)throw new Error(`Tariff file is empty: ${r}`);let i=[];for(let o=1;o<s.length;o+=1){let m=(s[o]??"").split(",").map(f=>f.trim().replace(/"/g,""));if(t>=m.length)throw new Error(`Column index ${t} not found in record ${o} with ${m.length} columns`);let u=m[t];if(u===void 0)throw new Error(`Column index ${t} is undefined in record ${o}`);let d=Number.parseFloat(u);if(Number.isNaN(d))throw new Error(`Could not parse '${u}' as number in row ${o+1}, column ${t+1}`);i.push(d)}if(i.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${i.length})`);return i}function Ua(e,t,n){let r=[];return t.forEach((a,s)=>{let i=a.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${a.name}`);n[s]?.isCompliance||e.columns[i]||r.push(i)}),r}import{spawn as qa}from"child_process";import it from"path";var zt=["vite-node","community/apps/cli/src/cli.ts"];async function Gt(e){let t=ct(e),n=e.failOn??"critical",r=it.resolve(e.csvPath),a=await Yt(e,"npx",[...zt,"check",r,"--json",`--fail-on=${n}`]),s=Zt(a),i=Ht(s)?s:void 0;return{ok:a.exitCode===0&&i!==void 0,command:"geometry validate",csv_path:r,repo_root:t,fail_on:n,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:i,counts:Ht(i?.counts)?i.counts:void 0,critical_issues:Array.isArray(i?.criticalIssues)?i.criticalIssues:void 0,warnings:Array.isArray(i?.warnings)?i.warnings:void 0,missing_elements:Array.isArray(i?.missingElements)?i.missingElements:void 0,error:i===void 0?Qt(a):void 0}}async function Kt(e){let t=ct(e),n=e.mode??"summary",r=it.resolve(e.csvPath),a=await Yt(e,"npx",[...zt,"thermal-bridges",r,Qr(n)]),s=n==="json"?Zt(a):void 0;return{ok:a.exitCode===0&&(n!=="json"||s!==void 0),command:"thermal-bridges auto",csv_path:r,repo_root:t,mode:n,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:s,proposal_count:Array.isArray(s)?s.length:void 0,error:n==="json"&&s===void 0?Qt(a):void 0}}async function Xt(e){let t=ct(e),n=e.mode??"summary",r=e.includeAuto===!0,a=it.resolve(e.csvPath),s=[...zt,"thermal-bridges",a,"--validate",...r?["--with-auto"]:[],Qr(n)],i=await Yt(e,"npx",s),o=n==="json"?Zt(i):void 0,m=Ht(o)?o:void 0;return{ok:i.exitCode===0&&(n!=="json"||m!==void 0),command:"thermal-bridges validate",csv_path:a,repo_root:t,include_auto:r,mode:n,exit_code:i.exitCode,signal:i.signal,stdout:i.stdout,stderr:i.stderr,parsed:m,issue_count:typeof m?.issueCount=="number"?m.issueCount:void 0,thermal_bridge_linear_rows:typeof m?.thermalBridgeLinearRows=="number"?m.thermalBridgeLinearRows:void 0,error:n==="json"&&m===void 0?Qt(i):void 0}}function ct(e){return it.resolve(e.repoRoot??nt(e.csvPath))}async function Yt(e,t,n){let r=ct(e);return(e.runner??Ha)(t,n,{cwd:r})}function Qr(e){return`--${e}`}function Zt(e){try{return JSON.parse(e.stdout)}catch{return}}function Qt(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ha=(e,t,n)=>new Promise((r,a)=>{let s=qa(e,[...t],{cwd:n.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",o="";s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),s.stdout.on("data",m=>{i+=m}),s.stderr.on("data",m=>{o+=m}),s.on("error",a),s.on("close",(m,u)=>{r({exitCode:m,signal:u,stdout:i,stderr:o})})});async function en(e,t={}){return Bt(e.workspace,t)}async function tn(e,t){return Lt(e.workspace,t)}import rn from"fs";import be from"path";import{fileURLToPath as za}from"url";var Ga=be.dirname(za(import.meta.url));function Ka(){let e=[],t=Ga;for(let s=0;s<6;s+=1){e.push(t);let i=be.dirname(t);if(i===t)break;t=i}e.push(process.cwd());let n=[];for(let s of e)n.push({directory:be.join(s,"wasm"),context:"helper-root"},{directory:be.join(s,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:be.join(s,"web","dist","wasm"),context:"rust-hem-runner"},{directory:be.join(s,"web","dist"),context:"rust-hem-runner"},{directory:be.join(s,"web","pkg"),context:"rust-hem-runner"},{directory:be.join(s,"apps","web","public","launch"),context:"vulcan-website"});let r=[],a=new Set;for(let s of n){let i=be.join(s.directory,"wasm_wrapper.js");if(a.has(i))continue;a.add(i),r.push(i);let o=be.join(s.directory,"wasm_wrapper_bg.wasm");if(rn.existsSync(i)&&rn.existsSync(o))return s}throw new Error(`WASM files not found. Tried:
12
+ -----END PUBLIC KEY-----`]);import{compactVerify as bn,importSPKI as Cn}from"jose";var Qt="EdDSA";async function ut(e,t){let n=e.trim();if(!n)throw new z("empty","Vulcan access token is empty.");let r=t.publicKeys??Zt,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),i=await Sn(n,r),o=En(i);if(o.iss!==He)throw new z("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${He}.`);if(o.aud!==ot)throw new z("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==ze)throw new z("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${ze}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new z("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>it)throw new z("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(s<o.iat-ct)throw new z("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let d=s>o.exp;if(d&&!t.allowExpired)throw new z("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:o,expired:d,expiresAt:new Date(o.exp*1e3),expiresInSeconds:o.exp-s}}async function Sn(e,t){for(let n of t)try{let r=await Cn(n,Qt),{payload:a}=await bn(e,r,{algorithms:[Qt]});return a}catch{}throw new z("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function En(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new z("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new z("malformed","Vulcan access token payload is not an object.");let n=t,r=We(n,"iss"),a=We(n,"aud"),s=We(n,"sub"),i=We(n,"org"),o=We(n,"jti"),d=lt(n,"iat"),u=lt(n,"exp"),m=lt(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new z("malformed","Vulcan access token must include a capabilities array.");let _=[];for(let h of n.capabilities){if(!st(h))throw new z("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(h)}.`);_.push(h)}if(_.length===0)throw new z("malformed","Vulcan access token grants no capabilities.");if(u<=d)throw new z("malformed","Vulcan access token expires no later than it was issued.");return{iss:r,aud:a,sub:s,org:i,jti:o,capabilities:Object.freeze(_),entitlement_schema_version:m,iat:d,exp:u}}function We(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new z("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function lt(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new z("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return n}var kn="mcp",xn=2880*60;async function er(e){let t=e;if(!t){let u=process.env.VULCAN_WORKSPACE;u?t=$e.join(u,"vulcan-mcp-config.json"):t=$e.join(process.cwd(),"vulcan-mcp-config.json")}t=$e.resolve(t);let n;try{n=await dt.readFile(t,"utf-8")}catch(u){let m=u;throw new Error(`Config file not found: ${t}. Please generate it from Vulcan \u2192 Integrations \u2192 MCP.`)}let r;try{r=JSON.parse(n)}catch(u){let m=u;throw new Error(`Invalid JSON in config file: ${m.message}`)}if(!r.workspace)throw new Error("Config file missing required field: workspace");if(!r.license_token||typeof r.license_token!="string")throw new Error('Your Vulcan MCP token is missing. Open Vulcan \u2192 Integrations \u2192 MCP and click "Generate config".');let a=$e.resolve($e.dirname(t),r.workspace);try{await dt.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}let s=$e.join(a,"input","batch_parameters");try{await dt.access(s)}catch{throw new Error(`Workspace missing required directory: ${s}. MCP only supports folder (FSA) workspaces backed by the real filesystem.`)}let{payload:i}=await mt(r.license_token),o=Math.floor(Date.now()/1e3),d=i.exp-o;if(d<xn){let u=Math.max(1,Math.round(d/3600));console.error(`[MCP Helper] Warning: your Vulcan access config expires in about ${u} hour(s). Open Vulcan -> Profile -> Integrations and click "Generate Config File" to avoid interruption.`)}return{workspace:a,license_token:r.license_token,configPath:t}}async function mt(e,t={}){try{let{claims:n}=await ut(e,{capability:kn,now:t.now,publicKeys:t.publicKeys});return{payload:n}}catch(n){throw new Error(An(n))}}function An(e){if(!(e instanceof z))return e instanceof Error?e.message:String(e);switch(e.code){case"missing_capability":return"This Vulcan access config does not include MCP. MCP requires a Vulcan Pro seat; open Vulcan -> Profile -> Integrations and generate a new config.";case"expired":return'Your Vulcan access config has expired. Open Vulcan -> Profile -> Integrations and click "Generate Config File" to continue.';case"unsupported_schema_version":return'This Vulcan access config was issued for a newer version of the Vulcan tools. Update the helper with "npm install -g @vulcan-energy/mcp-helper@latest".';case"lifetime_exceeded":return"This Vulcan access config declares a longer lifetime than Vulcan issues and was refused. Generate a new config.";case"clock_behind":return"This system clock is too far behind the access config issue time. Correct the clock, then restart the helper.";case"wrong_audience":case"wrong_issuer":return'This access config was not issued for local Vulcan tools. Open Vulcan -> Profile -> Integrations and click "Generate Config File".';default:return'Your Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and click "Generate Config File".'}}import{timingSafeEqual as Pn}from"crypto";function Rn(e){if(typeof e!="string")throw new Error("MCP request Bearer token is required");let t=/^Bearer[\t ]+([^\t ]+)$/i.exec(e.trim());if(!t?.[1])throw new Error("MCP request Bearer token is required");return t[1]}function jn(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Pn(n,r)}async function tr(e,t,n=mt){let r=Rn(e);if(!jn(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as y}from"zod";import Tn from"fs/promises";import Mn from"path";function rr(e,t={}){let n=[],r=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&n.push("Config must have at least one scenario");for(let[s,i]of Object.entries(e)){if(!i||typeof i!="object"){n.push(`Scenario '${s}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&n.push(`Scenario '${s}' must have exactly one base_json (found ${o.base_json.length})`):n.push(`Scenario '${s}' is missing required 'base_json' field (must be array)`);let d=!!(o.weather_file||o.weather_files),u=!!o.external_conditions;if(d){let m=o.weather_file||o.weather_files;Array.isArray(m)?m.length>1&&n.push(`Scenario '${s}' must have at most one weather_file (found ${m.length})`):n.push(`Scenario '${s}' weather_file/weather_files must be an array`)}u&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!d&&!u&&n.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),d&&u&&r.push(`Scenario '${s}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,_]of Object.entries(o))Array.isArray(_)||n.push(`Scenario '${s}': '${m}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function nr(e){try{if(!e||typeof e!="object")return null;let t=0;for(let n of Object.values(e)){if(!n||typeof n!="object")continue;let r=n,a=1;for(let s of Object.values(r))Array.isArray(s)&&(a*=s.length);t+=a}return t}catch{return null}}async function ar(e,t){let n=[],r=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:r};for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let i=s;for(let[o,d]of Object.entries(i))if(Array.isArray(d)&&!(o==="weather_file"||o==="weather_files"))for(let u of d){let m=Mn.join(e,"input","batch_parameters",o,`${String(u)}.json`);try{await Tn.access(m)}catch{r.push({scenario:a,category:o,parameter:String(u),path:m}),n.push(`Scenario '${a}': Parameter '${String(u)}' in category '${o}' not found at ${m}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as ea,readFile as Cr}from"fs/promises";import{join as Sr}from"path";import{fileURLToPath as ta}from"url";var On=vn(sr(),1),Fn=Object.defineProperty,$n=Object.getOwnPropertyNames,Nn=(e,t)=>function(){return e&&(t=(0,e[$n(e)[0]])(e=0)),t},Bn=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Ln={};Bn(Ln,{configureWasm:()=>In,getRuntimeApiUrl:()=>zn,getRuntimeWasmVariant:()=>Un,getVersionedWasmAssetPaths:()=>ht,getVersionedWasmJsUrl:()=>dr,getWasmAssetPaths:()=>ur,getWasmBaseUrl:()=>gt,getWasmBinaryUrl:()=>mr,getWasmJsUrl:()=>pr,getWasmRayonThreadCount:()=>ir,getWasmVariant:()=>lr,getWasmVersionInfo:()=>Ge,getWasmVersionJsonUrl:()=>cr,getWasmWasmUrl:()=>gr,initializeWasmRayonThreadPool:()=>Jn});function In(e={}){e.baseUrl&&(fr=Wn(e.baseUrl)),typeof e.preferHashed=="boolean"&&(_r=e.preferHashed)}function or(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Wn(e){return e.replace(/\/+$/,"")||"/"}function Dn(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Vn(){let e=or();if(e){if(Dn(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function gt(){return fr||Vn()}function ir(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Jn(e){let t=e,n=De.get(t);if(n)return n;let r=e.initialize_rayon_thread_pool;if(typeof r!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>r(ir())).then(()=>{});return De.set(t,a),a.catch(()=>{De.get(t)===a&&De.delete(t)}),a}function cr(){return`${gt()}/wasm_version.json`}async function Ge(){try{let e=await fetch(cr(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function lr(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function Un(){return lr(await Ge())}function qn(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function Hn(e){let t=qn(),r=!!((_r??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(r?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(r?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function ur(e){let t=gt(),n=e===void 0?await Ge():e,{jsFilename:r,wasmFilename:a}=Hn(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${a}`}}async function ht(){let e=await Ge(),{jsPath:t,wasmPath:n}=await ur(e),r=e?.build_id||e?.sha256||e?.timestamp;if(!r)return{jsPath:t,wasmPath:n,versionInfo:e};let a=`v=${encodeURIComponent(String(r))}`;return{jsPath:`${t}?${a}`,wasmPath:`${n}?${a}`,versionInfo:e}}async function dr(){let{jsPath:e}=await ht();return e}async function mr(){let{wasmPath:e}=await ht();return e}function zn(e){let t=or();return t?new URL(e,t.origin).toString():e}var De,fr,_r,pr,gr,hr=Nn({"src/wasmPath.ts"(){De=new WeakMap,pr=dr,gr=mr}});async function yr(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return null;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(r.files)||!r.files.length||r.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(r.files)}async function wr(e,t){let n=await yr(e,t),r=await e.listFiles(t,{withKind:!0});return n===null?r:r.filter(a=>n.has(typeof a=="string"?a:a.name))}async function vr(e,t){let n=t.lastIndexOf("/"),r=await yr(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}function yt(e){let t=new Map;for(let{run:i,startedAt:o,fileTime:d}of e){if(o!==void 0&&Number.isNaN(Date.parse(o)))throw new Error(`Run ${i} records an invalid start time: ${o}`);let u=t.get(i);t.set(i,{run:i,startedAt:u?.startedAt??o,fileTime:Math.max(u?.fileTime??d,d)})}let n=(i,o)=>{let d=`Runs ${i.run} and ${o.run} have the same time, so the helper cannot tell which run is newest. Run the config again.`;if(i.startedAt!==void 0&&o.startedAt!==void 0)return Date.parse(i.startedAt)-Date.parse(o.startedAt)||d;if(i.startedAt===void 0&&o.startedAt===void 0)return i.fileTime-o.fileTime||d;let[u,m]=i.startedAt===void 0?[o,i]:[i,o];return m.fileTime<Date.parse(u.startedAt)?u===i?1:-1:`The workspace holds a run recorded by an older version of Vulcan, which did not record when a run started (${m.run}). Its files are dated after run ${u.run} started, so they may have been copied, and the helper cannot tell which run is newest. Run the config again.`},r=[...t.values()],a=r.map(i=>r.filter(o=>o!==i).map(o=>n(i,o))),s=r.find((i,o)=>a[o].every(d=>typeof d=="number"&&d>0));return s||!r.length?s:{unknown:a.flat().find(i=>typeof i=="string")}}function wt(e,t){let n=e.map(r=>typeof r=="string"?r:r.name).filter(r=>r.endsWith(".csv")?t==="results_heat_source_wet"?r.includes("__results_heat_source_wet__"):t==="results_emitters"?r.includes("__results_emitters_"):r.endsWith(`__${t}.csv`):!1).sort((r,a)=>r.localeCompare(a));return n.find(r=>/(?:^|__)FHS__/.test(r))??n.find(r=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(r))}hr();function Gn(e){return e.startsWith("__")}function Ke(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!Gn(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function Kn(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function Xn(e){let t=Kn(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function Xe(e,t){let n=[];for(let r of Ke(t)){let a=Xn(r.value);for(let s=0;s<a;s+=1)n.push(`result_${e}_${r.name}_${s}`)}return n}function vt(e){return Math.floor(e/1e3)}function Yn(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function Zn(e){return e==="failure_context.json"}function br(e){return Yn(e)||Zn(e)}function Qn(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&pt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&pt(r))return r;let s=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(s&&pt(s))return s}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function pt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var os=Qn();hr();var Er;async function bt(e){return Er??=ra(),(await Er)(e)}async function ra(){for(let e of["./hem-target-runtime/csv-target.mjs","../hem-target-runtime/csv-target.mjs"]){let t=new URL(e,import.meta.url);try{await ea(ta(t))}catch{continue}return(await import(t.href)).csvTarget}throw new Error("The target CSV reader is not installed. Build the local target CLI assets or install a helper release including them.")}async function Ct(e,t){let n=new Set;for(let{value:r}of Ke(t))if(Array.isArray(r.base_json))for(let a of r.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");n.add(await na(e,a))}if(n.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...n][0]}async function na(e,t){try{return await bt(await Cr(Sr(e,"input/base_models",`${t}.csv`),"utf8"))}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await Cr(Sr(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof n.targetBundleId!="string"||!n.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return n.targetBundleId}catch(n){if(n.code==="ENOENT")return;throw n}}async function kr(e,t){if(Ke(t).some(({value:r})=>Array.isArray(r.heating_profiles)&&r.heating_profiles.length))return"Heating profiles require a saved, pinned HEM target batch; the legacy runner cannot apply post-FHS controls.";let n;try{n=await Ct(e,t)}catch(r){return r.message}if(n)return`This batch has no saved __hem snapshot. Its base models use HEM target '${n}' (a Geometry CSV with no TargetBundleId uses Rust a7). Create the batch again with vulcan_create_batch_config, or open it in Create Scenarios in the Vulcan app and save it. Either step saves its exact __hem source and snippet snapshot. The installed legacy runner cannot run it.`}import{fork as aa}from"child_process";import{resolve as sa}from"path";import{access as oa}from"fs/promises";import{fileURLToPath as St}from"url";var Ve=async e=>{let t=!!(e.targetManifestPath||e.targetManifestSha256);if(t&&(!e.targetManifestPath||!/^[a-f0-9]{64}$/.test(e.targetManifestSha256??"")))throw new Error("Supply both target_manifest and target_manifest_sha256 for an offline bundle, or neither to download the verified pinned target.");if(!t&&!e.targetBundleId)throw new Error("No HEM target identified. Save the source CSV with its TargetBundleId pin; installed legacy WASM cannot substitute it.");for(let n of["./hem-target-runtime/browser-adapter.mjs","../hem-target-runtime/browser-adapter.mjs"]){let r=new URL(n,import.meta.url);try{await oa(St(r))}catch{continue}let a=St(new URL("../../wasm/",r)),s=t?{...e,wasmDir:a,wasmRemedy:"Reinstall the package.",manifestPath:sa(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{...e,wasmDir:a,wasmRemedy:"Reinstall the package."};if(e.operation==="batch")return ia(St(r),s);let{runTargetBrowser:i}=await import(r.href);return i(s)}throw new Error("Target browser assets are not installed. Build the local target CLI assets or install a helper release including them.")};function ia(e,t){return new Promise((n,r)=>{let a=aa(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),s=setTimeout(()=>{a.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",i=>{clearTimeout(s),r(i)}),a.once("exit",i=>{clearTimeout(s),r(new Error(`Target batch stopped before startup (${i})`))}),a.once("message",i=>{clearTimeout(s),i.started?(a.unref(),n({status:"started"})):(a.kill(),r(new Error(i.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as ca}from"crypto";import ne from"fs/promises";import G from"path";async function kt(e,t,n={},r={}){let{config_name:a,base_model:s,weather_file:i,wrapper:o,parameters:d}=t;if(!a)throw new Error("config_name is required");if(!s)throw new Error("base_model is required");if(!d||typeof d!="object"||Array.isArray(d))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let u=la(d),m={base_json:[s],...o?{model_wrappers:[o]}:{},...u},_=await Ct(e,{scenario_1:m}),h=!!(t.targetManifestPath||t.targetManifestSha256||_);if(!i&&!h)throw new Error("weather_file is required");if(h&&(!/^[a-zA-Z0-9_. -]+$/.test(a)||a===".."))throw new Error("Invalid target config name");i&&(m.weather_files=[h&&!i.endsWith(".epw")?`${i}.epw`:i]);let p={scenario_1:m},S=rr(p,{requireWeather:!h});if(!S.valid)return{success:!1,valid:!1,errors:S.errors,warnings:S.warnings,message:`Config validation failed: ${S.errors.join("; ")}`};let x=nr(p);if(x===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let P=n.maxPermutations??500;if(!Number.isSafeInteger(P)||P<1)throw new Error("maxPermutations must be a positive integer");if(x>P)return{success:!1,valid:!1,errors:[`Total permutations (${x}) exceeds maximum of ${P}`],message:`Config would generate ${x} permutations, which exceeds the limit of ${P}`};let T=p;if(h){let B=await(r.runTarget??Ve)({workspace:e,operation:"snapshot",config:p,targetBundleId:_,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});T={...p,__hem:B}}else{let B=await ar(e,p);if(!B.valid)return{success:!1,valid:!1,errors:B.errors,missingFiles:B.missingFiles,message:`Some parameter files are missing: ${B.errors.slice(0,3).join("; ")}${B.errors.length>3?"...":""}`};let K=G.join(e,"input","batch_parameters","base_json",`${s}.json`);try{await ne.access(K)}catch{return{success:!1,valid:!1,errors:[`Base model '${s}' not found at ${K}`],message:`Base model file not found: ${s}`}}let Z=G.join(e,"input","batch_parameters","weather_files",i.endsWith(".epw")?i:`${i}.epw`);try{await ne.access(Z)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Z}`],message:`Weather file not found: ${i}`}}}let F=G.join(e,"input","batch_configs");if(h){let B=await ne.realpath(e);for(let K of["input","batch_configs"])if(B=G.join(B,K),await ne.mkdir(B).catch(Z=>{if(Z.code!=="EEXIST")throw Z}),await ne.realpath(B)!==B)throw new Error("Target config directory is a symlink")}else await ne.mkdir(F,{recursive:!0});let U=a.endsWith(".json")?a:`${a}.json`,V=G.join(F,U);try{return await ne.access(V),{success:!1,valid:!1,errors:[`Config file '${U}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await ne.writeFile(V,JSON.stringify(T,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:V,permutations:x,structure:p}}async function Ze(e,t,n){let{config_name:r,job_id:a}=t;if(!r)throw new Error("config_name is required");let s=a||n.generateJobId?.()||`mcp_${ca()}`,i=r.endsWith(".json")?r:`${r}.json`,o=G.join(e,"input","batch_configs",i),d;try{d=await ne.readFile(o,"utf8")}catch(h){let p=h;throw p.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${p.message}`)}let u=JSON.parse(d);if(u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let h=u.__hem;if(!h){let p="This batch names a HEM target but has no saved __hem source snapshot. Re-save the batch in the app (or create it with vulcan_create_batch_config).";return{job_id:s,status:"error",message:p,error:p}}try{return await(n.runTarget??Ve)({workspace:e,operation:"batch",config:u,targetBundleId:h.targetBundleId,configName:r.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:r,output_dir:G.join(e,"output"),message:"Exact target batch started. Read progress with vulcan_get_batch_status; runtime provenance is stored with outputs."}}catch(p){let S=p.message;return{job_id:s,status:"error",message:S,error:S}}}let m=await kr(e,u);if(m)return{job_id:s,status:"error",message:m,error:m};if(t.targetManifestPath||t.targetManifestSha256){let h="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:s,status:"error",message:h,error:h}}let _=G.join(e,"output");await ne.mkdir(_,{recursive:!0});try{let h=await n.processBatchConfig(d,e,_,r.replace(/\.json$/,""),s),p=JSON.parse(h);return p.error?{job_id:s,status:"error",message:`Batch execution failed: ${p.error}`,error:p.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:_}}catch(h){let p=h;return{job_id:s,status:"error",message:`Failed to start batch execution: ${p.message}`,error:p.message}}}async function xt(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,""),a=G.join(e,"output"),s;if(r&&!n){if(s=await Ye(e,r),!s.jobId){let F=s.error!==void 0?"error":s.unknown?"unknown":"not_run",U=s.error??s.unknown??s.changed??`Batch config '${r}' has no recorded run. A legacy engine run records its config only in its result folders: pass the job_id from vulcan_run_batch instead.`;return{config_name:r,status:F,progress:0,passes:0,failures:0,output_dir:a,error:U,...Pr(s.warnings)}}n=s.jobId}if(!n)throw new Error("Either job_id or config_name is required");if(/[\\/]/.test(n)||n==="."||n==="..")throw new Error(`Invalid job_id '${n}': a job id is a plain name, as vulcan_run_batch returns it`);let i=s?.warnings??[],o=G.join(a,`progress_${n}.json`),d=G.join(a,`sim_progress_${n}.json`),u=await Te(o,i),m=await Te(d,i),_=await jr(a,n,i);if(!s&&_.config){let F=await Ye(e,_.config);i.push(...F.warnings),F.jobId===n&&(s=F),r??=_.config}let h=_.records>0||typeof u?.targetBundleId=="string",p="queued",S=0,x=0,P=0,T=null;if(u?(Rr(u.status)?p=u.status:typeof u.percentage=="number"?(S=u.percentage,p=S>=100?"completed":"running"):typeof u.current_combination=="number"&&typeof u.total_combinations=="number"&&(S=Math.round(u.current_combination/u.total_combinations*100),p=S>=100?"completed":"running"),typeof u.percentage=="number"&&(S=u.percentage),typeof u.error=="string"&&(T=u.error,p="error")):_.records&&(_.stopped?(p="error",T=_.stopped):s?.expected!==void 0&&_.passes===s.expected?(p="completed",S=100):(p="unknown",T=`Job ${n} has finished ${_.passes} of ${s?.expected??"an unknown number of"} scenarios and recorded no failure. The app writes no progress file, so the helper cannot tell whether the run is still going or has stopped; check the app.`)),_.records&&({passes:x,failures:P}=_),s?.error!==void 0&&(T=s.error,p="error"),m&&!h&&(Rr(m.status)&&(p=m.status),typeof m.passes=="number"&&(x=m.passes),typeof m.failures=="number"&&(P=m.failures),typeof m.error=="string"&&(T=m.error,p="error")),!u&&!m&&!_.records){let F=G.join(a,n);try{let U=await ne.readdir(F);p=U.length>0?"completed":"queued",S=U.length>0?100:0}catch(U){throw U.code!=="ENOENT"?U:new Error(`Job ${n} does not exist in this workspace: ${a} holds no progress file, run record or folder for it.`)}}return{job_id:n,...r?{config_name:r}:{},status:p,progress:S,passes:x,failures:P,output_dir:a,error:T,batch_progress:u??null,sim_progress:h?null:m??null,...Pr(i)}}async function Ye(e,t){let n=G.join(e,"output"),r=[],a=[],s=async R=>(await ne.stat(R)).mtimeMs,i=R=>typeof R.startedAt=="string"?R.startedAt:void 0;for(let R of await ne.readdir(n).catch(Et)??[]){if(!R.startsWith("progress_")||!R.endsWith(".json"))continue;let j=await Te(G.join(n,R),r),c=R.slice(9,-5);j?.config_name===t&&a.push({run:c,jobId:c,startedAt:i(j),fileTime:await s(G.join(n,R))})}let o=G.join(e,"input","batch_configs",`${t}.json`),d=await Te(o,r),u=d?Xe(t,d):[],m,_=[];for(let R of u){let j=G.join(n,R),c=await ne.readdir(j,{withFileTypes:!0}).catch(Et);if(!c)continue;if(!c.some(f=>f.name==="target-run.json")){let f=c.filter(g=>g.isFile()&&br(g.name)).map(g=>G.join(j,g.name));if(!f.length)continue;m??=`Batch config '${t}' has results in output/${R} from the legacy engine, which does not record the job that wrote them. Pass the job_id from vulcan_run_batch.`,a.push({run:xr,fileTime:Math.max(...await Promise.all(f.map(s)))});continue}let l=R.slice(`result_${t}_`.length);for(let f of c.filter(g=>g.isDirectory()))for(let g of await ne.readdir(G.join(j,f.name),{withFileTypes:!0})){if(!g.isDirectory())continue;let w=G.join(j,f.name,g.name,"target-run.json"),M=r.length,b=await Te(w,r);if(!b){r.length>M&&_.push({warning:r.at(-1),fileTime:await s(w)});continue}b.name===l&&a.push({run:g.name,jobId:g.name,startedAt:i(b),fileTime:await s(w)})}}let h=G.join(n,`batch_status_${t}.json`),p=await Te(h,r),S=p?.status==="error"||p?.status==="running",x=S?i(p):void 0,P=x===void 0?void 0:a.find(R=>R.jobId&&R.startedAt===x)?.jobId;S&&!P&&a.push({run:Ar,startedAt:x,fileTime:await s(h)});let T=d?u.length:void 0,F=a.flatMap(R=>R.startedAt===void 0?[]:[Date.parse(R.startedAt)]),U=_.find(R=>!F.length||R.fileTime>=Math.max(...F));if(U)return{unknown:`The helper cannot read a run record of batch config '${t}', so it cannot tell which run is latest. ${U.warning}`,expected:T,warnings:r};if(!a.length)return{legacyCurrent:!0,expected:T,warnings:r};if(d&&vt(await s(o))>vt(Math.max(...a.map(R=>R.fileTime))))return{changed:`Batch config '${t}' was saved after its last run. Results from that run are earlier-run results. Run the config again.`,expected:T,warnings:r};let V=yt(a);if("unknown"in V)return{unknown:V.unknown,expected:T,warnings:r};if(V.run===xr)return{unknown:m,legacyCurrent:!0,expected:T,warnings:r};let B=p?.error_message,K=p?.status!=="error"?void 0:typeof B=="string"&&B?B:`The app recorded the run of batch config '${t}' as failed, with no reason.`;if(V.run!==Ar)return{jobId:V.run,...V.run===P?{error:K}:{},expected:T,warnings:r};if(p?.status==="running")return{unknown:`The app started a run of batch config '${t}' at ${x} and has written no scenario yet. It may still be preparing, or it stopped without recording why; check the app.`,expected:T,warnings:r};if(x!==void 0)return{error:K,expected:T,warnings:r};let Z=yt(a.filter(R=>R.jobId)),be=Z&&"run"in Z?Z.run:void 0;return{...be&&(await jr(n,be,r)).stopped?{jobId:be}:{},error:K,expected:T,warnings:r}}var xr="legacy engine results",Ar="the app's run status";async function jr(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let a of await ne.readdir(e,{withFileTypes:!0}).catch(Et)??[])if(!(!a.isDirectory()||!a.name.startsWith("result_")))for(let s of await ne.readdir(G.join(e,a.name),{withFileTypes:!0})){if(!s.isDirectory())continue;let i=await Te(G.join(e,a.name,s.name,t,"target-run.json"),n);if(!i)continue;r.records+=1;let o=`_${String(i.name)}`;a.name.endsWith(o)&&(r.config??=a.name.slice(7,-o.length)),i.status==="complete"?r.passes+=1:i.status==="failed"&&(r.failures+=1),(i.status==="failed"||i.status==="cancelled")&&(r.stopped??=`Scenario ${String(i.name)} ${i.status}${typeof i.error=="string"?`: ${i.error}`:""}`)}return r}async function Te(e,t){let n;try{n=await ne.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}try{return JSON.parse(n)}catch(r){t.push(`Skipped ${e}: ${r.message}`);return}}function Et(e){if(e.code!=="ENOENT")throw e}function Pr(e){return e.length?{warnings:e}:{}}function la(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function Rr(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Bs from"crypto";import Ae from"fs/promises";import te from"path";import Je from"fs";import xe from"path";import{fileURLToPath as ua}from"url";function Tr(e=process.cwd()){let t=xe.resolve(e);for(Je.existsSync(t)&&Je.statSync(t).isFile()&&(t=xe.dirname(t));;){if(Je.existsSync(xe.join(t,"package.json"))&&Je.existsSync(xe.join(t,"hem-batch-core"))&&Je.existsSync(xe.join(t,"web")))return t;let r=xe.dirname(t);if(r===t)break;t=r}let n=xe.dirname(ua(import.meta.url));return xe.resolve(n,"..","..","..")}import we from"fs";import _e from"path";import{pathToFileURL as da}from"url";var Mr=new Map,Or=!1,At=process.cwd(),$r=!1;async function Pt(e){let t=Mr.get(e);if(t)return t;ma();let n=_e.join(e,"wasm_wrapper.js"),r=_e.join(e,"wasm_wrapper_bg.wasm"),a=_e.join(e,"wasm_version.json");if(!we.existsSync(n)||!we.existsSync(r))throw new Error(`Browser WASM artifact not found in ${e}`);let s=await import(da(n).href);if(typeof s.initSync!="function")throw new Error("WASM module is missing initSync");if(s.initSync({module:we.readFileSync(r)}),s.setup_panic_hook?.(),typeof s.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let i={convertGeometryCsvToJson:s.convert_geometry_csv_to_json.bind(s),validateSnippetJs:s.validate_snippet_js?.bind(s),processBatchConfig:s.process_batch_config?.bind(s),calculateMetricsFromParsedData:s.calculate_metrics_from_parsed_data?.bind(s),setWorkspace:Qe,metadata:{source:n,wasm_path:r,wasm_version:pa(a),build_stamp:qe(s.build_stamp),build_info:ga(s.get_build_info),runtime_origin_descriptor:qe(s.runtime_origin_descriptor),hem_core_version:qe(s.metadata_hem_core_version),fhs_wrapper_version:qe(s.metadata_fhs_wrapper_version)}};return Mr.set(e,i),i}function Qe(e,t={}){At=_e.resolve(e),$r=t.confineToWorkspace===!0}function ma(){fa(),_a();let e=globalThis;e.self||(e.self=globalThis),e.window||(e.window=globalThis),typeof e.addEventListener!="function"&&(e.addEventListener=()=>{}),typeof e.postMessage!="function"&&(e.postMessage=()=>{});let t=e.self;typeof t.addEventListener!="function"&&(t.addEventListener=()=>{}),typeof t.postMessage!="function"&&(t.postMessage=()=>{}),typeof e.Worker!="function"&&(e.Worker=class{addEventListener(){}postMessage(){}terminate(){}}),e.write_file=(n,r)=>{let a=Ue(n);try{return we.mkdirSync(_e.dirname(a),{recursive:!0}),we.writeFileSync(a,r),!0}catch(s){return console.error(`[FS Bridge] write_file failed for ${a}:`,s.message),!1}},e.read_file=n=>{let r=Ue(n);return we.readFileSync(r,"utf8")},e.file_exists=n=>{let r=Ue(n);return we.existsSync(r)},e.create_dir_all=n=>{let r=Ue(n);try{return we.mkdirSync(r,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${r}:`,a.message),!1}},e.list_dir=n=>{let r=Ue(n);try{return we.readdirSync(r)}catch{return[]}}}function Ue(e){let t=_e.isAbsolute(e)?_e.resolve(e):_e.resolve(At,e);if($r){let n=_e.relative(At,t);if(n===".."||n.startsWith(`..${_e.sep}`)||_e.isAbsolute(n))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function fa(){if(Or)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},Or=!0}var Fr=!1;function _a(){if(Fr)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,n)=>{let r=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(r.startsWith("file:")&&r.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,n)}),Fr=!0}function pa(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function qe(e){return typeof e!="function"?void 0:e()||void 0}function ga(e){let t=qe(e);if(t)try{return JSON.parse(t)}catch{return t}}var Rt="The schema and defaults arguments were removed. The CSV's TargetBundleId row decides the schema; a CSV with no TargetBundleId row uses Rust HEM:FHS 1.0.0a7. The defaults are the target's own. A DefaultsPath row in the CSV must hold the same defaults.";async function jt(e){let{workspace:t,csvPath:n,outputPath:r}=e,a=te.isAbsolute(n)?n:te.join(t,n),s;try{s=await Ae.readFile(a,"utf8")}catch(o){let d=o;throw d.code==="ENOENT"?new Error(`CSV file not found at ${a}`):new Error(`Failed to read CSV file: ${d.message}`)}let i=await bt(s);try{let o=await(e.runTarget??Ve)({workspace:t,operation:"prepare",csv:s,targetBundleId:i,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),d=r?te.resolve(t,r):ha(t,a);if(te.extname(d)!==".json")throw new Error("Prepared target output must have a .json extension");return await Br(t,d),await Nr(t,te.join(t,"input/base_models",te.basename(d,".json")+".target.json"),JSON.stringify({targetBundleId:i,validation:o.validation,schema_omissions:o.schema_omissions,readiness:"wrapper_input"})),await Nr(t,d,JSON.stringify(o.model,null,2)),{ok:!0,json_path:te.relative(t,d),validation:o.validation,...o.schema_omissions?.length?{schema_omissions:o.schema_omissions}:{},schema_source:`target:${i}`,defaults_source:`target:${i}`}}catch(o){return{ok:!1,error:o.message}}}function ha(e,t){let n=te.basename(t,te.extname(t));return te.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function Br(e,t){let n=await Ae.realpath(e),r=te.relative(te.resolve(e),t);if(!r||r===".."||r.startsWith(`..${te.sep}`)||te.isAbsolute(r))throw new Error("Target preparation output must stay within the workspace");let a=te.join(n,r),s=n;for(let i of te.relative(n,te.dirname(a)).split(te.sep).filter(Boolean))if(s=te.join(s,i),await Ae.mkdir(s).catch(o=>{if(o.code!=="EEXIST")throw o}),await Ae.realpath(s)!==s)throw new Error("Target preparation output directory is a symlink");try{if(await Ae.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(i){if(i.code!=="ENOENT")throw i}return a}async function Nr(e,t,n){let r=await Br(e,t),a=await Ae.open(r,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await Ae.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return Ae.open(r,"w")});try{await a.writeFile(n)}finally{await a.close()}}import pe from"fs/promises";import ie from"path";async function Tt(e,t={}){let{category:n}=t,r=ie.join(e,"input","batch_parameters"),a=await pe.readdir(r,{withFileTypes:!0}),s={};for(let i of a){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let d=ie.join(r,o),u=await pe.readdir(d),m=[];for(let _ of u){if(!_.endsWith(".json"))continue;let h=_.replace(/\.json$/,""),p=ie.join(d,_);try{let S=await pe.readFile(p,"utf8"),x=JSON.parse(S);m.push({id:h,name:typeof x.name=="string"?x.name:h,description:typeof x.description=="string"?x.description:"",category:o})}catch(S){console.error(`Failed to parse ${p}: ${S.message}`)}}m.length>0&&(s[o]={category:o,parameters:m.sort((_,h)=>_.name.localeCompare(h.name))})}return{catalog:s,total_categories:Object.keys(s).length,total_parameters:Object.values(s).reduce((i,o)=>i+o.parameters.length,0)}}async function Mt(e,t){let{category:n,parameter_id:r}=t;if(!n)throw new Error("category is required");if(!r)throw new Error("parameter_id is required");let a=ie.join(e,"input","batch_parameters",n),s=ie.join(a,`${r}.json`),i=ie.join(a,`${r}.md`),o;try{let u=await pe.readFile(s,"utf8");o=JSON.parse(u)}catch(u){let m=u;throw m.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let d=null;try{d=await pe.readFile(i,"utf8")}catch(u){let m=u;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:n,parameter_id:r,json:o,markdown:d,has_markdown:d!==null}}async function Ot(e,t,n){let{category:r,parameter_id:a,content:s,markdown_content:i}=t;if(!r)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(s==null||s==="")throw new Error("content is required");let o=ya(s),[d,u,m]=await Promise.all([wa(e),va(e),ba(e,r)]),_=n.validateSnippetJs(r,JSON.stringify(o),JSON.stringify(d),JSON.stringify(u),m?JSON.stringify(m):null),h=JSON.parse(_);if(!h.ok){let P=(h.errors??[]).map(T=>typeof T=="string"?T:T.message||String(T));return{success:!1,valid:!1,errors:P,message:`Validation failed: ${P.join("; ")}`}}let p=ie.join(e,"input","batch_parameters",r);await pe.mkdir(p,{recursive:!0});let S=ie.join(p,`${a}.json`);await pe.writeFile(S,JSON.stringify(o,null,2),"utf8");let x=null;return i&&(x=ie.join(p,`${a}.md`),await pe.writeFile(x,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${r}'`,paths:{json:S,markdown:x}}}function ya(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}async function wa(e){let t=[ie.join(e,"input_core.schema.json"),ie.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),ie.join(e,"core-input.schema.json"),ie.join(e,"schemas","core-input.schema.json"),ie.join(e,"input.schema.json")];for(let n of t)try{return JSON.parse(await pe.readFile(n,"utf8"))}catch{}throw new Error(`Schema file not found. Tried: ${t.join(", ")}`)}async function va(e){let t=ie.join(e,"input","batch_parameters","base_json","demo_hp_annual.json");try{return JSON.parse(await pe.readFile(t,"utf8"))}catch(n){let r=n;throw new Error(`Baseline model not found at ${t}: ${r.message}`)}}async function ba(e,t){if(t!=="simplified_fabric")return null;let n=[ie.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),ie.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let r of n)try{return JSON.parse(await pe.readFile(r,"utf8"))}catch{}return null}import Lt from"fs/promises";import et from"path";import Oe from"fs/promises";import Me from"path";async function Ne(e,t){let n=Me.join(e,"output"),r=Wr(t.config_name),a=[],s=new Set,i=[],o=[];try{let d=Me.join(n,r),u=await Ft(d);u&&await Lr(d,a,s);let m;try{m=JSON.parse(await Oe.readFile(Me.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(P){if(P.code!=="ENOENT")throw P;if(!u)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let P of m===void 0?[]:Xe(r,m)){let T=Me.join(n,P);if(!await Ft(T))continue;let F=P.slice(`result_${r}_`.length);try{await Lr(T,a,s,F)}catch(U){let V=await Oe.readFile(Me.join(T,"target-run.json"),"utf8").then(JSON.parse,()=>{});V?.status==="failed"||V?.status==="cancelled"?i.push({name:F,...typeof V.jobId=="string"?{job_id:V.jobId}:{},error:typeof V.error=="string"?V.error:`The scenario's run is recorded as ${V.status}, with no reason.`}):V?.status==="running"?o.push(`Scenario ${F} has no results yet: its run${typeof V.jobId=="string"?` (job ${V.jobId})`:""} is recorded as running.`):o.push(`Failed to read result directory ${P}: ${U.message}`)}}a.sort((P,T)=>P.name.localeCompare(T.name));let _=m===void 0?void 0:await Ye(e,r),h=_?.jobId;o.push(..._?.warnings??[]),h&&_?.error!==void 0&&!i.some(P=>P.job_id===h)&&o.push(`The app recorded run ${h} of batch config '${r}' as failed after these scenarios finished: ${_.error}`);let p=_===void 0?[]:a.filter(P=>P.job_id===void 0?!_.legacyCurrent:P.job_id!==h),S=h||_?.legacyCurrent?void 0:_?.changed??_?.unknown??(_?.error!==void 0?`The latest run of batch config '${r}' failed before it wrote any scenario: ${_.error}`:void 0),x=a.filter(P=>!p.includes(P));return{config_name:r,models:x,total_models:x.length,output_dir:n,...h?{latest_job_id:h}:{},...p.length?{earlier_run_models:p}:{},...S?{latest_run_unknown:S}:{},...i.length?{failed_models:i}:{},...o.length?{warnings:o}:{}}}catch(d){return{config_name:r,models:[],total_models:0,output_dir:n,error:`Failed to list models: ${d.message}`}}}async function $t(e,t){let n=Wr(t.config_name),r=await Ne(e,{config_name:n}),a=r.models.find(m=>m.name===t.model_name)?.csv_path;if(!a)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,error:Nt(r,t.model_name)};let i=(await Oe.readFile(a,"utf8")).split(`
13
+ `).filter(m=>m.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let o=Ir(i[0]??"").map(m=>m.trim()),d=Ir(i[1]??"").map(m=>m.trim()),u=[];for(let m=1;m<o.length;m+=1){let _=o[m],h=m<d.length?d[m]:"";_&&u.push({name:_,unit:h||"",index:m-1})}return{config_name:n,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:a}}function Nt(e,t){let n=e.earlier_run_models?.find(r=>r.name===t);if(n){let r=e.latest_job_id?`The config's latest run is job ${e.latest_job_id}. `:e.latest_run_unknown?`${e.latest_run_unknown} `:"";return`Model ${t} has results only from ${n.job_id?`job ${n.job_id}`:"the legacy engine"}, an earlier run. ${r}They do not reflect the latest inputs: re-run the config.`}return e.error??`No completed actual-dwelling CSV found for model ${t}`}var Bt={fileExists:Ft,readFile:e=>Oe.readFile(e,"utf8"),listFiles:e=>Oe.readdir(e)};async function Lr(e,t,n,r){let s=(await wr(Bt,e)).map(u=>typeof u=="string"?u:u.name),i=await Oe.readFile(Me.join(e,"target-run.json"),"utf8").then(JSON.parse,()=>{}),o=typeof i?.jobId=="string"?i.jobId:void 0,d=(u,m)=>{n.has(u)||(n.add(u),t.push({name:u,csv_path:Me.join(e,m),has_results:!0,...o?{job_id:o}:{}}))};if(r){let u=wt(s,"results");u&&d(r,u);return}for(let u of s){if(!wt([u],"results"))continue;let m=u.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);m?.[1]&&d(m[1],u)}}function Wr(e){return e.replace(/\.json$/,"")}async function Ft(e){try{return await Oe.access(e),!0}catch{return!1}}function Ir(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}var Ca=new Set(["sumif","averageif","countif"]),Dr=new Set([">=","<=",">","<","="]);async function It(e,t,n){let{config_name:r,model_names:a,metric_definitions:s,time_range:i,tariff_file_path:o,tariff_column_index:d}=t;if(!r)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!s||!Array.isArray(s)||s.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=r.replace(/\.json$/,""),{encodedMetrics:m,metadata:_}=ka(s);if(_.some(F=>F.function.toLowerCase()==="cost")&&(!o||d===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let p;if(o&&d!==void 0){let F=await xa(o,d,e);p=JSON.stringify(F)}let S=[],x=await Ne(e,{config_name:u}),P=[],T=[];for(let F of a){let U=x.models.find(B=>B.name===F)?.csv_path;if(!U){let B=x.earlier_run_models?.find(Z=>Z.name===F),K=x.failed_models?.find(Z=>Z.name===F);if(K)T.push({model_name:F,...K.job_id?{job_id:K.job_id}:{},error:K.error});else if(B)P.push({model_name:F,...B.job_id?{job_id:B.job_id}:{}});else throw new Error(Nt(x,F));continue}let V=await Lt.readFile(U,"utf8");try{let B=Sa(V,F,r);if(_.some(re=>re.isCompliance)){let re=et.join(et.dirname(U),"fhs_compliance_report.json");if(!await vr(Bt,re))throw new Error("Completed FHS compliance report is unavailable");let R=JSON.parse(await Lt.readFile(re,"utf8")),j=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let c of j){let l=R[c];B[c]=typeof l=="number"&&Number.isFinite(l)?l:null}for(let c of _.filter(l=>l.isCompliance)){let l=j.find(f=>f===c.column);if(!l||B[l]===null)throw new Error(`Completed FHS compliance rate '${c.column}' is unavailable`)}}if(B.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${F}`);if(Object.keys(B.columns).length===0)throw new Error(`No columns found in CSV for model ${F}`);let K=Aa(B,m,_);if(K.length>0){let re=Object.keys(B.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${K.join(", ")}. Available columns: ${re.join(", ")}...`)}let Z=n.calculateMetricsFromParsedData(JSON.stringify(B),JSON.stringify(m),i?JSON.stringify(i):void 0,p);if(!Z||typeof Z!="string")throw new Error(`WASM returned invalid result: ${typeof Z}`);let be=JSON.parse(Z);if(!Array.isArray(be))throw new Error(`WASM returned non-array result: ${typeof be}`);be.forEach((re,R)=>{let j=_[R],[c=re.name,l="sum"]=re.name.split("|");S.push({id:j?.id||re.name,name:j?.name||re.name,column:j?.column||c,function:j?.function||l,comparator:j?.comparator,threshold:j?.threshold,value:re.value,model_name:F})})}catch(B){let K=B;if(K.code==="ENOENT"){console.warn(`CSV file not found for model ${F}: ${U}`);continue}throw new Error(`Failed to process model ${F}: ${K.message}`)}}return{metrics:S,total_models:a.length-P.length-T.length,total_metrics:S.length,...P.length?{earlier_run_models:P}:{},...T.length?{failed_models:T}:{},...x.latest_run_unknown?{latest_run_unknown:x.latest_run_unknown}:{},...x.warnings?{warnings:x.warnings}:{}}}function Sa(e,t,n){let r=e.split(`
14
+ `).filter(m=>m.trim());if(r.length<2)throw new Error("CSV must have at least headers and units rows");let a=(r[0]??"").split(",").map(m=>m.trim()),s=(r[1]??"").split(",").map(m=>m.trim()),i=[],o={},d=[],u=[];for(let m=1;m<a.length;m+=1){let _=a[m];_&&(o[_]=[],d.push(_),u.push(m<s.length&&s[m]||""))}for(let m=2;m<r.length;m+=1){let _=(r[m]??"").split(",").map(S=>S.trim());if(_.length===0||_.length===1&&!_[0])continue;let h=_[0];if(!h)continue;let p=Number.parseInt(h,10);if(!(Number.isNaN(p)||p<0)){i.push(p);for(let S=1;S<a.length&&S<_.length;S+=1){let x=a[S];if(!x||!o[x])continue;let P=_[S];if(P===void 0)continue;let T=Number.parseFloat(P);o[x].push(Number.isNaN(T)?0:T)}}}return{timestamps:i,columns:o,column_order:d,column_units:u,metadata:{model_name:t,config_name:n.replace(/\.json$/,""),total_points:i.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function Ea(e){let t=(e.function||e.type||"sum").toString(),n=t.toLowerCase();if(n==="cost")return"cost";if(!Ca.has(n))return n;let r=e.comparator||">=";if(!Dr.has(r))throw new Error(`Invalid comparator "${r}" for ${t}. Use one of ${Array.from(Dr).join(", ")}`);if(e.threshold===void 0||e.threshold===null||Number.isNaN(Number(e.threshold)))throw new Error(`threshold is required for ${t} metrics`);return`${n}${r}${e.threshold}`}function ka(e){let t=[],n=[];return e.forEach((r,a)=>{if(typeof r=="string"){let d=r.includes("|")?r:`${r}|sum`,[u=r,m="sum"]=d.split("|");t.push({name:d}),n.push({id:r,name:r,column:u,function:m,isCompliance:m.toLowerCase()==="compliance"});return}let s=r.column||(r.name?.includes("|")?r.name.split("|")[0]:r.name);if(!s)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(r)}`);let i=r.name?.includes("|")&&!r.function?r.name.split("|")[1]||"sum":Ea(r),o=`${s}|${i}`;t.push({name:o}),n.push({id:r.id||r.metric_id||`${s}_${i}`,name:r.name||r.id||s,column:s,function:i,comparator:r.comparator,threshold:r.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:n}}async function xa(e,t,n){let r=et.isAbsolute(e)?e:et.resolve(n,e),s=(await Lt.readFile(r,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${r}. Error: ${o.message}`)})).split(`
15
+ `).filter(o=>o.trim());if(s.length===0)throw new Error(`Tariff file is empty: ${r}`);let i=[];for(let o=1;o<s.length;o+=1){let d=(s[o]??"").split(",").map(_=>_.trim().replace(/"/g,""));if(t>=d.length)throw new Error(`Column index ${t} not found in record ${o} with ${d.length} columns`);let u=d[t];if(u===void 0)throw new Error(`Column index ${t} is undefined in record ${o}`);let m=Number.parseFloat(u);if(Number.isNaN(m))throw new Error(`Could not parse '${u}' as number in row ${o+1}, column ${t+1}`);i.push(m)}if(i.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${i.length})`);return i}function Aa(e,t,n){let r=[];return t.forEach((a,s)=>{let i=a.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${a.name}`);n[s]?.isCompliance||e.columns[i]||r.push(i)}),r}import{spawn as Pa}from"child_process";import tt from"path";var Dt=["vite-node","community/apps/cli/src/cli.ts"];async function Vt(e){let t=rt(e),n=e.failOn??"critical",r=tt.resolve(e.csvPath),a=await qt(e,"npx",[...Dt,"check",r,"--json",`--fail-on=${n}`]),s=Ht(a),i=Wt(s)?s:void 0;return{ok:a.exitCode===0&&i!==void 0,command:"geometry validate",csv_path:r,repo_root:t,fail_on:n,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:i,counts:Wt(i?.counts)?i.counts:void 0,critical_issues:Array.isArray(i?.criticalIssues)?i.criticalIssues:void 0,warnings:Array.isArray(i?.warnings)?i.warnings:void 0,missing_elements:Array.isArray(i?.missingElements)?i.missingElements:void 0,error:i===void 0?zt(a):void 0}}async function Jt(e){let t=rt(e),n=e.mode??"summary",r=tt.resolve(e.csvPath),a=await qt(e,"npx",[...Dt,"thermal-bridges",r,Vr(n)]),s=n==="json"?Ht(a):void 0;return{ok:a.exitCode===0&&(n!=="json"||s!==void 0),command:"thermal-bridges auto",csv_path:r,repo_root:t,mode:n,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:s,proposal_count:Array.isArray(s)?s.length:void 0,error:n==="json"&&s===void 0?zt(a):void 0}}async function Ut(e){let t=rt(e),n=e.mode??"summary",r=e.includeAuto===!0,a=tt.resolve(e.csvPath),s=[...Dt,"thermal-bridges",a,"--validate",...r?["--with-auto"]:[],Vr(n)],i=await qt(e,"npx",s),o=n==="json"?Ht(i):void 0,d=Wt(o)?o:void 0;return{ok:i.exitCode===0&&(n!=="json"||d!==void 0),command:"thermal-bridges validate",csv_path:a,repo_root:t,include_auto:r,mode:n,exit_code:i.exitCode,signal:i.signal,stdout:i.stdout,stderr:i.stderr,parsed:d,issue_count:typeof d?.issueCount=="number"?d.issueCount:void 0,thermal_bridge_linear_rows:typeof d?.thermalBridgeLinearRows=="number"?d.thermalBridgeLinearRows:void 0,error:n==="json"&&d===void 0?zt(i):void 0}}function rt(e){return tt.resolve(e.repoRoot??Tr(e.csvPath))}async function qt(e,t,n){let r=rt(e);return(e.runner??Ra)(t,n,{cwd:r})}function Vr(e){return`--${e}`}function Ht(e){try{return JSON.parse(e.stdout)}catch{return}}function zt(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ra=(e,t,n)=>new Promise((r,a)=>{let s=Pa(e,[...t],{cwd:n.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",o="";s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),s.stdout.on("data",d=>{i+=d}),s.stderr.on("data",d=>{o+=d}),s.on("error",a),s.on("close",(d,u)=>{r({exitCode:d,signal:u,stdout:i,stderr:o})})});async function Jr(e,t={}){return Tt(e.workspace,t)}async function Ur(e,t){return Mt(e.workspace,t)}import qr from"fs";import ve from"path";import{fileURLToPath as ja}from"url";var Ta=ve.dirname(ja(import.meta.url));function Ma(){let e=[],t=Ta;for(let s=0;s<6;s+=1){e.push(t);let i=ve.dirname(t);if(i===t)break;t=i}e.push(process.cwd());let n=[];for(let s of e)n.push({directory:ve.join(s,"wasm"),context:"helper-root"},{directory:ve.join(s,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:ve.join(s,"web","dist","wasm"),context:"rust-hem-runner"},{directory:ve.join(s,"web","dist"),context:"rust-hem-runner"},{directory:ve.join(s,"web","pkg"),context:"rust-hem-runner"},{directory:ve.join(s,"apps","web","public","launch"),context:"vulcan-website"});let r=[],a=new Set;for(let s of n){let i=ve.join(s.directory,"wasm_wrapper.js");if(a.has(i))continue;a.add(i),r.push(i);let o=ve.join(s.directory,"wasm_wrapper_bg.wasm");if(qr.existsSync(i)&&qr.existsSync(o))return s}throw new Error(`WASM files not found. Tried:
18
16
  `+r.map(s=>` - ${s}`).join(`
19
17
  `)+`
20
- Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var lt=null;async function Ae(){if(lt)return lt;try{let{directory:e,context:t}=Ka();return console.error(`[WASM] Loading from ${t}: ${e}`),lt=await Nt(e),console.error(`[WASM] Initialized successfully from ${t}`),lt}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function nn(e,t){let n;try{n=await Ae()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return It(e.workspace,t,{validateSnippetJs:n.validateSnippetJs})}async function an(e,t){return Ot(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import{randomUUID as Xa}from"crypto";import Ya from"fs/promises";import Za from"path";async function sn(e,t){let{workspace:n}=e,{config_name:r}=t;if(!r)throw new Error("config_name is required");let a=t.job_id||`mcp_${Xa()}`,s=Za.join(n,"input","batch_configs",r.endsWith(".json")?r:`${r}.json`),i=await Ya.readFile(s,"utf8").then(u=>JSON.parse(u),()=>{});if(!!(i&&typeof i=="object"&&("__hem"in i||"targetBundleId"in i))||t.target_manifest||t.target_manifest_sha256)return rt(n,{...t,job_id:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{processBatchConfig:()=>{throw new Error("Pinned execution cannot use legacy WASM")}});let m;try{m=await Ae()}catch(u){let d=u;return{job_id:a,status:"error",message:`WASM initialization failed: ${d.message}`,error:d.message}}return m.processBatchConfig?(Le(n),rt(n,{...t,job_id:a},{processBatchConfig:m.processBatchConfig})):{job_id:a,status:"error",message:"WASM process_batch_config function not available",error:"WASM function missing"}}async function on(e,t={}){return Ft(e.workspace,t)}async function cn(e,t){let n;try{n=await Ae()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return qt(e.workspace,t,{calculateMetricsFromParsedData:n.calculateMetricsFromParsedData})}async function ln(e,t){return Wt(e.workspace,t)}async function un(e,t){return Ie(e.workspace,t)}import Qa from"fs/promises";import es from"path";async function dn(e,t){let{workspace:n}=e,{csv_path:r,output_path:a,schema_path:s,defaults_path:i}=t;if(!r)throw new Error("csv_path is required");let o=await Qa.readFile(es.resolve(n,r),"utf8").catch(()=>{});if(o!==void 0&&!!Be(o)||t.target_manifest||t.target_manifest_sha256)return st({workspace:n,csvPath:r,outputPath:a,schemaPath:s,defaultsPath:i,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256,deps:{convertGeometryCsvToJson:()=>{throw new Error("Pinned preparation cannot use legacy WASM")}}});let u;try{u=await Ae()}catch(d){return{ok:!1,error:`WASM initialization failed: ${d.message}`}}return Le(n),st({workspace:n,csvPath:r,outputPath:a,schemaPath:s,defaultsPath:i,deps:{convertGeometryCsvToJson:u.convertGeometryCsvToJson}})}import mn from"path";async function fn(e,t){return Gt({csvPath:mn.isAbsolute(t.csv_path)?t.csv_path:mn.join(e.workspace,t.csv_path),failOn:t.fail_on,repoRoot:process.cwd()})}import _n from"path";async function pn(e,t){return Kt({csvPath:_n.isAbsolute(t.csv_path)?t.csv_path:_n.join(e.workspace,t.csv_path),mode:t.mode,repoRoot:process.cwd()})}import hn from"path";async function gn(e,t){return Xt({csvPath:hn.isAbsolute(t.csv_path)?t.csv_path:hn.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,repoRoot:process.cwd()})}var he={vulcan_list_parameters:y.object({category:y.string().optional().describe('Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")')}),vulcan_view_parameter:y.object({category:y.string().describe('Parameter category (e.g., "heat_source_wet", "controls", "base_json")'),parameter_id:y.string().describe("Parameter ID (filename without .json extension)")}),vulcan_save_parameter:y.object({category:y.string().describe('Parameter category (e.g., "heat_source_wet", "controls")'),parameter_id:y.string().describe("Parameter ID (filename without .json extension)"),content:y.record(y.string(),y.any()).describe("Parameter JSON content (must be valid JSON object)"),markdown_content:y.string().optional().describe("Optional markdown documentation for the parameter")}),vulcan_create_batch_config:y.object({config_name:y.string().describe("Configuration name (will be saved as {config_name}.json)"),base_model:y.string().describe("Base model filename (without .json extension)"),weather_file:y.string().optional().describe("EPW filename in batch_parameters/weather_files (extension optional); required for unpinned models, optional for pinned models (omit for reference weather)"),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it"),wrapper:y.string().optional().describe('Optional model wrapper (e.g., "fhs_compliance", "passthrough")'),parameters:y.preprocess(e=>!e||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([t,n])=>{if(typeof n=="string")try{let r=JSON.parse(n);return[t,Array.isArray(r)?r:[r]]}catch{return[t,[n]]}return[t,Array.isArray(n)?n:[n]]})),y.record(y.string(),y.array(y.string()))).describe("Object mapping category to array of parameter IDs")}),vulcan_run_batch:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),job_id:y.string().optional().describe("Optional custom job ID (defaults to mcp_{uuid})"),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; pinned batches otherwise download their verified target"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_get_batch_status:y.object({job_id:y.string().optional().describe("Job ID returned from vulcan_run_batch"),config_name:y.string().optional().describe("Configuration name (alternative to job_id, since config names are unique)")}).refine(e=>e.job_id||e.config_name,{message:"Either job_id or config_name must be provided"}),vulcan_calculate_metrics:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),model_names:y.array(y.string()).describe("Array of model names to calculate metrics for"),metric_definitions:y.array(y.object({id:y.string().optional(),name:y.string().optional(),column:y.string().optional(),function:y.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:y.string().optional(),threshold:y.number().optional()})).describe("Array of metric definitions"),time_range:y.object({start:y.number().optional(),end:y.number().optional()}).optional().describe("Optional time range filter"),tariff_file_path:y.string().optional().describe("Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."),tariff_column_index:y.number().optional().describe("Zero-based index of tariff column in CSV. Required for cost metrics.")}),vulcan_list_csv_columns:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),model_name:y.string().describe('Model name (e.g., "scenario_1_0")')}),vulcan_list_batch_models:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)")}),vulcan_merge_csv_to_json:y.object({csv_path:y.string().describe("Path to CSV file (relative to workspace or absolute)"),output_path:y.string().optional().describe("Optional: output JSON path (defaults to input/batch_parameters/base_json/{csv_filename}.json)"),schema_path:y.string().optional().describe("Optional: custom schema path (defaults to the core schema with workspace fallbacks)"),defaults_path:y.string().optional().describe("Optional: custom defaults path. Declared paths must load; standard defaults are used only for legacy CSVs without DefaultsPath."),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; pinned CSVs otherwise download their verified target"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_validate_geometry_csv:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),fail_on:y.enum(["none","critical","warning"]).optional().describe("Validation exit policy for the wrapped CLI. Defaults to critical.")}),vulcan_auto_thermal_bridges:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),mode:y.enum(["summary","json","csv-section"]).optional().describe("Wrapped auto-TB CLI output mode. Defaults to summary.")}),vulcan_validate_thermal_bridges:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),include_auto:y.boolean().optional().describe("Also synthesize auto-TB proposals before validation."),mode:y.enum(["summary","json"]).optional().describe("Wrapped TB validation CLI output mode. Defaults to summary.")})},yn=[{name:"vulcan_list_parameters",description:`List available parameter categories and their JSON snippets.
18
+ Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var nt=null;async function Be(){if(nt)return nt;try{let{directory:e,context:t}=Ma();return console.error(`[WASM] Loading from ${t}: ${e}`),nt=await Pt(e),console.error(`[WASM] Initialized successfully from ${t}`),nt}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function Hr(e,t){let n;try{n=await Be()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return Ot(e.workspace,t,{validateSnippetJs:n.validateSnippetJs})}async function zr(e,t){return kt(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import{randomUUID as Oa}from"crypto";import Fa from"fs/promises";import $a from"path";async function Gr(e,t){let{workspace:n}=e,{config_name:r}=t;if(!r)throw new Error("config_name is required");let a=t.job_id||`mcp_${Oa()}`,s=$a.join(n,"input","batch_configs",r.endsWith(".json")?r:`${r}.json`),i=await Fa.readFile(s,"utf8").then(u=>JSON.parse(u),()=>{});if(!!(i&&typeof i=="object"&&("__hem"in i||"targetBundleId"in i))||t.target_manifest||t.target_manifest_sha256)return Ze(n,{...t,job_id:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{processBatchConfig:()=>{throw new Error("Pinned execution cannot use legacy WASM")}});let d;try{d=await Be()}catch(u){let m=u;return{job_id:a,status:"error",message:`WASM initialization failed: ${m.message}`,error:m.message}}return d.processBatchConfig?(Qe(n),Ze(n,{...t,job_id:a},{processBatchConfig:d.processBatchConfig})):{job_id:a,status:"error",message:"WASM process_batch_config function not available",error:"WASM function missing"}}async function Kr(e,t={}){return xt(e.workspace,t)}async function Xr(e,t){let n;try{n=await Be()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return It(e.workspace,t,{calculateMetricsFromParsedData:n.calculateMetricsFromParsedData})}async function Yr(e,t){return $t(e.workspace,t)}async function Zr(e,t){return Ne(e.workspace,t)}async function Qr(e,t){let{workspace:n}=e,{csv_path:r,output_path:a}=t;if(!r)throw new Error("csv_path is required");return jt({workspace:n,csvPath:r,outputPath:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import en from"path";async function tn(e,t){return Vt({csvPath:en.isAbsolute(t.csv_path)?t.csv_path:en.join(e.workspace,t.csv_path),failOn:t.fail_on,repoRoot:process.cwd()})}import rn from"path";async function nn(e,t){return Jt({csvPath:rn.isAbsolute(t.csv_path)?t.csv_path:rn.join(e.workspace,t.csv_path),mode:t.mode,repoRoot:process.cwd()})}import an from"path";async function sn(e,t){return Ut({csvPath:an.isAbsolute(t.csv_path)?t.csv_path:an.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,repoRoot:process.cwd()})}var ge={vulcan_list_parameters:y.object({category:y.string().optional().describe('Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")')}),vulcan_view_parameter:y.object({category:y.string().describe('Parameter category (e.g., "heat_source_wet", "controls", "base_json")'),parameter_id:y.string().describe("Parameter ID (filename without .json extension)")}),vulcan_save_parameter:y.object({category:y.string().describe('Parameter category (e.g., "heat_source_wet", "controls")'),parameter_id:y.string().describe("Parameter ID (filename without .json extension)"),content:y.record(y.string(),y.any()).describe("Parameter JSON content (must be valid JSON object)"),markdown_content:y.string().optional().describe("Optional markdown documentation for the parameter")}),vulcan_create_batch_config:y.object({config_name:y.string().describe("Configuration name (will be saved as {config_name}.json)"),base_model:y.string().describe("Base model filename (without .json extension)"),weather_file:y.string().optional().describe("EPW filename in batch_parameters/weather_files (extension optional); required for unpinned models, optional for pinned models (omit for reference weather)"),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it"),wrapper:y.string().optional().describe('Optional model wrapper (e.g., "fhs_compliance", "passthrough")'),parameters:y.preprocess(e=>!e||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([t,n])=>{if(typeof n=="string")try{let r=JSON.parse(n);return[t,Array.isArray(r)?r:[r]]}catch{return[t,[n]]}return[t,Array.isArray(n)?n:[n]]})),y.record(y.string(),y.array(y.string()))).describe("Object mapping category to array of parameter IDs")}),vulcan_run_batch:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),job_id:y.string().optional().describe("Optional custom job ID (defaults to mcp_{uuid})"),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; pinned batches otherwise download their verified target"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_get_batch_status:y.object({job_id:y.string().optional().describe("Job ID returned from vulcan_run_batch"),config_name:y.string().optional().describe("Configuration name (alternative to job_id, since config names are unique)")}).refine(e=>e.job_id||e.config_name,{message:"Either job_id or config_name must be provided"}),vulcan_calculate_metrics:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),model_names:y.array(y.string()).describe("Array of model names to calculate metrics for"),metric_definitions:y.array(y.object({id:y.string().optional(),name:y.string().optional(),column:y.string().optional(),function:y.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:y.string().optional(),threshold:y.number().optional()})).describe("Array of metric definitions"),time_range:y.object({start:y.number().optional(),end:y.number().optional()}).optional().describe("Optional time range filter"),tariff_file_path:y.string().optional().describe("Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."),tariff_column_index:y.number().optional().describe("Zero-based index of tariff column in CSV. Required for cost metrics.")}),vulcan_list_csv_columns:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)"),model_name:y.string().describe('Model name (e.g., "scenario_1_0")')}),vulcan_list_batch_models:y.object({config_name:y.string().describe("Configuration name (with or without .json extension)")}),vulcan_merge_csv_to_json:y.object({csv_path:y.string().describe("Path to CSV file (relative to workspace or absolute)"),output_path:y.string().optional().describe("Optional: output JSON path (defaults to input/batch_parameters/base_json/{csv_filename}.json)"),target_manifest:y.string().optional().describe("Optional offline override: local bundle manifest path; the CSV's target is otherwise downloaded and verified"),target_manifest_sha256:y.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_validate_geometry_csv:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),fail_on:y.enum(["none","critical","warning"]).optional().describe("Validation exit policy for the wrapped CLI. Defaults to critical.")}),vulcan_auto_thermal_bridges:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),mode:y.enum(["summary","json","csv-section"]).optional().describe("Wrapped auto-TB CLI output mode. Defaults to summary.")}),vulcan_validate_thermal_bridges:y.object({csv_path:y.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),include_auto:y.boolean().optional().describe("Also synthesize auto-TB proposals before validation."),mode:y.enum(["summary","json"]).optional().describe("Wrapped TB validation CLI output mode. Defaults to summary.")})},on=[{name:"vulcan_list_parameters",description:`List available parameter categories and their JSON snippets.
21
19
 
22
20
  Use this to discover what parameters are available before creating batch configurations.
23
21
  Returns a catalog of all categories (e.g., base_json, heat_source_wet, controls) and their parameters.
@@ -85,27 +83,17 @@ Scenarios whose last run failed or was cancelled are listed in failed_models wit
85
83
  A model with no job_id comes from the legacy engine, whose runs cannot be dated. Read vulcan_get_batch_status and the warnings before presenting results as current.
86
84
 
87
85
  Example: List models from config "my_batch" to get ["scenario_1_0", "scenario_1_1", ...].
88
- See also: vulcan_get_batch_status to check if batch is complete, vulcan_calculate_metrics to analyze results.`,inputSchema:{type:"object",required:["config_name"],properties:{config_name:{type:"string"}}}},{name:"vulcan_merge_csv_to_json",description:`Convert a geometry CSV file to JSON format using WASM conversion.
86
+ See also: vulcan_get_batch_status to check if batch is complete, vulcan_calculate_metrics to analyze results.`,inputSchema:{type:"object",required:["config_name"],properties:{config_name:{type:"string"}}}},{name:"vulcan_merge_csv_to_json",description:`Convert a geometry CSV file to HEM input JSON, as the geometry canvas save does.
89
87
 
90
- This tool performs the same conversion as the geometry canvas save operation:
91
- - Parses CSV geometry data
92
- - Merges with the declared defaults template (supports CSV metadata DefaultsPath)
93
- - Validates against schema
94
- - Saves JSON to workspace
95
-
96
- The tool supports CSV metadata DefaultsPath (same as geometry canvas), which allows
97
- the CSV file to specify its own defaults template path in the metadata section.
98
- If a CSV declares DefaultsPath, that file must load; the standard defaults template
99
- is used only for legacy CSVs with no DefaultsPath row.
100
-
101
- A CSV saved by the current app pins a HEM target (TargetBundleId) and is prepared by that
102
- target's own schema, defaults and converter in Google Chrome (install it separately). The
103
- first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python) into
104
- ~/.cache/vulcan/hem-targets. target_manifest plus target_manifest_sha256 are an optional
105
- offline override.
88
+ The CSV's TargetBundleId row names its HEM target. A CSV with no TargetBundleId row uses
89
+ Rust HEM:FHS 1.0.0a7. The target's schema and defaults prepare the model, and the helper's
90
+ own converter runs in Google Chrome (install it separately). A DefaultsPath in the CSV must
91
+ hold the same defaults as the target. The first use downloads and verifies the target (about
92
+ 12 MB for Rust, 75 MB for Python) into ~/.cache/vulcan/hem-targets. target_manifest plus
93
+ target_manifest_sha256 are an optional offline override.
106
94
 
107
95
  Example: Convert input/base_models/my_model.csv to JSON.
108
- See also: vulcan_list_parameters to see available base models.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},output_path:{type:"string"},schema_path:{type:"string"},defaults_path:{type:"string"},target_manifest:{type:"string",description:"Optional offline override: local bundle manifest path"},target_manifest_sha256:{type:"string",description:"Expected SHA-256 of target_manifest; required with it"}}}},{name:"vulcan_validate_geometry_csv",description:`Validate a geometry CSV through the existing Vulcan geometry validator CLI.
96
+ See also: vulcan_list_parameters to see available base models.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},output_path:{type:"string"},target_manifest:{type:"string",description:"Optional offline override: local bundle manifest path"},target_manifest_sha256:{type:"string",description:"Expected SHA-256 of target_manifest; required with it"}}}},{name:"vulcan_validate_geometry_csv",description:`Validate a geometry CSV through the existing Vulcan geometry validator CLI.
109
97
 
110
98
  This wraps npm run validate:geometry-csv and reuses the same pure web validators used by
111
99
  Build Geometry. It reports element, zone, global, missing-element, and Part F findings
@@ -119,7 +107,7 @@ or csv-section for a pasteable Thermal Bridging Elements CSV section.`,inputSche
119
107
 
120
108
  This wraps the Community CLI's thermal-bridges --validate command and reuses findLinearThermalBridgeIssues plus
121
109
  validateElementCore. Set include_auto=true to validate existing CSV rows plus synthesized
122
- auto-TB proposals without mutating the CSV.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},include_auto:{type:"boolean"},mode:{type:"string",enum:["summary","json"]}}}}];async function wn(e,t,n){switch(e){case"vulcan_list_parameters":{let r=he.vulcan_list_parameters.parse(t);return await en(n,r)}case"vulcan_view_parameter":{let r=he.vulcan_view_parameter.parse(t);return await tn(n,r)}case"vulcan_save_parameter":{let{category:r,parameter_id:a,content:s,markdown_content:i}=t||{};if(!r||typeof r!="string")throw new Error("category is required and must be a string");if(!a||typeof a!="string")throw new Error("parameter_id is required and must be a string");if(!s||typeof s!="object"||Array.isArray(s))throw new Error("content is required and must be a JSON object");let o={category:r,parameter_id:a,content:s,...i?{markdown_content:i}:{}};return await nn(n,o)}case"vulcan_create_batch_config":{let{config_name:r,base_model:a,weather_file:s,wrapper:i,parameters:o,target_manifest:m,target_manifest_sha256:u}=t||{};if(!r||typeof r!="string")throw new Error("config_name is required and must be a string");if(!a||typeof a!="string")throw new Error("base_model is required and must be a string");if(s!==void 0&&typeof s!="string")throw new Error("weather_file must be a string");let d={};if(o){if(typeof o!="object"||Array.isArray(o))throw new Error("parameters must be an object mapping category to array of parameter IDs");d=Object.fromEntries(Object.entries(o).map(([h,p])=>{if(typeof p=="string")try{let C=JSON.parse(p);return[h,Array.isArray(C)?C:[C]]}catch{return[h,[p]]}return[h,Array.isArray(p)?p:[p]]}))}let f={config_name:r,base_model:a,weather_file:s,...i?{wrapper:i}:{},parameters:d,target_manifest:m,target_manifest_sha256:u};return await an(n,f)}case"vulcan_run_batch":{let r=he.vulcan_run_batch.parse(t);return await sn(n,r)}case"vulcan_get_batch_status":{let r=he.vulcan_get_batch_status.parse(t);return await on(n,r)}case"vulcan_calculate_metrics":{let r=he.vulcan_calculate_metrics.parse(t);return await cn(n,r)}case"vulcan_list_csv_columns":{let r=he.vulcan_list_csv_columns.parse(t);return await ln(n,r)}case"vulcan_list_batch_models":{let r=he.vulcan_list_batch_models.parse(t);return await un(n,r)}case"vulcan_merge_csv_to_json":{let r=he.vulcan_merge_csv_to_json.parse(t);return await dn(n,r)}case"vulcan_validate_geometry_csv":{let r=he.vulcan_validate_geometry_csv.parse(t);return await fn(n,r)}case"vulcan_auto_thermal_bridges":{let r=he.vulcan_auto_thermal_bridges.parse(t);return await pn(n,r)}case"vulcan_validate_thermal_bridges":{let r=he.vulcan_validate_thermal_bridges.parse(t);return await gn(n,r)}default:throw new Error(`Unknown tool: ${e}`)}}async function ac(e,t){let n=t||parseInt(process.env.HELPER_PORT||"5000",10),r;try{r=await or(e),console.error(`[MCP Helper] Config loaded from: ${r.configPath}`),console.error(`[MCP Helper] Workspace: ${r.workspace}`)}catch(m){console.error(`[MCP Helper] Failed to load config: ${m.message}`),process.exit(1)}let a=vn(),s={origin:!0,methods:["GET","OPTIONS"],credentials:!1},i=new ts({name:"vulcan-mcp-helper",version:"0.1.0"},{capabilities:{tools:{}}}),o=i._oninitialize?.bind(i);if(o){i.removeRequestHandler("initialize");let m=Cn.extend({params:Cn.shape.params.partial().transform((u={})=>({protocolVersion:u.protocolVersion||"2024-11-05",capabilities:u.capabilities||{},clientInfo:u.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});i.setRequestHandler(m,u=>o(u))}i.setRequestHandler(ns,async()=>({tools:yn})),i.setRequestHandler(as,async m=>{let{name:u,arguments:d}=m.params;console.error(`[MCP Helper] Tool call: ${u}`);try{let f=await wn(u,d,r);return{content:[{type:"text",text:JSON.stringify(f,null,2)}]}}catch(f){let h=f;throw console.error(`[MCP Helper] Tool call failed: ${h.message}`),h}}),a.post("/mcp",vn.raw({type:"application/json",limit:"10mb"}),async(m,u)=>{try{await ir(m.headers.authorization,r.license_token)}catch{console.error("[MCP Helper] Rejected unauthorized MCP request"),u.set("WWW-Authenticate",'Bearer realm="vulcan-mcp"').status(401).json({jsonrpc:"2.0",error:{code:-32001,message:"Unauthorized"},id:null});return}let d;try{let h=m.body.toString("utf-8");d=JSON.parse(h)}catch(h){let p=h;u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:p.message},id:null});return}let f=new rs({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{f.close()});try{await i.connect(f),await f.handleRequest(m,u,d)}catch(h){let p=h;console.error(`[MCP Helper] MCP request failed: ${p.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:p.message},id:d?.id||null})}}),a.get("/health",bn(s),(m,u)=>{u.json({status:"running",port:n,version:"0.1.0",name:"vulcan-mcp-helper"})}),a.get("/helper/status",bn(s),(m,u)=>{u.json({running:!0,port:n,version:"0.1.0",mcpReady:!0})}),a.listen(n,"127.0.0.1",()=>{console.error(`[MCP Helper] Server running on http://127.0.0.1:${n}`),console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${n}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${n}/health`),console.error(`[MCP Helper] Status API: http://127.0.0.1:${n}/helper/status`)})}export{ac as startServer};
110
+ auto-TB proposals without mutating the CSV.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},include_auto:{type:"boolean"},mode:{type:"string",enum:["summary","json"]}}}}];async function cn(e,t,n){switch(e){case"vulcan_list_parameters":{let r=ge.vulcan_list_parameters.parse(t);return await Jr(n,r)}case"vulcan_view_parameter":{let r=ge.vulcan_view_parameter.parse(t);return await Ur(n,r)}case"vulcan_save_parameter":{let{category:r,parameter_id:a,content:s,markdown_content:i}=t||{};if(!r||typeof r!="string")throw new Error("category is required and must be a string");if(!a||typeof a!="string")throw new Error("parameter_id is required and must be a string");if(!s||typeof s!="object"||Array.isArray(s))throw new Error("content is required and must be a JSON object");let o={category:r,parameter_id:a,content:s,...i?{markdown_content:i}:{}};return await Hr(n,o)}case"vulcan_create_batch_config":{let{config_name:r,base_model:a,weather_file:s,wrapper:i,parameters:o,target_manifest:d,target_manifest_sha256:u}=t||{};if(!r||typeof r!="string")throw new Error("config_name is required and must be a string");if(!a||typeof a!="string")throw new Error("base_model is required and must be a string");if(s!==void 0&&typeof s!="string")throw new Error("weather_file must be a string");let m={};if(o){if(typeof o!="object"||Array.isArray(o))throw new Error("parameters must be an object mapping category to array of parameter IDs");m=Object.fromEntries(Object.entries(o).map(([h,p])=>{if(typeof p=="string")try{let S=JSON.parse(p);return[h,Array.isArray(S)?S:[S]]}catch{return[h,[p]]}return[h,Array.isArray(p)?p:[p]]}))}let _={config_name:r,base_model:a,weather_file:s,...i?{wrapper:i}:{},parameters:m,target_manifest:d,target_manifest_sha256:u};return await zr(n,_)}case"vulcan_run_batch":{let r=ge.vulcan_run_batch.parse(t);return await Gr(n,r)}case"vulcan_get_batch_status":{let r=ge.vulcan_get_batch_status.parse(t);return await Kr(n,r)}case"vulcan_calculate_metrics":{let r=ge.vulcan_calculate_metrics.parse(t);return await Xr(n,r)}case"vulcan_list_csv_columns":{let r=ge.vulcan_list_csv_columns.parse(t);return await Yr(n,r)}case"vulcan_list_batch_models":{let r=ge.vulcan_list_batch_models.parse(t);return await Zr(n,r)}case"vulcan_merge_csv_to_json":{if(t?.schema_path!==void 0||t?.defaults_path!==void 0)throw new Error(Rt);let r=ge.vulcan_merge_csv_to_json.parse(t);return await Qr(n,r)}case"vulcan_validate_geometry_csv":{let r=ge.vulcan_validate_geometry_csv.parse(t);return await tn(n,r)}case"vulcan_auto_thermal_bridges":{let r=ge.vulcan_auto_thermal_bridges.parse(t);return await nn(n,r)}case"vulcan_validate_thermal_bridges":{let r=ge.vulcan_validate_thermal_bridges.parse(t);return await sn(n,r)}default:throw new Error(`Unknown tool: ${e}`)}}async function Ri(e,t){let n=t||parseInt(process.env.HELPER_PORT||"5000",10),r;try{r=await er(e),console.error(`[MCP Helper] Config loaded from: ${r.configPath}`),console.error(`[MCP Helper] Workspace: ${r.workspace}`)}catch(d){console.error(`[MCP Helper] Failed to load config: ${d.message}`),process.exit(1)}let a=ln(),s={origin:!0,methods:["GET","OPTIONS"],credentials:!1},i=new Na({name:"vulcan-mcp-helper",version:"0.1.0"},{capabilities:{tools:{}}}),o=i._oninitialize?.bind(i);if(o){i.removeRequestHandler("initialize");let d=dn.extend({params:dn.shape.params.partial().transform((u={})=>({protocolVersion:u.protocolVersion||"2024-11-05",capabilities:u.capabilities||{},clientInfo:u.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});i.setRequestHandler(d,u=>o(u))}i.setRequestHandler(La,async()=>({tools:on})),i.setRequestHandler(Ia,async d=>{let{name:u,arguments:m}=d.params;console.error(`[MCP Helper] Tool call: ${u}`);try{let _=await cn(u,m,r);return{content:[{type:"text",text:JSON.stringify(_,null,2)}]}}catch(_){let h=_;throw console.error(`[MCP Helper] Tool call failed: ${h.message}`),h}}),a.post("/mcp",ln.raw({type:"application/json",limit:"10mb"}),async(d,u)=>{try{await tr(d.headers.authorization,r.license_token)}catch{console.error("[MCP Helper] Rejected unauthorized MCP request"),u.set("WWW-Authenticate",'Bearer realm="vulcan-mcp"').status(401).json({jsonrpc:"2.0",error:{code:-32001,message:"Unauthorized"},id:null});return}let m;try{let h=d.body.toString("utf-8");m=JSON.parse(h)}catch(h){let p=h;u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:p.message},id:null});return}let _=new Ba({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{_.close()});try{await i.connect(_),await _.handleRequest(d,u,m)}catch(h){let p=h;console.error(`[MCP Helper] MCP request failed: ${p.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:p.message},id:m?.id||null})}}),a.get("/health",un(s),(d,u)=>{u.json({status:"running",port:n,version:"0.1.0",name:"vulcan-mcp-helper"})}),a.get("/helper/status",un(s),(d,u)=>{u.json({running:!0,port:n,version:"0.1.0",mcpReady:!0})}),a.listen(n,"127.0.0.1",()=>{console.error(`[MCP Helper] Server running on http://127.0.0.1:${n}`),console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${n}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${n}/health`),console.error(`[MCP Helper] Status API: http://127.0.0.1:${n}/helper/status`)})}export{Ri as startServer};
123
111
  /*! Bundled license information:
124
112
 
125
113
  papaparse/papaparse.js: