@vulcan-energy/mcp-helper 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,139 +1,73 @@
1
1
  #!/usr/bin/env node
2
- var kn=Object.create;var rr=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var xn=Object.getPrototypeOf,An=Object.prototype.hasOwnProperty;var Rn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var jn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Tn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Pn(t))!An.call(e,a)&&a!==r&&rr(e,a,{get:()=>t[a],enumerable:!(n=En(t,a))||n.enumerable});return e};var Mn=(e,t,r)=>(r=e!=null?kn(xn(e)):{},Tn(t||!e||!e.__esModule?rr(r,"default",{value:e,enumerable:!0}):r,e));var dr=jn((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 r(){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 n=!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",`
3
- `,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!n&&!!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=_,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||{},p=[];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++)p.push({file:this.files[L],inputElem:this,instanceConfig:m.extend({},l)})}),g(),this;function g(){if(p.length===0){j(c.complete)&&c.complete();return}var k=p[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(){p.splice(0,1),g()}}}a&&(t.onmessage=Ce);function u(c,l){l=l||{};var p=l.dynamicTyping||!1;if(j(p)&&(l.dynamicTypingFunction=p,p={}),l.dynamicTyping=p,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 _(l)),v.stream(c);function M(k){return k.charCodeAt(0)===65279?k.slice(1):k}}function d(c,l){var p=!1,g=!0,v=",",M=`\r
4
- `,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))&&(p=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||p===!0||typeof p=="function"&&p(I,D)||Array.isArray(p)&&p[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(p,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(p,le)}p=[...p.split(ee).slice(v)].join(ee)}if(this.isFirstChunk&&j(this._config.beforeFirstChunk)){var M=this._config.beforeFirstChunk(p);M!==void 0&&(p=M)}this.isFirstChunk=!1,this._halted=!1;var k=this._partialLine+p;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(p){j(this._config.error)?this._config.error(p):a&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:p,finished:!1})};function l(p){var g=re(p);g.chunkSize=parseInt(g.chunkSize),!p.step&&!p.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;n?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),n||(l.onload=R(this._chunkLoaded,this),l.onerror=R(this._chunkError,this)),l.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),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)}n&&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>=p(l),this.parseChunk(l.responseText)}},this._chunkError=function(g){var v=l.statusText||g;this._sendError(new Error(v))};function p(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 _(c){c=c||{},c.chunkSize||(c.chunkSize=o.LocalChunkSize),f.call(this,c);var l,p,g=typeof FileReader<"u";this.stream=function(v){this._input=v,p=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=p.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)}}_.prototype=Object.create(f.prototype),_.prototype.constructor=_;function C(c){c=c||{},f.call(this,c);var l;this.stream=function(p){return l=p,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var p=this._config.chunkSize,g;return p?(g=l.substring(0,p),l=l.substring(p)):(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=[],p=!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()):p=!0},this._streamData=R(function(v){try{l.push(typeof v=="string"?v:v.toString(this._config.encoding)),p&&(p=!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=Rn("stream").Duplex,p=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)},p.step=R(this._onCsvData,this),p.complete=R(this._onCsvComplete,this),f.call(this,p),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(p.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),p=-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(`
5
- `),V=E.length>1&&E[0].length<H[0].length;if(H.length===1||V)return`
6
- `;for(var se=0,te=0;te<H.length;te++)H[te][0]===`
7
- `&&se++;return se>=H.length/2?`\r
8
- `:"\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>p&&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,p=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),p!==`
9
- `&&p!=="\r"&&p!==`\r
10
- `&&(p=`
11
- `);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=p.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),P=0;P<fe.length;P++){if(W=fe[P],O+=W.length,P!==fe.length-1)O+=p.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(p,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(p,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(p,O);break}var je=De(N);if(x.substring(E+1+je,E+1+je+Y)===p){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(p,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(p,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:p,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=r(),l=new t.Worker(c);return l.onmessage=B,l.id=i++,s[l.id]=l,l}function B(c){var l=c.data,p=s[l.workerId],g=!1;if(l.error)p.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(p.userStep)){for(var k=0;k<l.results.data.length&&(p.userStep({data:l.results.data[k],errors:l.results.errors,meta:l.results.meta},M),!g);k++);delete l.results}else j(p.userChunk)&&(p.userChunk(l.results,M,l.file),delete l.results)}l.finished&&!g&&X(l.workerId,l.results)}function X(c,l){var p=s[c];j(p.userComplete)&&p.userComplete(l),p.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 p=o.parse(l.input,l.config);p&&t.postMessage({workerId:o.WORKER_ID,results:p,finished:!0})}}function re(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=re(c[p]);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 rs}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as ns}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as as,CallToolRequestSchema as ss,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,pt=300,z=class extends Error{code;constructor(t,r){super(r),this.name="CapabilityTokenError",this.code=t}};var ar=Object.freeze([`-----BEGIN PUBLIC KEY-----
2
+ var fa=Object.create;var $r=Object.defineProperty;var pa=Object.getOwnPropertyDescriptor;var _a=Object.getOwnPropertyNames;var ga=Object.getPrototypeOf,ha=Object.prototype.hasOwnProperty;var wa=(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 ya=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var va=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _a(t))!ha.call(e,s)&&s!==n&&$r(e,s,{get:()=>t[s],enumerable:!(r=pa(t,s))||r.enumerable});return e};var ba=(e,t,n)=>(n=e!=null?fa(ga(e)):{},va(t||!e||!e.__esModule?$r(n,"default",{value:e,enumerable:!0}):n,e));var Hr=ya((Nt,It)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof It=="object"&&typeof Nt<"u"?It.exports=t():e.Papa=t()})(Nt,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,s=t.IS_PAPA_WORKER||!1,a={},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",`
3
+ `,'"',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=N,o.ParserHandle=M,o.NetworkStreamer=h,o.FileStreamer=_,o.StringStreamer=S,o.ReadableStreamStreamer=x,typeof PAPA_BROWSER_CONTEXT>"u"&&(o.DuplexStreamStreamer=k),t.jQuery){var d=t.jQuery;d.fn.parse=function(c){var l=c.config||{},f=[];return this.each(function(v){var y=d(this).prop("tagName").toUpperCase()==="INPUT"&&d(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!y||!this.files||this.files.length===0)return!0;for(var D=0;D<this.files.length;D++)f.push({file:this.files[D],inputElem:this,instanceConfig:d.extend({},l)})}),g(),this;function g(){if(f.length===0){T(c.complete)&&c.complete();return}var v=f[0];if(T(c.before)){var y=c.before(v.file,v.inputElem);if(typeof y=="object")if(y.action==="abort"){w("AbortError",v.file,v.inputElem,y.reason);return}else if(y.action==="skip"){$();return}else typeof y.config=="object"&&(v.instanceConfig=d.extend(v.instanceConfig,y.config));else if(y==="skip"){$();return}}var D=v.instanceConfig.complete;v.instanceConfig.complete=function(q){T(D)&&D(q,v.file,v.inputElem),$()},o.parse(v.file,v.instanceConfig)}function w(v,y,D,q){T(c.error)&&c.error({name:v},y,D,q)}function $(){f.splice(0,1),g()}}}s&&(t.onmessage=Ce);function u(c,l){l=l||{};var f=l.dynamicTyping||!1;if(T(f)&&(l.dynamicTypingFunction=f,f={}),l.dynamicTyping=f,l.transform=T(l.transform)?l.transform:!1,l.worker&&o.WORKERS_SUPPORTED){var g=I();g.userStep=l.step,g.userChunk=l.chunk,g.userComplete=l.complete,g.userError=l.error,l.step=T(l.step),l.chunk=T(l.chunk),l.complete=T(l.complete),l.error=T(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 k(l),w.getStream();return typeof c=="string"?(c=$(c),l.download?w=new h(l):w=new S(l)):c.readable===!0&&T(c.read)&&T(c.on)?w=new x(l):(t.File&&c instanceof File||c instanceof Object)&&(w=new _(l)),w.stream(c);function $(v){return v.charCodeAt(0)===65279?v.slice(1):v}}function m(c,l){var f=!1,g=!0,w=",",$=`\r
4
+ `,v='"',y=v+v,D=!1,q=null,ee=!1;le();var F=new RegExp(R(v),"g");if(typeof c=="string"&&(c=JSON.parse(c)),Array.isArray(c)){if(!c.length||Array.isArray(c[0]))return P(null,c,D);if(typeof c[0]=="object")return P(q||Object.keys(c[0]),c,D)}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])),P(c.fields||[],c.data||[],D);throw new Error("Unable to serialize unrecognized input");function le(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!o.BAD_DELIMITERS.filter(function(V){return l.delimiter.indexOf(V)!==-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")&&(D=l.skipEmptyLines),typeof l.newline=="string"&&($=l.newline),typeof l.quoteChar=="string"&&(v=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&&(y=l.escapeChar+v),l.escapeFormulae instanceof RegExp?ee=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(ee=/^[=+\-@\t\r].*$/)}}function P(V,J,Z){var Y="";typeof V=="string"&&(V=JSON.parse(V)),typeof J=="string"&&(J=JSON.parse(J));var me=Array.isArray(V)&&V.length>0,se=!Array.isArray(J[0]);if(me&&g){for(var pe=0;pe<V.length;pe++)pe>0&&(Y+=w),Y+=L(V[pe],pe);J.length>0&&(Y+=$)}for(var U=0;U<J.length;U++){var Se=me?V.length:J[U].length,_e=!1,E=me?Object.keys(J[U]).length===0:J[U].length===0;if(Z&&!me&&(_e=Z==="greedy"?J[U].join("").trim()==="":J[U].length===1&&J[U][0].length===0),Z==="greedy"&&me){for(var A=[],B=0;B<Se;B++){var z=se?V[B]:B;A.push(J[U][z])}_e=A.join("").trim()===""}if(!_e){for(var b=0;b<Se;b++){b>0&&!E&&(Y+=w);var H=me&&se?V[b]:b;Y+=L(J[U][H],b)}U<J.length-1&&(!Z||Se>0&&!E)&&(Y+=$)}}return Y}function L(V,J){if(typeof V>"u"||V===null)return"";if(V.constructor===Date)return JSON.stringify(V).slice(1,25);var Z=!1;ee&&typeof V=="string"&&ee.test(V)&&(V="'"+V,Z=!0);var Y=V.toString().replace(F,y);return Z=Z||f===!0||typeof f=="function"&&f(V,J)||Array.isArray(f)&&f[J]||Me(Y,o.BAD_DELIMITERS)||Y.indexOf(w)>-1||Y.charAt(0)===" "||Y.charAt(Y.length-1)===" ",Z?v+Y+v:Y}function Me(V,J){for(var Z=0;Z<J.length;Z++)if(V.indexOf(J[Z])>-1)return!0;return!1}}function p(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 ee=this._config.newline;if(!ee){let le=this._config.quoteChar||'"';ee=this._handle.guessLineEndings(f,le)}f=[...f.split(ee).slice(w)].join(ee)}if(this.isFirstChunk&&T(this._config.beforeFirstChunk)){var $=this._config.beforeFirstChunk(f);$!==void 0&&(f=$)}this.isFirstChunk=!1,this._halted=!1;var v=this._partialLine+f;this._partialLine="";var y=this._handle.parse(v,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var D=y.meta.cursor;this._finished||(this._partialLine=v.substring(D-this._baseIndex),this._baseIndex=D),y&&y.data&&(this._rowCount+=y.data.length);var q=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(s)t.postMessage({results:y,workerId:o.WORKER_ID,finished:q});else if(T(this._config.chunk)&&!g){if(this._config.chunk(y,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}y=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(y.data),this._completeResults.errors=this._completeResults.errors.concat(y.errors),this._completeResults.meta=y.meta),!this._completed&&q&&T(this._config.complete)&&(!y||!y.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!q&&(!y||!y.meta.paused)&&this._nextChunk(),y},this._sendError=function(f){T(this._config.error)?this._config.error(f):s&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:f,finished:!1})};function l(f){var g=ne(f);g.chunkSize=parseInt(g.chunkSize),!f.step&&!f.chunk&&(g.chunkSize=null),this._handle=new M(g),this._handle.streamer=this,this._config=g}}function h(c){c=c||{},c.chunkSize||(c.chunkSize=o.RemoteChunkSize),p.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=j(this._chunkLoaded,this),l.onerror=j(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 $=this._start+this._config.chunkSize-1;l.setRequestHeader("Range","bytes="+this._start+"-"+$)}try{l.send(this._config.downloadRequestBody)}catch(v){this._chunkError(v.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(p.prototype),h.prototype.constructor=h;function _(c){c=c||{},c.chunkSize||(c.chunkSize=o.LocalChunkSize),p.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=j(this._chunkLoaded,this),l.onerror=j(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 $=Math.min(this._start+this._config.chunkSize,this._input.size);w=f.call(w,this._start,$)}var v=l.readAsText(w,this._config.encoding);g||this._chunkLoaded({target:{result:v}})},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)}}_.prototype=Object.create(p.prototype),_.prototype.constructor=_;function S(c){c=c||{},p.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||{},p.call(this,c);var l=[],f=!0,g=!1;this.pause=function(){p.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){p.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=j(function(w){try{l.push(typeof w=="string"?w:w.toString(this._config.encoding)),f&&(f=!1,this._checkIsFinished(),this.parseChunk(l.shift()))}catch($){this._streamError($)}},this),this._streamError=j(function(w){this._streamCleanUp(),this._sendError(w)},this),this._streamEnd=j(function(){this._streamCleanUp(),g=!0,this._streamData("")},this),this._streamCleanUp=j(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}x.prototype=Object.create(p.prototype),x.prototype.constructor=x;function k(c){var l=wa("stream").Duplex,f=ne(c),g=!0,w=!1,$=[],v=null;this._onCsvData=function(y){var D=y.data;!v.push(D)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){v.push(null)},f.step=j(this._onCsvData,this),f.complete=j(this._onCsvComplete,this),p.call(this,f),this._nextChunk=function(){w&&$.length===1&&(this._finished=!0),$.length?$.shift()():g=!0},this._addToParseQueue=function(y,D){$.push(j(function(){if(this.parseChunk(typeof y=="string"?y:y.toString(f.encoding)),T(D))return D()},this)),g&&(g=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(y,D,q){this._addToParseQueue(y,q)},this._onWriteComplete=function(){w=!0,this._addToParseQueue("")},this.getStream=function(){return v},v=new l({readableObjectMode:!0,decodeStrings:!1,read:j(this._onRead,this),write:j(this._onWrite,this)}),v.once("finish",j(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(k.prototype=Object.create(p.prototype),k.prototype.constructor=k);function M(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)))$/,$=this,v=0,y=0,D,q,ee=!1,F=!1,le,P=[],L={data:[],errors:[],meta:{}};if(T(c.step)){var Me=c.step;c.step=function(E){if(L=E,Y())Z();else{if(Z(),L.data.length===0)return;v+=E.data.length,c.preview&&v>c.preview?q.abort():(L.data=L.data[0],Me(L,$))}}}this.parse=function(E,A,B){var z=c.quoteChar||'"';if(c.newline||(c.newline=this.guessLineEndings(E,z)),le=!1,c.delimiter)T(c.delimiter)&&(c.delimiter=c.delimiter(E),L.meta.delimiter=c.delimiter);else{var b=Se(E,c.newline,c.skipEmptyLines,c.comments,c.delimitersToGuess);b.successful?c.delimiter=b.bestDelimiter:(le=!0,c.delimiter=o.DefaultDelimiter),L.meta.delimiter=c.delimiter}var H=ne(c);return c.preview&&c.header&&H.preview++,D=E,q=new N(H),L=q.parse(D,A,B),Z(),ee?{meta:{paused:!0}}:L||{meta:{paused:!1}}},this.paused=function(){return ee},this.pause=function(){ee=!0,q.abort(),D=T(c.chunk)?"":D.substring(q.getCharIndex())},this.resume=function(){$.streamer._halted?(ee=!1,$.streamer.parseChunk(D,!0)):setTimeout($.resume,3)},this.aborted=function(){return F},this.abort=function(){F=!0,q.abort(),L.meta.aborted=!0,T(c.complete)&&c.complete(L),D=""},this.guessLineEndings=function(E,A){E=E.substring(0,1024*1024);var B=new RegExp(R(A)+"([^]*?)"+R(A),"gm");E=E.replace(B,"");var z=E.split("\r"),b=E.split(`
5
+ `),H=b.length>1&&b[0].length<z[0].length;if(z.length===1||H)return`
6
+ `;for(var oe=0,te=0;te<z.length;te++)z[te][0]===`
7
+ `&&oe++;return oe>=z.length/2?`\r
8
+ `:"\r"};function V(E){return c.skipEmptyLines==="greedy"?E.join("").trim()==="":E.length===1&&E[0].length===0}function J(E){if(g.test(E)){var A=parseFloat(E);if(A>f&&A<l)return!0}return!1}function Z(){return L&&le&&(_e("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&(L.data=L.data.filter(function(E){return!V(E)})),Y()&&me(),U()}function Y(){return c.header&&P.length===0}function me(){if(!L)return;function E(B,z){T(c.transformHeader)&&(B=c.transformHeader(B,z)),P.push(B)}if(Array.isArray(L.data[0])){for(var A=0;Y()&&A<L.data.length;A++)L.data[A].forEach(E);L.data.splice(0,1)}else L.data.forEach(E)}function se(E){return c.dynamicTypingFunction&&c.dynamicTyping[E]===void 0&&(c.dynamicTyping[E]=c.dynamicTypingFunction(E)),(c.dynamicTyping[E]||c.dynamicTyping)===!0}function pe(E,A){return se(E)?A==="true"||A==="TRUE"?!0:A==="false"||A==="FALSE"?!1:J(A)?parseFloat(A):w.test(A)?new Date(A):A===""?null:A:A}function U(){if(!L||!c.header&&!c.dynamicTyping&&!c.transform)return L;function E(B,z){var b=c.header?{}:[],H;for(H=0;H<B.length;H++){var oe=H,te=B[H];c.header&&(oe=H>=P.length?"__parsed_extra":P[H]),c.transform&&(te=c.transform(te,oe)),te=pe(oe,te),oe==="__parsed_extra"?(b[oe]=b[oe]||[],b[oe].push(te)):b[oe]=te}return c.header&&(H>P.length?_e("FieldMismatch","TooManyFields","Too many fields: expected "+P.length+" fields but parsed "+H,y+z):H<P.length&&_e("FieldMismatch","TooFewFields","Too few fields: expected "+P.length+" fields but parsed "+H,y+z)),b}var A=1;return!L.data.length||Array.isArray(L.data[0])?(L.data=L.data.map(E),A=L.data.length):L.data=E(L.data,0),c.header&&L.meta&&(L.meta.fields=P),y+=A,L}function Se(E,A,B,z,b){var H,oe,te,Oe;b=b||[","," ","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var ke=0;ke<b.length;ke++){var qe=b[ke],$e=0,Ee=0,ce=0;te=void 0;for(var ye=new N({comments:z,delimiter:qe,newline:A,preview:10}).parse(E),ie=0;ie<ye.data.length;ie++){if(B&&V(ye.data[ie])){ce++;continue}var ue=ye.data[ie].length;if(Ee+=ue,typeof te>"u"){te=ue;continue}else ue>0&&($e+=Math.abs(ue-te),te=ue)}ye.data.length>0&&(Ee/=ye.data.length-ce),(typeof oe>"u"||$e<=oe)&&(typeof Oe>"u"||Ee>Oe)&&Ee>1.99&&(oe=$e,H=qe,Oe=Ee)}return c.delimiter=H,{successful:!!H,bestDelimiter:H}}function _e(E,A,B,z){var b={type:E,code:A,message:B};z!==void 0&&(b.row=z),L.errors.push(b)}}function R(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(c){c=c||{};var l=c.delimiter,f=c.newline,g=c.comments,w=c.step,$=c.preview,v=c.fastMode,y,D=null,q=!1;c.quoteChar===void 0||c.quoteChar===null?y='"':y=c.quoteChar;var ee=y;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),f!==`
9
+ `&&f!=="\r"&&f!==`\r
10
+ `&&(f=`
11
+ `);var F=0,le=!1;this.parse=function(P,L,Me){if(typeof P!="string")throw new Error("Input must be a string");var V=P.length,J=l.length,Z=f.length,Y=g.length,me=T(w);F=0;var se=[],pe=[],U=[],Se=0;if(!P)return ce();if(v||v!==!1&&P.indexOf(y)===-1){for(var _e=P.split(f),E=0;E<_e.length;E++){if(U=_e[E],F+=U.length,E!==_e.length-1)F+=f.length;else if(Me)return ce();if(!(g&&U.substring(0,Y)===g)){if(me){if(se=[],ke(U.split(l)),ye(),le)return ce()}else ke(U.split(l));if($&&E>=$)return se=se.slice(0,$),ce(!0)}}return ce()}for(var A=P.indexOf(l,F),B=P.indexOf(f,F),z=new RegExp(R(ee)+R(y),"g"),b=P.indexOf(y,F);;){if(P[F]===y){for(b=F,F++;;){if(b=P.indexOf(y,b+1),b===-1)return Me||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),$e();if(b===V-1){var H=P.substring(F,b).replace(z,y);return $e(H)}if(y===ee&&P[b+1]===ee){b++;continue}if(!(y!==ee&&b!==0&&P[b-1]===ee)){A!==-1&&A<b+1&&(A=P.indexOf(l,b+1)),B!==-1&&B<b+1&&(B=P.indexOf(f,b+1));var oe=B===-1?A:Math.min(A,B),te=qe(oe);if(P.substr(b+1+te,J)===l){U.push(P.substring(F,b).replace(z,y)),F=b+1+te+J,P[b+1+te+J]!==y&&(b=P.indexOf(y,F)),A=P.indexOf(l,F),B=P.indexOf(f,F);break}var Oe=qe(B);if(P.substring(b+1+Oe,b+1+Oe+Z)===f){if(U.push(P.substring(F,b).replace(z,y)),Ee(b+1+Oe+Z),A=P.indexOf(l,F),b=P.indexOf(y,F),me&&(ye(),le))return ce();if($&&se.length>=$)return ce(!0);break}pe.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:se.length,index:F}),b++}}continue}if(g&&U.length===0&&P.substring(F,F+Y)===g){if(B===-1)return ce();F=B+Z,B=P.indexOf(f,F),A=P.indexOf(l,F);continue}if(A!==-1&&(A<B||B===-1)){U.push(P.substring(F,A)),F=A+J,A=P.indexOf(l,F);continue}if(B!==-1){if(U.push(P.substring(F,B)),Ee(B+Z),me&&(ye(),le))return ce();if($&&se.length>=$)return ce(!0);continue}break}return $e();function ke(ie){se.push(ie),Se=F}function qe(ie){var ue=0;if(ie!==-1){var Pe=P.substring(b+1,ie);Pe&&Pe.trim()===""&&(ue=Pe.length)}return ue}function $e(ie){return Me||(typeof ie>"u"&&(ie=P.substring(F)),U.push(ie),F=V,ke(U),me&&ye()),ce()}function Ee(ie){F=ie,ke(U),U=[],B=P.indexOf(f,F)}function ce(ie){if(c.header&&!L&&se.length&&!q){let ue=se[0],Pe=Object.create(null),At=new Set(ue),Mr=!1;for(let De=0;De<ue.length;De++){let ve=ue[De];if(T(c.transformHeader)&&(ve=c.transformHeader(ve,De)),!Pe[ve])Pe[ve]=1,ue[De]=ve;else{let ze,Or=Pe[ve];do ze=`${ve}_${Or}`,Or++;while(At.has(ze));At.add(ze),ue[De]=ze,Pe[ve]++,Mr=!0,D===null&&(D={}),D[ze]=ve}At.add(ve)}Mr&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:f,aborted:le,truncated:!!ie,cursor:Se+(L||0),renamedHeaders:D}}}function ye(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function I(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=O,l.id=i++,a[l.id]=l,l}function O(c){var l=c.data,f=a[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,W(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},$={abort:w,pause:Q,resume:Q};if(T(f.userStep)){for(var v=0;v<l.results.data.length&&(f.userStep({data:l.results.data[v],errors:l.results.errors,meta:l.results.meta},$),!g);v++);delete l.results}else T(f.userChunk)&&(f.userChunk(l.results,$,l.file),delete l.results)}l.finished&&!g&&W(l.workerId,l.results)}function W(c,l){var f=a[c];T(f.userComplete)&&f.userComplete(l),f.terminate(),delete a[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 f=o.parse(l.input,l.config);f&&t.postMessage({workerId:o.WORKER_ID,results:f,finished:!0})}}function ne(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var f in c)l[f]=ne(c[f]);return l}function j(c,l){return function(){c.apply(l,arguments)}}function T(c){return typeof c=="function"}return o})});import{parseArgs as yo}from"util";import ia from"express";import fo from"cors";import{McpServer as po}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as _o}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as go}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ca}from"@modelcontextprotocol/sdk/types.js";var Fr={name:"@vulcan-energy/mcp-helper",version:"0.3.0",description:"Vulcan Home Energy Model tools for AI assistants over MCP (Claude Code, Codex, Claude Desktop, Cursor). Runs locally; Free tools need no account.",repository:{type:"git",url:"git+https://github.com/baziyer/rust-hem-runner.git",directory:"vulcan-mcp-server"},type:"module",main:"./dist/server.js",types:"./dist/server.d.ts",bin:{"vulcan-mcp-helper":"dist/bin/vulcan-mcp-helper.js"},scripts:{build:"tsup --config tsup.config.ts",dev:"tsx watch bin/vulcan-mcp-helper.ts",start:"node dist/bin/vulcan-mcp-helper.js",prepublishOnly:"npm run build && npm run clean",clean:"echo 'Package is ready for publishing'",test:"node --import tsx --test src/engine/requestAuth.test.ts src/engine/licenseToken.test.ts src/engine/config.test.ts src/tools/registry.test.ts src/tools/signIn.test.ts"},keywords:["claude","codex","energy-modeling","future-homes-standard","hem","home-energy-model","mcp","model-context-protocol","vulcan"],author:"",license:"UNLICENSED",dependencies:{"@modelcontextprotocol/sdk":"^1.32.2","@vulcan-energy/community-cli":"^0.1.0",cors:"^2.8.5",express:"^4.18.2",jose:"^6.1.2","playwright-core":"^1.59.1",zod:"^4.1.12"},devDependencies:{"@types/cors":"^2.8.17","@types/express":"^4.17.21","@types/node":"^20.10.0",tsup:"^8.5.0",tsx:"^4.7.0",typescript:"^5.3.3"},engines:{node:">=20.0.0"},files:["dist/","wasm/","schemas/","package.json","README.md","LICENSE","THIRD_PARTY_NOTICES.md"]};import Br from"fs/promises";import Xe from"path";var Nr=Object.freeze(["mcp","analyst"]);function Rt(e){return typeof e=="string"&&Nr.includes(e)}var ot="https://usevulcan.app",jt="vulcan-local-tools",it=1,Tt=10080*60,Mt=300,K=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var Ir=Object.freeze([`-----BEGIN PUBLIC KEY-----
12
12
  MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
13
- -----END PUBLIC KEY-----`]);import{compactVerify as On,importSPKI as Fn}from"jose";var sr="EdDSA";async function ht(e,t){let r=e.trim();if(!r)throw new z("empty","Vulcan access token is empty.");let n=t.publicKeys??ar,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),i=await $n(r,n),o=Nn(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-pt)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 $n(e,t){for(let r of t)try{let n=await Fn(r,sr),{payload:a}=await On(e,n,{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 Nn(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 r=t,n=Je(r,"iss"),a=Je(r,"aud"),s=Je(r,"sub"),i=Je(r,"org"),o=Je(r,"jti"),m=_t(r,"iat"),u=_t(r,"exp"),d=_t(r,"entitlement_schema_version");if(!Array.isArray(r.capabilities))throw new z("malformed","Vulcan access token must include a capabilities array.");let f=[];for(let h of r.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:n,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 r=e[t];if(typeof r!="string"||r.length===0)throw new z("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return r}function _t(e,t){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new z("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return r}var Bn="mcp",Ln=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 r;try{r=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 n;try{n=JSON.parse(r)}catch(u){let d=u;throw new Error(`Invalid JSON in config file: ${d.message}`)}if(!n.workspace)throw new Error("Config file missing required field: workspace");if(!n.license_token||typeof n.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),n.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(n.license_token),o=Math.floor(Date.now()/1e3),m=i.exp-o;if(m<Ln){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:n.license_token,configPath:t}}async function yt(e,t={}){try{let{claims:r}=await ht(e,{capability:Bn,now:t.now,publicKeys:t.publicKeys});return{payload:r}}catch(r){throw new Error(In(r))}}function In(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 Dn}from"crypto";function Wn(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 r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&Dn(r,n)}async function ir(e,t,r=yt){let n=Wn(e);if(!Jn(n,t))throw new Error("MCP request Bearer token is invalid");await r(n)}import{z as y}from"zod";import Vn from"fs/promises";import Un from"path";function cr(e,t={}){let r=[],n=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&r.push("Config must have at least one scenario");for(let[s,i]of Object.entries(e)){if(!i||typeof i!="object"){r.push(`Scenario '${s}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&r.push(`Scenario '${s}' must have exactly one base_json (found ${o.base_json.length})`):r.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&&r.push(`Scenario '${s}' must have at most one weather_file (found ${d.length})`):r.push(`Scenario '${s}' weather_file/weather_files must be an array`)}u&&!Array.isArray(o.external_conditions)&&r.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!m&&!u&&r.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),m&&u&&n.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)||r.push(`Scenario '${s}': '${d}' must be an array`)}return{valid:r.length===0,errors:r,warnings:n}}function lr(e){try{if(!e||typeof e!="object")return null;let t=0;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let n=r,a=1;for(let s of Object.values(n))Array.isArray(s)&&(a*=s.length);t+=a}return t}catch{return null}}async function ur(e,t){let r=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:n};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=Un.join(e,"input","batch_parameters",o,`${String(u)}.json`);try{await Vn.access(d)}catch{n.push({scenario:a,category:o,parameter:String(u),path:d}),r.push(`Scenario '${a}': Parameter '${String(u)}' in category '${o}' not found at ${d}`)}}}return{valid:r.length===0,errors:r,missingFiles:n}}import{readFile as jr}from"fs/promises";import{join as Tr}from"path";var qn=Mn(dr(),1),Hn=Object.defineProperty,zn=Object.getOwnPropertyNames,Gn=(e,t)=>function(){return e&&(t=(0,e[zn(e)[0]])(e=0)),t},Kn=(e,t)=>{for(var r in t)Hn(e,r,{get:t[r],enumerable:!0})},Xn={};Kn(Xn,{configureWasm:()=>Yn,getRuntimeApiUrl:()=>sa,getRuntimeWasmVariant:()=>ra,getVersionedWasmAssetPaths:()=>St,getVersionedWasmJsUrl:()=>gr,getWasmAssetPaths:()=>hr,getWasmBaseUrl:()=>Ct,getWasmBinaryUrl:()=>yr,getWasmJsUrl:()=>br,getWasmRayonThreadCount:()=>fr,getWasmVariant:()=>_r,getWasmVersionInfo:()=>Xe,getWasmVersionJsonUrl:()=>pr,getWasmWasmUrl:()=>Cr,initializeWasmRayonThreadPool:()=>ta});function Yn(e={}){e.baseUrl&&(wr=Zn(e.baseUrl)),typeof e.preferHashed=="boolean"&&(vr=e.preferHashed)}function mr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Zn(e){return e.replace(/\/+$/,"")||"/"}function Qn(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function ea(){let e=mr();if(e){if(Qn(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Ct(){return wr||ea()}function fr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function ta(e){let t=e,r=Ve.get(t);if(r)return r;let n=e.initialize_rayon_thread_pool;if(typeof n!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>n(fr())).then(()=>{});return Ve.set(t,a),a.catch(()=>{Ve.get(t)===a&&Ve.delete(t)}),a}function pr(){return`${Ct()}/wasm_version.json`}async function Xe(){try{let e=await fetch(pr(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function _r(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 ra(){return _r(await Xe())}function na(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function aa(e){let t=na(),n=!!((vr??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(n?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(n?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function hr(e){let t=Ct(),r=e===void 0?await Xe():e,{jsFilename:n,wasmFilename:a}=aa(r);return{jsPath:`${t}/${n}`,wasmPath:`${t}/${a}`}}async function St(){let e=await Xe(),{jsPath:t,wasmPath:r}=await hr(e),n=e?.build_id||e?.sha256||e?.timestamp;if(!n)return{jsPath:t,wasmPath:r,versionInfo:e};let a=`v=${encodeURIComponent(String(n))}`;return{jsPath:`${t}?${a}`,wasmPath:`${r}?${a}`,versionInfo:e}}async function gr(){let{jsPath:e}=await St();return e}async function yr(){let{wasmPath:e}=await St();return e}function sa(e){let t=mr();return t?new URL(e,t.origin).toString():e}var Ve,wr,vr,br,Cr,Sr=Gn({"src/wasmPath.ts"(){Ve=new WeakMap,br=gr,Cr=yr}});async function kr(e,t){let r=`${t}/target-run.json`;if(!await e.fileExists(r))return null;let n=JSON.parse(await e.readFile(r));if(n?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(n.files)||!n.files.length||n.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(n.files)}async function Er(e,t){let r=await kr(e,t),n=await e.listFiles(t,{withKind:!0});return r===null?n:n.filter(a=>r.has(typeof a=="string"?a:a.name))}async function Pr(e,t){let r=t.lastIndexOf("/"),n=await kr(e,t.slice(0,r));return(n===null||n.has(t.slice(r+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 r=(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.`},n=[...t.values()],a=n.map(i=>n.filter(o=>o!==i).map(o=>r(i,o))),s=n.find((i,o)=>a[o].every(m=>typeof m=="number"&&m>0));return s||!n.length?s:{unknown:a.flat().find(i=>typeof i=="string")}}function Et(e,t){let r=e.map(n=>typeof n=="string"?n:n.name).filter(n=>n.endsWith(".csv")?t==="results_heat_source_wet"?n.includes("__results_heat_source_wet__"):t==="results_emitters"?n.includes("__results_emitters_"):n.endsWith(`__${t}.csv`):!1).sort((n,a)=>n.localeCompare(a));return r.find(n=>/(?:^|__)FHS__/.test(n))??r.find(n=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(n))}Sr();function oa(e){return e.startsWith("__")}function Ye(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,r])=>!oa(t)&&!!r&&typeof r=="object"&&!Array.isArray(r)).map(([t,r])=>({name:t,value:r}))}function ia(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function ca(e){let t=ia(e);return t.length===0?1:t.reduce((r,n)=>r*n.length,1)}function Ze(e,t){let r=[];for(let n of Ye(t)){let a=ca(n.value);for(let s=0;s<a;s+=1)r.push(`result_${e}_${n.name}_${s}`)}return r}function Pt(e){return Math.floor(e/1e3)}function la(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function ua(e){return e==="failure_context.json"}function xr(e){return la(e)||ua(e)}function da(){try{let r=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(r&&bt(r))return r;let n=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(n&&bt(n))return n;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 As=da();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",ma="batch_parameters/base_json/defaults_template.json",fa="defaults/defaults_template.json";function pa(e){let r=e.split(`
14
- `).slice(0,50).find(s=>/^DefaultsPath,/i.test(s.trim()));return r&&(Qe(r)[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 ha(e){let t=e.trim();if(!t)return[];if(!_a(t))return[t];let r=t.replace(/\\/g,"/"),n=r.lastIndexOf(ma);return[n>=0?`${r.slice(0,n)}${fa}`:At,t]}async function Rr(e){let t=(e.explicitDefaultsPath??"").trim(),r=t||pa(e.csvContent);if(r){let n=ha(r),a;for(let i of n){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 "${r}". Conversion was aborted instead of silently substituting the standard defaults template. ${s}`)}for(let n of[At,Rt,"defaults_template.json"]){let a=xt.join(e.workspace,n);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=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let s=e[a];n?s==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=s:s==='"'?n=!0:s===","?(t.push(r),r=""):r+=s}return t.push(r),t}function jt(e,t=!1){let r="",n=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)){r=o[0],a=void 0;continue}if(r==="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"&&(n=Number(o[1]));continue}if(r!=="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(n)||n<1||n>3)return`Unsupported or invalid VulcanCsvVersion '${n}'; 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=n<3&&typeof o?.u_value_interpreted_value=="number"&&o.u_value_interpreted_value!==u,f=n>=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,r;for(let n of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!n.trim())continue;let a=Qe(n).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(r)throw new Error("CSV contains conflicting TargetBundleId metadata");r=a[1]}}return r}async function et(e,t){let r=new Set;for(let{value:n}of Ye(t))if(Array.isArray(n.base_json))for(let a of n.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");r.add(await ga(e,a))}if(r.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...r][0]}async function ga(e,t){try{let r=Be(await jr(Tr(e,"input/base_models",`${t}.csv`),"utf8"));if(r)return r}catch(r){if(r.code!=="ENOENT")throw r}try{let r=JSON.parse(await jr(Tr(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof r.targetBundleId!="string"||!r.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return r.targetBundleId}catch(r){if(r.code==="ENOENT")return;throw r}}async function Tt(e,t){if(Ye(t).some(({value:n})=>Array.isArray(n.heating_profiles)&&n.heating_profiles.length))return"Heating profiles require a saved, pinned HEM target batch; the legacy runner cannot apply post-FHS controls.";let r;try{r=await et(e,t)}catch(n){return n.message}if(r)return`This batch's base models pin HEM target '${r}'. 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 ya}from"child_process";import{resolve as wa}from"path";import{access as va}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 r of["./hem-target-runtime/browser-adapter.mjs","../hem-target-runtime/browser-adapter.mjs"]){let n=new URL(r,import.meta.url);try{await va(Mr(n))}catch{continue}let a=t?{...e,manifestPath:wa(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{...e};if(e.operation==="batch")return ba(Mr(n),a);let{runTargetBrowser:s}=await import(n.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 ba(e,t){return new Promise((r,n)=>{let a=ya(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),s=setTimeout(()=>{a.kill(),n(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",i=>{clearTimeout(s),n(i)}),a.once("exit",i=>{clearTimeout(s),n(new Error(`Target batch stopped before startup (${i})`))}),a.once("message",i=>{clearTimeout(s),i.started?(a.unref(),r({status:"started"})):(a.kill(),n(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 Ot(e,t,r={},n={}){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=Sa(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 _={scenario_1:d},C=cr(_,{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(_);if(w===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let S=r.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=_;if(h){let B=await(n.runTarget??Ue)({workspace:e,operation:"snapshot",config:_,targetBundleId:f,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});T={..._,__hem:B}}else{let B=await ur(e,_);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:_}}async function rt(e,t,r){let{config_name:n,job_id:a}=t;if(!n)throw new Error("config_name is required");let s=a||r.generateJobId?.()||`mcp_${Ca()}`,i=n.endsWith(".json")?n:`${n}.json`,o=G.join(e,"input","batch_configs",i),m;try{m=await ne.readFile(o,"utf8")}catch(h){let _=h;throw _.code==="ENOENT"?new Error(`Batch config '${n}' not found at ${o}`):new Error(`Failed to read config file: ${_.message}`)}let u=JSON.parse(m);if(u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let h=u.__hem;if(!h){let _="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:_,error:_}}try{return await(r.runTarget??Ue)({workspace:e,operation:"batch",config:u,targetBundleId:h.targetBundleId,configName:n.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:n,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(_){let C=_.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 r.processBatchConfig(m,e,f,n.replace(/\.json$/,""),s),_=JSON.parse(h);return _.error?{job_id:s,status:"error",message:`Batch execution failed: ${_.error}`,error:_.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:n,output_dir:f}}catch(h){let _=h;return{job_id:s,status:"error",message:`Failed to start batch execution: ${_.message}`,error:_.message}}}async function Ft(e,t={}){let{job_id:r}=t,n=t.config_name?.replace(/\.json$/,""),a=G.join(e,"output"),s;if(n&&!r){if(s=await tt(e,n),!s.jobId){let F=s.error!==void 0?"error":s.unknown?"unknown":"not_run",U=s.error??s.unknown??s.changed??`Batch config '${n}' 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:n,status:F,progress:0,passes:0,failures:0,output_dir:a,error:U,...$r(s.warnings)}}r=s.jobId}if(!r)throw new Error("Either job_id or config_name is required");if(/[\\/]/.test(r)||r==="."||r==="..")throw new Error(`Invalid job_id '${r}': a job id is a plain name, as vulcan_run_batch returns it`);let i=s?.warnings??[],o=G.join(a,`progress_${r}.json`),m=G.join(a,`sim_progress_${r}.json`),u=await Me(o,i),d=await Me(m,i),f=await Br(a,r,i);if(!s&&f.config){let F=await tt(e,f.config);i.push(...F.warnings),F.jobId===r&&(s=F),n??=f.config}let h=f.records>0||typeof u?.targetBundleId=="string",_="queued",C=0,w=0,S=0,T=null;if(u?(Nr(u.status)?_=u.status:typeof u.percentage=="number"?(C=u.percentage,_=C>=100?"completed":"running"):typeof u.current_combination=="number"&&typeof u.total_combinations=="number"&&(C=Math.round(u.current_combination/u.total_combinations*100),_=C>=100?"completed":"running"),typeof u.percentage=="number"&&(C=u.percentage),typeof u.error=="string"&&(T=u.error,_="error")):f.records&&(f.stopped?(_="error",T=f.stopped):s?.expected!==void 0&&f.passes===s.expected?(_="completed",C=100):(_="unknown",T=`Job ${r} 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,_="error"),d&&!h&&(Nr(d.status)&&(_=d.status),typeof d.passes=="number"&&(w=d.passes),typeof d.failures=="number"&&(S=d.failures),typeof d.error=="string"&&(T=d.error,_="error")),!u&&!d&&!f.records){let F=G.join(a,r);try{let U=await ne.readdir(F);_=U.length>0?"completed":"queued",C=U.length>0?100:0}catch(U){throw U.code!=="ENOENT"?U:new Error(`Job ${r} does not exist in this workspace: ${a} holds no progress file, run record or folder for it.`)}}return{job_id:r,...n?{config_name:n}:{},status:_,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 r=G.join(e,"output"),n=[],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(r).catch(Mt)??[]){if(!R.startsWith("progress_")||!R.endsWith(".json"))continue;let j=await Me(G.join(r,R),n),c=R.slice(9,-5);j?.config_name===t&&a.push({run:c,jobId:c,startedAt:i(j),fileTime:await s(G.join(r,R))})}let o=G.join(e,"input","batch_configs",`${t}.json`),m=await Me(o,n),u=m?Ze(t,m):[],d,f=[];for(let R of u){let j=G.join(r,R),c=await ne.readdir(j,{withFileTypes:!0}).catch(Mt);if(!c)continue;if(!c.some(p=>p.name==="target-run.json")){let p=c.filter(g=>g.isFile()&&xr(g.name)).map(g=>G.join(j,g.name));if(!p.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(p.map(s)))});continue}let l=R.slice(`result_${t}_`.length);for(let p of c.filter(g=>g.isDirectory()))for(let g of await ne.readdir(G.join(j,p.name),{withFileTypes:!0})){if(!g.isDirectory())continue;let v=G.join(j,p.name,g.name,"target-run.json"),M=n.length,k=await Me(v,n);if(!k){n.length>M&&f.push({warning:n.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(r,`batch_status_${t}.json`),_=await Me(h,n),C=_?.status==="error"||_?.status==="running",w=C?i(_):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:n};if(!a.length)return{legacyCurrent:!0,expected:T,warnings:n};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:n};let J=kt(a);if("unknown"in J)return{unknown:J.unknown,expected:T,warnings:n};if(J.run===Or)return{unknown:d,legacyCurrent:!0,expected:T,warnings:n};let B=_?.error_message,X=_?.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:n};if(_?.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:n};if(w!==void 0)return{error:X,expected:T,warnings:n};let Q=kt(a.filter(R=>R.jobId)),Ce=Q&&"run"in Q?Q.run:void 0;return{...Ce&&(await Br(r,Ce,n)).stopped?{jobId:Ce}:{},error:X,expected:T,warnings:n}}var Or="legacy engine results",Fr="the app's run status";async function Br(e,t,r){let n={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"),r);if(!i)continue;n.records+=1;let o=`_${String(i.name)}`;a.name.endsWith(o)&&(n.config??=a.name.slice(7,-o.length)),i.status==="complete"?n.passes+=1:i.status==="failed"&&(n.failures+=1),(i.status==="failed"||i.status==="cancelled")&&(n.stopped??=`Scenario ${String(i.name)} ${i.status}${typeof i.error=="string"?`: ${i.error}`:""}`)}return n}async function Me(e,t){let r;try{r=await ne.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}try{return JSON.parse(r)}catch(n){t.push(`Skipped ${e}: ${n.message}`);return}}function Mt(e){if(e.code!=="ENOENT")throw e}function $r(e){return e.length?{warnings:e}:{}}function Sa(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Array.isArray(r)?r.map(String):[String(r)]]))}function Nr(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import uo from"crypto";import ve from"fs/promises";import K from"path";import qe from"fs";import xe from"path";import{fileURLToPath as ka}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 n=xe.dirname(t);if(n===t)break;t=n}let r=xe.dirname(ka(import.meta.url));return xe.resolve(r,"..","..","..")}import Lr from"fs/promises";import at from"path";function Ea(e){let t=!1,r=null;for(let n of e.split(`
15
- `).slice(0,80)){let a=n.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"&&(r="ecaas_input_fhs"),s==="input_fhs"&&(r="input_fhs"),s==="input_core"&&(r="input_core")}}return r||(t?"input_fhs":"input_core")}async function Dr(e){let t=Ea(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 r=Pa({mode:t,repoRoot:e.repoRoot,workspace:e.workspace}),n=[];for(let a of r){n.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: ${n.join(", ")}`)}function Pa(e){let t=[];if(e.repoRoot&&t.push(at.join(e.repoRoot,...xa(e.mode))),e.workspace){let r=Aa(e.mode);t.push(...r.map(n=>at.join(e.workspace,...n)))}return[...new Set(t)]}function xa(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 Aa(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=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let s=e[a];n?s==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=s:s==='"'?n=!0:s===","?(t.push(r),r=""):r+=s}return t.push(r),t}import we from"fs";import pe from"path";import{pathToFileURL as Ra}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;ja();let r=pe.join(e,"wasm_wrapper.js"),n=pe.join(e,"wasm_wrapper_bg.wasm"),a=pe.join(e,"wasm_version.json");if(!we.existsSync(r)||!we.existsSync(n))throw new Error(`Browser WASM artifact not found in ${e}`);let s=await import(Ra(r).href);if(typeof s.initSync!="function")throw new Error("WASM module is missing initSync");if(s.initSync({module:we.readFileSync(n)}),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:r,wasm_path:n,wasm_version:Oa(a),build_stamp:ze(s.build_stamp),build_info:Fa(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=pe.resolve(e),Ur=t.confineToWorkspace===!0}function ja(){Ta(),Ma();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=(r,n)=>{let a=He(r);try{return we.mkdirSync(pe.dirname(a),{recursive:!0}),we.writeFileSync(a,n),!0}catch(s){return console.error(`[FS Bridge] write_file failed for ${a}:`,s.message),!1}},e.read_file=r=>{let n=He(r);return we.readFileSync(n,"utf8")},e.file_exists=r=>{let n=He(r);return we.existsSync(n)},e.create_dir_all=r=>{let n=He(r);try{return we.mkdirSync(n,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${n}:`,a.message),!1}},e.list_dir=r=>{let n=He(r);try{return we.readdirSync(n)}catch{return[]}}}function He(e){let t=pe.isAbsolute(e)?pe.resolve(e):pe.resolve($t,e);if(Ur){let r=pe.relative($t,t);if(r===".."||r.startsWith(`..${pe.sep}`)||pe.isAbsolute(r))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function Ta(){if(Jr)return;let e=console.error.bind(console);console.log=(...t)=>{let r=t[0];typeof r=="string"&&r.startsWith("[WASM]")||e(...t)},Jr=!0}var Vr=!1;function Ma(){if(Vr)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,r)=>{let n=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(n.startsWith("file:")&&n.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,r)}),Vr=!0}function Oa(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function ze(e){return typeof e!="function"?void 0:e()||void 0}function Fa(e){let t=ze(e);if(t)try{return JSON.parse(t)}catch{return t}}async function zr(e){let{workspace:t,csvContent:r,schemaJson:n,defaultsPath:a,deps:s}=e,i=jt(r);if(i)return{ok:!1,error:i};let o=await Rr({workspace:t,csvContent:r,explicitDefaultsPath:a}),m;try{m=await s.convertGeometryCsvToJson(r,n,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=$a(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:r,outputPath:n,schemaPath:a,defaultsPath:s,repoRoot:i,deps:o}=e,m=K.isAbsolute(r)?r:K.join(t,r),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=n?K.resolve(t,n):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}),_=await zr({workspace:t,csvContent:u,schemaJson:h.schemaJson,defaultsPath:s,deps:o});if(!_.ok||_.json===void 0||_.json===null)return{ok:!1,validation:_.validation,error:_.error||"WASM conversion returned invalid result",defaults_source:_.defaults_source,schema_source:h.source};let C=n?K.isAbsolute(n)?n:K.join(t,n):qr(t,m);await ve.mkdir(K.dirname(C),{recursive:!0});try{await ve.writeFile(C,JSON.stringify(_.json,null,2),"utf8")}catch(w){let S=w;return{ok:!1,validation:_.validation,error:`Failed to write JSON file: ${S.message}`,defaults_source:_.defaults_source,schema_source:h.source}}return{ok:!0,json_path:K.relative(t,C),validation:_.validation,defaults_source:_.defaults_source,schema_source:h.source}}function $a(e){try{return JSON.parse(e)}catch(t){return{ok:!1,error:`WASM returned invalid JSON: ${t.message}`}}}function qr(e,t){let r=K.basename(t,K.extname(t));return K.join(e,"input","batch_parameters","base_json",`${r}.json`)}async function Gr(e,t){let r=await ve.realpath(e),n=K.relative(K.resolve(e),t);if(!n||n===".."||n.startsWith(`..${K.sep}`)||K.isAbsolute(n))throw new Error("Target preparation output must stay within the workspace");let a=K.join(r,n),s=r;for(let i of K.relative(r,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,r){let n=await Gr(e,t),a=await ve.open(n,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await ve.realpath(n)!==n)throw new Error("Target preparation output is a symlink");return ve.open(n,"w")});try{await a.writeFile(r)}finally{await a.close()}}import _e from"fs/promises";import ie from"path";async function Bt(e,t={}){let{category:r}=t,n=ie.join(e,"input","batch_parameters"),a=await _e.readdir(n,{withFileTypes:!0}),s={};for(let i of a){if(!i.isDirectory())continue;let o=i.name;if(r&&o!==r)continue;let m=ie.join(n,o),u=await _e.readdir(m),d=[];for(let f of u){if(!f.endsWith(".json"))continue;let h=f.replace(/\.json$/,""),_=ie.join(m,f);try{let C=await _e.readFile(_,"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 ${_}: ${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:r,parameter_id:n}=t;if(!r)throw new Error("category is required");if(!n)throw new Error("parameter_id is required");let a=ie.join(e,"input","batch_parameters",r),s=ie.join(a,`${n}.json`),i=ie.join(a,`${n}.md`),o;try{let u=await _e.readFile(s,"utf8");o=JSON.parse(u)}catch(u){let d=u;throw d.code==="ENOENT"?new Error(`Parameter '${n}' not found in category '${r}'`):new Error(`Failed to read parameter JSON: ${d.message}`)}let m=null;try{m=await _e.readFile(i,"utf8")}catch(u){let d=u;d.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${d.message}`)}return{category:r,parameter_id:n,json:o,markdown:m,has_markdown:m!==null}}async function It(e,t,r){let{category:n,parameter_id:a,content:s,markdown_content:i}=t;if(!n)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=Na(s),[m,u,d]=await Promise.all([Ba(e),La(e),Ia(e,n)]),f=r.validateSnippetJs(n,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 _=ie.join(e,"input","batch_parameters",n);await _e.mkdir(_,{recursive:!0});let C=ie.join(_,`${a}.json`);await _e.writeFile(C,JSON.stringify(o,null,2),"utf8");let w=null;return i&&(w=ie.join(_,`${a}.md`),await _e.writeFile(w,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${n}'`,paths:{json:C,markdown:w}}}function Na(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}async function Ba(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 r of t)try{return JSON.parse(await _e.readFile(r,"utf8"))}catch{}throw new Error(`Schema file not found. Tried: ${t.join(", ")}`)}async function La(e){let t=ie.join(e,"input","batch_parameters","base_json","demo_hp_annual.json");try{return JSON.parse(await _e.readFile(t,"utf8"))}catch(r){let n=r;throw new Error(`Baseline model not found at ${t}: ${n.message}`)}}async function Ia(e,t){if(t!=="simplified_fabric")return null;let r=[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 n of r)try{return JSON.parse(await _e.readFile(n,"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 r=Oe.join(e,"output"),n=Yr(t.config_name),a=[],s=new Set,i=[],o=[];try{let m=Oe.join(r,n),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",`${n}.json`),"utf8"))}catch(S){if(S.code!=="ENOENT")throw S;if(!u)throw new Error(`Batch config '${n}' was not found in input/batch_configs.`)}for(let S of d===void 0?[]:Ze(n,d)){let T=Oe.join(r,S);if(!await Dt(T))continue;let F=S.slice(`result_${n}_`.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,n),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 '${n}' as failed after these scenarios finished: ${f.error}`);let _=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 '${n}' failed before it wrote any scenario: ${f.error}`:void 0),w=a.filter(S=>!_.includes(S));return{config_name:n,models:w,total_models:w.length,output_dir:r,...h?{latest_job_id:h}:{},..._.length?{earlier_run_models:_}:{},...C?{latest_run_unknown:C}:{},...i.length?{failed_models:i}:{},...o.length?{warnings:o}:{}}}catch(m){return{config_name:n,models:[],total_models:0,output_dir:r,error:`Failed to list models: ${m.message}`}}}async function Wt(e,t){let r=Yr(t.config_name),n=await Ie(e,{config_name:r}),a=n.models.find(d=>d.name===t.model_name)?.csv_path;if(!a)return{config_name:r,model_name:t.model_name,columns:[],total_columns:0,error:Jt(n,t.model_name)};let i=(await Fe.readFile(a,"utf8")).split(`
16
- `).filter(d=>d.trim());if(i.length<2)return{config_name:r,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:r,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:a}}function Jt(e,t){let r=e.earlier_run_models?.find(n=>n.name===t);if(r){let n=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 ${r.job_id?`job ${r.job_id}`:"the legacy engine"}, an earlier run. ${n}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,r,n){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)=>{r.has(u)||(r.add(u),t.push({name:u,csv_path:Oe.join(e,d),has_results:!0,...o?{job_id:o}:{}}))};if(n){let u=Et(s,"results");u&&m(n,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=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let s=e[a];n?s==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=s:s==='"'?n=!0:s===","?(t.push(r),r=""):r+=s}return t.push(r),t}var Da=new Set(["sumif","averageif","countif"]),Zr=new Set([">=","<=",">","<","="]);async function qt(e,t,r){let{config_name:n,model_names:a,metric_definitions:s,time_range:i,tariff_file_path:o,tariff_column_index:m}=t;if(!n)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=n.replace(/\.json$/,""),{encodedMetrics:d,metadata:f}=Va(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 _;if(o&&m!==void 0){let F=await Ua(o,m,e);_=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=Wa(J,F,n);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(p=>p===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=qa(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=r.calculateMetricsFromParsedData(JSON.stringify(B),JSON.stringify(d),i?JSON.stringify(i):void 0,_);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 Wa(e,t,r){let n=e.split(`
17
- `).filter(d=>d.trim());if(n.length<2)throw new Error("CSV must have at least headers and units rows");let a=(n[0]??"").split(",").map(d=>d.trim()),s=(n[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<n.length;d+=1){let f=(n[d]??"").split(",").map(C=>C.trim());if(f.length===0||f.length===1&&!f[0])continue;let h=f[0];if(!h)continue;let _=Number.parseInt(h,10);if(!(Number.isNaN(_)||_<0)){i.push(_);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:r.replace(/\.json$/,""),total_points:i.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function Ja(e){let t=(e.function||e.type||"sum").toString(),r=t.toLowerCase();if(r==="cost")return"cost";if(!Da.has(r))return r;let n=e.comparator||">=";if(!Zr.has(n))throw new Error(`Invalid comparator "${n}" 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`${r}${n}${e.threshold}`}function Va(e){let t=[],r=[];return e.forEach((n,a)=>{if(typeof n=="string"){let m=n.includes("|")?n:`${n}|sum`,[u=n,d="sum"]=m.split("|");t.push({name:m}),r.push({id:n,name:n,column:u,function:d,isCompliance:d.toLowerCase()==="compliance"});return}let s=n.column||(n.name?.includes("|")?n.name.split("|")[0]:n.name);if(!s)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(n)}`);let i=n.name?.includes("|")&&!n.function?n.name.split("|")[1]||"sum":Ja(n),o=`${s}|${i}`;t.push({name:o}),r.push({id:n.id||n.metric_id||`${s}_${i}`,name:n.name||n.id||s,column:s,function:i,comparator:n.comparator,threshold:n.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:r}}async function Ua(e,t,r){let n=ot.isAbsolute(e)?e:ot.resolve(r,e),s=(await Ut.readFile(n,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${n}. Error: ${o.message}`)})).split(`
18
- `).filter(o=>o.trim());if(s.length===0)throw new Error(`Tariff file is empty: ${n}`);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 qa(e,t,r){let n=[];return t.forEach((a,s)=>{let i=a.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${a.name}`);r[s]?.isCompliance||e.columns[i]||n.push(i)}),n}import{spawn as Ha}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),r=e.failOn??"critical",n=it.resolve(e.csvPath),a=await Yt(e,"npx",[...zt,"check",n,"--json",`--fail-on=${r}`]),s=Zt(a),i=Ht(s)?s:void 0;return{ok:a.exitCode===0&&i!==void 0,command:"geometry validate",csv_path:n,repo_root:t,fail_on:r,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),r=e.mode??"summary",n=it.resolve(e.csvPath),a=await Yt(e,"npx",[...zt,"thermal-bridges",n,Qr(r)]),s=r==="json"?Zt(a):void 0;return{ok:a.exitCode===0&&(r!=="json"||s!==void 0),command:"thermal-bridges auto",csv_path:n,repo_root:t,mode:r,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:r==="json"&&s===void 0?Qt(a):void 0}}async function Xt(e){let t=ct(e),r=e.mode??"summary",n=e.includeAuto===!0,a=it.resolve(e.csvPath),s=[...zt,"thermal-bridges",a,"--validate",...n?["--with-auto"]:[],Qr(r)],i=await Yt(e,"npx",s),o=r==="json"?Zt(i):void 0,m=Ht(o)?o:void 0;return{ok:i.exitCode===0&&(r!=="json"||m!==void 0),command:"thermal-bridges validate",csv_path:a,repo_root:t,include_auto:n,mode:r,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:r==="json"&&m===void 0?Qt(i):void 0}}function ct(e){return it.resolve(e.repoRoot??nt(e.csvPath))}async function Yt(e,t,r){let n=ct(e);return(e.runner??za)(t,r,{cwd:n})}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 za=(e,t,r)=>new Promise((n,a)=>{let s=Ha(e,[...t],{cwd:r.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)=>{n({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 Ga}from"url";var Ka=be.dirname(Ga(import.meta.url));function Xa(){let e=[],t=Ka;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 r=[];for(let s of e)r.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 n=[],a=new Set;for(let s of r){let i=be.join(s.directory,"wasm_wrapper.js");if(a.has(i))continue;a.add(i),n.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:
19
- `+n.map(s=>` - ${s}`).join(`
13
+ -----END PUBLIC KEY-----`]);import{compactVerify as Sa,importSPKI as ka}from"jose";var Lr="EdDSA";async function $t(e,t){let n=e.trim();if(!n)throw new K("empty","Vulcan access token is empty.");let r=t.publicKeys??Ir,s=t.now??(()=>new Date),a=Math.floor(s().getTime()/1e3),i=await Ea(n,r),o=Pa(i);if(o.iss!==ot)throw new K("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${ot}.`);if(o.aud!==jt)throw new K("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==it)throw new K("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${it}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new K("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>Tt)throw new K("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(a<o.iat-Mt)throw new K("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let d=a>o.exp;if(d&&!t.allowExpired)throw new K("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-a}}async function Ea(e,t){for(let n of t)try{let r=await ka(n,Lr),{payload:s}=await Sa(e,r,{algorithms:[Lr]});return s}catch{}throw new K("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 Pa(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new K("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new K("malformed","Vulcan access token payload is not an object.");let n=t,r=Ke(n,"iss"),s=Ke(n,"aud"),a=Ke(n,"sub"),i=Ke(n,"org"),o=Ke(n,"jti"),d=Ot(n,"iat"),u=Ot(n,"exp"),m=Ot(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new K("malformed","Vulcan access token must include a capabilities array.");let p=[];for(let h of n.capabilities){if(!Rt(h))throw new K("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(h)}.`);p.push(h)}if(p.length===0)throw new K("malformed","Vulcan access token grants no capabilities.");if(u<=d)throw new K("malformed","Vulcan access token expires no later than it was issued.");return{iss:r,aud:s,sub:a,org:i,jti:o,capabilities:Object.freeze(p),entitlement_schema_version:m,iat:d,exp:u}}function Ke(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new K("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function Ot(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new K("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return n}var xa="mcp",Aa=2880*60;async function Ft(e={}){let t=Xe.resolve(e.workspace??process.env.VULCAN_WORKSPACE??process.cwd()),n=Xe.resolve(e.configPath??Xe.join(t,"vulcan-mcp-config.json")),r;try{r=await Br.readFile(n,"utf-8")}catch{if(e.configPath)throw new Error(`Config file not found: ${n}. Generate one in Vulcan \u2192 Profile \u2192 Integrations \u2192 MCP, or omit --config to run Free.`)}let s=t,a;if(r!==void 0){let i;try{i=JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in config file ${n}: ${o.message}`)}if(i.workspace!==void 0){if(typeof i.workspace!="string")throw new Error("Config field workspace must be a string");s=Xe.resolve(Xe.dirname(n),i.workspace)}if(i.license_token!==void 0){if(typeof i.license_token!="string"||!i.license_token)throw new Error("Config field license_token must be a non-empty string");a=i.license_token}}try{await Br.access(s)}catch{throw new Error(`Workspace directory not found: ${s}`)}if(a){let{payload:i}=await ct(a,{allowExpired:!0}),o=i.exp-Math.floor(Date.now()/1e3);if(o<=0)console.error("[MCP Helper] Your Vulcan Pro access has expired: Free tools work; ask your assistant to sign in again (vulcan_sign_in) to renew.");else if(o<Aa){let d=Math.max(1,Math.round(o/3600));console.error(`[MCP Helper] Warning: your Vulcan access expires in about ${d} hour(s). Ask your assistant to sign in again (vulcan_sign_in), or open Vulcan -> Profile -> Integrations and click "Generate Config File".`)}}return{workspace:s,...a?{license_token:a}:{},...r!==void 0?{configPath:n}:{}}}async function Dr(e,t={}){if(!e.license_token)return{pro:!1,detail:"No Vulcan Pro access config is set; Free tools only."};try{return await ct(e.license_token,t),{pro:!0,detail:"Vulcan Pro access config is valid."}}catch(n){return{pro:!1,detail:n.message}}}async function ct(e,t={}){try{let{claims:n}=await $t(e,{capability:xa,now:t.now,publicKeys:t.publicKeys,allowExpired:t.allowExpired});return{payload:n}}catch(n){throw new Error(Ra(n))}}function Ra(e){if(!(e instanceof K))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. Call vulcan_sign_in to renew it, or open Vulcan -> Profile -> Integrations and click "Generate Config File".';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 ja}from"crypto";function Ta(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 Ma(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&ja(n,r)}async function Vr(e,t,n=ct){let r=Ta(e);if(!Ma(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as C}from"zod";import st from"fs/promises";import Te from"path";import Oa from"fs/promises";import $a from"path";function Wr(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[a,i]of Object.entries(e)){if(!i||typeof i!="object"){n.push(`Scenario '${a}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&n.push(`Scenario '${a}' must have exactly one base_json (found ${o.base_json.length})`):n.push(`Scenario '${a}' 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 '${a}' must have at most one weather_file (found ${m.length})`):n.push(`Scenario '${a}' weather_file/weather_files must be an array`)}u&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${a}' external_conditions must be an array`),t.requireWeather!==!1&&!d&&!u&&n.push(`Scenario '${a}' must have either 'weather_files' or 'external_conditions'`),d&&u&&r.push(`Scenario '${a}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,p]of Object.entries(o))Array.isArray(p)||n.push(`Scenario '${a}': '${m}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function Jr(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,s=1;for(let a of Object.values(r))Array.isArray(a)&&(s*=a.length);t+=s}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[s,a]of Object.entries(t)){if(!a||typeof a!="object")continue;let i=a;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=$a.join(e,"input","batch_parameters",o,`${String(u)}.json`);try{await Oa.access(m)}catch{r.push({scenario:s,category:o,parameter:String(u),path:m}),n.push(`Scenario '${s}': Parameter '${String(u)}' in category '${o}' not found at ${m}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as cs,readFile as dn}from"fs/promises";import{join as mn}from"path";import{fileURLToPath as ls}from"url";var Fa=ba(Hr(),1),Na=Object.defineProperty,Ia=Object.getOwnPropertyNames,La=(e,t)=>function(){return e&&(t=(0,e[Ia(e)[0]])(e=0)),t},Ba=(e,t)=>{for(var n in t)Na(e,n,{get:t[n],enumerable:!0})},Da={};Ba(Da,{configureWasm:()=>Va,getRuntimeApiUrl:()=>Ka,getRuntimeWasmVariant:()=>Ga,getVersionedWasmAssetPaths:()=>Dt,getVersionedWasmJsUrl:()=>Zr,getWasmAssetPaths:()=>Xr,getWasmBaseUrl:()=>Bt,getWasmBinaryUrl:()=>Yr,getWasmJsUrl:()=>tn,getWasmRayonThreadCount:()=>qr,getWasmVariant:()=>Kr,getWasmVersionInfo:()=>lt,getWasmVersionJsonUrl:()=>zr,getWasmWasmUrl:()=>rn,initializeWasmRayonThreadPool:()=>Ha});function Va(e={}){e.baseUrl&&(Qr=Wa(e.baseUrl)),typeof e.preferHashed=="boolean"&&(en=e.preferHashed)}function Gr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Wa(e){return e.replace(/\/+$/,"")||"/"}function Ja(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Ua(){let e=Gr();if(e){if(Ja(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Bt(){return Qr||Ua()}function qr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Ha(e){let t=e,n=Ze.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 s=Promise.resolve().then(()=>r(qr())).then(()=>{});return Ze.set(t,s),s.catch(()=>{Ze.get(t)===s&&Ze.delete(t)}),s}function zr(){return`${Bt()}/wasm_version.json`}async function lt(){try{let e=await fetch(zr(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function Kr(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 Ga(){return Kr(await lt())}function qa(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function za(e){let t=qa(),r=!!((en??!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 Xr(e){let t=Bt(),n=e===void 0?await lt():e,{jsFilename:r,wasmFilename:s}=za(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${s}`}}async function Dt(){let e=await lt(),{jsPath:t,wasmPath:n}=await Xr(e),r=e?.build_id||e?.sha256||e?.timestamp;if(!r)return{jsPath:t,wasmPath:n,versionInfo:e};let s=`v=${encodeURIComponent(String(r))}`;return{jsPath:`${t}?${s}`,wasmPath:`${n}?${s}`,versionInfo:e}}async function Zr(){let{jsPath:e}=await Dt();return e}async function Yr(){let{wasmPath:e}=await Dt();return e}function Ka(e){let t=Gr();return t?new URL(e,t.origin).toString():e}var Ze,Qr,en,tn,rn,nn=La({"src/wasmPath.ts"(){Ze=new WeakMap,tn=Zr,rn=Yr}});async function an(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(s=>typeof s!="string"||!s||s==="."||s===".."||s.includes("/")||s.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(r.files)}async function sn(e,t){let n=await an(e,t),r=await e.listFiles(t,{withKind:!0});return n===null?r:r.filter(s=>n.has(typeof s=="string"?s:s.name))}async function on(e,t){let n=t.lastIndexOf("/"),r=await an(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}function Vt(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()],s=r.map(i=>r.filter(o=>o!==i).map(o=>n(i,o))),a=r.find((i,o)=>s[o].every(d=>typeof d=="number"&&d>0));return a||!r.length?a:{unknown:s.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,s)=>r.localeCompare(s));return n.find(r=>/(?:^|__)FHS__/.test(r))??n.find(r=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(r))}nn();function cn(e){return e.startsWith("__")}function ut(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!cn(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function Xa(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function Za(e){let t=Xa(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function dt(e,t){let n=[];for(let r of ut(t)){let s=Za(r.value);for(let a=0;a<s;a+=1)n.push(`result_${e}_${r.name}_${a}`)}return n}function Jt(e){return Math.floor(e/1e3)}function Ya(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function Qa(e){return e==="failure_context.json"}function ln(e){return Ya(e)||Qa(e)}var es=["fhs_assumptions","fhs_compliance"];function ts(e){return es.some(t=>t===e)}var rs=new Set(["base_json","model_wrappers","weather_files","external_conditions"]);function ge(e,t,n){return{category:e,selections:[...t],message:n}}function ns(e){let t=0;for(let n of e){let r=1;for(let s of Object.values(n.parameters))s.length>0&&(r*=s.length);t+=r}return t}function as(e){let t=[],n=e.scenarios[0];e.scenarios.length!==1&&t.push(ge("scenarios",e.scenarios.slice(1).map(u=>u.name),"Free configurations contain exactly one scenario."));let r=n?.parameters??{},s=r.base_json??[];s.length!==1&&t.push(ge("base_json",s.slice(1),"Free configurations contain exactly one base model."));let a=r.model_wrappers??[],i=a.findIndex(ts),o=a.filter((u,m)=>m!==i);(a.length!==1||i!==0)&&t.push(ge("model_wrappers",o,"Free configurations use exactly one FHS wrapper."));for(let u of["weather_files","external_conditions"]){let m=r[u]??[];m.length>0&&t.push(ge(u,m,`Free configurations do not select ${u.replace(/_/g," ")}.`))}for(let[u,m]of Object.entries(r))rs.has(u)||m.length===0||t.push(ge(u,m,`Free configurations do not select ${u.replace(/_/g," ")} parameters.`));let d=ns(e.scenarios);return d!==1&&t.push(ge("permutations",[String(d)],"Free configurations compute exactly one permutation.")),{isFree:t.length===0,violations:t}}function ss(e,t){return cn(e)||e==="targetBundleId"&&typeof t=="string"}function os(e){return!e||typeof e!="object"?!1:Object.values(e).some(t=>Object.values(t??{}).some(n=>Array.isArray(n)?n.length>0:!!n))}function un(e){if(!e||typeof e!="object"||Array.isArray(e))return{isFree:!1,violations:[ge("config",[],"A batch configuration must be a JSON object.")]};let t=[],n=[];for(let[i,o]of Object.entries(e)){if(ss(i,o))continue;if(!o||typeof o!="object"||Array.isArray(o)){t.push(ge("config",[i],`Unrecognised batch configuration entry '${i}'.`));continue}let d={};for(let[u,m]of Object.entries(o))u==="zone_allocations"?os(m)&&t.push(ge("zone_allocations",[i],"Free configurations do not use per-zone selections.")):Array.isArray(m)?d[u]=m.map(String):t.push(ge(u,[i],`'${u}' in '${i}' must be a list of selections.`));n.push({name:i,parameters:d})}let r=e.__hem;(!r||typeof r!="object"||Array.isArray(r))&&t.push(ge("target",[],"Free runs use a model saved by the current Vulcan app, pinned to a HEM version."));let a=[...as({scenarios:n}).violations,...t];return{isFree:a.length===0,violations:a}}function is(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&Lt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&Lt(r))return r;let a=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(a&&Lt(a))return a}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function Lt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var Jo=is();nn();var fn;async function Ut(e){return fn??=us(),(await fn)(e)}async function us(){for(let e of["./hem-target-runtime/preparation.mjs","../hem-target-runtime/preparation.mjs"]){let t=new URL(e,import.meta.url);try{await cs(ls(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 Ht(e,t){let n=new Set;for(let{value:r}of ut(t))if(Array.isArray(r.base_json))for(let s of r.base_json){if(typeof s!="string"||/[\\/]/.test(s)||s==="..")throw new Error("Invalid base model name");n.add(await ds(e,s))}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 ds(e,t){try{return await Ut(await dn(mn(e,"input/base_models",`${t}.csv`),"utf8"))}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await dn(mn(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 pn(e,t){if(ut(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 Ht(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 vs}from"child_process";import{resolve as bs}from"path";import{access as Cs}from"fs/promises";import{fileURLToPath as zt}from"url";import{createHash as fs}from"crypto";import Ye from"fs";import xe from"path";import{fileURLToPath as ms}from"url";function Gt(e=process.cwd()){let t=xe.resolve(e);for(Ye.existsSync(t)&&Ye.statSync(t).isFile()&&(t=xe.dirname(t));;){if(Ye.existsSync(xe.join(t,"package.json"))&&Ye.existsSync(xe.join(t,"hem-batch-core"))&&Ye.existsSync(xe.join(t,"web")))return t;let r=xe.dirname(t);if(r===t)break;t=r}let n=xe.dirname(ms(import.meta.url));return xe.resolve(n,"..","..","..")}import he from"fs";import de from"path";import{fileURLToPath as ai,pathToFileURL as ps}from"url";var _n=new Map,gn=!1,qt=process.cwd(),yn=!1;async function mt(e,t){let n=t?`${e}?verified`:e,r=_n.get(n);if(r)return r;_s();let s=de.join(e,"wasm_wrapper.js"),a=de.join(e,"wasm_wrapper_bg.wasm"),i=de.join(e,"wasm_version.json");if(!he.existsSync(s)||!he.existsSync(a))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(ps(s).href+(t?"?verified":""));if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:t??he.readFileSync(a)}),o.setup_panic_hook?.(),typeof o.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let d={convertGeometryCsvToJson:o.convert_geometry_csv_to_json.bind(o),validateSnippetJs:o.validate_snippet_js?.bind(o),processBatchConfig:o.process_batch_config?.bind(o),calculateMetricsFromParsedData:o.calculate_metrics_from_parsed_data?.bind(o),setWorkspace:pt,prepareTargetScenario:o.prepare_target_scenario?.bind(o),metadata:{source:s,wasm_path:a,wasm_version:ws(i),build_stamp:et(o.build_stamp),build_info:ys(o.get_build_info),runtime_origin_descriptor:et(o.runtime_origin_descriptor),hem_core_version:et(o.metadata_hem_core_version),fhs_wrapper_version:et(o.metadata_fhs_wrapper_version)}};return _n.set(n,d),d}var hn=new Map;async function ft(e,t){let n=hn.get(e);if(n)return n;let r=d=>{try{return he.readFileSync(de.join(e,d))}catch{throw new Error(`The package WASM is incomplete: ${de.join(e,d)} is missing. ${t}`)}},s=JSON.parse(r("wasm_version.json").toString("utf8"));for(let d of["js_sha256","sha256"])if(!s[d])throw new Error(`${de.join(e,"wasm_version.json")} has no ${d}. ${t}`);let a=d=>fs("sha256").update(d).digest("hex"),i=r("wasm_wrapper_bg.wasm");if(a(r("wasm_wrapper.js"))!==s.js_sha256||a(i)!==s.sha256)throw new Error(`The WASM in ${e} does not match its wasm_version.json. ${t}`);let o={...await mt(e,i),versionInfo:s};return hn.set(e,o),o}function pt(e,t={}){qt=de.resolve(e),yn=t.confineToWorkspace===!0}function _s(){gs(),hs();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 s=Qe(n);try{return he.mkdirSync(de.dirname(s),{recursive:!0}),he.writeFileSync(s,r),!0}catch(a){return console.error(`[FS Bridge] write_file failed for ${s}:`,a.message),!1}},e.read_file=n=>{let r=Qe(n);return he.readFileSync(r,"utf8")},e.file_exists=n=>{let r=Qe(n);return he.existsSync(r)},e.create_dir_all=n=>{let r=Qe(n);try{return he.mkdirSync(r,{recursive:!0}),!0}catch(s){return console.error(`[FS Bridge] create_dir_all failed for ${r}:`,s.message),!1}},e.list_dir=n=>{let r=Qe(n);try{return he.readdirSync(r)}catch{return[]}}}function Qe(e){let t=de.isAbsolute(e)?de.resolve(e):de.resolve(qt,e);if(yn){let n=de.relative(qt,t);if(n===".."||n.startsWith(`..${de.sep}`)||de.isAbsolute(n))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function gs(){if(gn)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},gn=!0}var wn=!1;function hs(){if(wn)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)}),wn=!0}function ws(e){try{return JSON.parse(he.readFileSync(e,"utf8"))}catch{return}}function et(e){return typeof e!="function"?void 0:e()||void 0}function ys(e){let t=et(e);if(t)try{return JSON.parse(t)}catch{return t}}var tt=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.");let n=await Ss(),r=t?{targetBundleId:e.targetBundleId,manifestPath:bs(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{targetBundleId:e.targetBundleId};if(e.operation==="snapshot")return n.adapter.snapshotTarget({workspace:e.workspace,config:e.config,...r});let s=e.wasmDir??n.wasmDir,a=e.wasmRemedy??"Reinstall the package.";if(e.operation==="batch"){let m={workspace:e.workspace,config:e.config,configName:e.configName,jobId:e.jobId,...r,wasmDir:s,wasmRemedy:a};return e.foreground?n.adapter.runTargetBrowser(m,{loadPackageWasm:ft}):ks(n.adapterPath,m)}if(typeof e.csv!="string")throw new Error("CSV source required");let i=await n.adapter.workspaceReader(e.workspace),{manifest:o,text:d}=await n.adapter.readPreparationBundle(r),u=await ft(s,a);return n.preparation.prepareCsv({csv:e.csv,manifest:o,text:d,converter:{prepare_target_scenario:u.prepareTargetScenario},read:i})};async function Ss(){for(let e of["./hem-target-runtime/","../hem-target-runtime/"]){let t=new URL(e,import.meta.url),n=new URL("browser-adapter.mjs",t);try{await Cs(zt(n))}catch{continue}let[r,s]=await Promise.all([import(n.href),import(new URL("preparation.mjs",t).href)]);return{adapter:r,preparation:s,adapterPath:zt(n),wasmDir:zt(new URL("../../wasm/",t))}}throw new Error("Target assets are not installed. Build the local target CLI assets or install a helper release including them.")}function ks(e,t){return new Promise((n,r)=>{let s=vs(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),a=setTimeout(()=>{s.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);s.once("error",i=>{clearTimeout(a),r(i)}),s.once("exit",i=>{clearTimeout(a),r(new Error(`Target batch stopped before startup (${i})`))}),s.once("message",i=>{clearTimeout(a),i.started?(s.unref(),n({status:"started"})):(s.kill(),r(new Error(i.error??"Target batch failed to start")))}),s.send(t)})}import{randomUUID as Es}from"crypto";import ae from"fs/promises";import G from"path";async function Xt(e,t,n={},r={}){let{config_name:s,base_model:a,weather_file:i,wrapper:o,parameters:d}=t;if(!s)throw new Error("config_name is required");if(Ne(s),!a)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=Ps(d),m={base_json:[a],...o?{model_wrappers:[o]}:{},...u},p=await Ht(e,{scenario_1:m}),h=!!(t.targetManifestPath||t.targetManifestSha256||p);if(!i&&!h)throw new Error("weather_file is required");if(h&&(!/^[a-zA-Z0-9_. -]+$/.test(s)||s===".."))throw new Error("Invalid target config name");i&&(m.weather_files=[h&&!i.endsWith(".epw")?`${i}.epw`:i]);let _={scenario_1:m};await r.gate?.(h?{..._,__hem:{}}:_);let S=Wr(_,{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=Jr(_);if(x===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let k=n.maxPermutations??500;if(!Number.isSafeInteger(k)||k<1)throw new Error("maxPermutations must be a positive integer");if(x>k)return{success:!1,valid:!1,errors:[`Total permutations (${x}) exceeds maximum of ${k}`],message:`Config would generate ${x} permutations, which exceeds the limit of ${k}`};let M=_;if(h){let O=await(r.runTarget??tt)({workspace:e,operation:"snapshot",config:_,targetBundleId:p,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});M={..._,__hem:O}}else{let O=await Ur(e,_);if(!O.valid)return{success:!1,valid:!1,errors:O.errors,missingFiles:O.missingFiles,message:`Some parameter files are missing: ${O.errors.slice(0,3).join("; ")}${O.errors.length>3?"...":""}`};let W=G.join(e,"input","batch_parameters","base_json",`${a}.json`);try{await ae.access(W)}catch{return{success:!1,valid:!1,errors:[`Base model '${a}' not found at ${W}`],message:`Base model file not found: ${a}`}}let Q=G.join(e,"input","batch_parameters","weather_files",i.endsWith(".epw")?i:`${i}.epw`);try{await ae.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Q}`],message:`Weather file not found: ${i}`}}}await r.gate?.(M);let R=G.join(e,"input","batch_configs");if(h){let O=await ae.realpath(e);for(let W of["input","batch_configs"])if(O=G.join(O,W),await ae.mkdir(O).catch(Q=>{if(Q.code!=="EEXIST")throw Q}),await ae.realpath(O)!==O)throw new Error("Target config directory is a symlink")}else await ae.mkdir(R,{recursive:!0});let N=s.endsWith(".json")?s:`${s}.json`,I=G.join(R,N);try{return await ae.access(I),{success:!1,valid:!1,errors:[`Config file '${N}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await ae.writeFile(I,JSON.stringify(M,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${s}' created successfully`,config_path:I,permutations:x,structure:_}}async function Zt(e,t,n){let{config_name:r,job_id:s}=t;if(!r)throw new Error("config_name is required");let a=s||n.generateJobId?.()||`mcp_${Es()}`;Ne(r);let i=r.endsWith(".json")?r:`${r}.json`,o=G.join(e,"input","batch_configs",i),d;try{d=await ae.readFile(o,"utf8")}catch(h){let _=h;throw _.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${_.message}`)}let u=JSON.parse(d);if(await n.gate?.(u),u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let h=u.__hem;if(!h){let _="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:a,status:"error",message:_,error:_}}try{return await(n.runTarget??tt)({workspace:e,operation:"batch",config:u,targetBundleId:h.targetBundleId,configName:r.replace(/\.json$/,""),jobId:a,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:a,status:"started",config_name:r,output_dir:G.join(e,"output"),message:"Exact target batch started. Read progress with batch status (MCP: vulcan_get_batch_status; Analyst: vulcan-analyst batch status); runtime provenance is stored with outputs."}}catch(_){let S=_.message;return{job_id:a,status:"error",message:S,error:S}}}let m=await pn(e,u);if(m)return{job_id:a,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:a,status:"error",message:h,error:h}}let p=G.join(e,"output");await ae.mkdir(p,{recursive:!0});try{let h=await n.processBatchConfig(d,e,p,r.replace(/\.json$/,""),a),_=JSON.parse(h);return _.error?{job_id:a,status:"error",message:`Batch execution failed: ${_.error}`,error:_.error}:{job_id:a,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:p}}catch(h){let _=h;return{job_id:a,status:"error",message:`Failed to start batch execution: ${_.message}`,error:_.message}}}async function Yt(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,"");r&&Ne(r);let s=G.join(e,"output"),a;if(r&&!n){if(a=await _t(e,r),!a.jobId){let R=a.error!==void 0?"error":a.unknown?"unknown":"not_run",N=a.error??a.unknown??a.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:R,progress:0,passes:0,failures:0,output_dir:s,error:N,...Cn(a.warnings)}}n=a.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=a?.warnings??[],o=G.join(s,`progress_${n}.json`),d=G.join(s,`sim_progress_${n}.json`),u=await Fe(o,i),m=await Fe(d,i),p=await kn(s,n,i);if(!a&&p.config){let R=await _t(e,p.config);i.push(...R.warnings),R.jobId===n&&(a=R),r??=p.config}let h=p.records>0||typeof u?.targetBundleId=="string",_="queued",S=0,x=0,k=0,M=null;if(u?(Sn(u.status)?_=u.status:typeof u.percentage=="number"?(S=u.percentage,_=S>=100?"completed":"running"):typeof u.current_combination=="number"&&typeof u.total_combinations=="number"&&(S=Math.round(u.current_combination/u.total_combinations*100),_=S>=100?"completed":"running"),typeof u.percentage=="number"&&(S=u.percentage),typeof u.error=="string"&&(M=u.error,_="error")):p.records&&(p.stopped?(_="error",M=p.stopped):a?.expected!==void 0&&p.passes===a.expected?(_="completed",S=100):(_="unknown",M=`Job ${n} has finished ${p.passes} of ${a?.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.`)),p.records&&({passes:x,failures:k}=p),a?.error!==void 0&&(M=a.error,_="error"),m&&!h&&(Sn(m.status)&&(_=m.status),typeof m.passes=="number"&&(x=m.passes),typeof m.failures=="number"&&(k=m.failures),typeof m.error=="string"&&(M=m.error,_="error")),!u&&!m&&!p.records){let R=G.join(s,n);try{let N=await ae.readdir(R);_=N.length>0?"completed":"queued",S=N.length>0?100:0}catch(N){throw N.code!=="ENOENT"?N:new Error(`Job ${n} does not exist in this workspace: ${s} holds no progress file, run record or folder for it.`)}}return{job_id:n,...r?{config_name:r}:{},status:_,progress:S,passes:x,failures:k,output_dir:s,error:M,batch_progress:u??null,sim_progress:h?null:m??null,...Cn(i)}}async function _t(e,t){let n=G.join(e,"output"),r=[],s=[],a=async j=>(await ae.stat(j)).mtimeMs,i=j=>typeof j.startedAt=="string"?j.startedAt:void 0;for(let j of await ae.readdir(n).catch(Kt)??[]){if(!j.startsWith("progress_")||!j.endsWith(".json"))continue;let T=await Fe(G.join(n,j),r),c=j.slice(9,-5);T?.config_name===t&&s.push({run:c,jobId:c,startedAt:i(T),fileTime:await a(G.join(n,j))})}Ne(t);let o=G.join(e,"input","batch_configs",`${t}.json`),d=await Fe(o,r),u=d?dt(t,d):[],m,p=[];for(let j of u){let T=G.join(n,j),c=await ae.readdir(T,{withFileTypes:!0}).catch(Kt);if(!c)continue;if(!c.some(f=>f.name==="target-run.json")){let f=c.filter(g=>g.isFile()&&ln(g.name)).map(g=>G.join(T,g.name));if(!f.length)continue;m??=`Batch config '${t}' has results in output/${j} from the legacy engine, which does not record the job that wrote them. Pass the job_id from vulcan_run_batch.`,s.push({run:vn,fileTime:Math.max(...await Promise.all(f.map(a)))});continue}let l=j.slice(`result_${t}_`.length);for(let f of c.filter(g=>g.isDirectory()))for(let g of await ae.readdir(G.join(T,f.name),{withFileTypes:!0})){if(!g.isDirectory())continue;let w=G.join(T,f.name,g.name,"target-run.json"),$=r.length,v=await Fe(w,r);if(!v){r.length>$&&p.push({warning:r.at(-1),fileTime:await a(w)});continue}v.name===l&&s.push({run:g.name,jobId:g.name,startedAt:i(v),fileTime:await a(w)})}}let h=G.join(n,`batch_status_${t}.json`),_=await Fe(h,r),S=_?.status==="error"||_?.status==="running",x=S?i(_):void 0,k=x===void 0?void 0:s.find(j=>j.jobId&&j.startedAt===x)?.jobId;S&&!k&&s.push({run:bn,startedAt:x,fileTime:await a(h)});let M=d?u.length:void 0,R=s.flatMap(j=>j.startedAt===void 0?[]:[Date.parse(j.startedAt)]),N=p.find(j=>!R.length||j.fileTime>=Math.max(...R));if(N)return{unknown:`The helper cannot read a run record of batch config '${t}', so it cannot tell which run is latest. ${N.warning}`,expected:M,warnings:r};if(!s.length)return{legacyCurrent:!0,expected:M,warnings:r};if(d&&Jt(await a(o))>Jt(Math.max(...s.map(j=>j.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:M,warnings:r};let I=Vt(s);if("unknown"in I)return{unknown:I.unknown,expected:M,warnings:r};if(I.run===vn)return{unknown:m,legacyCurrent:!0,expected:M,warnings:r};let O=_?.error_message,W=_?.status!=="error"?void 0:typeof O=="string"&&O?O:`The app recorded the run of batch config '${t}' as failed, with no reason.`;if(I.run!==bn)return{jobId:I.run,...I.run===k?{error:W}:{},expected:M,warnings:r};if(_?.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:M,warnings:r};if(x!==void 0)return{error:W,expected:M,warnings:r};let Q=Vt(s.filter(j=>j.jobId)),Ce=Q&&"run"in Q?Q.run:void 0;return{...Ce&&(await kn(n,Ce,r)).stopped?{jobId:Ce}:{},error:W,expected:M,warnings:r}}var vn="legacy engine results",bn="the app's run status";async function kn(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let s of await ae.readdir(e,{withFileTypes:!0}).catch(Kt)??[])if(!(!s.isDirectory()||!s.name.startsWith("result_")))for(let a of await ae.readdir(G.join(e,s.name),{withFileTypes:!0})){if(!a.isDirectory())continue;let i=await Fe(G.join(e,s.name,a.name,t,"target-run.json"),n);if(!i)continue;r.records+=1;let o=`_${String(i.name)}`;s.name.endsWith(o)&&(r.config??=s.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 Fe(e,t){let n;try{n=await ae.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 Kt(e){if(e.code!=="ENOENT")throw e}function Cn(e){return e.length?{warnings:e}:{}}function Ne(e){let t=e.endsWith(".json")?e.slice(0,-5):e;if(!t.trim()||G.basename(t)!==t||/[\\/\0]/.test(t)||t.startsWith("."))throw new Error(`Invalid batch config name: ${JSON.stringify(e)} (no path separators or leading '.')`)}function Ps(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function Sn(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Pi from"crypto";import Ae from"fs/promises";import re from"path";import xs from"fs/promises";import Pn from"path";var Si=Pn.join("input","base_models");async function Qt(e){await En(e,"Workspace"),await En(Pn.join(e,"input","batch_parameters"),"Vulcan workspace input/batch_parameters").catch(t=>{throw new Error(`${t.message}. Point the tool at a folder opened as a workspace in the Vulcan app.`)})}async function En(e,t){try{if(!(await xs.stat(e)).isDirectory())throw new Error(`${t} is not a directory: ${e}`)}catch(n){let r=n;throw r.code==="ENOENT"?new Error(`${t} directory not found: ${e}`):r}}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 er(e){let{workspace:t,csvPath:n,outputPath:r}=e,s=re.isAbsolute(n)?n:re.join(t,n),a;try{a=await Ae.readFile(s,"utf8")}catch(o){let d=o;throw d.code==="ENOENT"?new Error(`CSV file not found at ${s}`):new Error(`Failed to read CSV file: ${d.message}`)}let i=await Ut(a);try{let o=await(e.runTarget??tt)({workspace:t,operation:"prepare",csv:a,targetBundleId:i,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),d=r?re.resolve(t,r):As(t,s);if(re.extname(d)!==".json")throw new Error("Prepared target output must have a .json extension");return await An(t,d),await xn(t,re.join(t,"input/base_models",re.basename(d,".json")+".target.json"),JSON.stringify({targetBundleId:i,validation:o.validation,schema_omissions:o.schema_omissions,readiness:"wrapper_input"})),await xn(t,d,JSON.stringify(o.model,null,2)),{ok:!0,json_path:re.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 As(e,t){let n=re.basename(t,re.extname(t));return re.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function An(e,t){let n=await Ae.realpath(e),r=re.relative(re.resolve(e),t);if(!r||r===".."||r.startsWith(`..${re.sep}`)||re.isAbsolute(r))throw new Error("Target preparation output must stay within the workspace");let s=re.join(n,r),a=n;for(let i of re.relative(n,re.dirname(s)).split(re.sep).filter(Boolean))if(a=re.join(a,i),await Ae.mkdir(a).catch(o=>{if(o.code!=="EEXIST")throw o}),await Ae.realpath(a)!==a)throw new Error("Target preparation output directory is a symlink");try{if(await Ae.realpath(s)!==s)throw new Error("Target preparation output is a symlink")}catch(i){if(i.code!=="ENOENT")throw i}return s}async function xn(e,t,n){let r=await An(e,t),s=await Ae.open(r,"wx").catch(async a=>{if(a.code!=="EEXIST")throw a;if(await Ae.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return Ae.open(r,"w")});try{await s.writeFile(n)}finally{await s.close()}}import{fileURLToPath as Rs}from"url";import fe from"fs/promises";import X from"path";function gt(e,t){if(!e||/[\/\\\0]/.test(e)||e.startsWith("."))throw new Error(`${t} must be a plain name, without path separators or a leading '.': ${JSON.stringify(e)}`)}async function tr(e,t={}){let{category:n}=t,r=X.join(e,"input","batch_parameters"),s=await fe.readdir(r,{withFileTypes:!0}),a={};for(let i of s){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let d=X.join(r,o),u=await fe.readdir(d),m=[];for(let p of u){if(!p.endsWith(".json"))continue;let h=p.replace(/\.json$/,""),_=X.join(d,p);try{let S=await fe.readFile(_,"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 ${_}: ${S.message}`)}}m.length>0&&(a[o]={category:o,parameters:m.sort((p,h)=>p.name.localeCompare(h.name))})}return{catalog:a,total_categories:Object.keys(a).length,total_parameters:Object.values(a).reduce((i,o)=>i+o.parameters.length,0)}}async function rr(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");gt(n,"category"),gt(r,"parameter_id");let s=X.join(e,"input","batch_parameters",n),a=X.join(s,`${r}.json`),i=X.join(s,`${r}.md`),o;try{let u=await fe.readFile(a,"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 fe.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 nr(e,t,n){let{category:r,parameter_id:s,content:a,markdown_content:i}=t;if(!r)throw new Error("category is required");if(!s)throw new Error("parameter_id is required");if(a==null||a==="")throw new Error("content is required");if(r!==r.toLowerCase())throw new Error(`category must be lowercase, as the workspace folders are: ${JSON.stringify(r)}`);gt(r,"category"),gt(s,"parameter_id");let o=js(a),[d,u]=await Promise.all([$s(e),Fs(e,r)]),m=await Os(e,Ms(d)?"input_fhs":"input_core"),p=I=>{let O=JSON.parse(n.validateSnippetJs(r,JSON.stringify(I),JSON.stringify(m),JSON.stringify(d),u?JSON.stringify(u):null));return O.ok?[]:(O.errors??[]).map(W=>typeof W=="string"?{path:"",message:W}:{path:W.path??"",message:W.message||String(W)})},h=p(o),_=h.length>0&&!Ts.has(r),S=I=>`${I.path}\0${I.message}`,x=_?new Set(p({}).map(S)):new Set,k=h.filter(I=>I.message.startsWith("Merge failed")||!x.has(S(I))).map(I=>I.message);if(k.length>0)return{success:!1,valid:!1,errors:k,message:`Validation failed: ${k.join("; ")}`};let M=X.join(e,"input","batch_parameters",r);await fe.mkdir(M,{recursive:!0});let R=X.join(M,`${s}.json`);await fe.writeFile(R,JSON.stringify(o,null,2),"utf8");let N=null;return i&&(N=X.join(M,`${s}.md`),await fe.writeFile(N,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${s}' saved successfully in category '${r}'`,paths:{json:R,markdown:N}}}function js(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}var Ts=new Set(["model_wrappers","weather_files","external_conditions","tariff","simplified_fabric"]);function Ms(e){return!!(e&&typeof e=="object"&&("General"in e||"PartGcompliance"in e))}function Rn(e){return["../schemas/","../../schemas/"].map(t=>Rs(new URL(t+e,import.meta.url)))}async function Os(e,t){let n=t==="input_fhs"?"input_fhs.schema.json":"core-input.schema.json",r=t==="input_fhs"?[X.join(e,"input_fhs.schema.json"),X.join(e,"schemas","input_fhs.schema.json"),X.join(Gt(e),"hem_fhs_upstream","schema","input_fhs.schema.json"),...Rn(n)]:[X.join(e,"input_core.schema.json"),X.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),X.join(e,"core-input.schema.json"),X.join(e,"schemas","core-input.schema.json"),X.join(e,"input.schema.json"),X.join(Gt(e),"hem_engine_upstream","schemas","core-input.schema.json"),...Rn(n)];for(let s of r)try{return JSON.parse(await fe.readFile(s,"utf8"))}catch{}throw new Error(`Schema file not found (${t}). Tried: ${r.join(", ")}`)}async function $s(e){let t=X.join(e,"input","batch_parameters","base_json"),n=(await fe.readdir(t).catch(()=>[])).filter(o=>o.endsWith(".json")).sort(),r=new Set(await fe.readdir(X.join(e,"input","base_models")).catch(()=>[])),s=n.filter(o=>!o.startsWith("defaults_template")),a=n.includes("demo_hp_annual.json")?"demo_hp_annual.json":s.find(o=>r.has(o.replace(/\.json$/,".csv")))??s[0];if(!a)throw new Error(`No base model to validate the snippet against: add one to ${t} (convert a geometry CSV with merge-csv-to-json).`);let i=X.join(t,a);try{return JSON.parse(await fe.readFile(i,"utf8"))}catch(o){throw new Error(`Could not read base model ${i}: ${o.message}`)}}async function Fs(e,t){if(t!=="simplified_fabric")return null;let n=[X.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),X.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let r of n)try{return JSON.parse(await fe.readFile(r,"utf8"))}catch{}return null}import cr from"fs/promises";import ht from"path";import Le from"fs/promises";import Ie from"path";async function Ve(e,t){let n=Ie.join(e,"output"),r=Mn(t.config_name);Ne(r);let s=[],a=new Set,i=[],o=[];try{let d=Ie.join(n,r),u=await ar(d);u&&await jn(d,s,a);let m;try{m=JSON.parse(await Le.readFile(Ie.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(k){if(k.code!=="ENOENT")throw k;if(!u)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let k of m===void 0?[]:dt(r,m)){let M=Ie.join(n,k);if(!await ar(M))continue;let R=k.slice(`result_${r}_`.length);try{await jn(M,s,a,R)}catch(N){let I=await Le.readFile(Ie.join(M,"target-run.json"),"utf8").then(JSON.parse,()=>{});I?.status==="failed"||I?.status==="cancelled"?i.push({name:R,...typeof I.jobId=="string"?{job_id:I.jobId}:{},error:typeof I.error=="string"?I.error:`The scenario's run is recorded as ${I.status}, with no reason.`}):I?.status==="running"?o.push(`Scenario ${R} has no results yet: its run${typeof I.jobId=="string"?` (job ${I.jobId})`:""} is recorded as running.`):o.push(`Failed to read result directory ${k}: ${N.message}`)}}s.sort((k,M)=>k.name.localeCompare(M.name));let p=m===void 0?void 0:await _t(e,r),h=p?.jobId;o.push(...p?.warnings??[]),h&&p?.error!==void 0&&!i.some(k=>k.job_id===h)&&o.push(`The app recorded run ${h} of batch config '${r}' as failed after these scenarios finished: ${p.error}`);let _=p===void 0?[]:s.filter(k=>k.job_id===void 0?!p.legacyCurrent:k.job_id!==h),S=h||p?.legacyCurrent?void 0:p?.changed??p?.unknown??(p?.error!==void 0?`The latest run of batch config '${r}' failed before it wrote any scenario: ${p.error}`:void 0),x=s.filter(k=>!_.includes(k));return{config_name:r,models:x,total_models:x.length,output_dir:n,...h?{latest_job_id:h}:{},..._.length?{earlier_run_models:_}:{},...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 sr(e,t){let n=Mn(t.config_name),r=await Ve(e,{config_name:n}),s=r.models.find(m=>m.name===t.model_name)?.csv_path;if(!s)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,error:or(r,t.model_name)};let i=(await Le.readFile(s,"utf8")).split(`
14
+ `).filter(m=>m.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:s,error:"CSV must have at least headers and units rows"};let o=Tn(i[0]??"").map(m=>m.trim()),d=Tn(i[1]??"").map(m=>m.trim()),u=[];for(let m=1;m<o.length;m+=1){let p=o[m],h=m<d.length?d[m]:"";p&&u.push({name:p,unit:h||"",index:m-1})}return{config_name:n,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:s}}function or(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 ir={fileExists:ar,readFile:e=>Le.readFile(e,"utf8"),listFiles:e=>Le.readdir(e)};async function jn(e,t,n,r){let a=(await sn(ir,e)).map(u=>typeof u=="string"?u:u.name),i=await Le.readFile(Ie.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:Ie.join(e,m),has_results:!0,...o?{job_id:o}:{}}))};if(r){let u=Wt(a,"results");u&&d(r,u);return}for(let u of a){if(!Wt([u],"results"))continue;let m=u.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);m?.[1]&&d(m[1],u)}}function Mn(e){return e.replace(/\.json$/,"")}async function ar(e){try{return await Le.access(e),!0}catch{return!1}}function Tn(e){let t=[],n="",r=!1;for(let s=0;s<e.length;s+=1){let a=e[s];r?a==='"'?e[s+1]==='"'?(n+='"',s+=1):r=!1:n+=a:a==='"'?r=!0:a===","?(t.push(n),n=""):n+=a}return t.push(n),t}var Ns=new Set(["sumif","averageif","countif"]),On=new Set([">=","<=",">","<","="]);async function lr(e,t,n){let{config_name:r,model_names:s,metric_definitions:a,time_range:i,tariff_file_path:o,tariff_column_index:d}=t;if(!r)throw new Error("config_name is required");if(!s||!Array.isArray(s)||s.length===0)throw new Error("model_names is required and must be a non-empty array");if(!a||!Array.isArray(a)||a.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=r.replace(/\.json$/,""),{encodedMetrics:m,metadata:p}=Bs(a);if(p.some(R=>R.function.toLowerCase()==="cost")&&(!o||d===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let _;if(o&&d!==void 0){let R=await Ds(o,d,e);_=JSON.stringify(R)}let S=[],x=await Ve(e,{config_name:u}),k=[],M=[];for(let R of s){let N=x.models.find(O=>O.name===R)?.csv_path;if(!N){let O=x.earlier_run_models?.find(Q=>Q.name===R),W=x.failed_models?.find(Q=>Q.name===R);if(W)M.push({model_name:R,...W.job_id?{job_id:W.job_id}:{},error:W.error});else if(O)k.push({model_name:R,...O.job_id?{job_id:O.job_id}:{}});else throw new Error(or(x,R));continue}let I=await cr.readFile(N,"utf8");try{let O=Is(I,R,r);if(p.some(ne=>ne.isCompliance)){let ne=ht.join(ht.dirname(N),"fhs_compliance_report.json");if(!await on(ir,ne))throw new Error("Completed FHS compliance report is unavailable");let j=JSON.parse(await cr.readFile(ne,"utf8")),T=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let c of T){let l=j[c];O[c]=typeof l=="number"&&Number.isFinite(l)?l:null}for(let c of p.filter(l=>l.isCompliance)){let l=T.find(f=>f===c.column);if(!l||O[l]===null)throw new Error(`Completed FHS compliance rate '${c.column}' is unavailable`)}}if(O.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${R}`);if(Object.keys(O.columns).length===0)throw new Error(`No columns found in CSV for model ${R}`);let W=Vs(O,m,p);if(W.length>0){let ne=Object.keys(O.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${W.join(", ")}. Available columns: ${ne.join(", ")}...`)}let Q=n.calculateMetricsFromParsedData(JSON.stringify(O),JSON.stringify(m),i?JSON.stringify(i):void 0,_);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((ne,j)=>{let T=p[j],[c=ne.name,l="sum"]=ne.name.split("|");S.push({id:T?.id||ne.name,name:T?.name||ne.name,column:T?.column||c,function:T?.function||l,comparator:T?.comparator,threshold:T?.threshold,value:ne.value,model_name:R})})}catch(O){let W=O;if(W.code==="ENOENT"){console.warn(`CSV file not found for model ${R}: ${N}`);continue}throw new Error(`Failed to process model ${R}: ${W.message}`)}}return{metrics:S,total_models:s.length-k.length-M.length,total_metrics:S.length,...k.length?{earlier_run_models:k}:{},...M.length?{failed_models:M}:{},...x.latest_run_unknown?{latest_run_unknown:x.latest_run_unknown}:{},...x.warnings?{warnings:x.warnings}:{}}}function Is(e,t,n){let r=e.split(`
15
+ `).filter(m=>m.trim());if(r.length<2)throw new Error("CSV must have at least headers and units rows");let s=(r[0]??"").split(",").map(m=>m.trim()),a=(r[1]??"").split(",").map(m=>m.trim()),i=[],o={},d=[],u=[];for(let m=1;m<s.length;m+=1){let p=s[m];p&&(o[p]=[],d.push(p),u.push(m<a.length&&a[m]||""))}for(let m=2;m<r.length;m+=1){let p=(r[m]??"").split(",").map(S=>S.trim());if(p.length===0||p.length===1&&!p[0])continue;let h=p[0];if(!h)continue;let _=Number.parseInt(h,10);if(!(Number.isNaN(_)||_<0)){i.push(_);for(let S=1;S<s.length&&S<p.length;S+=1){let x=s[S];if(!x||!o[x])continue;let k=p[S];if(k===void 0)continue;let M=Number.parseFloat(k);o[x].push(Number.isNaN(M)?0:M)}}}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 $n(e){return typeof e=="string"?(e.split("|")[1]??"").trim().toLowerCase()==="cost":e.name?.includes("|")&&!e.function&&!e.funcType?(e.name.split("|")[1]??"").trim().toLowerCase()==="cost":(e.function||e.funcType||e.type||"sum").toString().toLowerCase()==="cost"}function Ls(e){let t=(e.function||e.funcType||e.type||"sum").toString(),n=t.toLowerCase();if(n==="cost")return"cost";if(!Ns.has(n))return n;let r=e.comparator||">=";if(!On.has(r))throw new Error(`Invalid comparator "${r}" for ${t}. Use one of ${Array.from(On).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 Bs(e){let t=[],n=[];return e.forEach((r,s)=>{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 a=r.column||(r.name?.includes("|")?r.name.split("|")[0]:r.name);if(!a)throw new Error(`Metric definition at index ${s} missing column or name. Got: ${JSON.stringify(r)}`);let i=r.name?.includes("|")&&!r.function&&!r.funcType?r.name.split("|")[1]||"sum":Ls(r),o=`${a}|${i}`;t.push({name:o}),n.push({id:r.id||r.metric_id||`${a}_${i}`,name:r.name||r.id||a,column:a,function:i,comparator:r.comparator,threshold:r.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:n}}async function Ds(e,t,n){let r=ht.isAbsolute(e)?e:ht.resolve(n,e),a=(await cr.readFile(r,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${r}. Error: ${o.message}`)})).split(`
16
+ `).filter(o=>o.trim());if(a.length===0)throw new Error(`Tariff file is empty: ${r}`);let i=[];for(let o=1;o<a.length;o+=1){let d=(a[o]??"").split(",").map(p=>p.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 Vs(e,t,n){let r=[];return t.forEach((s,a)=>{let i=s.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${s.name}`);n[a]?.isCompliance||e.columns[i]||r.push(i)}),r}import{spawn as Ws}from"child_process";import{existsSync as Js,readFileSync as Us}from"fs";import{createRequire as Hs}from"module";import We from"path";var wt="@vulcan-energy/community-cli";function Fn(e=import.meta.url){let t=Hs(e),n;try{n=t.resolve(`${wt}/package.json`)}catch{throw new Error(`${wt} is not installed. It ships with this Vulcan tool; update the tool (npm install -g @vulcan-energy/mcp-helper@latest or @vulcan-energy/analyst@latest), or from a checkout run npm ci.`)}let s=JSON.parse(Us(n,"utf8")).bin?.["vulcan-community"];if(!s)throw new Error(`${wt} declares no vulcan-community bin.`);let a=We.join(We.dirname(n),s);if(!Js(a))throw new Error(`${wt} is not built (${a} missing); run its build first.`);return a}async function dr(e){let t=e.failOn??"critical",n=We.resolve(e.csvPath),r=await pr(e,["check",n,"--json",`--fail-on=${t}`]),s=_r(r),a=ur(s)?s:void 0;return{ok:r.exitCode===0&&a!==void 0,command:"geometry validate",csv_path:n,fail_on:t,exit_code:r.exitCode,signal:r.signal,stdout:a===void 0?r.stdout:"",stderr:r.stderr,parsed:a,counts:ur(a?.counts)?a.counts:void 0,critical_issues:Array.isArray(a?.criticalIssues)?a.criticalIssues:void 0,warnings:Array.isArray(a?.warnings)?a.warnings:void 0,missing_elements:Array.isArray(a?.missingElements)?a.missingElements:void 0,error:a===void 0?gr(r):void 0}}async function mr(e){let t=e.mode??"summary",n=We.resolve(e.csvPath),r=await pr(e,["thermal-bridges",n,Nn(t)]),s=t==="json"?_r(r):void 0;return{ok:r.exitCode===0&&(t!=="json"||s!==void 0),command:"thermal-bridges auto",csv_path:n,mode:t,exit_code:r.exitCode,signal:r.signal,stdout:t==="json"&&s!==void 0?"":r.stdout,stderr:r.stderr,parsed:s,proposal_count:Array.isArray(s)?s.length:void 0,error:t==="json"&&s===void 0?gr(r):void 0}}async function fr(e){let t=e.mode??"summary",n=e.includeAuto===!0,r=We.resolve(e.csvPath),s=["thermal-bridges",r,"--validate",...n?["--with-auto"]:[],Nn(t)],a=await pr(e,s),i=t==="json"?_r(a):void 0,o=ur(i)?i:void 0;return{ok:a.exitCode===0&&(t!=="json"||o!==void 0),command:"thermal-bridges validate",csv_path:r,include_auto:n,mode:t,exit_code:a.exitCode,signal:a.signal,stdout:t==="json"&&o!==void 0?"":a.stdout,stderr:a.stderr,parsed:o,issue_count:typeof o?.issueCount=="number"?o.issueCount:void 0,thermal_bridge_linear_rows:typeof o?.thermalBridgeLinearRows=="number"?o.thermalBridgeLinearRows:void 0,error:t==="json"&&o===void 0?gr(a):void 0}}async function pr(e,t){return(e.runner??Gs)(process.execPath,[e.communityCli??Fn(),...t],{cwd:We.resolve(e.workspace)})}function Nn(e){return`--${e}`}function _r(e){try{return JSON.parse(e.stdout)}catch{return}}function gr(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function ur(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Gs=(e,t,n)=>new Promise((r,s)=>{let a=Ws(e,[...t],{cwd:n.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",o="";a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),a.stdout.on("data",d=>{i+=d}),a.stderr.on("data",d=>{o+=d}),a.on("error",s),a.on("close",(d,u)=>{r({exitCode:d,signal:u,stdout:i,stderr:o})})});var nt="https://usevulcan.app/join",Ue="Free: one base model, one FHS wrapper (fhs_assumptions or fhs_compliance), no weather or other parameter variations, one permutation (the same rule as the Vulcan app). Anything more needs Vulcan Pro.";function qs(e){return e.isFree?null:{reason:`Advanced scenarios need Vulcan Pro. ${Ue}`,violations:e.violations}}function In(e){return qs(un(e))}var Je=class extends Error{constructor(n,r){super(n.reason);this.requirement=n;this.accessDetail=r;this.name="ProRequiredError"}requirement;accessDetail};function hr(e){return async t=>{let n=In(t);if(!n)return;let r=await e();if(!r.pro)throw new Je(n,r.detail)}}function wr(e){return e.model_names.length>1?{reason:"Comparing metrics across models needs Vulcan Pro."}:e.tariff_file_path||e.metric_definitions.some($n)?{reason:"Cost and tariff metrics need Vulcan Pro."}:null}function yr(e,t,n,r){return{status:"requires_pro",tool:e,reason:t.reason,...t.violations?{violations:t.violations}:{},access:n,upgrade_url:nt,unlock:r}}import zs from"fs/promises";import Ks from"path";async function yt(e){let t=Ks.join(e,"input","analytics","default_metrics.json"),n;try{n=JSON.parse(await zs.readFile(t,"utf8"))}catch(i){if(i.code==="ENOENT")return{metrics:[],cost_metrics:[],unsupported:[]};throw new Error(`Could not read ${t}: ${i.message}`)}if(!Array.isArray(n))throw new Error(`${t} must hold a list of metric templates`);let r=[],s=[],a=[];for(let i of n){if(!i?.column||!i.funcType)continue;let o=i.label??`${i.funcType} of ${i.column}`;if(i.funcType.toLowerCase()==="cost"){s.push(o);continue}if(i.resultsKey&&i.resultsKey!=="results"){a.push({name:o,reason:`reads the ${i.resultsKey} results file`});continue}if(i.normalization){a.push({name:o,reason:"is normalised (e.g. per floor area)"});continue}r.push({...i.id?{id:i.id}:{},name:o,column:i.column,function:i.funcType,...i.comparator?{comparator:i.comparator}:{},...typeof i.threshold=="number"?{threshold:i.threshold}:{}})}return{metrics:r,cost_metrics:s,unsupported:a}}import{createHash as Xs,randomUUID as Zs}from"crypto";import we from"fs/promises";import Ys from"os";import Re from"path";function vt(e=process.env){return(e.VULCAN_SITE_URL||"https://usevulcan.app").replace(/\/+$/,"")}function vr(e,t){let n=Number(e);return Number.isFinite(n)&&n>0?n:t}async function Bn(e,t,n,r=2e4){let s=n.siteUrl??vt(n.env),a;try{a=await(n.fetch??fetch)(`${s}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(r)})}catch(i){let o=i.cause?.code;throw new Error(`Could not reach Vulcan at ${s}${o?` (${o})`:""}; check the internet connection and try again.`)}return{status:a.status,body:await a.json().catch(()=>({}))}}function br(e,t){let n=t.env??process.env,r=n.VULCAN_STATE_DIR||Re.join(Ys.homedir(),".vulcan","sign-in"),s=t.siteUrl??vt(n);return Re.join(r,`${Xs("sha256").update(`${s}
17
+ ${e}`).digest("hex").slice(0,24)}.json`)}var Qs=/^[A-Za-z0-9_-]{43}$/,eo=/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;function Dn(e,t,n){let r=`${t.siteUrl??vt(t.env)}/connect`;return!e||typeof e.deviceCode!="string"||!Qs.test(e.deviceCode)||typeof e.userCode!="string"||!eo.test(e.userCode)||typeof e.url!="string"||!e.url.startsWith(r)||!["","?","/","#"].includes(e.url.charAt(r.length))||!Number.isFinite(e.expiresAt)||e.expiresAt<=n||e.expiresAt>n+36e5||!Number.isFinite(e.intervalMs)?null:{deviceCode:e.deviceCode,userCode:e.userCode,url:e.url,expiresAt:e.expiresAt,intervalMs:Math.min(Math.max(e.intervalMs,1e3),6e4)}}function Cr(e,t){return new Error(`Cannot keep the Vulcan sign-in in progress at ${e} (${t.message}). Remove it, or set VULCAN_STATE_DIR to a private folder, then try again.`)}async function bt(e,t={}){let n=br(e,t);try{await we.mkdir(Re.dirname(n),{recursive:!0,mode:448}),await we.chmod(Re.dirname(n),448);let r=await we.lstat(n).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!r)return null;let s=null;r.isFile()&&(s=await we.readFile(n,"utf8").then(i=>JSON.parse(i),()=>null));let a=Dn(s,t,(t.now??Date.now)());return a||await we.rm(n,{force:!0}),a}catch(r){throw Cr(n,r)}}async function Ct(e,t,n={}){let r=br(e,n),s=Re.join(Re.dirname(r),`.${Zs()}.tmp`);try{await we.mkdir(Re.dirname(r),{recursive:!0,mode:448}),await we.chmod(Re.dirname(r),448),await we.writeFile(s,JSON.stringify(t),{mode:384,flag:"wx"});try{return await we.link(s,r),t}catch(a){if(a.code!=="EEXIST")throw a}}catch(a){throw Cr(r,a)}finally{await we.rm(s,{force:!0}).catch(()=>{})}return await bt(e,n)??Ct(e,t,n)}async function je(e,t={}){let n=br(e,t);await we.rm(n,{force:!0}).catch(r=>{throw Cr(n,r)})}async function Sr(e,t={}){let{status:n,body:r}=await Bn("/api/agent/device",{client:e},t);if(n!==200||typeof r.device_code!="string"||typeof r.verification_uri_complete!="string")throw new Error(r.message??r.error??`Vulcan sign-in could not start (HTTP ${n}).`);let s=(t.now??Date.now)(),a=Dn({deviceCode:r.device_code,userCode:r.user_code,url:r.verification_uri_complete,expiresAt:s+Math.min(vr(r.expires_in,600),3600)*1e3,intervalMs:Math.max(1,vr(r.interval,5))*1e3},t,s);if(!a)throw new Error("Vulcan answered with a sign-in this tool does not recognise; update the tool and try again.");return a}var Ln=2e4;async function kr(e,t,n={}){let r=n.now??Date.now,s=n.sleep??(d=>new Promise(u=>setTimeout(u,d))),a=r()+t,i=e.intervalMs,o=null;for(;;){if(r()>=e.expiresAt)return{status:"expired"};try{let{status:d,body:u}=await Bn("/api/agent/device/token",{device_code:e.deviceCode},n,Ln);if(d===200&&typeof u.license_token=="string")return{status:"signed_in",token:u.license_token,expiresAt:String(u.expires_at??"")};if(d===403&&typeof u.code=="string")return{status:u.code==="not_entitled"?"free_account":"pro_ended"};if(u.error==="access_denied")return{status:"denied"};if(u.error==="expired_token"||u.error==="invalid_grant"||u.error==="invalid_request")return{status:"expired"};if(u.error==="slow_down")i=Math.min(Math.max(i+5e3,vr(u.interval,0)*1e3),6e4);else if(d>=500)o=typeof u.error=="string"&&u.error!=="server_error"?u.error:`Vulcan could not finish sign-in (HTTP ${d}); it will retry.`;else{if(u.error!=="authorization_pending")return{status:"error",message:typeof u.error=="string"?u.error:`Vulcan sign-in failed (HTTP ${d}).`};o=null}}catch(d){o=d.message}if(r()+i>=e.expiresAt)return{status:"expired"};if(r()+i+Ln>a)return o?{status:"error",message:o}:{status:"pending"};await s(i)}}async function Vn(e,t={}){return tr(e.workspace,t)}async function Wn(e,t){return rr(e.workspace,t)}import Jn from"fs";import be from"path";import{fileURLToPath as to}from"url";var ro=be.dirname(to(import.meta.url));function no(){let e=[],t=ro;for(let a=0;a<6;a+=1){e.push(t);let i=be.dirname(t);if(i===t)break;t=i}e.push(process.cwd());let n=[];for(let a of e)n.push({directory:be.join(a,"wasm"),context:"helper-root"},{directory:be.join(a,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:be.join(a,"web","dist","wasm"),context:"rust-hem-runner"},{directory:be.join(a,"web","dist"),context:"rust-hem-runner"},{directory:be.join(a,"web","pkg"),context:"rust-hem-runner"},{directory:be.join(a,"apps","web","public","launch"),context:"vulcan-website"});let r=[],s=new Set;for(let a of n){let i=be.join(a.directory,"wasm_wrapper.js");if(s.has(i))continue;s.add(i),r.push(i);let o=be.join(a.directory,"wasm_wrapper_bg.wasm");if(Jn.existsSync(i)&&Jn.existsSync(o))return a}throw new Error(`WASM files not found. Tried:
18
+ `+r.map(a=>` - ${a}`).join(`
20
19
  `)+`
21
- 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}=Xa();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 r;try{r=await Ae()}catch(n){let a=n;throw new Error(`WASM initialization failed: ${a.message}`)}if(!r.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return It(e.workspace,t,{validateSnippetJs:r.validateSnippetJs})}async function an(e,t){return Ot(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import{randomUUID as Ya}from"crypto";import Za from"fs/promises";import Qa from"path";async function sn(e,t){let{workspace:r}=e,{config_name:n}=t;if(!n)throw new Error("config_name is required");let a=t.job_id||`mcp_${Ya()}`,s=Qa.join(r,"input","batch_configs",n.endsWith(".json")?n:`${n}.json`),i=await Za.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(r,{...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(r),rt(r,{...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 r;try{r=await Ae()}catch(n){let a=n;throw new Error(`WASM initialization failed: ${a.message}`)}if(!r.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return qt(e.workspace,t,{calculateMetricsFromParsedData:r.calculateMetricsFromParsedData})}async function ln(e,t){return Wt(e.workspace,t)}async function un(e,t){return Ie(e.workspace,t)}import es from"fs/promises";import ts from"path";async function dn(e,t){let{workspace:r}=e,{csv_path:n,output_path:a,schema_path:s,defaults_path:i}=t;if(!n)throw new Error("csv_path is required");let o=await es.readFile(ts.resolve(r,n),"utf8").catch(()=>{});if(o!==void 0&&!!Be(o)||t.target_manifest||t.target_manifest_sha256)return st({workspace:r,csvPath:n,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(r),st({workspace:r,csvPath:n,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 pn from"path";async function _n(e,t){return Kt({csvPath:pn.isAbsolute(t.csv_path)?t.csv_path:pn.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,r])=>{if(typeof r=="string")try{let n=JSON.parse(r);return[t,Array.isArray(n)?n:[n]]}catch{return[t,[r]]}return[t,Array.isArray(r)?r:[r]]})),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.
20
+ Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var St=null;async function He(){if(St)return St;try{let{directory:e,context:t}=no();return console.error(`[WASM] Loading from ${t}: ${e}`),St=await mt(e),console.error(`[WASM] Initialized successfully from ${t}`),St}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function Un(e,t){let n;try{n=await He()}catch(r){let s=r;throw new Error(`WASM initialization failed: ${s.message}`)}if(!n.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return nr(e.workspace,t,{validateSnippetJs:n.validateSnippetJs})}async function Er(e,t,n){return Xt(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{},{gate:n})}import{randomUUID as ao}from"crypto";async function Pr(e,t,n){let{workspace:r}=e,{config_name:s}=t;if(!s)throw new Error("config_name is required");let a=t.job_id||`mcp_${ao()}`;return Zt(r,{...t,job_id:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{gate:n,processBatchConfig:async(...i)=>{let o=await He().catch(d=>{throw new Error(`WASM initialization failed: ${d.message}`)});if(!o.processBatchConfig)throw new Error("WASM process_batch_config function not available");return pt(r),o.processBatchConfig(...i)}})}async function kt(e,t={}){return Yt(e.workspace,t)}async function xr(e,t){let n;try{n=await He()}catch(r){let s=r;throw new Error(`WASM initialization failed: ${s.message}`)}if(!n.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return lr(e.workspace,t,{calculateMetricsFromParsedData:n.calculateMetricsFromParsedData})}async function Ar(e,t){return sr(e.workspace,t)}async function Et(e,t){return Ve(e.workspace,t)}async function Hn(e,t){let{workspace:n}=e,{csv_path:r,output_path:s}=t;if(!r)throw new Error("csv_path is required");return er({workspace:n,csvPath:r,outputPath:s,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import Gn from"path";async function qn(e,t){return dr({csvPath:Gn.isAbsolute(t.csv_path)?t.csv_path:Gn.join(e.workspace,t.csv_path),failOn:t.fail_on,workspace:e.workspace})}import zn from"path";async function Kn(e,t){return mr({csvPath:zn.isAbsolute(t.csv_path)?t.csv_path:zn.join(e.workspace,t.csv_path),mode:t.mode,workspace:e.workspace})}import Xn from"path";async function Zn(e,t){return fr({csvPath:Xn.isAbsolute(t.csv_path)?t.csv_path:Xn.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,workspace:e.workspace})}import{randomUUID as so}from"crypto";import Be from"fs/promises";import Rr from"path";var Yn=new WeakMap;function Qn(e){return{status:"awaiting_approval",sign_in_url:e.url,code:e.userCode,expires_in_seconds:Math.max(0,Math.round((e.expiresAt-Date.now())/1e3)),next_step:"Show the user sign_in_url and code in your reply now, before calling any tool: they open the link, sign in to Vulcan, check the code matches and click Connect. Then call vulcan_sign_in again to finish (it waits for their approval). The same code stays valid if this helper restarts."}}function ea(e){return e.configPath??Rr.join(e.workspace,"vulcan-mcp-config.json")}async function oo(e,t){let n=ea(e),r=n,s=await Be.realpath(n).catch(()=>null);s&&(await Be.lstat(n)).isSymbolicLink()&&(Rr.basename(s)==="vulcan-mcp-config.json"?r=s:await Be.rm(n));let a={};try{a=JSON.parse(await Be.readFile(r,"utf8"))}catch(o){if(o.code!=="ENOENT")throw new Error(`Could not update ${r}: ${o.message}. Fix or remove it, then sign in again.`)}let i=`${r}.${so()}.tmp`;try{await Be.writeFile(i,`${JSON.stringify({...a,license_token:t},null,2)}
21
+ `,{mode:384}),await Be.rename(i,r)}catch(o){throw await Be.rm(i,{force:!0}),o}return n}async function ta(e,t,n){let s=(Yn.get(e)??Promise.resolve()).catch(()=>{}).then(()=>io(e,t,n));return Yn.set(e,s),s}async function io(e,t,n){let r=`mcp:${Rr.resolve(ea(e))}`;try{let s=await n();if(s.pro)return await je(r).catch(()=>{}),{status:"signed_in",detail:s.detail};let a=await bt(r);return a?await co(e,t,n,r,a):Qn(await Ct(r,await Sr("Vulcan MCP helper")))}catch(s){return{status:"error",message:s.message}}}async function co(e,t,n,r,s){let a=await kr(s,(t.wait_seconds??40)*1e3);switch(a.status){case"pending":return Qn(s);case"signed_in":{await je(r);let i=e.license_token;e.license_token=a.token;let o=await n();if(!o.pro)return e.license_token=i,{status:"error",message:`Signed in, but the access Vulcan issued does not unlock this helper's Pro tools: ${o.detail}`};let d;try{d=await oo(e,a.token)}catch(u){return{status:"signed_in",detail:`Vulcan Pro tools are unlocked for this session, but the token could not be saved: ${u.message} Call vulcan_sign_in again after a restart.`,expires_at:a.expiresAt}}return e.configPath=d,{status:"signed_in",detail:"Vulcan Pro tools are unlocked.",expires_at:a.expiresAt,config_path:d,note:"The access token is saved in this file; keep it out of version control. It lasts up to seven days; call vulcan_sign_in again to renew."}}case"free_account":return await je(r),{status:"free_account",message:"Signed in, but this Vulcan account is on Free. Free tools need no sign-in and keep working; Pro tools need Vulcan Pro. After upgrading, call vulcan_sign_in again.",upgrade_url:nt};case"pro_ended":return await je(r),{status:"pro_ended",message:"Signed in, but this account's Vulcan Pro has ended. Free tools need no sign-in and keep working; renew Vulcan Pro for the Pro tools, then call vulcan_sign_in again.",upgrade_url:nt};case"denied":return await je(r),{status:"denied",message:"The user declined the sign-in. Call vulcan_sign_in to start again."};case"expired":return await je(r),{status:"expired",message:"The sign-in code expired or was already used. Call vulcan_sign_in for a new one."};case"error":return{status:"error",message:a.message}}}var Pt=C.string().optional().describe("Geometry CSV (relative to the workspace, or absolute). Omit when the workspace has one CSV in input/base_models; vulcan_list_parameters lists them."),at=C.string().describe("Batch configuration name (with or without .json)"),jr={target_manifest:C.string().optional().describe("Optional offline override: local HEM target bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:C.string().optional().describe("Expected SHA-256 of target_manifest; required with it")},lo=C.preprocess(e=>!e||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([t,n])=>{if(typeof n!="string")return[t,Array.isArray(n)?n:[n]];try{let r=JSON.parse(n);return[t,Array.isArray(r)?r:[r]]}catch{return[t,[n]]}})),C.record(C.string(),C.array(C.string())));var uo=[{name:"vulcan_sign_in",title:"Sign in to Vulcan",description:`Sign this helper in to the user's Vulcan account, to unlock the Pro tools their account includes. Free tools need no sign-in.
22
22
 
23
- Use this to discover what parameters are available before creating batch configurations.
24
- Returns a catalog of all categories (e.g., base_json, heat_source_wet, controls) and their parameters.
23
+ Two steps. The first call returns sign_in_url and a code: show both to the user in your reply straight away, before any other tool call, so they can open the link, sign in and approve. Then call vulcan_sign_in again: it waits up to wait_seconds for their approval and saves the access token in the workspace's vulcan-mcp-config.json. The code survives a restart of this helper. Call it again to renew when Pro tools report the access has expired.`,input:{wait_seconds:C.number().int().min(0).max(50).optional().describe("When a sign-in is in progress, how long this call may wait for the user to approve (default 40; most clients time a call out at 60). Each check can take up to 20 s, so a check only starts if it can finish in time; with 0 the call checks once.")},plan:"free",readOnly:!1,run:(e,t,n,r)=>ta(e,t,r)},{name:"vulcan_list_parameters",title:"List parameters",description:`List parameter categories and their JSON snippets in the workspace (input/batch_parameters), and the geometry CSVs in input/base_models.
25
24
 
26
- Example: Call with category='base_json' to see all base models available.
27
- See also: vulcan_view_parameter to see details of a specific parameter.`,inputSchema:{type:"object",properties:{category:{type:"string",description:'Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")'}}}},{name:"vulcan_view_parameter",description:`View a specific parameter JSON snippet and its markdown documentation.
25
+ Use this before creating batch configurations. Example: category="base_json" lists the base models.
26
+ See also: vulcan_view_parameter.`,input:{category:C.string().optional().describe('Optional category filter (e.g. "base_json", "heat_source_wet", "controls")')},plan:"free",readOnly:!0,workspaceLayout:!0,run:async(e,t)=>({...await Vn(e,t),geometry_csvs:await st.readdir(Te.join(e.workspace,"input","base_models")).then(n=>n.filter(r=>r.toLowerCase().endsWith(".csv")).sort().map(r=>`input/base_models/${r}`)).catch(()=>[])})},{name:"vulcan_view_parameter",title:"View parameter",description:`View one parameter JSON snippet and its markdown documentation.
28
27
 
29
- Use this to see the full content of a parameter after discovering it with vulcan_list_parameters.
30
- Returns both the JSON content and optional markdown documentation if available.
28
+ Example: category="heat_source_wet", parameter_id="hp". See also: vulcan_list_parameters.`,input:{category:C.string().describe('Parameter category (e.g. "heat_source_wet", "controls", "base_json")'),parameter_id:C.string().describe("Parameter ID (filename without .json)")},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Wn(e,t)},{name:"vulcan_save_parameter",title:"Save parameter",description:`Create or edit a parameter JSON snippet. It is validated against the HEM schema and baseline model before saving.
31
29
 
32
- Example: View the "hp" parameter in "heat_source_wet" category to see heat pump configuration.
33
- See also: vulcan_list_parameters to discover available parameters.`,inputSchema:{type:"object",required:["category","parameter_id"],properties:{category:{type:"string"},parameter_id:{type:"string"}}}},{name:"vulcan_save_parameter",description:`Create or edit a parameter JSON snippet with validation.
30
+ See also: vulcan_view_parameter to read an existing snippet first.`,input:{category:C.string().describe('Parameter category (e.g. "heat_source_wet", "controls")'),parameter_id:C.string().describe("Parameter ID (filename without .json)"),content:C.record(C.string(),C.unknown()).describe("Parameter JSON object"),markdown_content:C.string().optional().describe("Optional markdown documentation for the parameter")},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t)=>Un(e,t)},{name:"vulcan_create_batch_config",title:"Create batch configuration",description:`Create a batch configuration (base model, wrapper, weather and parameter variations) for vulcan_run_batch. All parameter files must exist.
34
31
 
35
- Use this to create new parameters or modify existing ones. The parameter will be validated
36
- against the schema and baseline model before saving. Validation ensures the parameter is
37
- compatible with the HEM engine.
32
+ A base model with a source CSV runs on the CSV's HEM target (no TargetBundleId row: Rust HEM:FHS 1.0.0a7), and the config captures its exact source. Running it with vulcan_run_batch downloads and verifies the target on first use (about 12 MB for Rust, 75 MB for Python) and needs Google Chrome. weather_file is optional for such a model; omit it for the target's reference weather.
38
33
 
39
- Example: Create a new heat pump configuration or modify an existing control schedule.
40
- See also: vulcan_view_parameter to view existing parameters before editing.`,inputSchema:{type:"object",required:["category","parameter_id","content"],properties:{category:{type:"string"},parameter_id:{type:"string"},content:{type:"object"},markdown_content:{type:"string"}}}},{name:"vulcan_create_batch_config",description:`Create a batch configuration with base model, weather file, wrapper, and parameters.
34
+ ${Ue}
35
+ See also: vulcan_list_parameters, vulcan_run_batch.`,input:{config_name:C.string().describe("Configuration name (saved as input/batch_configs/{config_name}.json)"),base_model:C.string().describe("Base model filename (without .json)"),weather_file:C.string().optional().describe("EPW filename in batch_parameters/weather_files (extension optional). Optional when the base model has a source CSV: omit it for the target's reference weather. Required only for a base model that has a prepared JSON and no source CSV"),wrapper:C.string().optional().describe('Model wrapper (e.g. "fhs_compliance", "fhs_assumptions", "passthrough")'),parameters:lo.describe("Object mapping category to an array of parameter IDs"),...jr},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t,n)=>Er(e,{...t,parameters:t.parameters},n)},{name:"vulcan_run_batch",title:"Run batch",description:`Run a batch configuration locally and asynchronously. Nothing is sent to Vulcan's servers.
41
36
 
42
- Use this to create a batch simulation configuration that can be executed with vulcan_run_batch.
43
- The config defines which parameters to combine in a batch run. All parameter files must exist. A base model whose CSV pins a HEM target (TargetBundleId) captures its exact source/snippet snapshot through that target: the first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python) and needs Google Chrome installed. weather_file is required only for unpinned models; omit it for a pinned model's reference weather. target_manifest plus target_manifest_sha256 are an optional offline override.
37
+ Unpinned batches run on the bundled engine. A batch from a pinned model runs its saved HEM target in Google Chrome (install it separately); the first use downloads and verifies the target. Long Python runs are expected; read progress with vulcan_get_batch_status.
44
38
 
45
- Example: Create a config comparing different insulation levels with a heat pump system.
46
- See also: vulcan_list_parameters to discover available parameters, vulcan_run_batch to execute.`,inputSchema:{type:"object",required:["config_name","base_model","parameters"],properties:{config_name:{type:"string"},base_model:{type:"string"},weather_file:{type:"string",description:"EPW filename (extension optional); required for unpinned models, optional for pinned models"},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"},wrapper:{type:"string"},parameters:{type:"object",additionalProperties:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}}}},{name:"vulcan_run_batch",description:`Run a batch simulation configuration asynchronously.
39
+ ${Ue}
40
+ See also: vulcan_create_batch_config, vulcan_get_batch_status.`,input:{config_name:at,job_id:C.string().optional().describe("Optional job ID (defaults to mcp_{uuid})"),...jr},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t,n)=>Pr(e,t,n)},{name:"vulcan_get_batch_status",title:"Get batch status",description:`Status, progress, pass/fail counts and warnings for a batch run.
47
41
 
48
- Use this to execute a batch configuration created with vulcan_create_batch_config.
49
- Unpinned batches run on the installed engine. A batch created from a pinned model runs its saved HEM target in Google Chrome (install it separately): the first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python), execution runs in the background, and vulcan_get_batch_status reads download and calculation progress. Long Python calculation duration is expected. target_manifest plus target_manifest_sha256 are an optional offline override.
42
+ Status is queued, running, completed or error; not_run when the config has no recorded run; unknown (with the reason) when the files cannot tell. Give job_id (from vulcan_run_batch) or config_name (reads that config's latest run, from the app or this helper).`,input:{job_id:C.string().optional().describe("Job ID returned by vulcan_run_batch"),config_name:C.string().optional().describe("Configuration name (alternative to job_id)")},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>{if(!t.job_id&&!t.config_name)throw new Error("Give job_id or config_name");return kt(e,t)}},{name:"vulcan_calculate_metrics",title:"Calculate metrics",description:`Aggregate result columns after a batch run: sum, average, peak, min, cost, and conditional sumIf/averageIf/countIf, with an optional time range.
50
43
 
51
- Example: Run a batch config named "insulation_test" to execute all parameter combinations.
52
- See also: vulcan_get_batch_status to check progress, vulcan_create_batch_config to create configs.`,inputSchema:{type:"object",required:["config_name"],properties:{config_name:{type:"string"},job_id:{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_get_batch_status",description:`Get the status, progress, and results summary of a batch run.
44
+ Cost metrics need tariff_file_path and tariff_column_index (a CSV with 17,520 half-hourly rows). Models with results only from an earlier run, or whose last run failed, are listed apart (earlier_run_models, failed_models); read the warnings before presenting results as current.
53
45
 
54
- Use this to check the progress of a batch simulation started with vulcan_run_batch.
55
- Returns current status (queued/running/completed/error; not_run when the config has no recorded run; unknown, with the reason, when the files cannot tell), progress percentage, pass/fail counts, and warnings naming any file it could not read.
46
+ Free: metrics for one model without cost or tariffs. Comparing models and cost metrics need Vulcan Pro.
47
+ See also: vulcan_list_batch_models, vulcan_list_csv_columns.`,input:{config_name:at,model_names:C.array(C.string()).describe("Model names to calculate metrics for (from vulcan_list_batch_models)"),metric_definitions:C.array(C.object({id:C.string().optional(),name:C.string().optional(),column:C.string().optional().describe("Result column name (from vulcan_list_csv_columns)"),function:C.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:C.string().optional(),threshold:C.number().optional()})).describe("Metric definitions"),time_range:C.object({start:C.number().optional(),end:C.number().optional()}).optional().describe("Optional timestep range"),tariff_file_path:C.string().optional().describe("Tariff CSV path (relative to the workspace, or absolute). Required for cost metrics."),tariff_column_index:C.number().optional().describe("Zero-based tariff column index. Required for cost metrics.")},plan:async(e,t)=>wr(t),readOnly:!0,workspaceLayout:!0,run:(e,t)=>xr(e,t)},{name:"vulcan_list_csv_columns",title:"List result columns",description:"List the columns (with units and indices) of one model's result CSV, before calculating metrics.",input:{config_name:at,model_name:C.string().describe('Model name (e.g. "scenario_1_0")')},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Ar(e,t)},{name:"vulcan_list_batch_models",title:"List batch models",description:"List the models with result CSVs from a config's latest run, each with its job_id. Results left by an earlier run are listed apart in earlier_run_models; failed or cancelled scenarios in failed_models.",input:{config_name:at},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Et(e,t)},{name:"vulcan_merge_csv_to_json",title:"Convert geometry CSV to HEM JSON",description:`Convert a geometry CSV to HEM input JSON, as saving from the geometry canvas does.
56
48
 
57
- You can provide either job_id (returned from vulcan_run_batch) or config_name. A config_name reads that config's latest run, whether the app or this helper started it; older engine runs do not record their job, so use their job_id.
49
+ The CSV's TargetBundleId row names its HEM target (no row: Rust HEM:FHS 1.0.0a7). The helper's own converter prepares the model with the target's schema and defaults. A DefaultsPath in the CSV must hold the same defaults as the target. The first use downloads and verifies the target's schema and defaults (under 1 MB) into ~/.cache/vulcan/hem-targets.`,input:{csv_path:Pt,output_path:C.string().optional().describe("Output JSON path (default input/batch_parameters/base_json/{csv name}.json)"),...jr,schema_path:C.unknown().optional().describe(`Removed. ${rt}`),defaults_path:C.unknown().optional().describe(`Removed. ${rt}`)},plan:"free",readOnly:!1,run:async(e,{schema_path:t,defaults_path:n,...r})=>{if(t!==void 0||n!==void 0)throw new Error(rt);let s=await Hn(e,{...r,csv_path:await xt(e,r.csv_path)});if(!s.ok)throw new Error(s.error??"Conversion failed");return s}},{name:"vulcan_validate_geometry_csv",title:"Validate geometry CSV",description:"Validate a geometry CSV with the same validators as the Vulcan geometry editor: element, zone, global, missing-element and Part F findings.",input:{csv_path:Pt,fail_on:C.enum(["none","critical","warning"]).optional().describe("Which findings fail the check (default critical)")},plan:"free",readOnly:!0,run:async(e,t)=>Tr(await qn(e,{...t,csv_path:await xt(e,t.csv_path)}))},{name:"vulcan_auto_thermal_bridges",title:"Propose thermal bridges",description:"Propose linear thermal bridges for each junction in a geometry CSV, with Table 3.7 default psi values. mode=json for structured proposals, summary for a table, csv-section for a pasteable Thermal Bridging Elements section. Calculated psi values (numerical solver) need Vulcan Pro in the app.",input:{csv_path:Pt,mode:C.enum(["summary","json","csv-section"]).optional().describe("Output mode (default summary)")},plan:"free",readOnly:!0,run:async(e,t)=>Tr(await Kn(e,{...t,csv_path:await xt(e,t.csv_path)}))},{name:"vulcan_validate_thermal_bridges",title:"Validate thermal bridges",description:"Validate the ThermalBridgeLinear rows in a geometry CSV. include_auto=true also validates the automatic proposals, without changing the CSV.",input:{csv_path:Pt,include_auto:C.boolean().optional().describe("Also validate the automatic thermal-bridge proposals"),mode:C.enum(["summary","json"]).optional().describe("Output mode (default summary)")},plan:"free",readOnly:!0,run:async(e,t)=>Tr(await Zn(e,{...t,csv_path:await xt(e,t.csv_path)}))},{name:"vulcan_run_model",title:"Run one model",description:`Run one model locally in a single call and return its results on the workspace's default metric templates (input/analytics/default_metrics.json): create a one-scenario configuration, run it, wait for it, and calculate each metric. Nothing is sent to Vulcan's servers.
58
50
 
59
- Example: Check status using config_name "my_batch_config" or job_id "mcp_abc123".
60
- See also: vulcan_run_batch to start a batch, vulcan_calculate_metrics to analyze results.`,inputSchema:{type:"object",properties:{job_id:{type:"string",description:"Job ID returned from vulcan_run_batch"},config_name:{type:"string",description:"Configuration name (alternative to job_id)"}}}},{name:"vulcan_calculate_metrics",description:`Calculate metrics by aggregating columns from simulation results.
51
+ Free runs use a model saved by the current Vulcan app (pinned to a HEM version), with its reference weather; Google Chrome is needed and the first use downloads the target. If the run outlasts wait_seconds, the result gives config_name: read it later with vulcan_get_batch_status and vulcan_calculate_metrics.
61
52
 
62
- Use this to compute metrics (sum, average, peak, min, cost) from CSV result files after a batch run.
63
- Supports time range filtering and conditional metrics (sumIf, averageIf).
53
+ ${Ue} Cost metrics need Vulcan Pro and a tariff (vulcan_calculate_metrics).`,input:{base_model:C.string().describe("Base model filename in input/batch_parameters/base_json (without .json)"),wrapper:C.string().optional().describe('Model wrapper (default "fhs_compliance"; Free runs use an FHS wrapper)'),weather_file:C.string().optional().describe("EPW filename; a weather choice needs Vulcan Pro"),wait_seconds:C.number().int().min(0).max(600).optional().describe("How long to wait for the run before returning (default 45; most MCP clients time out a call after 60)")},plan:"free",readOnly:!1,workspaceLayout:!0,run:async(e,t,n)=>{let r=t.wrapper??"fhs_compliance",s=new Date().toISOString().replace(/\D/g,"").slice(0,14),a=`agent_run_${t.base_model}_${s}_${Math.random().toString(36).slice(2,6)}`,i;try{i=await Er(e,{config_name:a,base_model:t.base_model,wrapper:r,...t.weather_file?{weather_file:t.weather_file}:{},parameters:{}},n)}catch(N){throw N instanceof Error&&/weather_file is required/.test(N.message)?new Error(`${t.base_model} is not pinned to a HEM version, so it would need a weather choice (Vulcan Pro). Re-save it in the current Vulcan app, or convert its geometry CSV with vulcan_merge_csv_to_json, to run it Free with its reference weather.`):N}if(!i.success)return{config_name:a,status:"not_created",...i};let o=await Pr(e,{config_name:a},n);if(o.status!=="started")return{config_name:a,...o};let d=Date.now()+(t.wait_seconds??45)*1e3,u=await kt(e,{config_name:a});for(;(u.status==="queued"||u.status==="running")&&Date.now()<d;)await new Promise(N=>setTimeout(N,2e3)),u=await kt(e,{config_name:a});if(u.status!=="completed")return{config_name:a,job_id:o.job_id,status:u.status,progress:u.progress,error:u.error,next:`Check again with vulcan_get_batch_status (config_name "${a}"), then vulcan_calculate_metrics.`};let m=await Et(e,{config_name:a}),p=m.models[0],h=p?.name,_=await yt(e.workspace),S=h?await ra(e,a,[h],_.metrics):{metrics:[],unavailable:[]},x=h?new Map((await Ar(e,{config_name:a,model_name:h}).catch(()=>({columns:[]}))).columns.map(N=>[N.name,N.unit])):new Map,k=p?.csv_path?await mo(Te.join(Te.dirname(Te.resolve(e.workspace,p.csv_path)),"fhs_compliance_report.json")):void 0,M=`input/base_models/${t.base_model}.csv`,R=await st.access(Te.join(e.workspace,M)).then(()=>!0,()=>!1);return{config_name:a,job_id:o.job_id,status:"completed",model:h,...R?{source:`${M} (the model's pinned source; edit this CSV, not base_json/${t.base_model}.json, to change what runs)`}:{},...k?{fhs_compliance:k}:{},metrics:S.metrics.map(({name:N,column:I,function:O,value:W})=>({name:N,column:I,function:O,value:W,unit:O==="compliance"?aa[I]??null:x.get(I)??null})),...S.unavailable.length||_.unsupported.length?{unavailable:[...S.unavailable,..._.unsupported]}:{},...h?{}:{note:m.latest_run_unknown??"The run completed but listed no current model; see vulcan_list_batch_models."},..._.metrics.length===0?{metrics_note:"This workspace has no default metric templates; list columns with vulcan_list_csv_columns and use vulcan_calculate_metrics."}:{},..._.cost_metrics.length>0?{cost_metrics_not_run:_.cost_metrics,cost_note:"Cost metrics need a tariff and Vulcan Pro."}:{}}}},{name:"vulcan_compare_scenarios",title:"Compare scenarios",description:"Compare every model from a batch run side by side on the workspace's default metric templates (input/analytics/default_metrics.json): one row per model, with failed or out-of-date models listed apart. Needs Vulcan Pro.",input:{config_name:at},plan:"pro",readOnly:!0,workspaceLayout:!0,run:async(e,t)=>{let n=await Et(e,t),r=await yt(e.workspace),s=n.models.length>0?await ra(e,t.config_name,n.models.map(o=>o.name),r.metrics):{metrics:[],unavailable:[]},a=r.metrics.map((o,d)=>({key:o.id??`metric_${d+1}`,name:o.name})),i=n.models.map(o=>({model:o.name,values:Object.fromEntries(a.map(d=>[d.key,s.metrics.find(u=>u.model_name===o.name&&(u.id===d.key||u.name===d.name))?.value??null]))}));return{config_name:t.config_name,columns:a,rows:i,...s.unavailable.length||r.unsupported.length?{unavailable:[...s.unavailable,...r.unsupported]}:{},...n.failed_models?.length?{failed_models:n.failed_models}:{},...n.earlier_run_models?.length?{earlier_run_models:n.earlier_run_models}:{},...n.latest_run_unknown?{latest_run_unknown:n.latest_run_unknown}:{},...r.cost_metrics.length?{cost_metrics_not_run:r.cost_metrics,cost_note:"Cost needs a tariff: use vulcan_calculate_metrics."}:{}}}}],aa={dwelling_emission_rate:"kgCO2e/m2/yr",dwelling_primary_energy_rate:"kWh/m2/yr",dwelling_fabric_energy_efficiency:"kWh/m2/yr"};async function mo(e){let t;try{t=JSON.parse(await st.readFile(e,"utf8"))}catch{return}let n=["emission_rate","primary_energy_rate","fabric_energy_efficiency"].map(r=>({measure:r,dwelling:t[`dwelling_${r}`]??null,target:t[`target_${r}`]??null,compliant:t[`${r}_compliant`]??null,unit:aa[`dwelling_${r}`]}));return{compliant:n.every(r=>r.compliant===!0),measures:n,note:"From the FHS wrapper's compliance report; a preview, not a lodged compliance result."}}async function xt(e,t){let n=await st.readdir(Te.join(e.workspace,"input","base_models")).then(i=>i.filter(o=>o.toLowerCase().endsWith(".csv")).sort().map(o=>`input/base_models/${o}`)).catch(()=>[]),r=n.length?`Geometry CSVs in this workspace: ${n.join(", ")}.`:"This workspace has no geometry CSVs in input/base_models.";if(t===void 0){if(n.length===1)return n[0];throw new Error(`Give csv_path. ${r}`)}let s=Te.isAbsolute(t)?t:Te.join(e.workspace,t);if(!(await st.stat(s).catch(()=>{}))?.isFile())throw new Error(`No geometry CSV at ${t}. ${r}`);return t}function Tr(e){if(e.error)throw new Error(`${e.error}${e.stderr?` (${e.stderr.trim().slice(0,500)})`:""}`);if("critical_issues"in e||"counts"in e){let{parsed:t,...n}=e;return n}return e}async function ra(e,t,n,r){let s=[],a=[];for(let i of r)try{let o=await xr(e,{config_name:t,model_names:n,metric_definitions:[i]});s.push(...o.metrics)}catch(o){a.push({name:i.name??i.column??"metric",reason:o.message})}return{metrics:s,unavailable:a}}function sa(e){let t=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{result:e};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}}function na(e,t,n){return sa(yr(e,t,n.detail,"If the user has Vulcan Pro, call vulcan_sign_in to sign in from here; otherwise they can upgrade at upgrade_url."))}function oa(e,t,n=Dr){for(let r of uo)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:r.input,annotations:{title:r.title,readOnlyHint:r.readOnly,openWorldHint:!1}},async s=>{if(r.workspaceLayout&&await Qt(t.workspace),r.plan!=="free"){let a=r.plan==="pro"?{reason:"This tool needs Vulcan Pro."}:await r.plan(t,s);if(a){let i=await n(t);if(!i.pro)return na(r.name,a,i)}}try{return sa(await r.run(t,s,hr(()=>n(t)),()=>n(t)))}catch(a){if(!(a instanceof Je))throw a;return na(r.name,a.requirement,{pro:!1,detail:a.accessDetail})}})}var Ge=Fr.version,ho=`Vulcan tools for Home Energy Model (HEM) workspaces. Everything runs on this machine; models and results are not sent to Vulcan.
54
+ Free: parameters, geometry CSV validation and conversion, automatic thermal bridges (Part F findings included in geometry validation), and single-model runs with FHS results against targets.
55
+ Vulcan Pro (https://usevulcan.app/join) adds scenario batches, weather and parameter variations, model comparison and cost metrics. A Pro tool called without Pro returns status "requires_pro" with what is missing; tell the user rather than retrying.`;function la(e){let t=new po({name:"vulcan-mcp-helper",version:Ge},{instructions:ho});return oa(t,e),wo(t),t}function wo(e){let t=e.server,n=t._oninitialize?.bind(e.server);if(!n)return;t.removeRequestHandler("initialize");let r=ca.extend({params:ca.shape.params.partial().optional().transform((s={})=>({protocolVersion:s.protocolVersion||"2024-11-05",capabilities:s.capabilities||{},clientInfo:s.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});t.setRequestHandler(r,s=>n(s))}function ua(e){console.error(`[MCP Helper] v${Ge}; workspace: ${e.workspace}`),console.error(e.configPath?`[MCP Helper] Config: ${e.configPath}`:"[MCP Helper] No config file: Free tools only.")}async function da(e={}){let t=await Ft(e);ua(t),await la(t).connect(new _o)}async function ma(e={},t){let n=t||parseInt(process.env.HELPER_PORT||"5000",10),r=await Ft(e),s=r.license_token;if(!s)throw new Error("HTTP mode needs a Vulcan Pro access config (license_token), used as its Bearer credential. Run with --stdio for Free use.");ua(r);let a=ia(),i=fo({origin:!0,methods:["GET","OPTIONS"],credentials:!1});a.post("/mcp",ia.raw({type:"application/json",limit:"10mb"}),async(o,d)=>{try{await Vr(o.headers.authorization,s)}catch(h){let _=h.message;console.error(`[MCP Helper] Rejected MCP request: ${_}`),d.set("WWW-Authenticate",'Bearer realm="vulcan-mcp"').status(401).json({jsonrpc:"2.0",error:{code:-32001,message:`Unauthorized: ${_}`},id:null});return}let u;try{u=JSON.parse(o.body.toString("utf-8"))}catch(h){d.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:h.message},id:null});return}let m=la(r),p=new go({sessionIdGenerator:void 0,enableJsonResponse:!0});d.on("close",()=>{p.close(),m.close()});try{await m.connect(p),await p.handleRequest(o,d,u)}catch(h){let _=h;console.error(`[MCP Helper] MCP request failed: ${_.message}`),d.headersSent||d.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:_.message},id:u?.id??null})}}),a.get("/health",i,(o,d)=>{d.json({status:"running",port:n,version:Ge,name:"vulcan-mcp-helper"})}),a.get("/helper/status",i,(o,d)=>{d.json({running:!0,port:n,version:Ge,mcpReady:!0})}),a.listen(n,"127.0.0.1",()=>{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`)})}Number(process.versions.node.split(".")[0])<20&&(console.error(`vulcan-mcp-helper requires Node >=20.0.0; current Node is ${process.versions.node}.`),process.exit(1));var vo=`Usage: vulcan-mcp-helper --stdio [--workspace <dir>] [--config <path>]
56
+ vulcan-mcp-helper [--config <path>] [--port <port>]
64
57
 
65
- For cost metrics, provide tariff_file_path and tariff_column_index to use time-of-use tariff rates.
66
- Tariff file must be CSV with 17,520 rows (half-hourly for a full year).
58
+ Vulcan tools for Home Energy Model workspaces. Everything runs on this machine.
67
59
 
68
- A requested model with results only from an earlier run gets no metrics. It is listed in earlier_run_models with that run's job_id.
69
- A requested model whose last run failed or was cancelled gets no metrics. It is listed in failed_models with that run's job_id and error.
70
- When no run of the config is current, latest_run_unknown says why (for example, the latest run failed before it wrote any scenario). warnings name files that could not be read and scenarios with no results yet.
71
- 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.
60
+ --stdio Talk MCP over stdin/stdout, as Claude Code, Codex, Claude Desktop and
61
+ Cursor launch it. Free tools need no account.
62
+ --workspace <dir> Workspace folder (default: VULCAN_WORKSPACE, else the current folder).
63
+ --config <path> vulcan-mcp-config.json with a Vulcan Pro license_token (default: the
64
+ workspace's vulcan-mcp-config.json when present).
65
+ --port <port> Local HTTP port for Pro configs (default 5000). HTTP needs the Pro token.
66
+ --version, -v Print the version.
67
+ --help, -h Show this help.
72
68
 
73
- Example: Calculate total electricity consumption and peak demand for all models in a batch.
74
- Example with tariff: Calculate cost using Octopus Agile rates from input/tariff_data_structured/Octopus.csv, column index 2.
75
- See also: vulcan_get_batch_status to check if batch is complete, vulcan_run_batch to start batch.`,inputSchema:{type:"object",required:["config_name","model_names","metric_definitions"],properties:{config_name:{type:"string"},model_names:{type:"array",items:{type:"string"}},metric_definitions:{type:"array"},time_range:{type:"object",description:"Optional time range filter (start and end timesteps)",properties:{start:{type:"number"},end:{type:"number"}}},tariff_file_path:{type:"string",description:"Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."},tariff_column_index:{type:"number",description:"Zero-based index of tariff column in CSV. Required for cost metrics."}}}},{name:"vulcan_list_csv_columns",description:`List available columns from a CSV result file.
76
-
77
- Use this to discover what columns are available in a model's results before calculating metrics.
78
- Returns column names, units, and their indices.
79
-
80
- Example: List columns for model "scenario_1_0" in config "my_batch" to see available data columns.
81
- See also: vulcan_list_batch_models to get model names, vulcan_calculate_metrics to compute metrics.`,inputSchema:{type:"object",required:["config_name","model_name"],properties:{config_name:{type:"string"},model_name:{type:"string"}}}},{name:"vulcan_list_batch_models",description:`List all model names from a completed batch run.
82
-
83
- Use this to discover which models were generated by a batch run, so you can use them in vulcan_calculate_metrics.
84
- Returns the models with result CSV files from the config's latest run, each with its job_id. Results an earlier run left behind (for example after a failed re-run) are listed apart in earlier_run_models: they do not reflect the latest inputs.
85
- Scenarios whose last run failed or was cancelled are listed in failed_models with that run's error. When no run is current, latest_run_unknown says why. warnings name files that could not be read and scenarios with no results yet.
86
- 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.
87
-
88
- Example: List models from config "my_batch" to get ["scenario_1_0", "scenario_1_1", ...].
89
- 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.
90
-
91
- This tool performs the same conversion as the geometry canvas save operation:
92
- - Parses CSV geometry data
93
- - Merges with the declared defaults template (supports CSV metadata DefaultsPath)
94
- - Validates against schema
95
- - Saves JSON to workspace
96
-
97
- The tool supports CSV metadata DefaultsPath (same as geometry canvas), which allows
98
- the CSV file to specify its own defaults template path in the metadata section.
99
- If a CSV declares DefaultsPath, that file must load; the standard defaults template
100
- is used only for legacy CSVs with no DefaultsPath row.
101
-
102
- A CSV saved by the current app pins a HEM target (TargetBundleId) and is prepared by that
103
- target's own schema, defaults and converter in Google Chrome (install it separately). The
104
- first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python) into
105
- ~/.cache/vulcan/hem-targets. target_manifest plus target_manifest_sha256 are an optional
106
- offline override.
107
-
108
- Example: Convert input/base_models/my_model.csv to JSON.
109
- 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.
110
-
111
- This wraps npm run validate:geometry-csv and reuses the same pure web validators used by
112
- Build Geometry. It reports element, zone, global, missing-element, and Part F findings
113
- without reimplementing validation logic in MCP.
114
-
115
- Example: Validate input/base_models/H283_target.csv before merging or running batches.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},fail_on:{type:"string",enum:["none","critical","warning"]}}}},{name:"vulcan_auto_thermal_bridges",description:`Generate auto thermal-bridge proposals through the existing Vulcan auto-TB CLI.
116
-
117
- This wraps the Community CLI's thermal-bridges command and reuses the web app's per-junction thermal-bridge
118
- proposal pipeline. Use mode=json for structured proposals, summary for a compact table,
119
- or csv-section for a pasteable Thermal Bridging Elements CSV section.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},mode:{type:"string",enum:["summary","json","csv-section"]}}}},{name:"vulcan_validate_thermal_bridges",description:`Validate ThermalBridgeLinear rows through the existing Vulcan TB validation CLI.
120
-
121
- This wraps the Community CLI's thermal-bridges --validate command and reuses findLinearThermalBridgeIssues plus
122
- validateElementCore. Set include_auto=true to validate existing CSV rows plus synthesized
123
- 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,r){switch(e){case"vulcan_list_parameters":{let n=he.vulcan_list_parameters.parse(t);return await en(r,n)}case"vulcan_view_parameter":{let n=he.vulcan_view_parameter.parse(t);return await tn(r,n)}case"vulcan_save_parameter":{let{category:n,parameter_id:a,content:s,markdown_content:i}=t||{};if(!n||typeof n!="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:n,parameter_id:a,content:s,...i?{markdown_content:i}:{}};return await nn(r,o)}case"vulcan_create_batch_config":{let{config_name:n,base_model:a,weather_file:s,wrapper:i,parameters:o,target_manifest:m,target_manifest_sha256:u}=t||{};if(!n||typeof n!="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,_])=>{if(typeof _=="string")try{let C=JSON.parse(_);return[h,Array.isArray(C)?C:[C]]}catch{return[h,[_]]}return[h,Array.isArray(_)?_:[_]]}))}let f={config_name:n,base_model:a,weather_file:s,...i?{wrapper:i}:{},parameters:d,target_manifest:m,target_manifest_sha256:u};return await an(r,f)}case"vulcan_run_batch":{let n=he.vulcan_run_batch.parse(t);return await sn(r,n)}case"vulcan_get_batch_status":{let n=he.vulcan_get_batch_status.parse(t);return await on(r,n)}case"vulcan_calculate_metrics":{let n=he.vulcan_calculate_metrics.parse(t);return await cn(r,n)}case"vulcan_list_csv_columns":{let n=he.vulcan_list_csv_columns.parse(t);return await ln(r,n)}case"vulcan_list_batch_models":{let n=he.vulcan_list_batch_models.parse(t);return await un(r,n)}case"vulcan_merge_csv_to_json":{let n=he.vulcan_merge_csv_to_json.parse(t);return await dn(r,n)}case"vulcan_validate_geometry_csv":{let n=he.vulcan_validate_geometry_csv.parse(t);return await fn(r,n)}case"vulcan_auto_thermal_bridges":{let n=he.vulcan_auto_thermal_bridges.parse(t);return await _n(r,n)}case"vulcan_validate_thermal_bridges":{let n=he.vulcan_validate_thermal_bridges.parse(t);return await gn(r,n)}default:throw new Error(`Unknown tool: ${e}`)}}async function Sn(e,t){let r=t||parseInt(process.env.HELPER_PORT||"5000",10),n;try{n=await or(e),console.error(`[MCP Helper] Config loaded from: ${n.configPath}`),console.error(`[MCP Helper] Workspace: ${n.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 rs({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(as,async()=>({tools:yn})),i.setRequestHandler(ss,async m=>{let{name:u,arguments:d}=m.params;console.error(`[MCP Helper] Tool call: ${u}`);try{let f=await wn(u,d,n);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,n.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 _=h;u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:_.message},id:null});return}let f=new ns({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{f.close()});try{await i.connect(f),await f.handleRequest(m,u,d)}catch(h){let _=h;console.error(`[MCP Helper] MCP request failed: ${_.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:_.message},id:d?.id||null})}}),a.get("/health",bn(s),(m,u)=>{u.json({status:"running",port:r,version:"0.1.0",name:"vulcan-mcp-helper"})}),a.get("/helper/status",bn(s),(m,u)=>{u.json({running:!0,port:r,version:"0.1.0",mcpReady:!0})}),a.listen(r,"127.0.0.1",()=>{console.error(`[MCP Helper] Server running on http://127.0.0.1:${r}`),console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${r}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${r}/health`),console.error(`[MCP Helper] Status API: http://127.0.0.1:${r}/helper/status`)})}function os(){let e=process.argv.slice(2),t={};for(let r=0;r<e.length;r++)if(e[r]==="--config"&&r+1<e.length)t.configPath=e[r+1],r++;else if(e[r]==="--port"&&r+1<e.length){let n=e[r+1];n||(console.error("Port argument is missing"),process.exit(1));let a=parseInt(n,10);(isNaN(a)||a<1||a>65535)&&(console.error(`Invalid port: ${n}`),process.exit(1)),t.port=a,r++}else(e[r]==="--help"||e[r]==="-h")&&(console.log(`
124
- Usage: vulcan-mcp-helper [--config <path>] [--port <port>]
125
-
126
- Options:
127
- --config <path> Path to vulcan-mcp-config.json (default: ./vulcan-mcp-config.json)
128
- --port <port> Port to listen on (default: 5000)
129
- --help, -h Show this help message
130
-
131
- Examples:
132
- vulcan-mcp-helper
133
- vulcan-mcp-helper --config /path/to/vulcan-mcp-config.json
134
- vulcan-mcp-helper --port 5000
135
- vulcan-mcp-helper --config ./config.json --port 5000
136
- `),process.exit(0));return t}async function is(){try{let{configPath:e,port:t}=os();await Sn(e,t)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}is();
69
+ Claude Code: claude mcp add vulcan -- npx -y @vulcan-energy/mcp-helper --stdio --workspace /path/to/workspace
70
+ Setup guide: https://usevulcan.app/docs/vulcan-mcp-server-guide`;async function bo(){let{values:e}=yo({options:{stdio:{type:"boolean"},workspace:{type:"string"},config:{type:"string"},port:{type:"string"},version:{type:"boolean",short:"v"},help:{type:"boolean",short:"h"}}});if(e.help){console.log(vo);return}if(e.version){console.log(Ge);return}let t={configPath:e.config,workspace:e.workspace};if(e.stdio){if(e.port)throw new Error("--port applies to HTTP mode, not --stdio");await da(t);return}let n;if(e.port!==void 0&&(n=Number.parseInt(e.port,10),!Number.isInteger(n)||n<1||n>65535))throw new Error(`Invalid port: ${e.port}`);await ma(t,n)}bo().catch(e=>{console.error(`Error: ${e.message}`),process.exit(1)});
137
71
  /*! Bundled license information:
138
72
 
139
73
  papaparse/papaparse.js: