@vulcan-energy/mcp-helper 0.2.3 → 0.2.4

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,24 +1,24 @@
1
1
  #!/usr/bin/env node
2
- var mn=Object.create;var zt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,hn=Object.prototype.hasOwnProperty;var gn=(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 yn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var wn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of pn(t))!hn.call(e,a)&&a!==r&&zt(e,a,{get:()=>t[a],enumerable:!(n=fn(t,a))||n.enumerable});return e};var vn=(e,t,r)=>(r=e!=null?mn(_n(e)):{},wn(t||!e||!e.__esModule?zt(r,"default",{value:e,enumerable:!0}):r,e));var rr=yn((_t,ht)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof ht=="object"&&typeof _t<"u"?ht.exports=t():e.Papa=t()})(_t,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function r(){var i=t.URL||t.webkitURL||null,l=e.toString();return s.BLOB_URL||(s.BLOB_URL=i.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,o={},c=0,s={};if(s.parse=u,s.unparse=m,s.RECORD_SEP="",s.UNIT_SEP="",s.BYTE_ORDER_MARK="\uFEFF",s.BAD_DELIMITERS=["\r",`
3
- `,'"',s.BYTE_ORDER_MARK],s.WORKERS_SUPPORTED=!n&&!!t.Worker,s.NODE_STREAM_INPUT=1,s.LocalChunkSize=1024*1024*10,s.RemoteChunkSize=1024*1024*5,s.DefaultDelimiter=",",s.Parser=N,s.ParserHandle=Z,s.NetworkStreamer=g,s.FileStreamer=h,s.StringStreamer=S,s.ReadableStreamStreamer=w,typeof PAPA_BROWSER_CONTEXT>"u"&&(s.DuplexStreamStreamer=T),t.jQuery){var d=t.jQuery;d.fn.parse=function(i){var l=i.config||{},f=[];return this.each(function(E){var v=d(this).prop("tagName").toUpperCase()==="INPUT"&&d(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!v||!this.files||this.files.length===0)return!0;for(var O=0;O<this.files.length;O++)f.push({file:this.files[O],inputElem:this,instanceConfig:d.extend({},l)})}),y(),this;function y(){if(f.length===0){$(i.complete)&&i.complete();return}var E=f[0];if($(i.before)){var v=i.before(E.file,E.inputElem);if(typeof v=="object")if(v.action==="abort"){b("AbortError",E.file,E.inputElem,v.reason);return}else if(v.action==="skip"){R();return}else typeof v.config=="object"&&(E.instanceConfig=d.extend(E.instanceConfig,v.config));else if(v==="skip"){R();return}}var O=E.instanceConfig.complete;E.instanceConfig.complete=function(D){$(O)&&O(D,E.file,E.inputElem),R()},s.parse(E.file,E.instanceConfig)}function b(E,v,O,D){$(i.error)&&i.error({name:E},v,O,D)}function R(){f.splice(0,1),y()}}}a&&(t.onmessage=fe);function u(i,l){l=l||{};var f=l.dynamicTyping||!1;if($(f)&&(l.dynamicTypingFunction=f,f={}),l.dynamicTyping=f,l.transform=$(l.transform)?l.transform:!1,l.worker&&s.WORKERS_SUPPORTED){var y=ne();y.userStep=l.step,y.userChunk=l.chunk,y.userComplete=l.complete,y.userError=l.error,l.step=$(l.step),l.chunk=$(l.chunk),l.complete=$(l.complete),l.error=$(l.error),delete l.worker,y.postMessage({input:i,config:l,workerId:y.id});return}var b=null;if(i===s.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return b=new T(l),b.getStream();return typeof i=="string"?(i=R(i),l.download?b=new g(l):b=new S(l)):i.readable===!0&&$(i.read)&&$(i.on)?b=new w(l):(t.File&&i instanceof File||i instanceof Object)&&(b=new h(l)),b.stream(i);function R(E){return E.charCodeAt(0)===65279?E.slice(1):E}}function m(i,l){var f=!1,y=!0,b=",",R=`\r
4
- `,E='"',v=E+E,O=!1,D=null,G=!1;ie();var A=new RegExp(q(E),"g");if(typeof i=="string"&&(i=JSON.parse(i)),Array.isArray(i)){if(!i.length||Array.isArray(i[0]))return P(null,i,O);if(typeof i[0]=="object")return P(D||Object.keys(i[0]),i,O)}else if(typeof i=="object")return typeof i.data=="string"&&(i.data=JSON.parse(i.data)),Array.isArray(i.data)&&(i.fields||(i.fields=i.meta&&i.meta.fields||D),i.fields||(i.fields=Array.isArray(i.data[0])?i.fields:typeof i.data[0]=="object"?Object.keys(i.data[0]):[]),!Array.isArray(i.data[0])&&typeof i.data[0]!="object"&&(i.data=[i.data])),P(i.fields||[],i.data||[],O);throw new Error("Unable to serialize unrecognized input");function ie(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!s.BAD_DELIMITERS.filter(function(F){return l.delimiter.indexOf(F)!==-1}).length&&(b=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")&&(O=l.skipEmptyLines),typeof l.newline=="string"&&(R=l.newline),typeof l.quoteChar=="string"&&(E=l.quoteChar),typeof l.header=="boolean"&&(y=l.header),Array.isArray(l.columns)){if(l.columns.length===0)throw new Error("Option columns is empty");D=l.columns}l.escapeChar!==void 0&&(v=l.escapeChar+E),l.escapeFormulae instanceof RegExp?G=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(G=/^[=+\-@\t\r].*$/)}}function P(F,B,H){var z="";typeof F=="string"&&(F=JSON.parse(F)),typeof B=="string"&&(B=JSON.parse(B));var le=Array.isArray(F)&&F.length>0,Q=!Array.isArray(B[0]);if(le&&y){for(var me=0;me<F.length;me++)me>0&&(z+=b),z+=j(F[me],me);B.length>0&&(z+=R)}for(var L=0;L<B.length;L++){var Se=le?F.length:B[L].length,pe=!1,k=le?Object.keys(B[L]).length===0:B[L].length===0;if(H&&!le&&(pe=H==="greedy"?B[L].join("").trim()==="":B[L].length===1&&B[L][0].length===0),H==="greedy"&&le){for(var x=[],M=0;M<Se;M++){var V=Q?F[M]:M;x.push(B[L][V])}pe=x.join("").trim()===""}if(!pe){for(var C=0;C<Se;C++){C>0&&!k&&(z+=b);var W=le&&Q?F[C]:C;z+=j(B[L][W],C)}L<B.length-1&&(!H||Se>0&&!k)&&(z+=R)}}return z}function j(F,B){if(typeof F>"u"||F===null)return"";if(F.constructor===Date)return JSON.stringify(F).slice(1,25);var H=!1;G&&typeof F=="string"&&G.test(F)&&(F="'"+F,H=!0);var z=F.toString().replace(A,v);return H=H||f===!0||typeof f=="function"&&f(F,B)||Array.isArray(f)&&f[B]||Re(z,s.BAD_DELIMITERS)||z.indexOf(b)>-1||z.charAt(0)===" "||z.charAt(z.length-1)===" ",H?E+z+E:z}function Re(F,B){for(var H=0;H<B.length;H++)if(F.indexOf(B[H])>-1)return!0;return!1}}function p(i){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,i),this.parseChunk=function(f,y){let b=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&b>0){let G=this._config.newline;if(!G){let ie=this._config.quoteChar||'"';G=this._handle.guessLineEndings(f,ie)}f=[...f.split(G).slice(b)].join(G)}if(this.isFirstChunk&&$(this._config.beforeFirstChunk)){var R=this._config.beforeFirstChunk(f);R!==void 0&&(f=R)}this.isFirstChunk=!1,this._halted=!1;var E=this._partialLine+f;this._partialLine="";var v=this._handle.parse(E,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var O=v.meta.cursor;this._finished||(this._partialLine=E.substring(O-this._baseIndex),this._baseIndex=O),v&&v.data&&(this._rowCount+=v.data.length);var D=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(a)t.postMessage({results:v,workerId:s.WORKER_ID,finished:D});else if($(this._config.chunk)&&!y){if(this._config.chunk(v,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}v=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(v.data),this._completeResults.errors=this._completeResults.errors.concat(v.errors),this._completeResults.meta=v.meta),!this._completed&&D&&$(this._config.complete)&&(!v||!v.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!D&&(!v||!v.meta.paused)&&this._nextChunk(),v},this._sendError=function(f){$(this._config.error)?this._config.error(f):a&&this._config.error&&t.postMessage({workerId:s.WORKER_ID,error:f,finished:!1})};function l(f){var y=de(f);y.chunkSize=parseInt(y.chunkSize),!f.step&&!f.chunk&&(y.chunkSize=null),this._handle=new Z(y),this._handle.streamer=this,this._config=y}}function g(i){i=i||{},i.chunkSize||(i.chunkSize=s.RemoteChunkSize),p.call(this,i);var l;n?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(y){this._input=y,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=I(this._chunkLoaded,this),l.onerror=I(this._chunkError,this)),l.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var y=this._config.downloadRequestHeaders;for(var b in y)l.setRequestHeader(b,y[b])}if(this._config.chunkSize){var R=this._start+this._config.chunkSize-1;l.setRequestHeader("Range","bytes="+this._start+"-"+R)}try{l.send(this._config.downloadRequestBody)}catch(E){this._chunkError(E.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>=f(l),this.parseChunk(l.responseText)}},this._chunkError=function(y){var b=l.statusText||y;this._sendError(new Error(b))};function f(y){var b=y.getResponseHeader("Content-Range");return b===null?-1:parseInt(b.substring(b.lastIndexOf("/")+1))}}g.prototype=Object.create(p.prototype),g.prototype.constructor=g;function h(i){i=i||{},i.chunkSize||(i.chunkSize=s.LocalChunkSize),p.call(this,i);var l,f,y=typeof FileReader<"u";this.stream=function(b){this._input=b,f=b.slice||b.webkitSlice||b.mozSlice,y?(l=new FileReader,l.onload=I(this._chunkLoaded,this),l.onerror=I(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 b=this._input;if(this._config.chunkSize){var R=Math.min(this._start+this._config.chunkSize,this._input.size);b=f.call(b,this._start,R)}var E=l.readAsText(b,this._config.encoding);y||this._chunkLoaded({target:{result:E}})},this._chunkLoaded=function(b){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(b.target.result)},this._chunkError=function(){this._sendError(l.error)}}h.prototype=Object.create(p.prototype),h.prototype.constructor=h;function S(i){i=i||{},p.call(this,i);var l;this.stream=function(f){return l=f,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var f=this._config.chunkSize,y;return f?(y=l.substring(0,f),l=l.substring(f)):(y=l,l=""),this._finished=!l,this.parseChunk(y)}}}S.prototype=Object.create(S.prototype),S.prototype.constructor=S;function w(i){i=i||{},p.call(this,i);var l=[],f=!0,y=!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(b){this._input=b,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){y&&l.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),l.length?this.parseChunk(l.shift()):f=!0},this._streamData=I(function(b){try{l.push(typeof b=="string"?b:b.toString(this._config.encoding)),f&&(f=!1,this._checkIsFinished(),this.parseChunk(l.shift()))}catch(R){this._streamError(R)}},this),this._streamError=I(function(b){this._streamCleanUp(),this._sendError(b)},this),this._streamEnd=I(function(){this._streamCleanUp(),y=!0,this._streamData("")},this),this._streamCleanUp=I(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}w.prototype=Object.create(p.prototype),w.prototype.constructor=w;function T(i){var l=gn("stream").Duplex,f=de(i),y=!0,b=!1,R=[],E=null;this._onCsvData=function(v){var O=v.data;!E.push(O)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){E.push(null)},f.step=I(this._onCsvData,this),f.complete=I(this._onCsvComplete,this),p.call(this,f),this._nextChunk=function(){b&&R.length===1&&(this._finished=!0),R.length?R.shift()():y=!0},this._addToParseQueue=function(v,O){R.push(I(function(){if(this.parseChunk(typeof v=="string"?v:v.toString(f.encoding)),$(O))return O()},this)),y&&(y=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(v,O,D){this._addToParseQueue(v,D)},this._onWriteComplete=function(){b=!0,this._addToParseQueue("")},this.getStream=function(){return E},E=new l({readableObjectMode:!0,decodeStrings:!1,read:I(this._onRead,this),write:I(this._onWrite,this)}),E.once("finish",I(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(T.prototype=Object.create(p.prototype),T.prototype.constructor=T);function Z(i){var l=Math.pow(2,53),f=-l,y=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,b=/^((\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)))$/,R=this,E=0,v=0,O,D,G=!1,A=!1,ie,P=[],j={data:[],errors:[],meta:{}};if($(i.step)){var Re=i.step;i.step=function(k){if(j=k,z())H();else{if(H(),j.data.length===0)return;E+=k.data.length,i.preview&&E>i.preview?D.abort():(j.data=j.data[0],Re(j,R))}}}this.parse=function(k,x,M){var V=i.quoteChar||'"';if(i.newline||(i.newline=this.guessLineEndings(k,V)),ie=!1,i.delimiter)$(i.delimiter)&&(i.delimiter=i.delimiter(k),j.meta.delimiter=i.delimiter);else{var C=Se(k,i.newline,i.skipEmptyLines,i.comments,i.delimitersToGuess);C.successful?i.delimiter=C.bestDelimiter:(ie=!0,i.delimiter=s.DefaultDelimiter),j.meta.delimiter=i.delimiter}var W=de(i);return i.preview&&i.header&&W.preview++,O=k,D=new N(W),j=D.parse(O,x,M),H(),G?{meta:{paused:!0}}:j||{meta:{paused:!1}}},this.paused=function(){return G},this.pause=function(){G=!0,D.abort(),O=$(i.chunk)?"":O.substring(D.getCharIndex())},this.resume=function(){R.streamer._halted?(G=!1,R.streamer.parseChunk(O,!0)):setTimeout(R.resume,3)},this.aborted=function(){return A},this.abort=function(){A=!0,D.abort(),j.meta.aborted=!0,$(i.complete)&&i.complete(j),O=""},this.guessLineEndings=function(k,x){k=k.substring(0,1024*1024);var M=new RegExp(q(x)+"([^]*?)"+q(x),"gm");k=k.replace(M,"");var V=k.split("\r"),C=k.split(`
5
- `),W=C.length>1&&C[0].length<V[0].length;if(V.length===1||W)return`
6
- `;for(var ee=0,X=0;X<V.length;X++)V[X][0]===`
7
- `&&ee++;return ee>=V.length/2?`\r
8
- `:"\r"};function F(k){return i.skipEmptyLines==="greedy"?k.join("").trim()==="":k.length===1&&k[0].length===0}function B(k){if(y.test(k)){var x=parseFloat(k);if(x>f&&x<l)return!0}return!1}function H(){return j&&ie&&(pe("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+s.DefaultDelimiter+"'"),ie=!1),i.skipEmptyLines&&(j.data=j.data.filter(function(k){return!F(k)})),z()&&le(),L()}function z(){return i.header&&P.length===0}function le(){if(!j)return;function k(M,V){$(i.transformHeader)&&(M=i.transformHeader(M,V)),P.push(M)}if(Array.isArray(j.data[0])){for(var x=0;z()&&x<j.data.length;x++)j.data[x].forEach(k);j.data.splice(0,1)}else j.data.forEach(k)}function Q(k){return i.dynamicTypingFunction&&i.dynamicTyping[k]===void 0&&(i.dynamicTyping[k]=i.dynamicTypingFunction(k)),(i.dynamicTyping[k]||i.dynamicTyping)===!0}function me(k,x){return Q(k)?x==="true"||x==="TRUE"?!0:x==="false"||x==="FALSE"?!1:B(x)?parseFloat(x):b.test(x)?new Date(x):x===""?null:x:x}function L(){if(!j||!i.header&&!i.dynamicTyping&&!i.transform)return j;function k(M,V){var C=i.header?{}:[],W;for(W=0;W<M.length;W++){var ee=W,X=M[W];i.header&&(ee=W>=P.length?"__parsed_extra":P[W]),i.transform&&(X=i.transform(X,ee)),X=me(ee,X),ee==="__parsed_extra"?(C[ee]=C[ee]||[],C[ee].push(X)):C[ee]=X}return i.header&&(W>P.length?pe("FieldMismatch","TooManyFields","Too many fields: expected "+P.length+" fields but parsed "+W,v+V):W<P.length&&pe("FieldMismatch","TooFewFields","Too few fields: expected "+P.length+" fields but parsed "+W,v+V)),C}var x=1;return!j.data.length||Array.isArray(j.data[0])?(j.data=j.data.map(k),x=j.data.length):j.data=k(j.data,0),i.header&&j.meta&&(j.meta.fields=P),v+=x,j}function Se(k,x,M,V,C){var W,ee,X,je;C=C||[","," ","|",";",s.RECORD_SEP,s.UNIT_SEP];for(var Ee=0;Ee<C.length;Ee++){var Be=C[Ee],Me=0,ke=0,ae=0;X=void 0;for(var ye=new N({comments:V,delimiter:Be,newline:x,preview:10}).parse(k),te=0;te<ye.data.length;te++){if(M&&F(ye.data[te])){ae++;continue}var ce=ye.data[te].length;if(ke+=ce,typeof X>"u"){X=ce;continue}else ce>0&&(Me+=Math.abs(ce-X),X=ce)}ye.data.length>0&&(ke/=ye.data.length-ae),(typeof ee>"u"||Me<=ee)&&(typeof je>"u"||ke>je)&&ke>1.99&&(ee=Me,W=Be,je=ke)}return i.delimiter=W,{successful:!!W,bestDelimiter:W}}function pe(k,x,M,V){var C={type:k,code:x,message:M};V!==void 0&&(C.row=V),j.errors.push(C)}}function q(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(i){i=i||{};var l=i.delimiter,f=i.newline,y=i.comments,b=i.step,R=i.preview,E=i.fastMode,v,O=null,D=!1;i.quoteChar===void 0||i.quoteChar===null?v='"':v=i.quoteChar;var G=v;if(i.escapeChar!==void 0&&(G=i.escapeChar),(typeof l!="string"||s.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),y===l)throw new Error("Comment character same as delimiter");y===!0?y="#":(typeof y!="string"||s.BAD_DELIMITERS.indexOf(y)>-1)&&(y=!1),f!==`
9
- `&&f!=="\r"&&f!==`\r
10
- `&&(f=`
11
- `);var A=0,ie=!1;this.parse=function(P,j,Re){if(typeof P!="string")throw new Error("Input must be a string");var F=P.length,B=l.length,H=f.length,z=y.length,le=$(b);A=0;var Q=[],me=[],L=[],Se=0;if(!P)return ae();if(E||E!==!1&&P.indexOf(v)===-1){for(var pe=P.split(f),k=0;k<pe.length;k++){if(L=pe[k],A+=L.length,k!==pe.length-1)A+=f.length;else if(Re)return ae();if(!(y&&L.substring(0,z)===y)){if(le){if(Q=[],Ee(L.split(l)),ye(),ie)return ae()}else Ee(L.split(l));if(R&&k>=R)return Q=Q.slice(0,R),ae(!0)}}return ae()}for(var x=P.indexOf(l,A),M=P.indexOf(f,A),V=new RegExp(q(G)+q(v),"g"),C=P.indexOf(v,A);;){if(P[A]===v){for(C=A,A++;;){if(C=P.indexOf(v,C+1),C===-1)return Re||me.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:Q.length,index:A}),Me();if(C===F-1){var W=P.substring(A,C).replace(V,v);return Me(W)}if(v===G&&P[C+1]===G){C++;continue}if(!(v!==G&&C!==0&&P[C-1]===G)){x!==-1&&x<C+1&&(x=P.indexOf(l,C+1)),M!==-1&&M<C+1&&(M=P.indexOf(f,C+1));var ee=M===-1?x:Math.min(x,M),X=Be(ee);if(P.substr(C+1+X,B)===l){L.push(P.substring(A,C).replace(V,v)),A=C+1+X+B,P[C+1+X+B]!==v&&(C=P.indexOf(v,A)),x=P.indexOf(l,A),M=P.indexOf(f,A);break}var je=Be(M);if(P.substring(C+1+je,C+1+je+H)===f){if(L.push(P.substring(A,C).replace(V,v)),ke(C+1+je+H),x=P.indexOf(l,A),C=P.indexOf(v,A),le&&(ye(),ie))return ae();if(R&&Q.length>=R)return ae(!0);break}me.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:Q.length,index:A}),C++}}continue}if(y&&L.length===0&&P.substring(A,A+z)===y){if(M===-1)return ae();A=M+H,M=P.indexOf(f,A),x=P.indexOf(l,A);continue}if(x!==-1&&(x<M||M===-1)){L.push(P.substring(A,x)),A=x+B,x=P.indexOf(l,A);continue}if(M!==-1){if(L.push(P.substring(A,M)),ke(M+H),le&&(ye(),ie))return ae();if(R&&Q.length>=R)return ae(!0);continue}break}return Me();function Ee(te){Q.push(te),Se=A}function Be(te){var ce=0;if(te!==-1){var Pe=P.substring(C+1,te);Pe&&Pe.trim()===""&&(ce=Pe.length)}return ce}function Me(te){return Re||(typeof te>"u"&&(te=P.substring(A)),L.push(te),A=F,Ee(L),le&&ye()),ae()}function ke(te){A=te,Ee(L),L=[],M=P.indexOf(f,A)}function ae(te){if(i.header&&!j&&Q.length&&!D){let ce=Q[0],Pe=Object.create(null),ot=new Set(ce),qt=!1;for(let Te=0;Te<ce.length;Te++){let we=ce[Te];if($(i.transformHeader)&&(we=i.transformHeader(we,Te)),!Pe[we])Pe[we]=1,ce[Te]=we;else{let Le,Ht=Pe[we];do Le=`${we}_${Ht}`,Ht++;while(ot.has(Le));ot.add(Le),ce[Te]=Le,Pe[we]++,qt=!0,O===null&&(O={}),O[Le]=we}ot.add(we)}qt&&console.warn("Duplicate headers found and renamed."),D=!0}return{data:Q,errors:me,meta:{delimiter:l,linebreak:f,aborted:ie,truncated:!!te,cursor:Se+(j||0),renamedHeaders:O}}}function ye(){b(ae()),Q=[],me=[]}},this.abort=function(){ie=!0},this.getCharIndex=function(){return A}}function ne(){if(!s.WORKERS_SUPPORTED)return!1;var i=r(),l=new t.Worker(i);return l.onmessage=Y,l.id=c++,o[l.id]=l,l}function Y(i){var l=i.data,f=o[l.workerId],y=!1;if(l.error)f.userError(l.error,l.file);else if(l.results&&l.results.data){var b=function(){y=!0,K(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},R={abort:b,pause:ue,resume:ue};if($(f.userStep)){for(var E=0;E<l.results.data.length&&(f.userStep({data:l.results.data[E],errors:l.results.errors,meta:l.results.meta},R),!y);E++);delete l.results}else $(f.userChunk)&&(f.userChunk(l.results,R,l.file),delete l.results)}l.finished&&!y&&K(l.workerId,l.results)}function K(i,l){var f=o[i];$(f.userComplete)&&f.userComplete(l),f.terminate(),delete o[i]}function ue(){throw new Error("Not implemented.")}function fe(i){var l=i.data;if(typeof s.WORKER_ID>"u"&&l&&(s.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:s.WORKER_ID,results:s.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var f=s.parse(l.input,l.config);f&&t.postMessage({workerId:s.WORKER_ID,results:f,finished:!0})}}function de(i){if(typeof i!="object"||i===null)return i;var l=Array.isArray(i)?[]:{};for(var f in i)l[f]=de(i[f]);return l}function I(i,l){return function(){i.apply(l,arguments)}}function $(i){return typeof i=="function"}return s})});import cn from"express";import ln from"cors";import{Server as Da}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Va}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as Ja,CallToolRequestSchema as Ua,InitializeRequestSchema as un}from"@modelcontextprotocol/sdk/types.js";import ft from"fs/promises";import Oe from"path";var Gt=Object.freeze(["mcp","analyst"]);function it(e){return typeof e=="string"&&Gt.includes(e)}var He="https://usevulcan.app",ct="vulcan-local-tools",ze=1,lt=10080*60,ut=300,J=class extends Error{code;constructor(t,r){super(r),this.name="CapabilityTokenError",this.code=t}};var Kt=Object.freeze([`-----BEGIN PUBLIC KEY-----
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-----
12
12
  MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
13
- -----END PUBLIC KEY-----`]);import{compactVerify as bn,importSPKI as Cn}from"jose";var Xt="EdDSA";async function mt(e,t){let r=e.trim();if(!r)throw new J("empty","Vulcan access token is empty.");let n=t.publicKeys??Kt,a=t.now??(()=>new Date),o=Math.floor(a().getTime()/1e3),c=await Sn(r,n),s=En(c);if(s.iss!==He)throw new J("wrong_issuer",`Vulcan access token was issued by ${s.iss}, not ${He}.`);if(s.aud!==ct)throw new J("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(s.entitlement_schema_version!==ze)throw new J("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${s.entitlement_schema_version}, but this build understands version ${ze}. Update your Vulcan tools.`);if(!s.capabilities.includes(t.capability))throw new J("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(s.exp-s.iat>lt)throw new J("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(o<s.iat-ut)throw new J("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let d=o>s.exp;if(d&&!t.allowExpired)throw new J("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:s,expired:d,expiresAt:new Date(s.exp*1e3),expiresInSeconds:s.exp-o}}async function Sn(e,t){for(let r of t)try{let n=await Cn(r,Xt),{payload:a}=await bn(e,n,{algorithms:[Xt]});return a}catch{}throw new J("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function En(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new J("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new J("malformed","Vulcan access token payload is not an object.");let r=t,n=Ie(r,"iss"),a=Ie(r,"aud"),o=Ie(r,"sub"),c=Ie(r,"org"),s=Ie(r,"jti"),d=dt(r,"iat"),u=dt(r,"exp"),m=dt(r,"entitlement_schema_version");if(!Array.isArray(r.capabilities))throw new J("malformed","Vulcan access token must include a capabilities array.");let p=[];for(let g of r.capabilities){if(!it(g))throw new J("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(g)}.`);p.push(g)}if(p.length===0)throw new J("malformed","Vulcan access token grants no capabilities.");if(u<=d)throw new J("malformed","Vulcan access token expires no later than it was issued.");return{iss:n,aud:a,sub:o,org:c,jti:s,capabilities:Object.freeze(p),entitlement_schema_version:m,iat:d,exp:u}}function Ie(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new J("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return r}function dt(e,t){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new J("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return r}var kn="mcp",Pn=2880*60;async function Yt(e){let t=e;if(!t){let u=process.env.VULCAN_WORKSPACE;u?t=Oe.join(u,"vulcan-mcp-config.json"):t=Oe.join(process.cwd(),"vulcan-mcp-config.json")}t=Oe.resolve(t);let r;try{r=await ft.readFile(t,"utf-8")}catch(u){let m=u;throw new Error(`Config file not found: ${t}. Please generate it from Vulcan \u2192 Integrations \u2192 MCP.`)}let n;try{n=JSON.parse(r)}catch(u){let m=u;throw new Error(`Invalid JSON in config file: ${m.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=Oe.resolve(Oe.dirname(t),n.workspace);try{await ft.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}let o=Oe.join(a,"input","batch_parameters");try{await ft.access(o)}catch{throw new Error(`Workspace missing required directory: ${o}. MCP only supports folder (FSA) workspaces backed by the real filesystem.`)}let{payload:c}=await pt(n.license_token),s=Math.floor(Date.now()/1e3),d=c.exp-s;if(d<Pn){let u=Math.max(1,Math.round(d/3600));console.error(`[MCP Helper] Warning: your Vulcan access config expires in about ${u} hour(s). Open Vulcan -> Profile -> Integrations and click "Generate Config File" to avoid interruption.`)}return{workspace:a,license_token:n.license_token,configPath:t}}async function pt(e,t={}){try{let{claims:r}=await mt(e,{capability:kn,now:t.now,publicKeys:t.publicKeys});return{payload:r}}catch(r){throw new Error(xn(r))}}function xn(e){if(!(e instanceof J))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 An}from"crypto";function Rn(e){if(typeof e!="string")throw new Error("MCP request Bearer token is required");let t=/^Bearer[\t ]+([^\t ]+)$/i.exec(e.trim());if(!t?.[1])throw new Error("MCP request Bearer token is required");return t[1]}function jn(e,t){let r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&An(r,n)}async function Zt(e,t,r=pt){let n=Rn(e);if(!jn(n,t))throw new Error("MCP request Bearer token is invalid");await r(n)}import{z as _}from"zod";import Mn from"fs/promises";import Tn from"path";function Qt(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[o,c]of Object.entries(e)){if(!c||typeof c!="object"){r.push(`Scenario '${o}' must be an object`);continue}let s=c;Array.isArray(s.base_json)?s.base_json.length!==1&&r.push(`Scenario '${o}' must have exactly one base_json (found ${s.base_json.length})`):r.push(`Scenario '${o}' is missing required 'base_json' field (must be array)`);let d=!!(s.weather_file||s.weather_files),u=!!s.external_conditions;if(d){let m=s.weather_file||s.weather_files;Array.isArray(m)?m.length>1&&r.push(`Scenario '${o}' must have at most one weather_file (found ${m.length})`):r.push(`Scenario '${o}' weather_file/weather_files must be an array`)}u&&!Array.isArray(s.external_conditions)&&r.push(`Scenario '${o}' external_conditions must be an array`),t.requireWeather!==!1&&!d&&!u&&r.push(`Scenario '${o}' must have either 'weather_files' or 'external_conditions'`),d&&u&&n.push(`Scenario '${o}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,p]of Object.entries(s))Array.isArray(p)||r.push(`Scenario '${o}': '${m}' must be an array`)}return{valid:r.length===0,errors:r,warnings:n}}function er(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 o of Object.values(n))Array.isArray(o)&&(a*=o.length);t+=a}return t}catch{return null}}async function tr(e,t){let r=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:n};for(let[a,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let c=o;for(let[s,d]of Object.entries(c))if(Array.isArray(d)&&!(s==="weather_file"||s==="weather_files"))for(let u of d){let m=Tn.join(e,"input","batch_parameters",s,`${String(u)}.json`);try{await Mn.access(m)}catch{n.push({scenario:a,category:s,parameter:String(u),path:m}),r.push(`Scenario '${a}': Parameter '${String(u)}' in category '${s}' not found at ${m}`)}}}return{valid:r.length===0,errors:r,missingFiles:n}}import{readFile as br}from"fs/promises";import{join as Cr}from"path";var On=vn(rr(),1),Fn=Object.defineProperty,$n=Object.getOwnPropertyNames,Nn=(e,t)=>function(){return e&&(t=(0,e[$n(e)[0]])(e=0)),t},Bn=(e,t)=>{for(var r in t)Fn(e,r,{get:t[r],enumerable:!0})},Ln={};Bn(Ln,{configureWasm:()=>In,getRuntimeApiUrl:()=>zn,getRuntimeWasmVariant:()=>Un,getVersionedWasmAssetPaths:()=>wt,getVersionedWasmJsUrl:()=>cr,getWasmAssetPaths:()=>ir,getWasmBaseUrl:()=>yt,getWasmBinaryUrl:()=>lr,getWasmJsUrl:()=>mr,getWasmRayonThreadCount:()=>ar,getWasmVariant:()=>or,getWasmVersionInfo:()=>Ge,getWasmVersionJsonUrl:()=>sr,getWasmWasmUrl:()=>fr,initializeWasmRayonThreadPool:()=>Jn});function In(e={}){e.baseUrl&&(ur=Wn(e.baseUrl)),typeof e.preferHashed=="boolean"&&(dr=e.preferHashed)}function nr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Wn(e){return e.replace(/\/+$/,"")||"/"}function Dn(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Vn(){let e=nr();if(e){if(Dn(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function yt(){return ur||Vn()}function ar(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Jn(e){let t=e,r=We.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(ar())).then(()=>{});return We.set(t,a),a.catch(()=>{We.get(t)===a&&We.delete(t)}),a}function sr(){return`${yt()}/wasm_version.json`}async function Ge(){try{let e=await fetch(sr(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function or(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function Un(){return or(await Ge())}function qn(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function Hn(e){let t=qn(),n=!!((dr??!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 ir(e){let t=yt(),r=e===void 0?await Ge():e,{jsFilename:n,wasmFilename:a}=Hn(r);return{jsPath:`${t}/${n}`,wasmPath:`${t}/${a}`}}async function wt(){let e=await Ge(),{jsPath:t,wasmPath:r}=await ir(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 cr(){let{jsPath:e}=await wt();return e}async function lr(){let{wasmPath:e}=await wt();return e}function zn(e){let t=nr();return t?new URL(e,t.origin).toString():e}var We,ur,dr,mr,fr,pr=Nn({"src/wasmPath.ts"(){We=new WeakMap,mr=cr,fr=lr}});async function _r(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 hr(e,t){let r=await _r(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 gr(e,t){let r=t.lastIndexOf("/"),n=await _r(e,t.slice(0,r));return(n===null||n.has(t.slice(r+1)))&&await e.fileExists(t)}function vt(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))}pr();function Gn(e){return e.startsWith("__")}function yr(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,r])=>!Gn(t)&&!!r&&typeof r=="object"&&!Array.isArray(r)).map(([t,r])=>({name:t,value:r}))}function Kn(){try{let r=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(r&&gt(r))return r;let n=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(n&&gt(n))return n;let o=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(o&&gt(o))return o}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function gt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var fs=Kn();pr();import wr from"fs/promises";import bt from"path";var Ct="input/defaults/defaults_template.json",St="input/batch_parameters/base_json/defaults_template.json",Xn="batch_parameters/base_json/defaults_template.json",Yn="defaults/defaults_template.json";function Zn(e){let r=e.split(`
14
- `).slice(0,50).find(o=>/^DefaultsPath,/i.test(o.trim()));return r&&(Ke(r)[1]||"").trim()||null}function Qn(e){let t=e.trim().replace(/\\/g,"/");return t===St||t.endsWith("/batch_parameters/base_json/defaults_template.json")}function ea(e){let t=e.trim();if(!t)return[];if(!Qn(t))return[t];let r=t.replace(/\\/g,"/"),n=r.lastIndexOf(Xn);return[n>=0?`${r.slice(0,n)}${Yn}`:Ct,t]}async function vr(e){let t=(e.explicitDefaultsPath??"").trim(),r=t||Zn(e.csvContent);if(r){let n=ea(r),a;for(let c of n){let s=bt.isAbsolute(c)?c:bt.join(e.workspace,c);try{return{defaultsJson:await wr.readFile(s,"utf8"),source:t?`custom: ${c}`:`CSV metadata: ${c}`,path:s}}catch(d){a=d}}let o=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. ${o}`)}for(let n of[Ct,St,"defaults_template.json"]){let a=bt.join(e.workspace,n);try{return{defaultsJson:await wr.readFile(a,"utf8"),source:"legacy fallback: standard defaults template",path:a}}catch{}}throw new Error(`Defaults file not found. Tried ${Ct}, ${St}, defaults_template.json`)}function Ke(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}function Et(e,t=!1){let r="",n=1,a,o=[];for(let c of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!c.trim())continue;let s=Ke(c).map(u=>u.trim());if(s[0]=s[0]?.replace(/^#\s*/,"")??"",s[0]&&s.slice(1).every(u=>!u)){r=s[0],a=void 0;continue}if(r==="Metadata"){if(s[0]==="TargetBundleId"&&s[1]&&!t)return`CSV pins TargetBundleId '${s[1]}'. Merge it with vulcan_merge_csv_to_json, which prepares it with its pinned target; the installed legacy converter cannot substitute that bundle.`;s[0]==="VulcanCsvVersion"&&(n=Number(s[1]));continue}if(r!=="Non-Exposed Elements")continue;if(!a){a=s;continue}let d=Object.fromEntries(a.map((u,m)=>[u,s[m]??""]));d.Type==="BuildingElementPartyWall"&&o.push(d)}if(!Number.isInteger(n)||n<1||n>3)return`Unsupported or invalid VulcanCsvVersion '${n}'; supported versions are 1, 2 and 3.`;for(let c of o){let s={};if(c.extra_json)try{s=JSON.parse(c.extra_json)}catch{return`Invalid extra_json for party wall '${c.Name||"unnamed"}'; resolve it before finalizing CSV version 3.`}let d=!!c.u_value||s&&Object.hasOwn(s,"u_value"),u=c.u_value?Number(c.u_value):s?.u_value,m=n<3&&typeof s?.u_value_interpreted_value=="number"&&s.u_value_interpreted_value!==u,p=n>=3&&s?.u_value_interpretation!=="whole_wall"&&s?.u_value_interpretation!=="half_construction";if(d&&(p||m))return`E_CSV_MIGRATION: Party wall '${c.Name||"unnamed"}' has unresolved legacy U-value meaning. Explicitly select whole_wall or half_construction before finalizing CSV version 3.`}}function Fe(e){let t=!1,r;for(let n of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!n.trim())continue;let a=Ke(n).map(o=>o.trim());if(a[0]=a[0]?.replace(/^#\s*/,"")??"",a[0]&&a.slice(1).every(o=>!o)){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 Xe(e,t){let r=new Set;for(let{value:n}of yr(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 ta(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 ta(e,t){try{let r=JSON.parse(await br(Cr(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")throw r}try{return Fe(await br(Cr(e,"input/base_models",`${t}.csv`),"utf8"))}catch(r){if(r.code==="ENOENT")return;throw r}}async function kt(e,t){let r;try{r=await Xe(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 ra}from"child_process";import{resolve as na}from"path";import{access as aa}from"fs/promises";import{fileURLToPath as Sr}from"url";var De=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 aa(Sr(n))}catch{continue}let a=t?{...e,manifestPath:na(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{...e};if(e.operation==="batch")return sa(Sr(n),a);let{runTargetBrowser:o}=await import(n.href);return o(a)}throw new Error("Target browser assets are not installed. Build the local target CLI assets or install a helper release including them.")};function sa(e,t){return new Promise((r,n)=>{let a=ra(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),o=setTimeout(()=>{a.kill(),n(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",c=>{clearTimeout(o),n(c)}),a.once("exit",c=>{clearTimeout(o),n(new Error(`Target batch stopped before startup (${c})`))}),a.once("message",c=>{clearTimeout(o),c.started?(a.unref(),r({status:"started"})):(a.kill(),n(new Error(c.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as oa}from"crypto";import se from"fs/promises";import oe from"path";async function Pt(e,t,r={},n={}){let{config_name:a,base_model:o,weather_file:c,wrapper:s,parameters:d}=t;if(!a)throw new Error("config_name is required");if(!o)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=ia(d),m={base_json:[o],...s?{model_wrappers:[s]}:{},...u},p=await Xe(e,{scenario_1:m}),g=!!(t.targetManifestPath||t.targetManifestSha256||p);if(!c&&!g)throw new Error("weather_file is required");if(g&&(!/^[a-zA-Z0-9_. -]+$/.test(a)||a===".."))throw new Error("Invalid target config name");c&&(m.weather_files=[g&&!c.endsWith(".epw")?`${c}.epw`:c]);let h={scenario_1:m},S=Qt(h,{requireWeather:!g});if(!S.valid)return{success:!1,valid:!1,errors:S.errors,warnings:S.warnings,message:`Config validation failed: ${S.errors.join("; ")}`};let w=er(h);if(w===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let T=r.maxPermutations??500;if(!Number.isSafeInteger(T)||T<1)throw new Error("maxPermutations must be a positive integer");if(w>T)return{success:!1,valid:!1,errors:[`Total permutations (${w}) exceeds maximum of ${T}`],message:`Config would generate ${w} permutations, which exceeds the limit of ${T}`};let Z=h;if(g){let Y=await(n.runTarget??De)({workspace:e,operation:"snapshot",config:h,targetBundleId:p,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});Z={...h,__hem:Y}}else{let Y=await tr(e,h);if(!Y.valid)return{success:!1,valid:!1,errors:Y.errors,missingFiles:Y.missingFiles,message:`Some parameter files are missing: ${Y.errors.slice(0,3).join("; ")}${Y.errors.length>3?"...":""}`};let K=oe.join(e,"input","batch_parameters","base_json",`${o}.json`);try{await se.access(K)}catch{return{success:!1,valid:!1,errors:[`Base model '${o}' not found at ${K}`],message:`Base model file not found: ${o}`}}let ue=oe.join(e,"input","batch_parameters","weather_files",c.endsWith(".epw")?c:`${c}.epw`);try{await se.access(ue)}catch{return{success:!1,valid:!1,errors:[`Weather file '${c}' not found at ${ue}`],message:`Weather file not found: ${c}`}}}let q=oe.join(e,"input","batch_configs");if(g){let Y=await se.realpath(e);for(let K of["input","batch_configs"])if(Y=oe.join(Y,K),await se.mkdir(Y).catch(ue=>{if(ue.code!=="EEXIST")throw ue}),await se.realpath(Y)!==Y)throw new Error("Target config directory is a symlink")}else await se.mkdir(q,{recursive:!0});let N=a.endsWith(".json")?a:`${a}.json`,ne=oe.join(q,N);try{return await se.access(ne),{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 se.writeFile(ne,JSON.stringify(Z,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:ne,permutations:w,structure:h}}async function Ye(e,t,r){let{config_name:n,job_id:a}=t;if(!n)throw new Error("config_name is required");let o=a||r.generateJobId?.()||`mcp_${oa()}`,c=n.endsWith(".json")?n:`${n}.json`,s=oe.join(e,"input","batch_configs",c),d;try{d=await se.readFile(s,"utf8")}catch(g){let h=g;throw h.code==="ENOENT"?new Error(`Batch config '${n}' not found at ${s}`):new Error(`Failed to read config file: ${h.message}`)}let u=JSON.parse(d);if(u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let g=u.__hem;if(!g){let h="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:o,status:"error",message:h,error:h}}try{return await(r.runTarget??De)({workspace:e,operation:"batch",config:u,targetBundleId:g.targetBundleId,configName:n.replace(/\.json$/,""),jobId:o,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:o,status:"started",config_name:n,output_dir:oe.join(e,"output"),message:"Exact target batch started. Read progress with vulcan_get_batch_status; runtime provenance is stored with outputs."}}catch(h){let S=h.message;return{job_id:o,status:"error",message:S,error:S}}}let m=await kt(e,u);if(m)return{job_id:o,status:"error",message:m,error:m};if(t.targetManifestPath||t.targetManifestSha256){let g="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:o,status:"error",message:g,error:g}}let p=oe.join(e,"output");await se.mkdir(p,{recursive:!0});try{let g=await r.processBatchConfig(d,e,p,n.replace(/\.json$/,""),o),h=JSON.parse(g);return h.error?{job_id:o,status:"error",message:`Batch execution failed: ${h.error}`,error:h.error}:{job_id:o,status:"started",message:"Batch execution started successfully",config_name:n,output_dir:p}}catch(g){let h=g;return{job_id:o,status:"error",message:`Failed to start batch execution: ${h.message}`,error:h.message}}}async function xt(e,t={}){let{job_id:r,config_name:n}=t;if(n&&!r){let S=oe.join(e,"output"),w=n.replace(/\.json$/,"");try{let Z=(await se.readdir(S)).filter(N=>N.startsWith("progress_")&&N.endsWith(".json")).map(N=>({name:N,jobId:N.replace("progress_","").replace(".json",""),path:oe.join(S,N),isMcp:N.startsWith("progress_mcp_")})),q=await Promise.all(Z.map(async N=>{try{let ne=await se.stat(N.path);return{...N,mtime:ne.mtime}}catch{return{...N,mtime:new Date(0)}}}));q.sort((N,ne)=>N.isMcp&&!ne.isMcp?-1:!N.isMcp&&ne.isMcp?1:ne.mtime.getTime()-N.mtime.getTime()),q[0]&&(r=q[0].jobId)}catch(T){console.warn(`Failed to find job_id for config_name '${n}': ${T.message}`)}if(!r)return{config_name:w,status:"queued",progress:0,passes:0,failures:0,output_dir:oe.join(e,"output"),error:null,batch_progress:void 0,sim_progress:void 0}}if(!r)throw new Error("Either job_id or config_name is required");let a=oe.join(e,"output"),o=oe.join(a,`progress_${r}.json`),c=oe.join(a,`sim_progress_${r}.json`),s=null,d=null;try{s=JSON.parse(await se.readFile(o,"utf8"))}catch(S){let w=S;w.code!=="ENOENT"&&console.warn(`Failed to read batch progress: ${w.message}`)}try{d=JSON.parse(await se.readFile(c,"utf8"))}catch(S){let w=S;w.code!=="ENOENT"&&console.warn(`Failed to read simulation progress: ${w.message}`)}let u="queued",m=0,p=0,g=0,h=null;if(s&&(Er(s.status)?u=s.status:typeof s.percentage=="number"?(m=s.percentage,u=m>=100?"completed":"running"):typeof s.current_combination=="number"&&typeof s.total_combinations=="number"&&(m=Math.round(s.current_combination/s.total_combinations*100),u=m>=100?"completed":"running"),typeof s.percentage=="number"&&(m=s.percentage),typeof s.error=="string"&&(h=s.error,u="error")),d&&!s?.targetBundleId&&(Er(d.status)&&(u=d.status),typeof d.passes=="number"&&(p=d.passes),typeof d.failures=="number"&&(g=d.failures),typeof d.error=="string"&&(h=d.error,u="error")),!s&&!d){let S=oe.join(a,r);try{let w=await se.readdir(S);u=w.length>0?"completed":"queued",m=w.length>0?100:0}catch{u="queued"}}return{job_id:r,...n?{config_name:n.replace(/\.json$/,"")}:{},status:u,progress:m,passes:p,failures:g,output_dir:a,error:h,batch_progress:s,sim_progress:s?.targetBundleId?null:d}}function ia(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Array.isArray(r)?r.map(String):[String(r)]]))}function Er(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Gs from"crypto";import be from"fs/promises";import U from"path";import Ve from"fs";import xe from"path";import{fileURLToPath as ca}from"url";function Ze(e=process.cwd()){let t=xe.resolve(e);for(Ve.existsSync(t)&&Ve.statSync(t).isFile()&&(t=xe.dirname(t));;){if(Ve.existsSync(xe.join(t,"package.json"))&&Ve.existsSync(xe.join(t,"hem-batch-core"))&&Ve.existsSync(xe.join(t,"web")))return t;let n=xe.dirname(t);if(n===t)break;t=n}let r=xe.dirname(ca(import.meta.url));return xe.resolve(r,"..","..","..")}import kr from"fs/promises";import Qe from"path";function la(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=Pr(a)[1]?.trim().toUpperCase()==="TRUE";continue}if(/^SchemaProfile,/i.test(a)){let o=Pr(a)[1]?.trim().toLowerCase();o==="ecaas_input_fhs"&&(r="ecaas_input_fhs"),o==="input_fhs"&&(r="input_fhs"),o==="input_core"&&(r="input_core")}}return r||(t?"input_fhs":"input_core")}async function xr(e){let t=la(e.csvContent);if(e.explicitSchemaPath){let a=Qe.isAbsolute(e.explicitSchemaPath)?e.explicitSchemaPath:Qe.resolve(e.workspace??process.cwd(),e.explicitSchemaPath);return{mode:t,source:a,schemaJson:await kr.readFile(a,"utf8")}}let r=ua({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 kr.readFile(a,"utf8")}}catch{}}throw new Error(`Schema file not found for ${t}. Tried: ${n.join(", ")}`)}function ua(e){let t=[];if(e.repoRoot&&t.push(Qe.join(e.repoRoot,...da(e.mode))),e.workspace){let r=ma(e.mode);t.push(...r.map(n=>Qe.join(e.workspace,...n)))}return[...new Set(t)]}function da(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 ma(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 Pr(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}import ve from"fs";import _e from"path";import{pathToFileURL as fa}from"url";var Ar=new Map,Rr=!1,At=process.cwd(),Mr=!1;async function Rt(e){let t=Ar.get(e);if(t)return t;pa();let r=_e.join(e,"wasm_wrapper.js"),n=_e.join(e,"wasm_wrapper_bg.wasm"),a=_e.join(e,"wasm_version.json");if(!ve.existsSync(r)||!ve.existsSync(n))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(fa(r).href);if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:ve.readFileSync(n)}),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 c={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:$e,metadata:{source:r,wasm_path:n,wasm_version:ga(a),build_stamp:Ue(o.build_stamp),build_info:ya(o.get_build_info),runtime_origin_descriptor:Ue(o.runtime_origin_descriptor),hem_core_version:Ue(o.metadata_hem_core_version),fhs_wrapper_version:Ue(o.metadata_fhs_wrapper_version)}};return Ar.set(e,c),c}function $e(e,t={}){At=_e.resolve(e),Mr=t.confineToWorkspace===!0}function pa(){_a(),ha();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=Je(r);try{return ve.mkdirSync(_e.dirname(a),{recursive:!0}),ve.writeFileSync(a,n),!0}catch(o){return console.error(`[FS Bridge] write_file failed for ${a}:`,o.message),!1}},e.read_file=r=>{let n=Je(r);return ve.readFileSync(n,"utf8")},e.file_exists=r=>{let n=Je(r);return ve.existsSync(n)},e.create_dir_all=r=>{let n=Je(r);try{return ve.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=Je(r);try{return ve.readdirSync(n)}catch{return[]}}}function Je(e){let t=_e.isAbsolute(e)?_e.resolve(e):_e.resolve(At,e);if(Mr){let r=_e.relative(At,t);if(r===".."||r.startsWith(`..${_e.sep}`)||_e.isAbsolute(r))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function _a(){if(Rr)return;let e=console.error.bind(console);console.log=(...t)=>{let r=t[0];typeof r=="string"&&r.startsWith("[WASM]")||e(...t)},Rr=!0}var jr=!1;function ha(){if(jr)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)}),jr=!0}function ga(e){try{return JSON.parse(ve.readFileSync(e,"utf8"))}catch{return}}function Ue(e){return typeof e!="function"?void 0:e()||void 0}function ya(e){let t=Ue(e);if(t)try{return JSON.parse(t)}catch{return t}}async function Fr(e){let{workspace:t,csvContent:r,schemaJson:n,defaultsPath:a,deps:o}=e,c=Et(r);if(c)return{ok:!1,error:c};let s=await vr({workspace:t,csvContent:r,explicitDefaultsPath:a}),d;try{d=await o.convertGeometryCsvToJson(r,n,s.defaultsJson)}catch(m){return{ok:!1,error:`WASM conversion failed: ${m.message}`,defaults_source:s.source,defaults_path:s.path}}if(!d||typeof d!="string")return{ok:!1,error:"WASM returned empty or invalid result",defaults_source:s.source,defaults_path:s.path};let u=wa(d);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:s.source,defaults_path:s.path}:{ok:!0,json:u.json,validation:u.validation,defaults_source:s.source,defaults_path:s.path}}async function et(e){let{workspace:t,csvPath:r,outputPath:n,schemaPath:a,defaultsPath:o,repoRoot:c,deps:s}=e,d=U.isAbsolute(r)?r:U.join(t,r),u;try{u=await be.readFile(d,"utf8")}catch(w){let T=w;throw T.code==="ENOENT"?new Error(`CSV file not found at ${d}`):new Error(`Failed to read CSV file: ${T.message}`)}let m=Fe(u),p=Et(u,!!m);if(p)return{ok:!1,error:p};if(m){if(a||o)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(s.runTarget??De)({workspace:t,operation:"prepare",csv:u,targetBundleId:m,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),T=n?U.resolve(t,n):Tr(t,d);if(U.extname(T)!==".json")throw new Error("Prepared target output must have a .json extension");return await $r(t,T),await Or(t,U.join(t,"input/base_models",U.basename(T,".json")+".target.json"),JSON.stringify({targetBundleId:m,validation:w.validation,schema_omissions:w.schema_omissions,readiness:"wrapper_input"})),await Or(t,T,JSON.stringify(w.model,null,2)),{ok:!0,json_path:U.relative(t,T),validation:w.validation,schema_source:`target:${m}`,defaults_source:`target:${m}`}}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 g=await xr({repoRoot:c??Ze(t),workspace:t,csvContent:u,explicitSchemaPath:a}),h=await Fr({workspace:t,csvContent:u,schemaJson:g.schemaJson,defaultsPath:o,deps:s});if(!h.ok||h.json===void 0||h.json===null)return{ok:!1,validation:h.validation,error:h.error||"WASM conversion returned invalid result",defaults_source:h.defaults_source,schema_source:g.source};let S=n?U.isAbsolute(n)?n:U.join(t,n):Tr(t,d);await be.mkdir(U.dirname(S),{recursive:!0});try{await be.writeFile(S,JSON.stringify(h.json,null,2),"utf8")}catch(w){let T=w;return{ok:!1,validation:h.validation,error:`Failed to write JSON file: ${T.message}`,defaults_source:h.defaults_source,schema_source:g.source}}return{ok:!0,json_path:U.relative(t,S),validation:h.validation,defaults_source:h.defaults_source,schema_source:g.source}}function wa(e){try{return JSON.parse(e)}catch(t){return{ok:!1,error:`WASM returned invalid JSON: ${t.message}`}}}function Tr(e,t){let r=U.basename(t,U.extname(t));return U.join(e,"input","batch_parameters","base_json",`${r}.json`)}async function $r(e,t){let r=await be.realpath(e),n=U.relative(U.resolve(e),t);if(!n||n===".."||n.startsWith(`..${U.sep}`)||U.isAbsolute(n))throw new Error("Target preparation output must stay within the workspace");let a=U.join(r,n),o=r;for(let c of U.relative(r,U.dirname(a)).split(U.sep).filter(Boolean))if(o=U.join(o,c),await be.mkdir(o).catch(s=>{if(s.code!=="EEXIST")throw s}),await be.realpath(o)!==o)throw new Error("Target preparation output directory is a symlink");try{if(await be.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(c){if(c.code!=="ENOENT")throw c}return a}async function Or(e,t,r){let n=await $r(e,t),a=await be.open(n,"wx").catch(async o=>{if(o.code!=="EEXIST")throw o;if(await be.realpath(n)!==n)throw new Error("Target preparation output is a symlink");return be.open(n,"w")});try{await a.writeFile(r)}finally{await a.close()}}import he from"fs/promises";import re from"path";async function jt(e,t={}){let{category:r}=t,n=re.join(e,"input","batch_parameters"),a=await he.readdir(n,{withFileTypes:!0}),o={};for(let c of a){if(!c.isDirectory())continue;let s=c.name;if(r&&s!==r)continue;let d=re.join(n,s),u=await he.readdir(d),m=[];for(let p of u){if(!p.endsWith(".json"))continue;let g=p.replace(/\.json$/,""),h=re.join(d,p);try{let S=await he.readFile(h,"utf8"),w=JSON.parse(S);m.push({id:g,name:typeof w.name=="string"?w.name:g,description:typeof w.description=="string"?w.description:"",category:s})}catch(S){console.error(`Failed to parse ${h}: ${S.message}`)}}m.length>0&&(o[s]={category:s,parameters:m.sort((p,g)=>p.name.localeCompare(g.name))})}return{catalog:o,total_categories:Object.keys(o).length,total_parameters:Object.values(o).reduce((c,s)=>c+s.parameters.length,0)}}async function Mt(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=re.join(e,"input","batch_parameters",r),o=re.join(a,`${n}.json`),c=re.join(a,`${n}.md`),s;try{let u=await he.readFile(o,"utf8");s=JSON.parse(u)}catch(u){let m=u;throw m.code==="ENOENT"?new Error(`Parameter '${n}' not found in category '${r}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let d=null;try{d=await he.readFile(c,"utf8")}catch(u){let m=u;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:r,parameter_id:n,json:s,markdown:d,has_markdown:d!==null}}async function Tt(e,t,r){let{category:n,parameter_id:a,content:o,markdown_content:c}=t;if(!n)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(o==null||o==="")throw new Error("content is required");let s=va(o),[d,u,m]=await Promise.all([ba(e),Ca(e),Sa(e,n)]),p=r.validateSnippetJs(n,JSON.stringify(s),JSON.stringify(d),JSON.stringify(u),m?JSON.stringify(m):null),g=JSON.parse(p);if(!g.ok){let T=(g.errors??[]).map(Z=>typeof Z=="string"?Z:Z.message||String(Z));return{success:!1,valid:!1,errors:T,message:`Validation failed: ${T.join("; ")}`}}let h=re.join(e,"input","batch_parameters",n);await he.mkdir(h,{recursive:!0});let S=re.join(h,`${a}.json`);await he.writeFile(S,JSON.stringify(s,null,2),"utf8");let w=null;return c&&(w=re.join(h,`${a}.md`),await he.writeFile(w,c,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${n}'`,paths:{json:S,markdown:w}}}function va(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=[re.join(e,"input_core.schema.json"),re.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),re.join(e,"core-input.schema.json"),re.join(e,"schemas","core-input.schema.json"),re.join(e,"input.schema.json")];for(let r of t)try{return JSON.parse(await he.readFile(r,"utf8"))}catch{}throw new Error(`Schema file not found. Tried: ${t.join(", ")}`)}async function Ca(e){let t=re.join(e,"input","batch_parameters","base_json","demo_hp_annual.json");try{return JSON.parse(await he.readFile(t,"utf8"))}catch(r){let n=r;throw new Error(`Baseline model not found at ${t}: ${n.message}`)}}async function Sa(e,t){if(t!=="simplified_fabric")return null;let r=[re.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),re.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let n of r)try{return JSON.parse(await he.readFile(n,"utf8"))}catch{}return null}import $t from"fs/promises";import rt from"path";import qe from"fs/promises";import tt from"path";async function Ne(e,t){let r=tt.join(e,"output"),n=Lr(t.config_name),a=[],o=new Set;try{let c=tt.join(r,n);await Ir(c)&&await Nr(c,a,o);let d=(await qe.readdir(r)).filter(u=>u.startsWith(`result_${n}_`));for(let u of d){let m=tt.join(r,u);try{await Nr(m,a,o,u.slice(`result_${n}_`.length))}catch(p){console.warn(`Failed to read result directory ${u}: ${p.message}`)}}return a.sort((u,m)=>u.name.localeCompare(m.name)),{config_name:n,models:a,total_models:a.length,output_dir:r}}catch(c){return{config_name:n,models:[],total_models:0,output_dir:r,error:`Failed to list models: ${c.message}`}}}async function Ot(e,t){let r=Lr(t.config_name),n=await Ne(e,{config_name:r}),a=n.models.find(m=>m.name===t.model_name)?.csv_path;if(!a)return{config_name:r,model_name:t.model_name,columns:[],total_columns:0,error:n.error??`No completed actual-dwelling CSV found for model ${t.model_name}`};let c=(await qe.readFile(a,"utf8")).split(`
16
- `).filter(m=>m.trim());if(c.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 s=Br(c[0]??"").map(m=>m.trim()),d=Br(c[1]??"").map(m=>m.trim()),u=[];for(let m=1;m<s.length;m+=1){let p=s[m],g=m<d.length?d[m]:"";p&&u.push({name:p,unit:g||"",index:m-1})}return{config_name:r,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:a}}var Ft={fileExists:Ir,readFile:e=>qe.readFile(e,"utf8"),listFiles:e=>qe.readdir(e)};async function Nr(e,t,r,n){let o=(await hr(Ft,e)).map(s=>typeof s=="string"?s:s.name),c=(s,d)=>{r.has(s)||(r.add(s),t.push({name:s,csv_path:tt.join(e,d),has_results:!0}))};if(n){let s=vt(o,"results");s&&c(n,s);return}for(let s of o){if(!vt([s],"results"))continue;let d=s.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);d?.[1]&&c(d[1],s)}}function Lr(e){return e.replace(/\.json$/,"")}async function Ir(e){try{return await qe.access(e),!0}catch{return!1}}function Br(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}var Ea=new Set(["sumif","averageif","countif"]),Wr=new Set([">=","<=",">","<","="]);async function Nt(e,t,r){let{config_name:n,model_names:a,metric_definitions:o,time_range:c,tariff_file_path:s,tariff_column_index:d}=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(!o||!Array.isArray(o)||o.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=n.replace(/\.json$/,""),{encodedMetrics:m,metadata:p}=xa(o);if(p.some(w=>w.function.toLowerCase()==="cost")&&(!s||d===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let h;if(s&&d!==void 0){let w=await Aa(s,d,e);h=JSON.stringify(w)}let S=[];for(let w of a){let{csvPath:T,csvContent:Z}=await Ra({workspace:e,cleanConfigName:u,modelName:w});try{let q=ka(Z,w,n);if(p.some(K=>K.isCompliance)){let K=rt.join(rt.dirname(T),"fhs_compliance_report.json");if(!await gr(Ft,K))throw new Error("Completed FHS compliance report is unavailable");let ue=JSON.parse(await $t.readFile(K,"utf8")),fe=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let de of fe){let I=ue[de];q[de]=typeof I=="number"&&Number.isFinite(I)?I:null}for(let de of p.filter(I=>I.isCompliance)){let I=fe.find($=>$===de.column);if(!I||q[I]===null)throw new Error(`Completed FHS compliance rate '${de.column}' is unavailable`)}}if(q.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${w}`);if(Object.keys(q.columns).length===0)throw new Error(`No columns found in CSV for model ${w}`);let N=ja(q,m,p);if(N.length>0){let K=Object.keys(q.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${N.join(", ")}. Available columns: ${K.join(", ")}...`)}let ne=r.calculateMetricsFromParsedData(JSON.stringify(q),JSON.stringify(m),c?JSON.stringify(c):void 0,h);if(!ne||typeof ne!="string")throw new Error(`WASM returned invalid result: ${typeof ne}`);let Y=JSON.parse(ne);if(!Array.isArray(Y))throw new Error(`WASM returned non-array result: ${typeof Y}`);Y.forEach((K,ue)=>{let fe=p[ue],[de=K.name,I="sum"]=K.name.split("|");S.push({id:fe?.id||K.name,name:fe?.name||K.name,column:fe?.column||de,function:fe?.function||I,comparator:fe?.comparator,threshold:fe?.threshold,value:K.value,model_name:w})})}catch(q){let N=q;if(N.code==="ENOENT"){console.warn(`CSV file not found for model ${w}: ${T}`);continue}throw new Error(`Failed to process model ${w}: ${N.message}`)}}return{metrics:S,total_models:a.length,total_metrics:S.length}}function ka(e,t,r){let n=e.split(`
17
- `).filter(m=>m.trim());if(n.length<2)throw new Error("CSV must have at least headers and units rows");let a=(n[0]??"").split(",").map(m=>m.trim()),o=(n[1]??"").split(",").map(m=>m.trim()),c=[],s={},d=[],u=[];for(let m=1;m<a.length;m+=1){let p=a[m];p&&(s[p]=[],d.push(p),u.push(m<o.length&&o[m]||""))}for(let m=2;m<n.length;m+=1){let p=(n[m]??"").split(",").map(S=>S.trim());if(p.length===0||p.length===1&&!p[0])continue;let g=p[0];if(!g)continue;let h=Number.parseInt(g,10);if(!(Number.isNaN(h)||h<0)){c.push(h);for(let S=1;S<a.length&&S<p.length;S+=1){let w=a[S];if(!w||!s[w])continue;let T=p[S];if(T===void 0)continue;let Z=Number.parseFloat(T);s[w].push(Number.isNaN(Z)?0:Z)}}}return{timestamps:c,columns:s,column_order:d,column_units:u,metadata:{model_name:t,config_name:r.replace(/\.json$/,""),total_points:c.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function Pa(e){let t=(e.function||e.type||"sum").toString(),r=t.toLowerCase();if(r==="cost")return"cost";if(!Ea.has(r))return r;let n=e.comparator||">=";if(!Wr.has(n))throw new Error(`Invalid comparator "${n}" for ${t}. Use one of ${Array.from(Wr).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 xa(e){let t=[],r=[];return e.forEach((n,a)=>{if(typeof n=="string"){let d=n.includes("|")?n:`${n}|sum`,[u=n,m="sum"]=d.split("|");t.push({name:d}),r.push({id:n,name:n,column:u,function:m,isCompliance:m.toLowerCase()==="compliance"});return}let o=n.column||(n.name?.includes("|")?n.name.split("|")[0]:n.name);if(!o)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(n)}`);let c=n.name?.includes("|")&&!n.function?n.name.split("|")[1]||"sum":Pa(n),s=`${o}|${c}`;t.push({name:s}),r.push({id:n.id||n.metric_id||`${o}_${c}`,name:n.name||n.id||o,column:o,function:c,comparator:n.comparator,threshold:n.threshold,isCompliance:c.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:r}}async function Aa(e,t,r){let n=rt.isAbsolute(e)?e:rt.resolve(r,e),o=(await $t.readFile(n,"utf8").catch(s=>{throw new Error(`Failed to read tariff file: ${n}. Error: ${s.message}`)})).split(`
18
- `).filter(s=>s.trim());if(o.length===0)throw new Error(`Tariff file is empty: ${n}`);let c=[];for(let s=1;s<o.length;s+=1){let d=(o[s]??"").split(",").map(p=>p.trim().replace(/"/g,""));if(t>=d.length)throw new Error(`Column index ${t} not found in record ${s} with ${d.length} columns`);let u=d[t];if(u===void 0)throw new Error(`Column index ${t} is undefined in record ${s}`);let m=Number.parseFloat(u);if(Number.isNaN(m))throw new Error(`Could not parse '${u}' as number in row ${s+1}, column ${t+1}`);c.push(m)}if(c.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${c.length})`);return c}async function Ra(e){let{workspace:t,cleanConfigName:r,modelName:n}=e,a=await Ne(t,{config_name:r}),o=a.models.find(c=>c.name===n)?.csv_path;if(!o)throw new Error(a.error??`No completed actual-dwelling CSV found for model ${n}`);return{csvPath:o,csvContent:await $t.readFile(o,"utf8")}}function ja(e,t,r){let n=[];return t.forEach((a,o)=>{let c=a.name.split("|")[0];if(!c)throw new Error(`Invalid metric name format: ${a.name}`);r[o]?.isCompliance||e.columns[c]||n.push(c)}),n}import{spawn as Ma}from"child_process";import nt from"path";var Lt=["vite-node","community/apps/cli/src/cli.ts"];async function It(e){let t=at(e),r=e.failOn??"critical",n=nt.resolve(e.csvPath),a=await Vt(e,"npx",[...Lt,"check",n,"--json",`--fail-on=${r}`]),o=Jt(a),c=Bt(o)?o:void 0;return{ok:a.exitCode===0&&c!==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:c,counts:Bt(c?.counts)?c.counts:void 0,critical_issues:Array.isArray(c?.criticalIssues)?c.criticalIssues:void 0,warnings:Array.isArray(c?.warnings)?c.warnings:void 0,missing_elements:Array.isArray(c?.missingElements)?c.missingElements:void 0,error:c===void 0?Ut(a):void 0}}async function Wt(e){let t=at(e),r=e.mode??"summary",n=nt.resolve(e.csvPath),a=await Vt(e,"npx",[...Lt,"thermal-bridges",n,Dr(r)]),o=r==="json"?Jt(a):void 0;return{ok:a.exitCode===0&&(r!=="json"||o!==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:o,proposal_count:Array.isArray(o)?o.length:void 0,error:r==="json"&&o===void 0?Ut(a):void 0}}async function Dt(e){let t=at(e),r=e.mode??"summary",n=e.includeAuto===!0,a=nt.resolve(e.csvPath),o=[...Lt,"thermal-bridges",a,"--validate",...n?["--with-auto"]:[],Dr(r)],c=await Vt(e,"npx",o),s=r==="json"?Jt(c):void 0,d=Bt(s)?s:void 0;return{ok:c.exitCode===0&&(r!=="json"||d!==void 0),command:"thermal-bridges validate",csv_path:a,repo_root:t,include_auto:n,mode:r,exit_code:c.exitCode,signal:c.signal,stdout:c.stdout,stderr:c.stderr,parsed:d,issue_count:typeof d?.issueCount=="number"?d.issueCount:void 0,thermal_bridge_linear_rows:typeof d?.thermalBridgeLinearRows=="number"?d.thermalBridgeLinearRows:void 0,error:r==="json"&&d===void 0?Ut(c):void 0}}function at(e){return nt.resolve(e.repoRoot??Ze(e.csvPath))}async function Vt(e,t,r){let n=at(e);return(e.runner??Ta)(t,r,{cwd:n})}function Dr(e){return`--${e}`}function Jt(e){try{return JSON.parse(e.stdout)}catch{return}}function Ut(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ta=(e,t,r)=>new Promise((n,a)=>{let o=Ma(e,[...t],{cwd:r.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),c="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",d=>{c+=d}),o.stderr.on("data",d=>{s+=d}),o.on("error",a),o.on("close",(d,u)=>{n({exitCode:d,signal:u,stdout:c,stderr:s})})});async function Vr(e,t={}){return jt(e.workspace,t)}async function Jr(e,t){return Mt(e.workspace,t)}import Ur from"fs";import Ce from"path";import{fileURLToPath as Oa}from"url";var Fa=Ce.dirname(Oa(import.meta.url));function $a(){let e=[],t=Fa;for(let o=0;o<6;o+=1){e.push(t);let c=Ce.dirname(t);if(c===t)break;t=c}e.push(process.cwd());let r=[];for(let o of e)r.push({directory:Ce.join(o,"wasm"),context:"helper-root"},{directory:Ce.join(o,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:Ce.join(o,"web","dist","wasm"),context:"rust-hem-runner"},{directory:Ce.join(o,"web","dist"),context:"rust-hem-runner"},{directory:Ce.join(o,"web","pkg"),context:"rust-hem-runner"},{directory:Ce.join(o,"apps","web","public","launch"),context:"vulcan-website"});let n=[],a=new Set;for(let o of r){let c=Ce.join(o.directory,"wasm_wrapper.js");if(a.has(c))continue;a.add(c),n.push(c);let s=Ce.join(o.directory,"wasm_wrapper_bg.wasm");if(Ur.existsSync(c)&&Ur.existsSync(s))return o}throw new Error(`WASM files not found. Tried:
19
- `+n.map(o=>` - ${o}`).join(`
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(`
20
20
  `)+`
21
- Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var st=null;async function Ae(){if(st)return st;try{let{directory:e,context:t}=$a();return console.error(`[WASM] Loading from ${t}: ${e}`),st=await Rt(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 qr(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 Tt(e.workspace,t,{validateSnippetJs:r.validateSnippetJs})}async function Hr(e,t){return Pt(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import{randomUUID as Na}from"crypto";import Ba from"fs/promises";import La from"path";async function zr(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_${Na()}`,o=La.join(r,"input","batch_configs",n.endsWith(".json")?n:`${n}.json`),c=await Ba.readFile(o,"utf8").then(u=>JSON.parse(u),()=>{});if(!!(c&&typeof c=="object"&&("__hem"in c||"targetBundleId"in c))||t.target_manifest||t.target_manifest_sha256)return Ye(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 d;try{d=await Ae()}catch(u){let m=u;return{job_id:a,status:"error",message:`WASM initialization failed: ${m.message}`,error:m.message}}return d.processBatchConfig?($e(r),Ye(r,{...t,job_id:a},{processBatchConfig:d.processBatchConfig})):{job_id:a,status:"error",message:"WASM process_batch_config function not available",error:"WASM function missing"}}async function Gr(e,t={}){return xt(e.workspace,t)}async function Kr(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 Nt(e.workspace,t,{calculateMetricsFromParsedData:r.calculateMetricsFromParsedData})}async function Xr(e,t){return Ot(e.workspace,t)}async function Yr(e,t){return Ne(e.workspace,t)}import Ia from"fs/promises";import Wa from"path";async function Zr(e,t){let{workspace:r}=e,{csv_path:n,output_path:a,schema_path:o,defaults_path:c}=t;if(!n)throw new Error("csv_path is required");let s=await Ia.readFile(Wa.resolve(r,n),"utf8").catch(()=>{});if(s!==void 0&&!!Fe(s)||t.target_manifest||t.target_manifest_sha256)return et({workspace:r,csvPath:n,outputPath:a,schemaPath:o,defaultsPath:c,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(m){return{ok:!1,error:`WASM initialization failed: ${m.message}`}}return $e(r),et({workspace:r,csvPath:n,outputPath:a,schemaPath:o,defaultsPath:c,deps:{convertGeometryCsvToJson:u.convertGeometryCsvToJson}})}import Qr from"path";async function en(e,t){return It({csvPath:Qr.isAbsolute(t.csv_path)?t.csv_path:Qr.join(e.workspace,t.csv_path),failOn:t.fail_on,repoRoot:process.cwd()})}import tn from"path";async function rn(e,t){return Wt({csvPath:tn.isAbsolute(t.csv_path)?t.csv_path:tn.join(e.workspace,t.csv_path),mode:t.mode,repoRoot:process.cwd()})}import nn from"path";async function an(e,t){return Dt({csvPath:nn.isAbsolute(t.csv_path)?t.csv_path:nn.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,repoRoot:process.cwd()})}var ge={vulcan_list_parameters:_.object({category:_.string().optional().describe('Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")')}),vulcan_view_parameter:_.object({category:_.string().describe('Parameter category (e.g., "heat_source_wet", "controls", "base_json")'),parameter_id:_.string().describe("Parameter ID (filename without .json extension)")}),vulcan_save_parameter:_.object({category:_.string().describe('Parameter category (e.g., "heat_source_wet", "controls")'),parameter_id:_.string().describe("Parameter ID (filename without .json extension)"),content:_.record(_.string(),_.any()).describe("Parameter JSON content (must be valid JSON object)"),markdown_content:_.string().optional().describe("Optional markdown documentation for the parameter")}),vulcan_create_batch_config:_.object({config_name:_.string().describe("Configuration name (will be saved as {config_name}.json)"),base_model:_.string().describe("Base model filename (without .json extension)"),weather_file:_.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:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it"),wrapper:_.string().optional().describe('Optional model wrapper (e.g., "fhs_compliance", "passthrough")'),parameters:_.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]]})),_.record(_.string(),_.array(_.string()))).describe("Object mapping category to array of parameter IDs")}),vulcan_run_batch:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),job_id:_.string().optional().describe("Optional custom job ID (defaults to mcp_{uuid})"),target_manifest:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned batches otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_get_batch_status:_.object({job_id:_.string().optional().describe("Job ID returned from vulcan_run_batch"),config_name:_.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:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),model_names:_.array(_.string()).describe("Array of model names to calculate metrics for"),metric_definitions:_.array(_.object({id:_.string().optional(),name:_.string().optional(),column:_.string().optional(),function:_.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:_.string().optional(),threshold:_.number().optional()})).describe("Array of metric definitions"),time_range:_.object({start:_.number().optional(),end:_.number().optional()}).optional().describe("Optional time range filter"),tariff_file_path:_.string().optional().describe("Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."),tariff_column_index:_.number().optional().describe("Zero-based index of tariff column in CSV. Required for cost metrics.")}),vulcan_list_csv_columns:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),model_name:_.string().describe('Model name (e.g., "scenario_1_0")')}),vulcan_list_batch_models:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)")}),vulcan_merge_csv_to_json:_.object({csv_path:_.string().describe("Path to CSV file (relative to workspace or absolute)"),output_path:_.string().optional().describe("Optional: output JSON path (defaults to input/batch_parameters/base_json/{csv_filename}.json)"),schema_path:_.string().optional().describe("Optional: custom schema path (defaults to the core schema with workspace fallbacks)"),defaults_path:_.string().optional().describe("Optional: custom defaults path. Declared paths must load; standard defaults are used only for legacy CSVs without DefaultsPath."),target_manifest:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned CSVs otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_validate_geometry_csv:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),fail_on:_.enum(["none","critical","warning"]).optional().describe("Validation exit policy for the wrapped CLI. Defaults to critical.")}),vulcan_auto_thermal_bridges:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),mode:_.enum(["summary","json","csv-section"]).optional().describe("Wrapped auto-TB CLI output mode. Defaults to summary.")}),vulcan_validate_thermal_bridges:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),include_auto:_.boolean().optional().describe("Also synthesize auto-TB proposals before validation."),mode:_.enum(["summary","json"]).optional().describe("Wrapped TB validation CLI output mode. Defaults to summary.")})},sn=[{name:"vulcan_list_parameters",description:`List available parameter categories and their JSON snippets.
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.
22
22
 
23
23
  Use this to discover what parameters are available before creating batch configurations.
24
24
  Returns a catalog of all categories (e.g., base_json, heat_source_wet, controls) and their parameters.
@@ -52,9 +52,9 @@ Example: Run a batch config named "insulation_test" to execute all parameter com
52
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.
53
53
 
54
54
  Use this to check the progress of a batch simulation started with vulcan_run_batch.
55
- Returns current status (queued/running/completed/error), progress percentage, and pass/fail counts.
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.
56
56
 
57
- You can provide either job_id (returned from vulcan_run_batch) or config_name (since config names are unique).
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.
58
58
 
59
59
  Example: Check status using config_name "my_batch_config" or job_id "mcp_abc123".
60
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.
@@ -65,6 +65,11 @@ Supports time range filtering and conditional metrics (sumIf, averageIf).
65
65
  For cost metrics, provide tariff_file_path and tariff_column_index to use time-of-use tariff rates.
66
66
  Tariff file must be CSV with 17,520 rows (half-hourly for a full year).
67
67
 
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.
72
+
68
73
  Example: Calculate total electricity consumption and peak demand for all models in a batch.
69
74
  Example with tariff: Calculate cost using Octopus Agile rates from input/tariff_data_structured/Octopus.csv, column index 2.
70
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,7 +81,9 @@ Example: List columns for model "scenario_1_0" in config "my_batch" to see avail
76
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.
77
82
 
78
83
  Use this to discover which models were generated by a batch run, so you can use them in vulcan_calculate_metrics.
79
- Returns all model names that have result CSV files.
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.
80
87
 
81
88
  Example: List models from config "my_batch" to get ["scenario_1_0", "scenario_1_1", ...].
82
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.
@@ -113,7 +120,7 @@ or csv-section for a pasteable Thermal Bridging Elements CSV section.`,inputSche
113
120
 
114
121
  This wraps the Community CLI's thermal-bridges --validate command and reuses findLinearThermalBridgeIssues plus
115
122
  validateElementCore. Set include_auto=true to validate existing CSV rows plus synthesized
116
- 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 on(e,t,r){switch(e){case"vulcan_list_parameters":{let n=ge.vulcan_list_parameters.parse(t);return await Vr(r,n)}case"vulcan_view_parameter":{let n=ge.vulcan_view_parameter.parse(t);return await Jr(r,n)}case"vulcan_save_parameter":{let{category:n,parameter_id:a,content:o,markdown_content:c}=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(!o||typeof o!="object"||Array.isArray(o))throw new Error("content is required and must be a JSON object");let s={category:n,parameter_id:a,content:o,...c?{markdown_content:c}:{}};return await qr(r,s)}case"vulcan_create_batch_config":{let{config_name:n,base_model:a,weather_file:o,wrapper:c,parameters:s,target_manifest:d,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(o!==void 0&&typeof o!="string")throw new Error("weather_file must be a string");let m={};if(s){if(typeof s!="object"||Array.isArray(s))throw new Error("parameters must be an object mapping category to array of parameter IDs");m=Object.fromEntries(Object.entries(s).map(([g,h])=>{if(typeof h=="string")try{let S=JSON.parse(h);return[g,Array.isArray(S)?S:[S]]}catch{return[g,[h]]}return[g,Array.isArray(h)?h:[h]]}))}let p={config_name:n,base_model:a,weather_file:o,...c?{wrapper:c}:{},parameters:m,target_manifest:d,target_manifest_sha256:u};return await Hr(r,p)}case"vulcan_run_batch":{let n=ge.vulcan_run_batch.parse(t);return await zr(r,n)}case"vulcan_get_batch_status":{let n=ge.vulcan_get_batch_status.parse(t);return await Gr(r,n)}case"vulcan_calculate_metrics":{let n=ge.vulcan_calculate_metrics.parse(t);return await Kr(r,n)}case"vulcan_list_csv_columns":{let n=ge.vulcan_list_csv_columns.parse(t);return await Xr(r,n)}case"vulcan_list_batch_models":{let n=ge.vulcan_list_batch_models.parse(t);return await Yr(r,n)}case"vulcan_merge_csv_to_json":{let n=ge.vulcan_merge_csv_to_json.parse(t);return await Zr(r,n)}case"vulcan_validate_geometry_csv":{let n=ge.vulcan_validate_geometry_csv.parse(t);return await en(r,n)}case"vulcan_auto_thermal_bridges":{let n=ge.vulcan_auto_thermal_bridges.parse(t);return await rn(r,n)}case"vulcan_validate_thermal_bridges":{let n=ge.vulcan_validate_thermal_bridges.parse(t);return await an(r,n)}default:throw new Error(`Unknown tool: ${e}`)}}async function dn(e,t){let r=t||parseInt(process.env.HELPER_PORT||"5000",10),n;try{n=await Yt(e),console.error(`[MCP Helper] Config loaded from: ${n.configPath}`),console.error(`[MCP Helper] Workspace: ${n.workspace}`)}catch(d){console.error(`[MCP Helper] Failed to load config: ${d.message}`),process.exit(1)}let a=cn(),o={origin:!0,methods:["GET","OPTIONS"],credentials:!1},c=new Da({name:"vulcan-mcp-helper",version:"0.1.0"},{capabilities:{tools:{}}}),s=c._oninitialize?.bind(c);if(s){c.removeRequestHandler("initialize");let d=un.extend({params:un.shape.params.partial().transform((u={})=>({protocolVersion:u.protocolVersion||"2024-11-05",capabilities:u.capabilities||{},clientInfo:u.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});c.setRequestHandler(d,u=>s(u))}c.setRequestHandler(Ja,async()=>({tools:sn})),c.setRequestHandler(Ua,async d=>{let{name:u,arguments:m}=d.params;console.error(`[MCP Helper] Tool call: ${u}`);try{let p=await on(u,m,n);return{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}catch(p){let g=p;throw console.error(`[MCP Helper] Tool call failed: ${g.message}`),g}}),a.post("/mcp",cn.raw({type:"application/json",limit:"10mb"}),async(d,u)=>{try{await Zt(d.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 m;try{let g=d.body.toString("utf-8");m=JSON.parse(g)}catch(g){let h=g;u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:h.message},id:null});return}let p=new Va({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{p.close()});try{await c.connect(p),await p.handleRequest(d,u,m)}catch(g){let h=g;console.error(`[MCP Helper] MCP request failed: ${h.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:h.message},id:m?.id||null})}}),a.get("/health",ln(o),(d,u)=>{u.json({status:"running",port:r,version:"0.1.0",name:"vulcan-mcp-helper"})}),a.get("/helper/status",ln(o),(d,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 qa(){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(`
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(`
117
124
  Usage: vulcan-mcp-helper [--config <path>] [--port <port>]
118
125
 
119
126
  Options:
@@ -126,7 +133,7 @@ Examples:
126
133
  vulcan-mcp-helper --config /path/to/vulcan-mcp-config.json
127
134
  vulcan-mcp-helper --port 5000
128
135
  vulcan-mcp-helper --config ./config.json --port 5000
129
- `),process.exit(0));return t}async function Ha(){try{let{configPath:e,port:t}=qa();await dn(e,t)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}Ha();
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();
130
137
  /*! Bundled license information:
131
138
 
132
139
  papaparse/papaparse.js: