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