@vulcan-energy/mcp-helper 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,58 +1,60 @@
1
1
  #!/usr/bin/env node
2
- var ga=Object.create;var Ir=Object.defineProperty;var ha=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var ya=Object.getPrototypeOf,va=Object.prototype.hasOwnProperty;var ba=(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 Ca=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Sa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wa(t))!va.call(e,s)&&s!==n&&Ir(e,s,{get:()=>t[s],enumerable:!(r=ha(t,s))||r.enumerable});return e};var ka=(e,t,n)=>(n=e!=null?ga(ya(e)):{},Sa(t||!e||!e.__esModule?Ir(n,"default",{value:e,enumerable:!0}):n,e));var zr=Ca((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 o.BLOB_URL||(o.BLOB_URL=c.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",l,")();"],{type:"text/javascript"})))}var r=!t.document&&!!t.postMessage,s=t.IS_PAPA_WORKER||!1,a={},i=0,o={};if(o.parse=u,o.unparse=f,o.RECORD_SEP="",o.UNIT_SEP="",o.BYTE_ORDER_MARK="\uFEFF",o.BAD_DELIMITERS=["\r",`
3
- `,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!r&&!!t.Worker,o.NODE_STREAM_INPUT=1,o.LocalChunkSize=1024*1024*10,o.RemoteChunkSize=1024*1024*5,o.DefaultDelimiter=",",o.Parser=$,o.ParserHandle=b,o.NetworkStreamer=g,o.FileStreamer=_,o.StringStreamer=C,o.ReadableStreamStreamer=R,typeof PAPA_BROWSER_CONTEXT>"u"&&(o.DuplexStreamStreamer=I),t.jQuery){var d=t.jQuery;d.fn.parse=function(c){var l=c.config||{},m=[];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++)m.push({file:this.files[B],inputElem:this,instanceConfig:d.extend({},l)})}),h(),this;function h(){if(m.length===0){M(c.complete)&&c.complete();return}var v=m[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(G){M(B)&&B(G,v.file,v.inputElem),O()},o.parse(v.file,v.instanceConfig)}function w(v,y,B,G){M(c.error)&&c.error({name:v},y,B,G)}function O(){m.splice(0,1),h()}}}s&&(t.onmessage=Ce);function u(c,l){l=l||{};var m=l.dynamicTyping||!1;if(M(m)&&(l.dynamicTypingFunction=m,m={}),l.dynamicTyping=m,l.transform=M(l.transform)?l.transform:!1,l.worker&&o.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===o.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 f(c,l){var m=!1,h=!0,w=",",O=`\r
4
- `,v='"',y=v+v,B=!1,G=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(G||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||G),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"&&!o.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))&&(m=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");G=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 fe=Array.isArray(D)&&D.length>0,se=!Array.isArray(J[0]);if(fe&&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=fe?D.length:J[U].length,_e=!1,P=fe?Object.keys(J[U]).length===0:J[U].length===0;if(Z&&!fe&&(_e=Z==="greedy"?J[U].join("").trim()==="":J[U].length===1&&J[U][0].length===0),Z==="greedy"&&fe){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 q=fe&&se?D[S]:S;Y+=N(J[U][q],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||m===!0||typeof m=="function"&&m(D,J)||Array.isArray(m)&&m[J]||$e(Y,o.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(m,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(m,le)}m=[...m.split(ee).slice(w)].join(ee)}if(this.isFirstChunk&&M(this._config.beforeFirstChunk)){var O=this._config.beforeFirstChunk(m);O!==void 0&&(m=O)}this.isFirstChunk=!1,this._halted=!1;var v=this._partialLine+m;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 G=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(s)t.postMessage({results:y,workerId:o.WORKER_ID,finished:G});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&&G&&M(this._config.complete)&&(!y||!y.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!G&&(!y||!y.meta.paused)&&this._nextChunk(),y},this._sendError=function(m){M(this._config.error)?this._config.error(m):s&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:m,finished:!1})};function l(m){var h=ae(m);h.chunkSize=parseInt(h.chunkSize),!m.step&&!m.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=o.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>=m(l),this.parseChunk(l.responseText)}},this._chunkError=function(h){var w=l.statusText||h;this._sendError(new Error(w))};function m(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=o.LocalChunkSize),p.call(this,c);var l,m,h=typeof FileReader<"u";this.stream=function(w){this._input=w,m=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=m.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(m){return l=m,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var m=this._config.chunkSize,h;return m?(h=l.substring(0,m),l=l.substring(m)):(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=[],m=!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()):m=!0},this._streamData=T(function(w){try{l.push(typeof w=="string"?w:w.toString(this._config.encoding)),m&&(m=!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=ba("stream").Duplex,m=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)},m.step=T(this._onCsvData,this),m.complete=T(this._onCsvComplete,this),p.call(this,m),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(m.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,G){this._addToParseQueue(y,G)},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),m=-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,G,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?G.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=o.DefaultDelimiter),N.meta.delimiter=c.delimiter}var q=ae(c);return c.preview&&c.header&&q.preview++,B=P,G=new $(q),N=G.parse(B,j,L),Z(),ee?{meta:{paused:!0}}:N||{meta:{paused:!1}}},this.paused=function(){return ee},this.pause=function(){ee=!0,G.abort(),B=M(c.chunk)?"":B.substring(G.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,G.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(`
5
- `),q=S.length>1&&S[0].length<z[0].length;if(z.length===1||q)return`
6
- `;for(var oe=0,te=0;te<z.length;te++)z[te][0]===`
7
- `&&oe++;return oe>=z.length/2?`\r
8
- `:"\r"};function 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>m&&j<l)return!0}return!1}function Z(){return N&&le&&(_e("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&(N.data=N.data.filter(function(P){return!D(P)})),Y()&&fe(),U()}function Y(){return c.header&&A.length===0}function fe(){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?{}:[],q;for(q=0;q<L.length;q++){var oe=q,te=L[q];c.header&&(oe=q>=A.length?"__parsed_extra":A[q]),c.transform&&(te=c.transform(te,oe)),te=pe(oe,te),oe==="__parsed_extra"?(S[oe]=S[oe]||[],S[oe].push(te)):S[oe]=te}return c.header&&(q>A.length?_e("FieldMismatch","TooManyFields","Too many fields: expected "+A.length+" fields but parsed "+q,y+z):q<A.length&&_e("FieldMismatch","TooFewFields","Too few fields: expected "+A.length+" fields but parsed "+q,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 q,oe,te,Oe;S=S||[","," ","|",";",o.RECORD_SEP,o.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),ie=0;ie<ye.data.length;ie++){if(L&&D(ye.data[ie])){ce++;continue}var ue=ye.data[ie].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 oe>"u"||Fe<=oe)&&(typeof Oe>"u"||Ee>Oe)&&Ee>1.99&&(oe=Fe,q=Ge,Oe=Ee)}return c.delimiter=q,{successful:!!q,bestDelimiter:q}}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,m=c.newline,h=c.comments,w=c.step,O=c.preview,v=c.fastMode,y,B=null,G=!1;c.quoteChar===void 0||c.quoteChar===null?y='"':y=c.quoteChar;var ee=y;if(c.escapeChar!==void 0&&(ee=c.escapeChar),(typeof l!="string"||o.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),h===l)throw new Error("Comment character same as delimiter");h===!0?h="#":(typeof h!="string"||o.BAD_DELIMITERS.indexOf(h)>-1)&&(h=!1),m!==`
9
- `&&m!=="\r"&&m!==`\r
10
- `&&(m=`
11
- `);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=m.length,Y=h.length,fe=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(m),P=0;P<_e.length;P++){if(U=_e[P],F+=U.length,P!==_e.length-1)F+=m.length;else if($e)return ce();if(!(h&&U.substring(0,Y)===h)){if(fe){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(m,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 q=A.substring(F,S).replace(z,y);return Fe(q)}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(m,S+1));var oe=L===-1?j:Math.min(j,L),te=Ge(oe);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(m,F);break}var Oe=Ge(L);if(A.substring(S+1+Oe,S+1+Oe+Z)===m){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),fe&&(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(m,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),fe&&(ye(),le))return ce();if(O&&se.length>=O)return ce(!0);continue}break}return Fe();function ke(ie){se.push(ie),Se=F}function Ge(ie){var ue=0;if(ie!==-1){var Pe=A.substring(S+1,ie);Pe&&Pe.trim()===""&&(ue=Pe.length)}return ue}function Fe(ie){return $e||(typeof ie>"u"&&(ie=A.substring(F)),U.push(ie),F=D,ke(U),fe&&ye()),ce()}function Ee(ie){F=ie,ke(U),U=[],L=A.indexOf(m,F)}function ce(ie){if(c.header&&!N&&se.length&&!G){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 ze,Nr=Pe[ve];do ze=`${ve}_${Nr}`,Nr++;while(Mt.has(ze));Mt.add(ze),ue[De]=ze,Pe[ve]++,Fr=!0,B===null&&(B={}),B[ze]=ve}Mt.add(ve)}Fr&&console.warn("Duplicate headers found and renamed."),G=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:m,aborted:le,truncated:!!ie,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(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=E,l.id=i++,a[l.id]=l,l}function E(c){var l=c.data,m=a[l.workerId],h=!1;if(l.error)m.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(m.userStep)){for(var v=0;v<l.results.data.length&&(m.userStep({data:l.results.data[v],errors:l.results.errors,meta:l.results.meta},O),!h);v++);delete l.results}else M(m.userChunk)&&(m.userChunk(l.results,O,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var m=a[c];M(m.userComplete)&&m.userComplete(l),m.terminate(),delete a[c]}function Q(){throw new Error("Not implemented.")}function Ce(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var m=o.parse(l.input,l.config);m&&t.postMessage({workerId:o.WORKER_ID,results:m,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var m in c)l[m]=ae(c[m]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return o})});import{parseArgs as Co}from"util";import ua from"express";import go from"cors";import{McpServer as ho}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as wo}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as yo}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 Xe 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",ct=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-----
2
+ var ba=Object.create;var Dr=Object.defineProperty;var Ca=Object.getOwnPropertyDescriptor;var Sa=Object.getOwnPropertyNames;var ka=Object.getPrototypeOf,Ea=Object.prototype.hasOwnProperty;var Pa=(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 xa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ra=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Sa(t))!Ea.call(e,a)&&a!==n&&Dr(e,a,{get:()=>t[a],enumerable:!(r=Ca(t,a))||r.enumerable});return e};var Aa=(e,t,n)=>(n=e!=null?ba(ka(e)):{},Ra(t||!e||!e.__esModule?Dr(n,"default",{value:e,enumerable:!0}):n,e));var Zr=xa((Vt,Wt)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Wt=="object"&&typeof Vt<"u"?Wt.exports=t():e.Papa=t()})(Vt,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function n(){var c=t.URL||t.webkitURL||null,l=e.toString();return o.BLOB_URL||(o.BLOB_URL=c.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",l,")();"],{type:"text/javascript"})))}var r=!t.document&&!!t.postMessage,a=t.IS_PAPA_WORKER||!1,s={},i=0,o={};if(o.parse=d,o.unparse=m,o.RECORD_SEP="",o.UNIT_SEP="",o.BYTE_ORDER_MARK="\uFEFF",o.BAD_DELIMITERS=["\r",`
3
+ `,'"',o.BYTE_ORDER_MARK],o.WORKERS_SUPPORTED=!r&&!!t.Worker,o.NODE_STREAM_INPUT=1,o.LocalChunkSize=1024*1024*10,o.RemoteChunkSize=1024*1024*5,o.DefaultDelimiter=",",o.Parser=$,o.ParserHandle=C,o.NetworkStreamer=g,o.FileStreamer=f,o.StringStreamer=v,o.ReadableStreamStreamer=A,typeof PAPA_BROWSER_CONTEXT>"u"&&(o.DuplexStreamStreamer=I),t.jQuery){var u=t.jQuery;u.fn.parse=function(c){var l=c.config||{},p=[];return this.each(function(b){var y=u(this).prop("tagName").toUpperCase()==="INPUT"&&u(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++)p.push({file:this.files[B],inputElem:this,instanceConfig:u.extend({},l)})}),h(),this;function h(){if(p.length===0){M(c.complete)&&c.complete();return}var b=p[0];if(M(c.before)){var y=c.before(b.file,b.inputElem);if(typeof y=="object")if(y.action==="abort"){w("AbortError",b.file,b.inputElem,y.reason);return}else if(y.action==="skip"){O();return}else typeof y.config=="object"&&(b.instanceConfig=u.extend(b.instanceConfig,y.config));else if(y==="skip"){O();return}}var B=b.instanceConfig.complete;b.instanceConfig.complete=function(q){M(B)&&B(q,b.file,b.inputElem),O()},o.parse(b.file,b.instanceConfig)}function w(b,y,B,q){M(c.error)&&c.error({name:b},y,B,q)}function O(){p.splice(0,1),h()}}}a&&(t.onmessage=Se);function d(c,l){l=l||{};var p=l.dynamicTyping||!1;if(M(p)&&(l.dynamicTypingFunction=p,p={}),l.dynamicTyping=p,l.transform=M(l.transform)?l.transform:!1,l.worker&&o.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===o.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 v(l)):c.readable===!0&&M(c.read)&&M(c.on)?w=new A(l):(t.File&&c instanceof File||c instanceof Object)&&(w=new f(l)),w.stream(c);function O(b){return b.charCodeAt(0)===65279?b.slice(1):b}}function m(c,l){var p=!1,h=!0,w=",",O=`\r
4
+ `,b='"',y=b+b,B=!1,q=null,ee=!1;le();var F=new RegExp(x(b),"g");if(typeof c=="string"&&(c=JSON.parse(c)),Array.isArray(c)){if(!c.length||Array.isArray(c[0]))return R(null,c,B);if(typeof c[0]=="object")return R(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])),R(c.fields||[],c.data||[],B);throw new Error("Unable to serialize unrecognized input");function le(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!o.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))&&(p=l.quotes),(typeof l.skipEmptyLines=="boolean"||typeof l.skipEmptyLines=="string")&&(B=l.skipEmptyLines),typeof l.newline=="string"&&(O=l.newline),typeof l.quoteChar=="string"&&(b=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+b),l.escapeFormulae instanceof RegExp?ee=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(ee=/^[=+\-@\t\r].*$/)}}function R(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 H=0;H<J.length;H++){var ke=me?D.length:J[H].length,ge=!1,P=me?Object.keys(J[H]).length===0:J[H].length===0;if(Z&&!me&&(ge=Z==="greedy"?J[H].join("").trim()==="":J[H].length===1&&J[H][0].length===0),Z==="greedy"&&me){for(var j=[],L=0;L<ke;L++){var G=se?D[L]:L;j.push(J[H][G])}ge=j.join("").trim()===""}if(!ge){for(var k=0;k<ke;k++){k>0&&!P&&(Y+=w);var z=me&&se?D[k]:k;Y+=N(J[H][z],k)}H<J.length-1&&(!Z||ke>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||p===!0||typeof p=="function"&&p(D,J)||Array.isArray(p)&&p[J]||Fe(Y,o.BAD_DELIMITERS)||Y.indexOf(w)>-1||Y.charAt(0)===" "||Y.charAt(Y.length-1)===" ",Z?b+Y+b:Y}function Fe(D,J){for(var Z=0;Z<J.length;Z++)if(D.indexOf(J[Z])>-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(p,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(p,le)}p=[...p.split(ee).slice(w)].join(ee)}if(this.isFirstChunk&&M(this._config.beforeFirstChunk)){var O=this._config.beforeFirstChunk(p);O!==void 0&&(p=O)}this.isFirstChunk=!1,this._halted=!1;var b=this._partialLine+p;this._partialLine="";var y=this._handle.parse(b,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var B=y.meta.cursor;this._finished||(this._partialLine=b.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(a)t.postMessage({results:y,workerId:o.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(p){M(this._config.error)?this._config.error(p):a&&this._config.error&&t.postMessage({workerId:o.WORKER_ID,error:p,finished:!1})};function l(p){var h=ae(p);h.chunkSize=parseInt(h.chunkSize),!p.step&&!p.chunk&&(h.chunkSize=null),this._handle=new C(h),this._handle.streamer=this,this._config=h}}function g(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(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(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>=p(l),this.parseChunk(l.responseText)}},this._chunkError=function(h){var w=l.statusText||h;this._sendError(new Error(w))};function p(h){var w=h.getResponseHeader("Content-Range");return w===null?-1:parseInt(w.substring(w.lastIndexOf("/")+1))}}g.prototype=Object.create(_.prototype),g.prototype.constructor=g;function f(c){c=c||{},c.chunkSize||(c.chunkSize=o.LocalChunkSize),_.call(this,c);var l,p,h=typeof FileReader<"u";this.stream=function(w){this._input=w,p=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=p.call(w,this._start,O)}var b=l.readAsText(w,this._config.encoding);h||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)}}f.prototype=Object.create(_.prototype),f.prototype.constructor=f;function v(c){c=c||{},_.call(this,c);var l;this.stream=function(p){return l=p,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var p=this._config.chunkSize,h;return p?(h=l.substring(0,p),l=l.substring(p)):(h=l,l=""),this._finished=!l,this.parseChunk(h)}}}v.prototype=Object.create(v.prototype),v.prototype.constructor=v;function A(c){c=c||{},_.call(this,c);var l=[],p=!0,h=!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(){h&&l.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),l.length?this.parseChunk(l.shift()):p=!0},this._streamData=T(function(w){try{l.push(typeof w=="string"?w:w.toString(this._config.encoding)),p&&(p=!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)}A.prototype=Object.create(_.prototype),A.prototype.constructor=A;function I(c){var l=Pa("stream").Duplex,p=ae(c),h=!0,w=!1,O=[],b=null;this._onCsvData=function(y){var B=y.data;!b.push(B)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){b.push(null)},p.step=T(this._onCsvData,this),p.complete=T(this._onCsvComplete,this),_.call(this,p),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(p.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 b},b=new l({readableObjectMode:!0,decodeStrings:!1,read:T(this._onRead,this),write:T(this._onWrite,this)}),b.once("finish",T(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(I.prototype=Object.create(_.prototype),I.prototype.constructor=I);function C(c){var l=Math.pow(2,53),p=-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,b=0,y=0,B,q,ee=!1,F=!1,le,R=[],N={data:[],errors:[],meta:{}};if(M(c.step)){var Fe=c.step;c.step=function(P){if(N=P,Y())Z();else{if(Z(),N.data.length===0)return;b+=P.data.length,c.preview&&b>c.preview?q.abort():(N.data=N.data[0],Fe(N,O))}}}this.parse=function(P,j,L){var G=c.quoteChar||'"';if(c.newline||(c.newline=this.guessLineEndings(P,G)),le=!1,c.delimiter)M(c.delimiter)&&(c.delimiter=c.delimiter(P),N.meta.delimiter=c.delimiter);else{var k=ke(P,c.newline,c.skipEmptyLines,c.comments,c.delimitersToGuess);k.successful?c.delimiter=k.bestDelimiter:(le=!0,c.delimiter=o.DefaultDelimiter),N.meta.delimiter=c.delimiter}var z=ae(c);return c.preview&&c.header&&z.preview++,B=P,q=new $(z),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 G=P.split("\r"),k=P.split(`
5
+ `),z=k.length>1&&k[0].length<G[0].length;if(G.length===1||z)return`
6
+ `;for(var oe=0,te=0;te<G.length;te++)G[te][0]===`
7
+ `&&oe++;return oe>=G.length/2?`\r
8
+ `:"\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>p&&j<l)return!0}return!1}function Z(){return N&&le&&(ge("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&(N.data=N.data.filter(function(P){return!D(P)})),Y()&&me(),H()}function Y(){return c.header&&R.length===0}function me(){if(!N)return;function P(L,G){M(c.transformHeader)&&(L=c.transformHeader(L,G)),R.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 H(){if(!N||!c.header&&!c.dynamicTyping&&!c.transform)return N;function P(L,G){var k=c.header?{}:[],z;for(z=0;z<L.length;z++){var oe=z,te=L[z];c.header&&(oe=z>=R.length?"__parsed_extra":R[z]),c.transform&&(te=c.transform(te,oe)),te=pe(oe,te),oe==="__parsed_extra"?(k[oe]=k[oe]||[],k[oe].push(te)):k[oe]=te}return c.header&&(z>R.length?ge("FieldMismatch","TooManyFields","Too many fields: expected "+R.length+" fields but parsed "+z,y+G):z<R.length&&ge("FieldMismatch","TooFewFields","Too few fields: expected "+R.length+" fields but parsed "+z,y+G)),k}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=R),y+=j,N}function ke(P,j,L,G,k){var z,oe,te,Ne;k=k||[","," ","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var Ee=0;Ee<k.length;Ee++){var Ke=k[Ee],Ie=0,Pe=0,ce=0;te=void 0;for(var ve=new $({comments:G,delimiter:Ke,newline:j,preview:10}).parse(P),ie=0;ie<ve.data.length;ie++){if(L&&D(ve.data[ie])){ce++;continue}var ue=ve.data[ie].length;if(Pe+=ue,typeof te>"u"){te=ue;continue}else ue>0&&(Ie+=Math.abs(ue-te),te=ue)}ve.data.length>0&&(Pe/=ve.data.length-ce),(typeof oe>"u"||Ie<=oe)&&(typeof Ne>"u"||Pe>Ne)&&Pe>1.99&&(oe=Ie,z=Ke,Ne=Pe)}return c.delimiter=z,{successful:!!z,bestDelimiter:z}}function ge(P,j,L,G){var k={type:P,code:j,message:L};G!==void 0&&(k.row=G),N.errors.push(k)}}function x(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(c){c=c||{};var l=c.delimiter,p=c.newline,h=c.comments,w=c.step,O=c.preview,b=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"||o.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),h===l)throw new Error("Comment character same as delimiter");h===!0?h="#":(typeof h!="string"||o.BAD_DELIMITERS.indexOf(h)>-1)&&(h=!1),p!==`
9
+ `&&p!=="\r"&&p!==`\r
10
+ `&&(p=`
11
+ `);var F=0,le=!1;this.parse=function(R,N,Fe){if(typeof R!="string")throw new Error("Input must be a string");var D=R.length,J=l.length,Z=p.length,Y=h.length,me=M(w);F=0;var se=[],pe=[],H=[],ke=0;if(!R)return ce();if(b||b!==!1&&R.indexOf(y)===-1){for(var ge=R.split(p),P=0;P<ge.length;P++){if(H=ge[P],F+=H.length,P!==ge.length-1)F+=p.length;else if(Fe)return ce();if(!(h&&H.substring(0,Y)===h)){if(me){if(se=[],Ee(H.split(l)),ve(),le)return ce()}else Ee(H.split(l));if(O&&P>=O)return se=se.slice(0,O),ce(!0)}}return ce()}for(var j=R.indexOf(l,F),L=R.indexOf(p,F),G=new RegExp(x(ee)+x(y),"g"),k=R.indexOf(y,F);;){if(R[F]===y){for(k=F,F++;;){if(k=R.indexOf(y,k+1),k===-1)return Fe||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),Ie();if(k===D-1){var z=R.substring(F,k).replace(G,y);return Ie(z)}if(y===ee&&R[k+1]===ee){k++;continue}if(!(y!==ee&&k!==0&&R[k-1]===ee)){j!==-1&&j<k+1&&(j=R.indexOf(l,k+1)),L!==-1&&L<k+1&&(L=R.indexOf(p,k+1));var oe=L===-1?j:Math.min(j,L),te=Ke(oe);if(R.substr(k+1+te,J)===l){H.push(R.substring(F,k).replace(G,y)),F=k+1+te+J,R[k+1+te+J]!==y&&(k=R.indexOf(y,F)),j=R.indexOf(l,F),L=R.indexOf(p,F);break}var Ne=Ke(L);if(R.substring(k+1+Ne,k+1+Ne+Z)===p){if(H.push(R.substring(F,k).replace(G,y)),Pe(k+1+Ne+Z),j=R.indexOf(l,F),k=R.indexOf(y,F),me&&(ve(),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}),k++}}continue}if(h&&H.length===0&&R.substring(F,F+Y)===h){if(L===-1)return ce();F=L+Z,L=R.indexOf(p,F),j=R.indexOf(l,F);continue}if(j!==-1&&(j<L||L===-1)){H.push(R.substring(F,j)),F=j+J,j=R.indexOf(l,F);continue}if(L!==-1){if(H.push(R.substring(F,L)),Pe(L+Z),me&&(ve(),le))return ce();if(O&&se.length>=O)return ce(!0);continue}break}return Ie();function Ee(ie){se.push(ie),ke=F}function Ke(ie){var ue=0;if(ie!==-1){var xe=R.substring(k+1,ie);xe&&xe.trim()===""&&(ue=xe.length)}return ue}function Ie(ie){return Fe||(typeof ie>"u"&&(ie=R.substring(F)),H.push(ie),F=D,Ee(H),me&&ve()),ce()}function Pe(ie){F=ie,Ee(H),H=[],L=R.indexOf(p,F)}function ce(ie){if(c.header&&!N&&se.length&&!q){let ue=se[0],xe=Object.create(null),$t=new Set(ue),Lr=!1;for(let We=0;We<ue.length;We++){let be=ue[We];if(M(c.transformHeader)&&(be=c.transformHeader(be,We)),!xe[be])xe[be]=1,ue[We]=be;else{let Xe,Br=xe[be];do Xe=`${be}_${Br}`,Br++;while($t.has(Xe));$t.add(Xe),ue[We]=Xe,xe[be]++,Lr=!0,B===null&&(B={}),B[Xe]=be}$t.add(be)}Lr&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:p,aborted:le,truncated:!!ie,cursor:ke+(N||0),renamedHeaders:B}}}function ve(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function V(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=E,l.id=i++,s[l.id]=l,l}function E(c){var l=c.data,p=s[l.workerId],h=!1;if(l.error)p.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(p.userStep)){for(var b=0;b<l.results.data.length&&(p.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},O),!h);b++);delete l.results}else M(p.userChunk)&&(p.userChunk(l.results,O,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var p=s[c];M(p.userComplete)&&p.userComplete(l),p.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Se(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var p=o.parse(l.input,l.config);p&&t.postMessage({workerId:o.WORKER_ID,results:p,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=ae(c[p]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return o})});import{parseArgs as Po}from"util";import _a from"express";import vo from"cors";import{McpServer as bo}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Co}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as So}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ga}from"@modelcontextprotocol/sdk/types.js";var Vr={name:"@vulcan-energy/mcp-helper",version:"0.3.3",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 Ur from"fs/promises";import Ye from"path";var Wr=Object.freeze(["mcp","analyst"]);function Ot(e){return typeof e=="string"&&Wr.includes(e)}var it="https://usevulcan.app",Ft="vulcan-local-tools",ct=1,Nt=10080*60,It=300,K=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var Jr=Object.freeze([`-----BEGIN PUBLIC KEY-----
12
12
  MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
13
- -----END PUBLIC KEY-----`]);import{compactVerify as Pa,importSPKI as xa}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),i=await Aa(n,r),o=Ra(i);if(o.iss!==it)throw new K("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${it}.`);if(o.aud!==Ot)throw new K("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==ct)throw new K("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${ct}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new K("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>Ft)throw new K("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(a<o.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>o.exp;if(d&&!t.allowExpired)throw new K("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:o,expired:d,expiresAt:new Date(o.exp*1e3),expiresInSeconds:o.exp-a}}async function Aa(e,t){for(let n of t)try{let r=await xa(n,Vr),{payload:s}=await Pa(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 Ra(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new K("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new K("malformed","Vulcan access token payload is not an object.");let n=t,r=Ke(n,"iss"),s=Ke(n,"aud"),a=Ke(n,"sub"),i=Ke(n,"org"),o=Ke(n,"jti"),d=It(n,"iat"),u=It(n,"exp"),f=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:i,jti:o,capabilities:Object.freeze(p),entitlement_schema_version:f,iat:d,exp:u}}function Ke(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new K("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function 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 ja="mcp",Ta=2880*60;async function Bt(e={}){let t=Xe.resolve(e.workspace??process.env.VULCAN_WORKSPACE??process.cwd()),n=Xe.resolve(e.configPath??Xe.join(t,"vulcan-mcp-config.json")),r;try{r=await 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 i;try{i=JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in config file ${n}: ${o.message}`)}if(i.workspace!==void 0){if(typeof i.workspace!="string")throw new Error("Config field workspace must be a string");s=Xe.resolve(Xe.dirname(n),i.workspace)}if(i.license_token!==void 0){if(typeof i.license_token!="string"||!i.license_token)throw new Error("Config field license_token must be a non-empty string");a=i.license_token}}try{await Wr.access(s)}catch{throw new Error(`Workspace directory not found: ${s}`)}if(a){let{payload:i}=await lt(a,{allowExpired:!0}),o=i.exp-Math.floor(Date.now()/1e3);if(o<=0)console.error("[MCP Helper] Your Vulcan Pro access has expired: Free tools work; ask your assistant to sign in again (vulcan_sign_in) to renew.");else if(o<Ta){let d=Math.max(1,Math.round(o/3600));console.error(`[MCP Helper] Warning: your Vulcan access expires in about ${d} hour(s). Ask your assistant to sign in again (vulcan_sign_in), or open Vulcan -> Profile -> Integrations and click "Generate Config File".`)}}return{workspace:s,...a?{license_token:a}:{},...r!==void 0?{configPath:n}:{}}}async function Jr(e,t={}){if(!e.license_token)return{pro:!1,detail:"No Vulcan Pro access config is set; Free tools only."};try{return await lt(e.license_token,t),{pro:!0,detail:"Vulcan Pro access config is valid."}}catch(n){return{pro:!1,detail:n.message}}}async function lt(e,t={}){try{let{claims:n}=await Lt(e,{capability:ja,now:t.now,publicKeys:t.publicKeys,allowExpired:t.allowExpired});return{payload:n}}catch(n){throw new Error(Ma(n))}}function Ma(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 $a}from"crypto";function Oa(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 Fa(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&$a(n,r)}async function Ur(e,t,n=lt){let r=Oa(e);if(!Fa(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as k}from"zod";import ot from"fs/promises";import Me from"path";import Na from"fs/promises";import Ia 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,i]of Object.entries(e)){if(!i||typeof i!="object"){n.push(`Scenario '${a}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&n.push(`Scenario '${a}' must have exactly one base_json (found ${o.base_json.length})`):n.push(`Scenario '${a}' is missing required 'base_json' field (must be array)`);let d=!!(o.weather_file||o.weather_files),u=!!o.external_conditions;if(d){let f=o.weather_file||o.weather_files;Array.isArray(f)?f.length>1&&n.push(`Scenario '${a}' must have at most one weather_file (found ${f.length})`):n.push(`Scenario '${a}' weather_file/weather_files must be an array`)}u&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${a}' external_conditions must be an array`),t.requireWeather!==!1&&!d&&!u&&n.push(`Scenario '${a}' must have either 'weather_files' or 'external_conditions'`),d&&u&&r.push(`Scenario '${a}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[f,p]of Object.entries(o))Array.isArray(p)||n.push(`Scenario '${a}': '${f}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function qr(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 Gr(e,t){let n=[],r=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:r};for(let[s,a]of Object.entries(t)){if(!a||typeof a!="object")continue;let i=a;for(let[o,d]of Object.entries(i))if(Array.isArray(d)&&!(o==="weather_file"||o==="weather_files"))for(let u of d){let f=Ia.join(e,"input","batch_parameters",o,`${String(u)}.json`);try{await Na.access(f)}catch{r.push({scenario:s,category:o,parameter:String(u),path:f}),n.push(`Scenario '${s}': Parameter '${String(u)}' in category '${o}' not found at ${f}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as fs,readFile as pn}from"fs/promises";import{join as _n}from"path";import{fileURLToPath as ms}from"url";var La=ka(zr(),1),Ba=Object.defineProperty,Da=Object.getOwnPropertyNames,Va=(e,t)=>function(){return e&&(t=(0,e[Da(e)[0]])(e=0)),t},Wa=(e,t)=>{for(var n in t)Ba(e,n,{get:t[n],enumerable:!0})},Ja={};Wa(Ja,{configureWasm:()=>Ua,getRuntimeApiUrl:()=>Ya,getRuntimeWasmVariant:()=>Ka,getVersionedWasmAssetPaths:()=>Ut,getVersionedWasmJsUrl:()=>en,getWasmAssetPaths:()=>Qr,getWasmBaseUrl:()=>Jt,getWasmBinaryUrl:()=>tn,getWasmJsUrl:()=>an,getWasmRayonThreadCount:()=>Xr,getWasmVariant:()=>Yr,getWasmVersionInfo:()=>ut,getWasmVersionJsonUrl:()=>Zr,getWasmWasmUrl:()=>sn,initializeWasmRayonThreadPool:()=>za});function Ua(e={}){e.baseUrl&&(rn=Ha(e.baseUrl)),typeof e.preferHashed=="boolean"&&(nn=e.preferHashed)}function Kr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Ha(e){return e.replace(/\/+$/,"")||"/"}function qa(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Ga(){let e=Kr();if(e){if(qa(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Jt(){return rn||Ga()}function Xr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function za(e){let t=e,n=Ze.get(t);if(n)return n;let r=e.initialize_rayon_thread_pool;if(typeof r!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let s=Promise.resolve().then(()=>r(Xr())).then(()=>{});return Ze.set(t,s),s.catch(()=>{Ze.get(t)===s&&Ze.delete(t)}),s}function Zr(){return`${Jt()}/wasm_version.json`}async function ut(){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 Ka(){return Yr(await ut())}function Xa(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function Za(e){let t=Xa(),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 ut():e,{jsFilename:r,wasmFilename:s}=Za(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${s}`}}async function Ut(){let e=await ut(),{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 Ya(e){let t=Kr();return t?new URL(e,t.origin).toString():e}var Ze,rn,nn,an,sn,on=Va({"src/wasmPath.ts"(){Ze=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: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,f]=i.startedAt===void 0?[o,i]:[i,o];return f.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 (${f.run}). Its files are dated after run ${u.run} started, so they may have been copied, and the helper cannot tell which run is newest. Run the config again.`},r=[...t.values()],s=r.map(i=>r.filter(o=>o!==i).map(o=>n(i,o))),a=r.find((i,o)=>s[o].every(d=>typeof d=="number"&&d>0));return a||!r.length?a:{unknown:s.flat().find(i=>typeof i=="string")}}function qt(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 dt(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 Qa(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function es(e){let t=Qa(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function ft(e,t){let n=[];for(let r of dt(t)){let s=es(r.value);for(let a=0;a<s;a+=1)n.push(`result_${e}_${r.name}_${a}`)}return n}function Gt(e){return Math.floor(e/1e3)}function ts(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function rs(e){return e==="failure_context.json"}function fn(e){return ts(e)||rs(e)}var ns=["fhs_assumptions","fhs_compliance"];var as=[...ns,"epc_quick","epc_full"];function ss(e){return as.some(t=>t===e)}var os=new Set(["base_json","model_wrappers","weather_files","external_conditions"]);function ge(e,t,n){return{category:e,selections:[...t],message:n}}function is(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 cs(e){let t=[],n=e.scenarios[0];e.scenarios.length!==1&&t.push(ge("scenarios",e.scenarios.slice(1).map(u=>u.name),"Free configurations contain exactly one scenario."));let r=n?.parameters??{},s=r.base_json??[];s.length!==1&&t.push(ge("base_json",s.slice(1),"Free configurations contain exactly one base model."));let a=r.model_wrappers??[],i=a.findIndex(ss),o=a.filter((u,f)=>f!==i);(a.length!==1||i!==0)&&t.push(ge("model_wrappers",o,"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 f=r[u]??[];f.length>0&&t.push(ge(u,f,`Free configurations do not select ${u.replace(/_/g," ")}.`))}for(let[u,f]of Object.entries(r))os.has(u)||f.length===0||t.push(ge(u,f,`Free configurations do not select ${u.replace(/_/g," ")} parameters.`));let d=is(e.scenarios);return d!==1&&t.push(ge("permutations",[String(d)],"Free configurations compute exactly one permutation.")),{isFree:t.length===0,violations:t}}function ls(e,t){return dn(e)||e==="targetBundleId"&&typeof t=="string"}function us(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 mn(e){if(!e||typeof e!="object"||Array.isArray(e))return{isFree:!1,violations:[ge("config",[],"A batch configuration must be a JSON object.")]};let t=[],n=[];for(let[i,o]of Object.entries(e)){if(ls(i,o))continue;if(!o||typeof o!="object"||Array.isArray(o)){t.push(ge("config",[i],`Unrecognised batch configuration entry '${i}'.`));continue}let d={};for(let[u,f]of Object.entries(o))u==="zone_allocations"?us(f)&&t.push(ge("zone_allocations",[i],"Free configurations do not use per-zone selections.")):Array.isArray(f)?d[u]=f.map(String):t.push(ge(u,[i],`'${u}' in '${i}' must be a list of selections.`));n.push({name:i,parameters:d})}let r=e.__hem;(!r||typeof r!="object"||Array.isArray(r))&&t.push(ge("target",[],"Free runs use a model saved by the current Vulcan app, pinned to a HEM version."));let a=[...cs({scenarios:n}).violations,...t];return{isFree:a.length===0,violations:a}}function ds(){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 qo=ds();on();var mt;async function pt(e){return mt??=gn(),(await mt).csvTarget(e)}async function zt(e,t){let n=await Ye(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 fs(ms(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 Ye(e,t){let n=new Set;for(let{value:r}of dt(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 ps(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 ps(e,t){try{return await pt(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(dt(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 Ye(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 Ss}from"child_process";import{resolve as ks}from"path";import{access as Es}from"fs/promises";import{fileURLToPath as Yt}from"url";import{createHash as gs}from"crypto";import Qe from"fs";import xe from"path";import{fileURLToPath as _s}from"url";function Xt(e=process.cwd()){let t=xe.resolve(e);for(Qe.existsSync(t)&&Qe.statSync(t).isFile()&&(t=xe.dirname(t));;){if(Qe.existsSync(xe.join(t,"package.json"))&&Qe.existsSync(xe.join(t,"hem-batch-core"))&&Qe.existsSync(xe.join(t,"web")))return t;let r=xe.dirname(t);if(r===t)break;t=r}let n=xe.dirname(_s(import.meta.url));return xe.resolve(n,"..","..","..")}import he from"fs";import de from"path";import{fileURLToPath as ii,pathToFileURL as hs}from"url";var hn=new Map,wn=!1,Zt=process.cwd(),bn=!1;async function _t(e,t){let n=t?`${e}?verified`:e,r=hn.get(n);if(r)return r;ws();let s=de.join(e,"wasm_wrapper.js"),a=de.join(e,"wasm_wrapper_bg.wasm"),i=de.join(e,"wasm_version.json");if(!he.existsSync(s)||!he.existsSync(a))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(hs(s).href+(t?"?verified":""));if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:t??he.readFileSync(a)}),o.setup_panic_hook?.(),typeof o.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let d={convertGeometryCsvToJson:o.convert_geometry_csv_to_json.bind(o),validateSnippetJs:o.validate_snippet_js?.bind(o),processBatchConfig:o.process_batch_config?.bind(o),calculateMetricsFromParsedData:o.calculate_metrics_from_parsed_data?.bind(o),setWorkspace:ht,prepareTargetScenario:o.prepare_target_scenario?.bind(o),metadata:{source:s,wasm_path:a,wasm_version:bs(i),build_stamp:tt(o.build_stamp),build_info:Cs(o.get_build_info),runtime_origin_descriptor:tt(o.runtime_origin_descriptor),hem_core_version:tt(o.metadata_hem_core_version),fhs_wrapper_version:tt(o.metadata_fhs_wrapper_version)}};return hn.set(n,d),d}var yn=new Map;async function gt(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=>gs("sha256").update(d).digest("hex"),i=r("wasm_wrapper_bg.wasm");if(a(r("wasm_wrapper.js"))!==s.js_sha256||a(i)!==s.sha256)throw new Error(`The WASM in ${e} does not match its wasm_version.json. ${t}`);let o={...await _t(e,i),versionInfo:s};return yn.set(e,o),o}function ht(e,t={}){Zt=de.resolve(e),bn=t.confineToWorkspace===!0}function ws(){ys(),vs();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=et(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=et(n);return he.readFileSync(r,"utf8")},e.file_exists=n=>{let r=et(n);return he.existsSync(r)},e.create_dir_all=n=>{let r=et(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=et(n);try{return he.readdirSync(r)}catch{return[]}}}function et(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 ys(){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 vs(){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 bs(e){try{return JSON.parse(he.readFileSync(e,"utf8"))}catch{return}}function tt(e){return typeof e!="function"?void 0:e()||void 0}function Cs(e){let t=tt(e);if(t)try{return JSON.parse(t)}catch{return t}}var rt=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 Ps(),r=t?{targetBundleId:e.targetBundleId,manifestPath:ks(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 f={workspace:e.workspace,config:e.config,configName:e.configName,jobId:e.jobId,...r,wasmDir:s,wasmRemedy:a};return e.foreground?n.adapter.runTargetBrowser(f,{loadPackageWasm:gt}):xs(n.adapterPath,f)}if(typeof e.csv!="string")throw new Error("CSV source required");let i=await n.adapter.workspaceReader(e.workspace),{manifest:o,text:d}=await n.adapter.readPreparationBundle(r),u=await gt(s,a);return n.preparation.prepareCsv({csv:e.csv,manifest:o,text:d,converter:{prepare_target_scenario:u.prepareTargetScenario},read:i})};async function Ps(){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 Es(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 xs(e,t){return new Promise((n,r)=>{let s=Ss(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),a=setTimeout(()=>{s.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);s.once("error",i=>{clearTimeout(a),r(i)}),s.once("exit",i=>{clearTimeout(a),r(new Error(`Target batch stopped before startup (${i})`))}),s.once("message",i=>{clearTimeout(a),i.started?(s.unref(),n({status:"started"})):(s.kill(),r(new Error(i.error??"Target batch failed to start")))}),s.send(t)})}import{randomUUID as As}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:i,wrapper:o,parameters:d}=t;if(!s)throw new Error("config_name is required");if(Ne(s),!a)throw new Error("base_model is required");if(!d||typeof d!="object"||Array.isArray(d))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let u=Rs(d),f={base_json:[a],...o?{model_wrappers:[o]}:{},...u},p=await Ye(e,{scenario_1:f}),g=!!(t.targetManifestPath||t.targetManifestSha256||p);if(!i&&!g)throw new Error("weather_file is required");if(g&&(!/^[a-zA-Z0-9_. -]+$/.test(s)||s===".."))throw new Error("Invalid target config name");i&&(f.weather_files=[g&&!i.endsWith(".epw")?`${i}.epw`:i]);let _={scenario_1:f};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=qr(_);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??rt)({workspace:e,operation:"snapshot",config:_,targetBundleId:p,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});b={..._,__hem:E}}else{let E=await Gr(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",i.endsWith(".epw")?i:`${i}.epw`);try{await re.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Q}`],message:`Weather file not found: ${i}`}}}await r.gate?.(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_${As()}`;Ne(r);let i=r.endsWith(".json")?r:`${r}.json`,o=H.join(e,"input","batch_configs",i),d;try{d=await re.readFile(o,"utf8")}catch(g){let _=g;throw _.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${_.message}`)}let u=JSON.parse(d);if(await n.gate?.(u),u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let 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??rt)({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 f=await Kt(e,u);if(f)return{job_id:a,status:"error",message:f,error:f};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 wt(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 i=a?.warnings??[],o=H.join(s,`progress_${n}.json`),d=H.join(s,`sim_progress_${n}.json`),u=await Ae(o,i),f=await Ae(d,i),p=await xn(s,n,i);if(!a&&p.config){let x=await wt(e,p.config);i.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"),f&&!g&&(En(f.status)&&(_=f.status),typeof f.passes=="number"&&(R=f.passes),typeof f.failures=="number"&&(I=f.failures),typeof f.error=="string"&&(b=f.error,_="error")),!u&&!f&&!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:f??null,...kn(i)}}async function wt(e,t){let n=H.join(e,"output"),r=[],s=[],a=async T=>(await re.stat(T)).mtimeMs,i=T=>typeof T.startedAt=="string"?T.startedAt:void 0;for(let T of await re.readdir(n).catch(yt)??[]){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:i(M),fileTime:await a(H.join(n,T))})}Ne(t);let o=H.join(e,"input","batch_configs",`${t}.json`),d=await Ae(o,r),u=d?ft(t,d):[],f,p=[];for(let T of u){let M=H.join(n,T),c=await re.readdir(M,{withFileTypes:!0}).catch(yt);if(!c)continue;if(!c.some(m=>m.name==="target-run.json")){let m=c.filter(h=>h.isFile()&&fn(h.name)).map(h=>H.join(M,h.name));if(!m.length)continue;f??=`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(m.map(a)))});continue}let l=T.slice(`result_${t}_`.length);for(let m of c.filter(h=>h.isDirectory()))for(let h of await re.readdir(H.join(M,m.name),{withFileTypes:!0})){if(!h.isDirectory())continue;let w=H.join(M,m.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:i(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?i(_):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&&Gt(await a(o))>Gt(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:f,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(yt)??[])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),i=s.isDirectory()?await Ae(H.join(a,"target-run.json"),[]):void 0;i?.kind==="overheating"&&!i.parentJob&&n.push({name:t,job_id:s.name,status:String(i.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(yt)??[])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 i=await Ae(H.join(e,s.name,a.name,t,"target-run.json"),n);if(!i||i.kind==="overheating")continue;r.records+=1;let o=`_${String(i.name)}`;s.name.endsWith(o)&&(r.config??=s.name.slice(7,-o.length)),i.status==="complete"?r.passes+=1:i.status==="failed"&&(r.failures+=1),(i.status==="failed"||i.status==="cancelled")&&(r.stopped??=`Scenario ${String(i.name)} ${i.status}${typeof i.error=="string"?`: ${i.error}`:""}`)}return r}async function 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 yt(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 Rs(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 Ri from"crypto";import Re from"fs/promises";import ne from"path";import js from"fs/promises";import Rn from"path";var Pi=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 js.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 nt="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(o){let d=o;throw d.code==="ENOENT"?new Error(`CSV file not found at ${s}`):new Error(`Failed to read CSV file: ${d.message}`)}let i=await pt(a);try{let o=await(e.runTarget??rt)({workspace:t,operation:"prepare",csv:a,targetBundleId:i,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),d=r?ne.resolve(t,r):Ts(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:i,validation:o.validation,schema_omissions:o.schema_omissions,readiness:"wrapper_input"})),await jn(t,d,JSON.stringify(o.model,null,2)),{ok:!0,json_path:ne.relative(t,d),validation:o.validation,...o.schema_omissions?.length?{schema_omissions:o.schema_omissions}:{},schema_source:`target:${i}`,defaults_source:`target:${i}`,...o.notice?{notice:o.notice}:{}}}catch(o){return{ok:!1,error:o.message}}}function Ts(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 i of ne.relative(n,ne.dirname(s)).split(ne.sep).filter(Boolean))if(a=ne.join(a,i),await Re.mkdir(a).catch(o=>{if(o.code!=="EEXIST")throw o}),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(i){if(i.code!=="ENOENT")throw i}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 Ms}from"url";import me from"fs/promises";import X from"path";function vt(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 me.readdir(r,{withFileTypes:!0}),a={};for(let i of s){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let d=X.join(r,o),u=await me.readdir(d),f=[];for(let p of u){if(!p.endsWith(".json"))continue;let g=p.replace(/\.json$/,""),_=X.join(d,p);try{let C=await me.readFile(_,"utf8"),R=JSON.parse(C);f.push({id:g,name:typeof R.name=="string"?R.name:g,description:typeof R.description=="string"?R.description:"",category:o})}catch(C){console.error(`Failed to parse ${_}: ${C.message}`)}}f.length>0&&(a[o]={category:o,parameters:f.sort((p,g)=>p.name.localeCompare(g.name))})}return{catalog:a,total_categories:Object.keys(a).length,total_parameters:Object.values(a).reduce((i,o)=>i+o.parameters.length,0)}}async function 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");vt(n,"category"),vt(r,"parameter_id");let s=X.join(e,"input","batch_parameters",n),a=X.join(s,`${r}.json`),i=X.join(s,`${r}.md`),o;try{let u=await me.readFile(a,"utf8");o=JSON.parse(u)}catch(u){let f=u;throw f.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${f.message}`)}let d=null;try{d=await me.readFile(i,"utf8")}catch(u){let f=u;f.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${f.message}`)}return{category:n,parameter_id:r,json:o,markdown:d,has_markdown:d!==null}}async function or(e,t,n){let{category:r,parameter_id:s,content:a,markdown_content:i}=t;if(!r)throw new Error("category is required");if(!s)throw new Error("parameter_id is required");if(a==null||a==="")throw new Error("content is required");if(r!==r.toLowerCase())throw new Error(`category must be lowercase, as the workspace folders are: ${JSON.stringify(r)}`);vt(r,"category"),vt(s,"parameter_id");let o=$s(a),[d,u]=await Promise.all([Is(e),Ls(e,r)]),f=await Ns(e,Fs(d)?"input_fhs":"input_core"),p=V=>{let E=JSON.parse(n.validateSnippetJs(r,JSON.stringify(V),JSON.stringify(f),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(o),_=g.length>0&&!Os.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 me.mkdir(b,{recursive:!0});let x=X.join(b,`${s}.json`);await me.writeFile(x,JSON.stringify(o,null,2),"utf8");let $=null;return i&&($=X.join(b,`${s}.md`),await me.writeFile($,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${s}' saved successfully in category '${r}'`,paths:{json:x,markdown:$}}}function $s(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}var Os=new Set(["model_wrappers","weather_files","external_conditions","tariff","simplified_fabric"]);function Fs(e){return!!(e&&typeof e=="object"&&("General"in e||"PartGcompliance"in e))}function Mn(e){return["../schemas/","../../schemas/"].map(t=>Ms(new URL(t+e,import.meta.url)))}async function Ns(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 me.readFile(s,"utf8"))}catch{}throw new Error(`Schema file not found (${t}). Tried: ${r.join(", ")}`)}async function Is(e){let t=X.join(e,"input","batch_parameters","base_json"),n=(await me.readdir(t).catch(()=>[])).filter(o=>o.endsWith(".json")).sort(),r=new Set(await me.readdir(X.join(e,"input","base_models")).catch(()=>[])),s=n.filter(o=>!o.startsWith("defaults_template")),a=n.includes("demo_hp_annual.json")?"demo_hp_annual.json":s.find(o=>r.has(o.replace(/\.json$/,".csv")))??s[0];if(!a)throw new Error(`No base model to validate the snippet against: add one to ${t} (convert a geometry CSV with merge-csv-to-json).`);let i=X.join(t,a);try{return JSON.parse(await me.readFile(i,"utf8"))}catch(o){throw new Error(`Could not read base model ${i}: ${o.message}`)}}async function Ls(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 me.readFile(r,"utf8"))}catch{}return null}import dr from"fs/promises";import bt 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,i=[],o=[],d=[];try{let u=Ie.join(n,r),f=await ir(u);f&&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(!f)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let b of p===void 0?[]:ft(r,p)){let x=Ie.join(n,b);if(!await ir(x))continue;let $=b.slice(`result_${r}_`.length);o.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"?i.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 wt(e,r),_=g?.jobId;d.push(...g?.warnings??[]),_&&g?.error!==void 0&&!i.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}:{},...i.length?{failed_models:i}:{},...o.length?{overheating_runs:o}:{},...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(f=>f.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 i=(await Le.readFile(s,"utf8")).split(`
14
- `).filter(f=>f.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:s,error:"CSV must have at least headers and units rows"};let o=On(i[0]??"").map(f=>f.trim()),d=On(i[1]??"").map(f=>f.trim()),u=[];for(let f=1;f<o.length;f+=1){let p=o[f],g=f<d.length?d[f]:"";p&&u.push({name:p,unit:g||"",index:f-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:ir,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),i=await Le.readFile(Ie.join(e,"target-run.json"),"utf8").then(JSON.parse,()=>{}),o=typeof i?.jobId=="string"?i.jobId:void 0,d=(u,f)=>{n.has(u)||(n.add(u),t.push({name:u,csv_path:Ie.join(e,f),has_results:!0,...o?{job_id:o}:{}}))};if(r){let u=qt(a,"results");u&&d(r,u);return}for(let u of a){if(!qt([u],"results"))continue;let f=u.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);f?.[1]&&d(f[1],u)}}function Fn(e){return e.replace(/\.json$/,"")}async function ir(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 Bs=new Set(["sumif","averageif","countif"]),Nn=new Set([">=","<=",">","<","="]);async function fr(e,t,n){let{config_name:r,model_names:s,metric_definitions:a,time_range:i,tariff_file_path:o,tariff_column_index:d}=t;if(!r)throw new Error("config_name is required");if(!s||!Array.isArray(s)||s.length===0)throw new Error("model_names is required and must be a non-empty array");if(!a||!Array.isArray(a)||a.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=r.replace(/\.json$/,""),{encodedMetrics:f,metadata:p}=Ws(a);if(p.some(x=>x.function.toLowerCase()==="cost")&&(!o||d===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let _;if(o&&d!==void 0){let x=await Js(o,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=Ds(V,x,r);if(p.some(ae=>ae.isCompliance)){let ae=bt.join(bt.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(m=>m===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=Us(E,f,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(f),i?JSON.stringify(i):void 0,_);if(!Q||typeof Q!="string")throw new Error(`WASM returned invalid result: ${typeof Q}`);let Ce=JSON.parse(Q);if(!Array.isArray(Ce))throw new Error(`WASM returned non-array result: ${typeof Ce}`);Ce.forEach((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 Ds(e,t,n){let r=e.split(`
15
- `).filter(f=>f.trim());if(r.length<2)throw new Error("CSV must have at least headers and units rows");let s=(r[0]??"").split(",").map(f=>f.trim()),a=(r[1]??"").split(",").map(f=>f.trim()),i=[],o={},d=[],u=[];for(let f=1;f<s.length;f+=1){let p=s[f];p&&(o[p]=[],d.push(p),u.push(f<a.length&&a[f]||""))}for(let f=2;f<r.length;f+=1){let p=(r[f]??"").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)){i.push(_);for(let C=1;C<s.length&&C<p.length;C+=1){let R=s[C];if(!R||!o[R])continue;let I=p[C];if(I===void 0)continue;let b=Number.parseFloat(I);o[R].push(Number.isNaN(b)?0:b)}}}return{timestamps:i,columns:o,column_order:d,column_units:u,metadata:{model_name:t,config_name:n.replace(/\.json$/,""),total_points:i.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function 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 Vs(e){let t=(e.function||e.funcType||e.type||"sum").toString(),n=t.toLowerCase();if(n==="cost")return"cost";if(!Bs.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 Ws(e){let t=[],n=[];return e.forEach((r,s)=>{if(typeof r=="string"){let d=r.includes("|")?r:`${r}|sum`,[u=r,f="sum"]=d.split("|");t.push({name:d}),n.push({id:r,name:r,column:u,function:f,isCompliance:f.toLowerCase()==="compliance"});return}let a=r.column||(r.name?.includes("|")?r.name.split("|")[0]:r.name);if(!a)throw new Error(`Metric definition at index ${s} missing column or name. Got: ${JSON.stringify(r)}`);let i=r.name?.includes("|")&&!r.function&&!r.funcType?r.name.split("|")[1]||"sum":Vs(r),o=`${a}|${i}`;t.push({name:o}),n.push({id:r.id||r.metric_id||`${a}_${i}`,name:r.name||r.id||a,column:a,function:i,comparator:r.comparator,threshold:r.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:n}}async function Js(e,t,n){let r=bt.isAbsolute(e)?e:bt.resolve(n,e),a=(await dr.readFile(r,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${r}. Error: ${o.message}`)})).split(`
16
- `).filter(o=>o.trim());if(a.length===0)throw new Error(`Tariff file is empty: ${r}`);let i=[];for(let o=1;o<a.length;o+=1){let d=(a[o]??"").split(",").map(p=>p.trim().replace(/"/g,""));if(t>=d.length)throw new Error(`Column index ${t} not found in record ${o} with ${d.length} columns`);let u=d[t];if(u===void 0)throw new Error(`Column index ${t} is undefined in record ${o}`);let f=Number.parseFloat(u);if(Number.isNaN(f))throw new Error(`Could not parse '${u}' as number in row ${o+1}, column ${t+1}`);i.push(f)}if(i.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${i.length})`);return i}function Us(e,t,n){let r=[];return t.forEach((s,a)=>{let i=s.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${s.name}`);n[a]?.isCompliance||e.columns[i]||r.push(i)}),r}import{spawn as Hs}from"child_process";import{existsSync as qs,readFileSync as Gs}from"fs";import{createRequire as zs}from"module";import We from"path";var Ct="@vulcan-energy/community-cli";function Ln(e=import.meta.url){let t=zs(e),n;try{n=t.resolve(`${Ct}/package.json`)}catch{throw new Error(`${Ct} 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(Gs(n,"utf8")).bin?.["vulcan-community"];if(!s)throw new Error(`${Ct} declares no vulcan-community bin.`);let a=We.join(We.dirname(n),s);if(!qs(a))throw new Error(`${Ct} 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=mr(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:mr(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),i=t==="json"?wr(a):void 0,o=mr(i)?i:void 0;return{ok:a.exitCode===0&&(t!=="json"||o!==void 0),command:"thermal-bridges validate",csv_path:r,include_auto:n,mode:t,exit_code:a.exitCode,signal:a.signal,stdout:t==="json"&&o!==void 0?"":a.stdout,stderr:a.stderr,parsed:o,issue_count:typeof o?.issueCount=="number"?o.issueCount:void 0,thermal_bridge_linear_rows:typeof o?.thermalBridgeLinearRows=="number"?o.thermalBridgeLinearRows:void 0,error:t==="json"&&o===void 0?yr(a):void 0}}async function hr(e,t){return(e.runner??Ks)(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 mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ks=(e,t,n)=>new Promise((r,s)=>{let a=Hs(e,[...t],{cwd:n.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",o="";a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),a.stdout.on("data",d=>{i+=d}),a.stderr.on("data",d=>{o+=d}),a.on("error",s),a.on("close",(d,u)=>{r({exitCode:d,signal:u,stdout:i,stderr:o})})});var at="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 Xs(e){return e.isFree?null:{reason:`Advanced scenarios need Vulcan Pro. ${Ue}`,violations:e.violations}}function Dn(e){return Xs(mn(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:at,unlock:r}}import Zs from"fs/promises";import Ys from"path";async function St(e){let t=Ys.join(e,"input","analytics","default_metrics.json"),n;try{n=JSON.parse(await Zs.readFile(t,"utf8"))}catch(i){if(i.code==="ENOENT")return{metrics:[],cost_metrics:[],unsupported:[]};throw new Error(`Could not read ${t}: ${i.message}`)}if(!Array.isArray(n))throw new Error(`${t} must hold a list of metric templates`);let r=[],s=[],a=[];for(let i of n){if(!i?.column||!i.funcType)continue;let o=i.label??`${i.funcType} of ${i.column}`;if(i.funcType.toLowerCase()==="cost"){s.push(o);continue}if(i.resultsKey&&i.resultsKey!=="results"){a.push({name:o,reason:`reads the ${i.resultsKey} results file`});continue}if(i.normalization){a.push({name:o,reason:"is normalised (e.g. per floor area)"});continue}r.push({...i.id?{id:i.id}:{},name:o,column:i.column,function:i.funcType,...i.comparator?{comparator:i.comparator}:{},...typeof i.threshold=="number"?{threshold:i.threshold}:{}})}return{metrics:r,cost_metrics:s,unsupported:a}}import{createHash as Qs,randomUUID as eo}from"crypto";import we from"fs/promises";import to from"os";import je from"path";function kt(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??kt(n.env),a;try{a=await(n.fetch??fetch)(`${s}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(r)})}catch(i){let o=i.cause?.code;throw new Error(`Could not reach Vulcan at ${s}${o?` (${o})`:""}; check the internet connection and try again.`)}return{status:a.status,body:await a.json().catch(()=>({}))}}function kr(e,t){let n=t.env??process.env,r=n.VULCAN_STATE_DIR||je.join(to.homedir(),".vulcan","sign-in"),s=t.siteUrl??kt(n);return je.join(r,`${Qs("sha256").update(`${s}
17
- ${e}`).digest("hex").slice(0,24)}.json`)}var ro=/^[A-Za-z0-9_-]{43}$/,no=/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;function Jn(e,t,n){let r=`${t.siteUrl??kt(t.env)}/connect`;return!e||typeof e.deviceCode!="string"||!ro.test(e.deviceCode)||typeof e.userCode!="string"||!no.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 Et(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(i=>{if(i.code==="ENOENT")return null;throw i});if(!r)return null;let s=null;r.isFile()&&(s=await we.readFile(n,"utf8").then(i=>JSON.parse(i),()=>null));let a=Jn(s,t,(t.now??Date.now)());return a||await we.rm(n,{force:!0}),a}catch(r){throw Er(n,r)}}async function Pt(e,t,n={}){let r=kr(e,n),s=je.join(je.dirname(r),`.${eo()}.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 Et(e,n)??Pt(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,i=e.intervalMs,o=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")i=Math.min(Math.max(i+5e3,Sr(u.interval,0)*1e3),6e4);else if(d>=500)o=typeof u.error=="string"&&u.error!=="server_error"?u.error:`Vulcan could not finish sign-in (HTTP ${d}); it will retry.`;else{if(u.error!=="authorization_pending")return{status:"error",message:typeof u.error=="string"?u.error:`Vulcan sign-in failed (HTTP ${d}).`};o=null}}catch(d){o=d.message}if(r()+i>=e.expiresAt)return{status:"expired"};if(r()+i+Vn>a)return o?{status:"error",message:o}:{status:"pending"};await s(i)}}async function Un(e,t={}){return ar(e.workspace,t)}async function Hn(e,t){return sr(e.workspace,t)}import qn from"fs";import be from"path";import{fileURLToPath as ao}from"url";var so=be.dirname(ao(import.meta.url));function oo(){let e=[],t=so;for(let a=0;a<6;a+=1){e.push(t);let i=be.dirname(t);if(i===t)break;t=i}e.push(process.cwd());let n=[];for(let a of e)n.push({directory:be.join(a,"wasm"),context:"helper-root"},{directory:be.join(a,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:be.join(a,"web","dist","wasm"),context:"rust-hem-runner"},{directory:be.join(a,"web","dist"),context:"rust-hem-runner"},{directory:be.join(a,"web","pkg"),context:"rust-hem-runner"},{directory:be.join(a,"apps","web","public","launch"),context:"vulcan-website"});let r=[],s=new Set;for(let a of n){let i=be.join(a.directory,"wasm_wrapper.js");if(s.has(i))continue;s.add(i),r.push(i);let o=be.join(a.directory,"wasm_wrapper_bg.wasm");if(qn.existsSync(i)&&qn.existsSync(o))return a}throw new Error(`WASM files not found. Tried:
18
- `+r.map(a=>` - ${a}`).join(`
13
+ -----END PUBLIC KEY-----`]);import{compactVerify as Ta,importSPKI as Ma}from"jose";var Hr="EdDSA";async function Bt(e,t){let n=e.trim();if(!n)throw new K("empty","Vulcan access token is empty.");let r=t.publicKeys??Jr,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),i=await $a(n,r),o=Oa(i);if(o.iss!==it)throw new K("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${it}.`);if(o.aud!==Ft)throw new K("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==ct)throw new K("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${ct}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new K("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>Nt)throw new K("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(s<o.iat-It)throw new K("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let u=s>o.exp;if(u&&!t.allowExpired)throw new K("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:o,expired:u,expiresAt:new Date(o.exp*1e3),expiresInSeconds:o.exp-s}}async function $a(e,t){for(let n of t)try{let r=await Ma(n,Hr),{payload:a}=await Ta(e,r,{algorithms:[Hr]});return a}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 Oa(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"),a=Ze(n,"aud"),s=Ze(n,"sub"),i=Ze(n,"org"),o=Ze(n,"jti"),u=Lt(n,"iat"),d=Lt(n,"exp"),m=Lt(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new K("malformed","Vulcan access token must include a capabilities array.");let _=[];for(let g of n.capabilities){if(!Ot(g))throw new K("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(g)}.`);_.push(g)}if(_.length===0)throw new K("malformed","Vulcan access token grants no capabilities.");if(d<=u)throw new K("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:u,exp:d}}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 Lt(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 Fa="mcp",Na=2880*60;async function Dt(e={}){let t=Ye.resolve(e.workspace??process.env.VULCAN_WORKSPACE??process.cwd()),n=Ye.resolve(e.configPath??Ye.join(t,"vulcan-mcp-config.json")),r;try{r=await Ur.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 a=t,s;if(r!==void 0){let i;try{i=JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in config file ${n}: ${o.message}`)}if(i.workspace!==void 0){if(typeof i.workspace!="string")throw new Error("Config field workspace must be a string");a=Ye.resolve(Ye.dirname(n),i.workspace)}if(i.license_token!==void 0){if(typeof i.license_token!="string"||!i.license_token)throw new Error("Config field license_token must be a non-empty string");s=i.license_token}}try{await Ur.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}if(s){let{payload:i}=await lt(s,{allowExpired:!0}),o=i.exp-Math.floor(Date.now()/1e3);if(o<=0)console.error("[MCP Helper] Your Vulcan Pro access has expired: Free tools work; ask your assistant to sign in again (vulcan_sign_in) to renew.");else if(o<Na){let u=Math.max(1,Math.round(o/3600));console.error(`[MCP Helper] Warning: your Vulcan access expires in about ${u} hour(s). Ask your assistant to sign in again (vulcan_sign_in), or open Vulcan -> Profile -> Integrations and click "Generate Config File".`)}}return{workspace:a,...s?{license_token:s}:{},...r!==void 0?{configPath:n}:{}}}async function zr(e,t={}){if(!e.license_token)return{pro:!1,detail:"No Vulcan Pro access config is set; Free tools only."};try{return await lt(e.license_token,t),{pro:!0,detail:"Vulcan Pro access config is valid."}}catch(n){return{pro:!1,detail:n.message}}}async function lt(e,t={}){try{let{claims:n}=await Bt(e,{capability:Fa,now:t.now,publicKeys:t.publicKeys,allowExpired:t.allowExpired});return{payload:n}}catch(n){throw new Error(Ia(n))}}function Ia(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 La}from"crypto";function Ba(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 Da(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&La(n,r)}async function qr(e,t,n=lt){let r=Ba(e);if(!Da(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as S}from"zod";import ot from"fs/promises";import Oe from"path";import Va from"fs/promises";import Wa from"path";function Gr(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 u=!!(o.weather_file||o.weather_files),d=!!o.external_conditions;if(u){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`)}d&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!u&&!d&&n.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),u&&d&&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 Kr(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 Xr(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,u]of Object.entries(i))if(Array.isArray(u)&&!(o==="weather_file"||o==="weather_files"))for(let d of u){let m=Wa.join(e,"input","batch_parameters",o,`${String(d)}.json`);try{await Va.access(m)}catch{r.push({scenario:a,category:o,parameter:String(d),path:m}),n.push(`Scenario '${a}': Parameter '${String(d)}' in category '${o}' not found at ${m}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as hs,readFile as wn}from"fs/promises";import{join as yn}from"path";import{fileURLToPath as ws}from"url";var Ja=Aa(Zr(),1),Ha=Object.defineProperty,Ua=Object.getOwnPropertyNames,za=(e,t)=>function(){return e&&(t=(0,e[Ua(e)[0]])(e=0)),t},qa=(e,t)=>{for(var n in t)Ha(e,n,{get:t[n],enumerable:!0})},Ga={};qa(Ga,{configureWasm:()=>Ka,getRuntimeApiUrl:()=>ns,getRuntimeWasmVariant:()=>es,getVersionedWasmAssetPaths:()=>Ut,getVersionedWasmJsUrl:()=>nn,getWasmAssetPaths:()=>rn,getWasmBaseUrl:()=>Ht,getWasmBinaryUrl:()=>an,getWasmJsUrl:()=>cn,getWasmRayonThreadCount:()=>Qr,getWasmVariant:()=>tn,getWasmVersionInfo:()=>ut,getWasmVersionJsonUrl:()=>en,getWasmWasmUrl:()=>ln,initializeWasmRayonThreadPool:()=>Qa});function Ka(e={}){e.baseUrl&&(sn=Xa(e.baseUrl)),typeof e.preferHashed=="boolean"&&(on=e.preferHashed)}function Yr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Xa(e){return e.replace(/\/+$/,"")||"/"}function Za(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Ya(){let e=Yr();if(e){if(Za(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Ht(){return sn||Ya()}function Qr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Qa(e){let t=e,n=Qe.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(Qr())).then(()=>{});return Qe.set(t,a),a.catch(()=>{Qe.get(t)===a&&Qe.delete(t)}),a}function en(){return`${Ht()}/wasm_version.json`}async function ut(){try{let e=await fetch(en(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function tn(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 es(){return tn(await ut())}function ts(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function rs(e){let t=ts(),r=!!((on??!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 rn(e){let t=Ht(),n=e===void 0?await ut():e,{jsFilename:r,wasmFilename:a}=rs(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${a}`}}async function Ut(){let e=await ut(),{jsPath:t,wasmPath:n}=await rn(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 nn(){let{jsPath:e}=await Ut();return e}async function an(){let{wasmPath:e}=await Ut();return e}function ns(e){let t=Yr();return t?new URL(e,t.origin).toString():e}var Qe,sn,on,cn,ln,un=za({"src/wasmPath.ts"(){Qe=new WeakMap,cn=nn,ln=an}});async function dn(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 mn(e,t){let n=await dn(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 fn(e,t){let n=t.lastIndexOf("/"),r=await dn(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}async function pn(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return t;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);let a=r.archive??t;if(typeof a!="string"||a!==t&&!a.startsWith(`${t}/`)||a.split("/").some(s=>!s||s==="."||s==="..")||a.includes("\\"))throw new Error(`Invalid target result archive: ${t}`);return a}function zt(e){let t=new Map;for(let{run:i,startedAt:o,fileTime:u}of e){if(o!==void 0&&Number.isNaN(Date.parse(o)))throw new Error(`Run ${i} records an invalid start time: ${o}`);let d=t.get(i);t.set(i,{run:i,startedAt:d?.startedAt??o,fileTime:Math.max(d?.fileTime??u,u)})}let n=(i,o)=>{let u=`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)||u;if(i.startedAt===void 0&&o.startedAt===void 0)return i.fileTime-o.fileTime||u;let[d,m]=i.startedAt===void 0?[o,i]:[i,o];return m.fileTime<Date.parse(d.startedAt)?d===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 ${d.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(u=>typeof u=="number"&&u>0));return s||!r.length?s:{unknown:a.flat().find(i=>typeof i=="string")}}function qt(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))}un();function _n(e){return e.startsWith("__")}function dt(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!_n(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function as(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function ss(e){let t=as(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function mt(e,t){let n=[];for(let r of dt(t)){let a=ss(r.value);for(let s=0;s<a;s+=1)n.push(`result_${e}_${r.name}_${s}`)}return n}function Gt(e){return Math.floor(e/1e3)}function os(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function is(e){return e==="failure_context.json"}function gn(e){return os(e)||is(e)}var cs=["fhs_assumptions","fhs_compliance"];var ls=[...cs,"epc_quick","epc_full"];function us(e){return ls.some(t=>t===e)}var ds=new Set(["base_json","model_wrappers","weather_files","external_conditions"]);function he(e,t,n){return{category:e,selections:[...t],message:n}}function ms(e){let t=0;for(let n of e){let r=1;for(let a of Object.values(n.parameters))a.length>0&&(r*=a.length);t+=r}return t}function fs(e){let t=[],n=e.scenarios[0];e.scenarios.length!==1&&t.push(he("scenarios",e.scenarios.slice(1).map(d=>d.name),"Free configurations contain exactly one scenario."));let r=n?.parameters??{},a=r.base_json??[];a.length!==1&&t.push(he("base_json",a.slice(1),"Free configurations contain exactly one base model."));let s=r.model_wrappers??[],i=s.findIndex(us),o=s.filter((d,m)=>m!==i);(s.length!==1||i!==0)&&t.push(he("model_wrappers",o,"Free configurations use exactly one model wrapper: fhs_assumptions, fhs_compliance, epc_quick or epc_full."));for(let d of["weather_files","external_conditions"]){let m=r[d]??[];m.length>0&&t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")}.`))}for(let[d,m]of Object.entries(r))ds.has(d)||m.length===0||t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")} parameters.`));let u=ms(e.scenarios);return u!==1&&t.push(he("permutations",[String(u)],"Free configurations compute exactly one permutation.")),{isFree:t.length===0,violations:t}}function ps(e,t){return _n(e)||e==="targetBundleId"&&typeof t=="string"}function _s(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 hn(e){if(!e||typeof e!="object"||Array.isArray(e))return{isFree:!1,violations:[he("config",[],"A batch configuration must be a JSON object.")]};let t=[],n=[];for(let[i,o]of Object.entries(e)){if(ps(i,o))continue;if(!o||typeof o!="object"||Array.isArray(o)){t.push(he("config",[i],`Unrecognised batch configuration entry '${i}'.`));continue}let u={};for(let[d,m]of Object.entries(o))d==="zone_allocations"?_s(m)&&t.push(he("zone_allocations",[i],"Free configurations do not use per-zone selections.")):Array.isArray(m)?u[d]=m.map(String):t.push(he(d,[i],`'${d}' in '${i}' must be a list of selections.`));n.push({name:i,parameters:u})}let r=e.__hem;(!r||typeof r!="object"||Array.isArray(r))&&t.push(he("target",[],"Free runs use a model saved by the current Vulcan app, pinned to a HEM version."));let s=[...fs({scenarios:n}).violations,...t];return{isFree:s.length===0,violations:s}}function gs(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&Jt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&Jt(r))return r;let s=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(s&&Jt(s))return s}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function Jt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var Xo=gs();un();var ft;async function pt(e){return ft??=vn(),(await ft).csvTarget(e)}async function Kt(e,t){let n=await Le(e,{scenario_1:{base_json:[t]}});return n?(ft??=vn(),(await ft).singleRunWrapper(n)):"fhs_compliance"}async function vn(){for(let e of["./hem-target-runtime/preparation.mjs","../hem-target-runtime/preparation.mjs"]){let t=new URL(e,import.meta.url);try{await hs(ws(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 Le(e,t){let n=new Set;for(let{value:r}of dt(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 ys(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 ys(e,t){try{return await pt(await wn(yn(e,"input/base_models",`${t}.csv`),"utf8"))}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await wn(yn(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 Xt(e,t){if(dt(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 Le(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 Rs}from"child_process";import{join as Qt,resolve as As}from"path";import{access as js,readFile as er}from"fs/promises";import{fileURLToPath as tr}from"url";import{createHash as bs}from"crypto";import et from"fs";import Re from"path";import{fileURLToPath as vs}from"url";function Zt(e=process.cwd()){let t=Re.resolve(e);for(et.existsSync(t)&&et.statSync(t).isFile()&&(t=Re.dirname(t));;){if(et.existsSync(Re.join(t,"package.json"))&&et.existsSync(Re.join(t,"hem-batch-core"))&&et.existsSync(Re.join(t,"web")))return t;let r=Re.dirname(t);if(r===t)break;t=r}let n=Re.dirname(vs(import.meta.url));return Re.resolve(n,"..","..","..")}import we from"fs";import de from"path";import{fileURLToPath as di,pathToFileURL as Cs}from"url";var bn=new Map,Cn=!1,Yt=process.cwd(),En=!1;async function _t(e,t){let n=t?`${e}?verified`:e,r=bn.get(n);if(r)return r;Ss();let a=de.join(e,"wasm_wrapper.js"),s=de.join(e,"wasm_wrapper_bg.wasm"),i=de.join(e,"wasm_version.json");if(!we.existsSync(a)||!we.existsSync(s))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(Cs(a).href+(t?"?verified":""));if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:t??we.readFileSync(s)}),o.setup_panic_hook?.(),typeof o.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let u={convertGeometryCsvToJson:o.convert_geometry_csv_to_json.bind(o),validateSnippetJs:o.validate_snippet_js?.bind(o),processBatchConfig:o.process_batch_config?.bind(o),calculateMetricsFromParsedData:o.calculate_metrics_from_parsed_data?.bind(o),setWorkspace:ht,prepareTargetScenario:o.prepare_target_scenario?.bind(o),metadata:{source:a,wasm_path:s,wasm_version:Ps(i),build_stamp:rt(o.build_stamp),build_info:xs(o.get_build_info),runtime_origin_descriptor:rt(o.runtime_origin_descriptor),hem_core_version:rt(o.metadata_hem_core_version),fhs_wrapper_version:rt(o.metadata_fhs_wrapper_version)}};return bn.set(n,u),u}var Sn=new Map;async function gt(e,t){let n=Sn.get(e);if(n)return n;let r=u=>{try{return we.readFileSync(de.join(e,u))}catch{throw new Error(`The package WASM is incomplete: ${de.join(e,u)} is missing. ${t}`)}},a=JSON.parse(r("wasm_version.json").toString("utf8"));for(let u of["js_sha256","sha256"])if(!a[u])throw new Error(`${de.join(e,"wasm_version.json")} has no ${u}. ${t}`);let s=u=>bs("sha256").update(u).digest("hex"),i=r("wasm_wrapper_bg.wasm");if(s(r("wasm_wrapper.js"))!==a.js_sha256||s(i)!==a.sha256)throw new Error(`The WASM in ${e} does not match its wasm_version.json. ${t}`);let o={...await _t(e,i),versionInfo:a};return Sn.set(e,o),o}function ht(e,t={}){Yt=de.resolve(e),En=t.confineToWorkspace===!0}function Ss(){ks(),Es();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=tt(n);try{return we.mkdirSync(de.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=tt(n);return we.readFileSync(r,"utf8")},e.file_exists=n=>{let r=tt(n);return we.existsSync(r)},e.create_dir_all=n=>{let r=tt(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=tt(n);try{return we.readdirSync(r)}catch{return[]}}}function tt(e){let t=de.isAbsolute(e)?de.resolve(e):de.resolve(Yt,e);if(En){let n=de.relative(Yt,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 ks(){if(Cn)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},Cn=!0}var kn=!1;function Es(){if(kn)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)}),kn=!0}function Ps(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function rt(e){return typeof e!="function"?void 0:e()||void 0}function xs(e){let t=rt(e);if(t)try{return JSON.parse(t)}catch{return t}}var Be=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 Pn(),r=t?{targetBundleId:e.targetBundleId,manifestPath:As(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 a=e.wasmDir??n.wasmDir,s=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:a,wasmRemedy:s};return e.foreground?n.adapter.runTargetBrowser(m,{loadPackageWasm:gt}):Ts(n.adapterPath,m)}if(typeof e.csv!="string")throw new Error("CSV source required");let i=await n.adapter.workspaceReader(e.workspace),{manifest:o,text:u}=await n.adapter.readPreparationBundle(r),d=await gt(a,s);return n.preparation.prepareCsv({csv:e.csv,manifest:o,text:u,converter:{prepare_target_scenario:d.prepareTargetScenario},read:i})};async function rr(e){let{workspace:t,baseModel:n}=e,r=await Le(t,{scenario_1:{base_json:[n]}});if(!r)return{status:"unavailable",reason:`${n} is not pinned to a HEM version. Re-save it in the current Vulcan app, or convert its geometry CSV with vulcan_merge_csv_to_json.`};let a=await Pn(),s=a.preparation.heatingSizingUnavailable(r);if(s)return{status:"unavailable",reason:s};let i=await er(Qt(t,"input/base_models",`${n}.csv`),"utf8").catch(_=>{if(_.code!=="ENOENT")throw _}),o=i===void 0?{model:JSON.parse(await er(Qt(t,"input/batch_parameters/base_json",`${n}.json`),"utf8")),validation:JSON.parse(await er(Qt(t,"input/base_models",`${n}.target.json`),"utf8")).validation}:await Be({...e,operation:"prepare",csv:i,targetBundleId:r}),u=o.validation?.errors??[];if(u.length)return{status:"unavailable",reason:"Fix the model errors to size the heating.",errors:u.map(_=>_.message)};if(!Object.keys(o.model.SpaceHeatSystem??{}).length)return{status:"unavailable",reason:"The model has no space heating system to size."};let d=await a.adapter.resolveReleaseBundle(r),m=await a.adapter.loadDesignHeatLossTarget(d.manifestPath,d.manifestSha256);return m.reason?{status:"unavailable",reason:m.reason}:a.preparation.sizeTargetHeating(m.module,JSON.stringify(o.model))}async function Pn(){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 js(tr(n))}catch{continue}let[r,a]=await Promise.all([import(n.href),import(new URL("preparation.mjs",t).href)]);return{adapter:r,preparation:a,adapterPath:tr(n),wasmDir:tr(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 Ts(e,t){return new Promise((n,r)=>{let a=Rs(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 Ms}from"crypto";import re from"fs/promises";import U from"path";async function nr(e,t,n={},r={}){let{config_name:a,base_model:s,weather_file:i,wrapper:o,parameters:u}=t;if(!a)throw new Error("config_name is required");if(De(a),!s)throw new Error("base_model is required");if(!u||typeof u!="object"||Array.isArray(u))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let d=$s(u),m={base_json:[s],...o?{model_wrappers:[o]}:{},...d},_=await Le(e,{scenario_1:m}),g=!!(t.targetManifestPath||t.targetManifestSha256||_);if(!i&&!g)throw new Error("weather_file is required");i&&(m.weather_files=[g&&!i.endsWith(".epw")?`${i}.epw`:i]);let f={scenario_1:m};await r.gate?.(g?{...f,__hem:{}}:f);let v=Gr(f,{requireWeather:!g});if(!v.valid)return{success:!1,valid:!1,errors:v.errors,warnings:v.warnings,message:`Config validation failed: ${v.errors.join("; ")}`};let A=Kr(f);if(A===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(A>I)return{success:!1,valid:!1,errors:[`Total permutations (${A}) exceeds maximum of ${I}`],message:`Config would generate ${A} permutations, which exceeds the limit of ${I}`};let C=f;if(g){let E=await(r.runTarget??Be)({workspace:e,operation:"snapshot",config:f,targetBundleId:_,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});C={...f,__hem:E}}else{let E=await Xr(e,f);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=U.join(e,"input","batch_parameters","base_json",`${s}.json`);try{await re.access(W)}catch{return{success:!1,valid:!1,errors:[`Base model '${s}' not found at ${W}`],message:`Base model file not found: ${s}`}}let Q=U.join(e,"input","batch_parameters","weather_files",i.endsWith(".epw")?i:`${i}.epw`);try{await re.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Q}`],message:`Weather file not found: ${i}`}}}await r.gate?.(C);let x=U.join(e,"input","batch_configs");if(g){let E=await re.realpath(e);for(let W of["input","batch_configs"])if(E=U.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 $=a.endsWith(".json")?a:`${a}.json`,V=U.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(C,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:V,permutations:A,structure:f}}async function ar(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_${Ms()}`;De(r);let i=r.endsWith(".json")?r:`${r}.json`,o=U.join(e,"input","batch_configs",i),u;try{u=await re.readFile(o,"utf8")}catch(g){let f=g;throw f.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${f.message}`)}let d=JSON.parse(u);if(await n.gate?.(d),d&&typeof d=="object"&&("__hem"in d||"targetBundleId"in d)){let g=d.__hem;if(!g){let f="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:f,error:f}}try{return await(n.runTarget??Be)({workspace:e,operation:"batch",config:d,targetBundleId:g.targetBundleId,configName:r.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:r,output_dir:U.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(f){let v=f.message;return{job_id:s,status:"error",message:v,error:v}}}let m=await Xt(e,d);if(m)return{job_id:s,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:s,status:"error",message:g,error:g}}let _=U.join(e,"output");await re.mkdir(_,{recursive:!0});try{let g=await n.processBatchConfig(u,e,_,r.replace(/\.json$/,""),s),f=JSON.parse(g);return f.error?{job_id:s,status:"error",message:`Batch execution failed: ${f.error}`,error:f.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:_}}catch(g){let f=g;return{job_id:s,status:"error",message:`Failed to start batch execution: ${f.message}`,error:f.message}}}async function sr(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,"");r&&De(r);let a=U.join(e,"output"),s;if(r&&!n){if(s=await wt(e,r),!s.jobId){let x=s.error!==void 0?"error":s.unknown?"unknown":"not_run",$=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:x,progress:0,passes:0,failures:0,output_dir:a,error:$,...An(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=U.join(a,`progress_${n}.json`),u=U.join(a,`sim_progress_${n}.json`),d=await Ae(o,i),m=await Ae(u,i),_=await Mn(a,n,i);if(!s&&_.config){let x=await wt(e,_.config);i.push(...x.warnings),x.jobId===n&&(s=x),r??=_.config}let g=_.records>0||typeof d?.targetBundleId=="string",f="queued",v=0,A=0,I=0,C=null;if(d?(jn(d.status)?f=d.status:typeof d.percentage=="number"?(v=d.percentage,f=v>=100?"completed":"running"):typeof d.current_combination=="number"&&typeof d.total_combinations=="number"&&(v=Math.round(d.current_combination/d.total_combinations*100),f=v>=100?"completed":"running"),typeof d.percentage=="number"&&(v=d.percentage),typeof d.error=="string"&&(C=d.error,f="error")):_.records&&(_.stopped?(f="error",C=_.stopped):s?.expected!==void 0&&_.passes===s.expected?(f="completed",v=100):(f="unknown",C=`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:A,failures:I}=_),s?.error!==void 0&&(C=s.error,f="error"),m&&!g&&(jn(m.status)&&(f=m.status),typeof m.passes=="number"&&(A=m.passes),typeof m.failures=="number"&&(I=m.failures),typeof m.error=="string"&&(C=m.error,f="error")),!d&&!m&&!_.records){let x=U.join(a,n);try{let $=await re.readdir(x);f=$.length>0?"completed":"queued",v=$.length>0?100:0}catch($){throw $.code!=="ENOENT"?$: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:f,progress:v,passes:A,failures:I,output_dir:a,error:C,batch_progress:d??null,sim_progress:g?null:m??null,...An(i)}}async function wt(e,t){let n=U.join(e,"output"),r=[],a=[],s=async T=>(await re.stat(T)).mtimeMs,i=T=>typeof T.startedAt=="string"?T.startedAt:void 0;for(let T of await re.readdir(n).catch(yt)??[]){if(!T.startsWith("progress_")||!T.endsWith(".json"))continue;let M=await Ae(U.join(n,T),r),c=T.slice(9,-5);M?.config_name===t&&a.push({run:c,jobId:c,startedAt:i(M),fileTime:await s(U.join(n,T))})}De(t);let o=U.join(e,"input","batch_configs",`${t}.json`),u=await Ae(o,r),d=u?mt(t,u):[],m,_=[];for(let T of d){let M=U.join(n,T),c=await re.readdir(M,{withFileTypes:!0}).catch(yt);if(!c)continue;if(!c.some(p=>p.name==="target-run.json")){let p=c.filter(h=>h.isFile()&&gn(h.name)).map(h=>U.join(M,h.name));if(!p.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.`,a.push({run:xn,fileTime:Math.max(...await Promise.all(p.map(s)))});continue}let l=T.slice(`result_${t}_`.length);for(let p of c.filter(h=>h.isDirectory()))for(let h of await re.readdir(U.join(M,p.name),{withFileTypes:!0})){if(!h.isDirectory())continue;let w=U.join(M,p.name,h.name,"target-run.json"),O=r.length,b=await Ae(w,r);if(!b){r.length>O&&_.push({warning:r.at(-1),fileTime:await s(w)});continue}b.name!==l||b.kind==="overheating"||a.push({run:h.name,jobId:h.name,startedAt:i(b),fileTime:await s(w)})}}let g=U.join(n,`batch_status_${t}.json`),f=await Ae(g,r),v=f?.status==="error"||f?.status==="running",A=v?i(f):void 0,I=A===void 0?void 0:a.find(T=>T.jobId&&T.startedAt===A)?.jobId;v&&!I&&a.push({run:Rn,startedAt:A,fileTime:await s(g)});let C=u?d.length:void 0,x=a.flatMap(T=>T.startedAt===void 0?[]:[Date.parse(T.startedAt)]),$=_.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:C,warnings:r};if(!a.length)return{legacyCurrent:!0,expected:C,warnings:r};if(u&&Gt(await s(o))>Gt(Math.max(...a.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:C,warnings:r};let V=zt(a);if("unknown"in V)return{unknown:V.unknown,expected:C,warnings:r};if(V.run===xn)return{unknown:m,legacyCurrent:!0,expected:C,warnings:r};let E=f?.error_message,W=f?.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!==Rn)return{jobId:V.run,...V.run===I?{error:W}:{},expected:C,warnings:r};if(f?.status==="running")return{unknown:`The app started a run of batch config '${t}' at ${A} and has written no scenario yet. It may still be preparing, or it stopped without recording why; check the app.`,expected:C,warnings:r};if(A!==void 0)return{error:W,expected:C,warnings:r};let Q=zt(a.filter(T=>T.jobId)),Se=Q&&"run"in Q?Q.run:void 0;return{...Se&&(await Mn(n,Se,r)).stopped?{jobId:Se}:{},error:W,expected:C,warnings:r}}var xn="legacy engine results";async function Tn(e,t){let n=[];for(let r of await re.readdir(e,{withFileTypes:!0}).catch(yt)??[])if(r.isDirectory())for(let a of await re.readdir(U.join(e,r.name),{withFileTypes:!0})){let s=U.join(e,r.name,a.name),i=a.isDirectory()?await Ae(U.join(s,"target-run.json"),[]):void 0;i?.kind==="overheating"&&!i.parentJob&&n.push({name:t,job_id:a.name,status:String(i.status),path:s})}return n}var Rn="the app's run status";async function Mn(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let a of await re.readdir(e,{withFileTypes:!0}).catch(yt)??[])if(!(!a.isDirectory()||!a.name.startsWith("result_")))for(let s of await re.readdir(U.join(e,a.name),{withFileTypes:!0})){if(!s.isDirectory())continue;let i=await Ae(U.join(e,a.name,s.name,t,"target-run.json"),n);if(!i||i.kind==="overheating")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 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 yt(e){if(e.code!=="ENOENT")throw e}function An(e){return e.length?{warnings:e}:{}}function De(e){let t=e.endsWith(".json")?e.slice(0,-5):e;if(!t.trim()||U.basename(t)!==t||/[\\/\0]/.test(t)||t.startsWith("."))throw new Error(`Invalid batch config name: ${JSON.stringify(e)} (no path separators or leading '.')`)}function $s(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function jn(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Oi from"crypto";import je from"fs/promises";import ne from"path";import Os from"fs/promises";import On from"path";var Ti=On.join("input","base_models");async function or(e){await $n(e,"Workspace"),await $n(On.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 $n(e,t){try{if(!(await Os.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 nt="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 ir(e){let{workspace:t,csvPath:n,outputPath:r}=e,a=ne.isAbsolute(n)?n:ne.join(t,n),s;try{s=await je.readFile(a,"utf8")}catch(o){let u=o;throw u.code==="ENOENT"?new Error(`CSV file not found at ${a}`):new Error(`Failed to read CSV file: ${u.message}`)}let i=await pt(s);try{let o=await(e.runTarget??Be)({workspace:t,operation:"prepare",csv:s,targetBundleId:i,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),u=r?ne.resolve(t,r):Fs(t,a);if(ne.extname(u)!==".json")throw new Error("Prepared target output must have a .json extension");return await Nn(t,u),await Fn(t,ne.join(t,"input/base_models",ne.basename(u,".json")+".target.json"),JSON.stringify({targetBundleId:i,validation:o.validation,schema_omissions:o.schema_omissions,readiness:"wrapper_input"})),await Fn(t,u,JSON.stringify(o.model,null,2)),{ok:!0,json_path:ne.relative(t,u),validation:o.validation,...o.schema_omissions?.length?{schema_omissions:o.schema_omissions}:{},schema_source:`target:${i}`,defaults_source:`target:${i}`,...o.notice?{notice:o.notice}:{}}}catch(o){return{ok:!1,error:o.message}}}function Fs(e,t){let n=ne.basename(t,ne.extname(t));return ne.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function Nn(e,t){let n=await je.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 a=ne.join(n,r),s=n;for(let i of ne.relative(n,ne.dirname(a)).split(ne.sep).filter(Boolean))if(s=ne.join(s,i),await je.mkdir(s).catch(o=>{if(o.code!=="EEXIST")throw o}),await je.realpath(s)!==s)throw new Error("Target preparation output directory is a symlink");try{if(await je.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(i){if(i.code!=="ENOENT")throw i}return a}async function Fn(e,t,n){let r=await Nn(e,t),a=await je.open(r,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await je.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return je.open(r,"w")});try{await a.writeFile(n)}finally{await a.close()}}import{fileURLToPath as Ns}from"url";import fe from"fs/promises";import X from"path";function vt(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 cr(e,t={}){let{category:n}=t,r=X.join(e,"input","batch_parameters"),a=await fe.readdir(r,{withFileTypes:!0}),s={};for(let i of a){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let u=X.join(r,o),d=await fe.readdir(u),m=[];for(let _ of d){if(!_.endsWith(".json"))continue;let g=_.replace(/\.json$/,""),f=X.join(u,_);try{let v=await fe.readFile(f,"utf8"),A=JSON.parse(v);m.push({id:g,name:typeof A.name=="string"?A.name:g,description:typeof A.description=="string"?A.description:"",category:o})}catch(v){console.error(`Failed to parse ${f}: ${v.message}`)}}m.length>0&&(s[o]={category:o,parameters:m.sort((_,g)=>_.name.localeCompare(g.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 lr(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");vt(n,"category"),vt(r,"parameter_id");let a=X.join(e,"input","batch_parameters",n),s=X.join(a,`${r}.json`),i=X.join(a,`${r}.md`),o;try{let d=await fe.readFile(s,"utf8");o=JSON.parse(d)}catch(d){let m=d;throw m.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let u=null;try{u=await fe.readFile(i,"utf8")}catch(d){let m=d;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:n,parameter_id:r,json:o,markdown:u,has_markdown:u!==null}}async function ur(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");if(r!==r.toLowerCase())throw new Error(`category must be lowercase, as the workspace folders are: ${JSON.stringify(r)}`);vt(r,"category"),vt(a,"parameter_id");let o=Is(s),[u,d]=await Promise.all([Vs(e),Ws(e,r)]),m=await Ds(e,Bs(u)?"input_fhs":"input_core"),_=V=>{let E=JSON.parse(n.validateSnippetJs(r,JSON.stringify(V),JSON.stringify(m),JSON.stringify(u),d?JSON.stringify(d):null));return E.ok?[]:(E.errors??[]).map(W=>typeof W=="string"?{path:"",message:W}:{path:W.path??"",message:W.message||String(W)})},g=_(o),f=g.length>0&&!Ls.has(r),v=V=>`${V.path}\0${V.message}`,A=f?new Set(_({}).map(v)):new Set,I=g.filter(V=>V.message.startsWith("Merge failed")||!A.has(v(V))).map(V=>V.message);if(I.length>0)return{success:!1,valid:!1,errors:I,message:`Validation failed: ${I.join("; ")}`};let C=X.join(e,"input","batch_parameters",r);await fe.mkdir(C,{recursive:!0});let x=X.join(C,`${a}.json`);await fe.writeFile(x,JSON.stringify(o,null,2),"utf8");let $=null;return i&&($=X.join(C,`${a}.md`),await fe.writeFile($,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${r}'`,paths:{json:x,markdown:$}}}function Is(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}var Ls=new Set(["model_wrappers","weather_files","external_conditions","tariff","simplified_fabric"]);function Bs(e){return!!(e&&typeof e=="object"&&("General"in e||"PartGcompliance"in e))}function In(e){return["../schemas/","../../schemas/"].map(t=>Ns(new URL(t+e,import.meta.url)))}async function Ds(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(Zt(e),"hem_fhs_upstream","schema","input_fhs.schema.json"),...In(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(Zt(e),"hem_engine_upstream","schemas","core-input.schema.json"),...In(n)];for(let a of r)try{return JSON.parse(await fe.readFile(a,"utf8"))}catch{}throw new Error(`Schema file not found (${t}). Tried: ${r.join(", ")}`)}async function Vs(e){let t=X.join(e,"input","batch_parameters","base_json"),n=(await fe.readdir(t).catch(()=>[])).filter(o=>o.endsWith(".json")).sort(),r=new Set(await fe.readdir(X.join(e,"input","base_models")).catch(()=>[])),a=n.filter(o=>!o.startsWith("defaults_template")),s=n.includes("demo_hp_annual.json")?"demo_hp_annual.json":a.find(o=>r.has(o.replace(/\.json$/,".csv")))??a[0];if(!s)throw new Error(`No base model to validate the snippet against: add one to ${t} (convert a geometry CSV with merge-csv-to-json).`);let i=X.join(t,s);try{return JSON.parse(await fe.readFile(i,"utf8"))}catch(o){throw new Error(`Could not read base model ${i}: ${o.message}`)}}async function Ws(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 pr from"fs/promises";import Ct from"path";import Te from"fs/promises";import _e from"path";async function Je(e,t){let n=_e.join(e,"output"),r=Dn(t.config_name);De(r);let a=[],s=new Set,i=[],o=[],u=[];try{let d=_e.join(n,r),m=await bt(d);m&&await Ln(e,d,a,s);let _;try{_=JSON.parse(await Te.readFile(_e.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(C){if(C.code!=="ENOENT")throw C;if(!m)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let C of _===void 0?[]:mt(r,_)){let x=_e.join(n,C);if(!await bt(x))continue;let $=C.slice(`result_${r}_`.length);o.push(...await Tn(x,$));try{await Ln(e,x,a,s,$)}catch(V){let E=await Te.readFile(_e.join(x,"target-run.json"),"utf8").then(JSON.parse,()=>{});E?.status==="failed"||E?.status==="cancelled"?i.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"?u.push(`Scenario ${$} has no results yet: its run${typeof E.jobId=="string"?` (job ${E.jobId})`:""} is recorded as running.`):u.push(`Failed to read result directory ${C}: ${V.message}`)}}a.sort((C,x)=>C.name.localeCompare(x.name));let g=_===void 0?void 0:await wt(e,r),f=g?.jobId;u.push(...g?.warnings??[]),f&&g?.error!==void 0&&!i.some(C=>C.job_id===f)&&u.push(`The app recorded run ${f} of batch config '${r}' as failed after these scenarios finished: ${g.error}`);let v=g===void 0?[]:a.filter(C=>C.job_id===void 0?!g.legacyCurrent:C.job_id!==f),A=f||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=a.filter(C=>!v.includes(C));return{config_name:r,models:I,total_models:I.length,output_dir:n,...f?{latest_job_id:f}:{},...v.length?{earlier_run_models:v}:{},...A?{latest_run_unknown:A}:{},...i.length?{failed_models:i}:{},...o.length?{overheating_runs:o}:{},...u.length?{warnings:u}:{}}}catch(d){return{config_name:r,models:[],total_models:0,output_dir:n,error:`Failed to list models: ${d.message}`}}}async function dr(e,t){let n=Dn(t.config_name),r=await Je(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:mr(r,t.model_name)};let i=(await Te.readFile(a,"utf8")).split(`
14
+ `).filter(m=>m.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let o=Bn(i[0]??"").map(m=>m.trim()),u=Bn(i[1]??"").map(m=>m.trim()),d=[];for(let m=1;m<o.length;m+=1){let _=o[m],g=m<u.length?u[m]:"";_&&d.push({name:_,unit:g||"",index:m-1})}return{config_name:n,model_name:t.model_name,columns:d,total_columns:d.length,csv_path:a}}function mr(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 fr={fileExists:bt,readFile:e=>Te.readFile(e,"utf8"),listFiles:e=>Te.readdir(e)};async function Ln(e,t,n,r,a){let s={fileExists:f=>bt(_e.join(e,f)),readFile:f=>Te.readFile(_e.join(e,f),"utf8")},i=_e.relative(e,t).split(_e.sep).join("/"),o=_e.join(e,await pn(s,i)),d=(await mn(fr,o)).map(f=>typeof f=="string"?f:f.name),m=await Te.readFile(_e.join(o,"target-run.json"),"utf8").then(JSON.parse,()=>{}),_=typeof m?.jobId=="string"?m.jobId:void 0,g=(f,v)=>{r.has(f)||(r.add(f),n.push({name:f,csv_path:_e.join(o,v),has_results:!0,..._?{job_id:_}:{}}))};if(a){let f=qt(d,"results");f&&g(a,f);return}for(let f of d){if(!qt([f],"results"))continue;let v=f.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);v?.[1]&&g(v[1],f)}}function Dn(e){return e.replace(/\.json$/,"")}async function bt(e){try{return await Te.access(e),!0}catch{return!1}}function Bn(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}var Js=new Set(["sumif","averageif","countif"]),Vn=new Set([">=","<=",">","<","="]);async function _r(e,t,n){let{config_name:r,model_names:a,metric_definitions:s,time_range:i,tariff_file_path:o,tariff_column_index:u}=t;if(!r)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!s||!Array.isArray(s)||s.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let d=r.replace(/\.json$/,""),{encodedMetrics:m,metadata:_}=zs(s);if(_.some(x=>x.function.toLowerCase()==="cost")&&(!o||u===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let f;if(o&&u!==void 0){let x=await qs(o,u,e);f=JSON.stringify(x)}let v=[],A=await Je(e,{config_name:d}),I=[],C=[];for(let x of a){let $=A.models.find(E=>E.name===x)?.csv_path;if(!$){let E=A.earlier_run_models?.find(Q=>Q.name===x),W=A.failed_models?.find(Q=>Q.name===x);if(W)C.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(mr(A,x));continue}let V=await pr.readFile($,"utf8");try{let E=Hs(V,x,r);if(_.some(ae=>ae.isCompliance)){let ae=Ct.join(Ct.dirname($),"fhs_compliance_report.json");if(!await fn(fr,ae))throw new Error("Completed FHS compliance report is unavailable");let T=JSON.parse(await pr.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 _.filter(l=>l.isCompliance)){let l=M.find(p=>p===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=Gs(E,m,_);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),i?JSON.stringify(i):void 0,f);if(!Q||typeof Q!="string")throw new Error(`WASM returned invalid result: ${typeof Q}`);let Se=JSON.parse(Q);if(!Array.isArray(Se))throw new Error(`WASM returned non-array result: ${typeof Se}`);Se.forEach((ae,T)=>{let M=_[T],[c=ae.name,l="sum"]=ae.name.split("|");v.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:v,total_models:a.length-I.length-C.length,total_metrics:v.length,...I.length?{earlier_run_models:I}:{},...C.length?{failed_models:C}:{},...A.latest_run_unknown?{latest_run_unknown:A.latest_run_unknown}:{},...A.warnings?{warnings:A.warnings}:{}}}function Hs(e,t,n){let r=e.split(`
15
+ `).filter(m=>m.trim());if(r.length<2)throw new Error("CSV must have at least headers and units rows");let a=(r[0]??"").split(",").map(m=>m.trim()),s=(r[1]??"").split(",").map(m=>m.trim()),i=[],o={},u=[],d=[];for(let m=1;m<a.length;m+=1){let _=a[m];_&&(o[_]=[],u.push(_),d.push(m<s.length&&s[m]||""))}for(let m=2;m<r.length;m+=1){let _=(r[m]??"").split(",").map(v=>v.trim());if(_.length===0||_.length===1&&!_[0])continue;let g=_[0];if(!g)continue;let f=Number.parseInt(g,10);if(!(Number.isNaN(f)||f<0)){i.push(f);for(let v=1;v<a.length&&v<_.length;v+=1){let A=a[v];if(!A||!o[A])continue;let I=_[v];if(I===void 0)continue;let C=Number.parseFloat(I);o[A].push(Number.isNaN(C)?0:C)}}}return{timestamps:i,columns:o,column_order:u,column_units:d,metadata:{model_name:t,config_name:n.replace(/\.json$/,""),total_points:i.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function Wn(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 Us(e){let t=(e.function||e.funcType||e.type||"sum").toString(),n=t.toLowerCase();if(n==="cost")return"cost";if(!Js.has(n))return n;let r=e.comparator||">=";if(!Vn.has(r))throw new Error(`Invalid comparator "${r}" for ${t}. Use one of ${Array.from(Vn).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 zs(e){let t=[],n=[];return e.forEach((r,a)=>{if(typeof r=="string"){let u=r.includes("|")?r:`${r}|sum`,[d=r,m="sum"]=u.split("|");t.push({name:u}),n.push({id:r,name:r,column:d,function:m,isCompliance:m.toLowerCase()==="compliance"});return}let s=r.column||(r.name?.includes("|")?r.name.split("|")[0]:r.name);if(!s)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(r)}`);let i=r.name?.includes("|")&&!r.function&&!r.funcType?r.name.split("|")[1]||"sum":Us(r),o=`${s}|${i}`;t.push({name:o}),n.push({id:r.id||r.metric_id||`${s}_${i}`,name:r.name||r.id||s,column:s,function:i,comparator:r.comparator,threshold:r.threshold,isCompliance:i.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:n}}async function qs(e,t,n){let r=Ct.isAbsolute(e)?e:Ct.resolve(n,e),s=(await pr.readFile(r,"utf8").catch(o=>{throw new Error(`Failed to read tariff file: ${r}. Error: ${o.message}`)})).split(`
16
+ `).filter(o=>o.trim());if(s.length===0)throw new Error(`Tariff file is empty: ${r}`);let i=[];for(let o=1;o<s.length;o+=1){let u=(s[o]??"").split(",").map(_=>_.trim().replace(/"/g,""));if(t>=u.length)throw new Error(`Column index ${t} not found in record ${o} with ${u.length} columns`);let d=u[t];if(d===void 0)throw new Error(`Column index ${t} is undefined in record ${o}`);let m=Number.parseFloat(d);if(Number.isNaN(m))throw new Error(`Could not parse '${d}' as number in row ${o+1}, column ${t+1}`);i.push(m)}if(i.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${i.length})`);return i}function Gs(e,t,n){let r=[];return t.forEach((a,s)=>{let i=a.name.split("|")[0];if(!i)throw new Error(`Invalid metric name format: ${a.name}`);n[s]?.isCompliance||e.columns[i]||r.push(i)}),r}import{spawn as Ks}from"child_process";import{existsSync as Xs,readFileSync as Zs}from"fs";import{createRequire as Ys}from"module";import He from"path";var St="@vulcan-energy/community-cli";function Jn(e=import.meta.url){let t=Ys(e),n;try{n=t.resolve(`${St}/package.json`)}catch{throw new Error(`${St} 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 a=JSON.parse(Zs(n,"utf8")).bin?.["vulcan-community"];if(!a)throw new Error(`${St} declares no vulcan-community bin.`);let s=He.join(He.dirname(n),a);if(!Xs(s))throw new Error(`${St} is not built (${s} missing); run its build first.`);return s}async function hr(e){let t=e.failOn??"critical",n=He.resolve(e.csvPath),r=await vr(e,["check",n,"--json",`--fail-on=${t}`]),a=br(r),s=gr(a)?a:void 0;return{ok:r.exitCode===0&&s!==void 0,command:"geometry validate",csv_path:n,fail_on:t,exit_code:r.exitCode,signal:r.signal,stdout:s===void 0?r.stdout:"",stderr:r.stderr,parsed:s,counts:gr(s?.counts)?s.counts:void 0,critical_issues:Array.isArray(s?.criticalIssues)?s.criticalIssues:void 0,warnings:Array.isArray(s?.warnings)?s.warnings:void 0,missing_elements:Array.isArray(s?.missingElements)?s.missingElements:void 0,error:s===void 0?Cr(r):void 0}}async function wr(e){let t=e.mode??"summary",n=He.resolve(e.csvPath),r=await vr(e,["thermal-bridges",n,Hn(t)]),a=t==="json"?br(r):void 0;return{ok:r.exitCode===0&&(t!=="json"||a!==void 0),command:"thermal-bridges auto",csv_path:n,mode:t,exit_code:r.exitCode,signal:r.signal,stdout:t==="json"&&a!==void 0?"":r.stdout,stderr:r.stderr,parsed:a,proposal_count:Array.isArray(a)?a.length:void 0,error:t==="json"&&a===void 0?Cr(r):void 0}}async function yr(e){let t=e.mode??"summary",n=e.includeAuto===!0,r=He.resolve(e.csvPath),a=["thermal-bridges",r,"--validate",...n?["--with-auto"]:[],Hn(t)],s=await vr(e,a),i=t==="json"?br(s):void 0,o=gr(i)?i:void 0;return{ok:s.exitCode===0&&(t!=="json"||o!==void 0),command:"thermal-bridges validate",csv_path:r,include_auto:n,mode:t,exit_code:s.exitCode,signal:s.signal,stdout:t==="json"&&o!==void 0?"":s.stdout,stderr:s.stderr,parsed:o,issue_count:typeof o?.issueCount=="number"?o.issueCount:void 0,thermal_bridge_linear_rows:typeof o?.thermalBridgeLinearRows=="number"?o.thermalBridgeLinearRows:void 0,error:t==="json"&&o===void 0?Cr(s):void 0}}async function vr(e,t){return(e.runner??Qs)(process.execPath,[e.communityCli??Jn(),...t],{cwd:He.resolve(e.workspace)})}function Hn(e){return`--${e}`}function br(e){try{return JSON.parse(e.stdout)}catch{return}}function Cr(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Qs=(e,t,n)=>new Promise((r,a)=>{let s=Ks(e,[...t],{cwd:n.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),i="",o="";s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),s.stdout.on("data",u=>{i+=u}),s.stderr.on("data",u=>{o+=u}),s.on("error",a),s.on("close",(u,d)=>{r({exitCode:u,signal:d,stdout:i,stderr:o})})});var at="https://usevulcan.app/join",ze="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 eo(e){return e.isFree?null:{reason:`Advanced scenarios need Vulcan Pro. ${ze}`,violations:e.violations}}function Un(e){return eo(hn(e))}var Ue=class extends Error{constructor(n,r){super(n.reason);this.requirement=n;this.accessDetail=r;this.name="ProRequiredError"}requirement;accessDetail};function Sr(e){return async t=>{let n=Un(t);if(!n)return;let r=await e();if(!r.pro)throw new Ue(n,r.detail)}}function kr(e){return e.model_names.length>1?{reason:"Comparing metrics across models needs Vulcan Pro."}:e.tariff_file_path||e.metric_definitions.some(Wn)?{reason:"Cost and tariff metrics need Vulcan Pro."}:null}function Er(e,t,n,r){return{status:"requires_pro",tool:e,reason:t.reason,...t.violations?{violations:t.violations}:{},access:n,upgrade_url:at,unlock:r}}import to from"fs/promises";import ro from"path";async function kt(e){let t=ro.join(e,"input","analytics","default_metrics.json"),n;try{n=JSON.parse(await to.readFile(t,"utf8"))}catch(i){if(i.code==="ENOENT")return{metrics:[],cost_metrics:[],unsupported:[]};throw new Error(`Could not read ${t}: ${i.message}`)}if(!Array.isArray(n))throw new Error(`${t} must hold a list of metric templates`);let r=[],a=[],s=[];for(let i of n){if(!i?.column||!i.funcType)continue;let o=i.label??`${i.funcType} of ${i.column}`;if(i.funcType.toLowerCase()==="cost"){a.push(o);continue}if(i.resultsKey&&i.resultsKey!=="results"){s.push({name:o,reason:`reads the ${i.resultsKey} results file`});continue}if(i.normalization){s.push({name:o,reason:"is normalised (e.g. per floor area)"});continue}r.push({...i.id?{id:i.id}:{},name:o,column:i.column,function:i.funcType,...i.comparator?{comparator:i.comparator}:{},...typeof i.threshold=="number"?{threshold:i.threshold}:{}})}return{metrics:r,cost_metrics:a,unsupported:s}}import{createHash as no,randomUUID as ao}from"crypto";import ye from"fs/promises";import so from"os";import Me from"path";function Et(e=process.env){return(e.VULCAN_SITE_URL||"https://usevulcan.app").replace(/\/+$/,"")}function Pr(e,t){let n=Number(e);return Number.isFinite(n)&&n>0?n:t}async function qn(e,t,n,r=2e4){let a=n.siteUrl??Et(n.env),s;try{s=await(n.fetch??fetch)(`${a}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(r)})}catch(i){let o=i.cause?.code;throw new Error(`Could not reach Vulcan at ${a}${o?` (${o})`:""}; check the internet connection and try again.`)}return{status:s.status,body:await s.json().catch(()=>({}))}}function xr(e,t){let n=t.env??process.env,r=n.VULCAN_STATE_DIR||Me.join(so.homedir(),".vulcan","sign-in"),a=t.siteUrl??Et(n);return Me.join(r,`${no("sha256").update(`${a}
17
+ ${e}`).digest("hex").slice(0,24)}.json`)}var oo=/^[A-Za-z0-9_-]{43}$/,io=/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;function Gn(e,t,n){let r=`${t.siteUrl??Et(t.env)}/connect`;return!e||typeof e.deviceCode!="string"||!oo.test(e.deviceCode)||typeof e.userCode!="string"||!io.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 Rr(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 Pt(e,t={}){let n=xr(e,t);try{await ye.mkdir(Me.dirname(n),{recursive:!0,mode:448}),await ye.chmod(Me.dirname(n),448);let r=await ye.lstat(n).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(!r)return null;let a=null;r.isFile()&&(a=await ye.readFile(n,"utf8").then(i=>JSON.parse(i),()=>null));let s=Gn(a,t,(t.now??Date.now)());return s||await ye.rm(n,{force:!0}),s}catch(r){throw Rr(n,r)}}async function xt(e,t,n={}){let r=xr(e,n),a=Me.join(Me.dirname(r),`.${ao()}.tmp`);try{await ye.mkdir(Me.dirname(r),{recursive:!0,mode:448}),await ye.chmod(Me.dirname(r),448),await ye.writeFile(a,JSON.stringify(t),{mode:384,flag:"wx"});try{return await ye.link(a,r),t}catch(s){if(s.code!=="EEXIST")throw s}}catch(s){throw Rr(r,s)}finally{await ye.rm(a,{force:!0}).catch(()=>{})}return await Pt(e,n)??xt(e,t,n)}async function $e(e,t={}){let n=xr(e,t);await ye.rm(n,{force:!0}).catch(r=>{throw Rr(n,r)})}async function Ar(e,t={}){let{status:n,body:r}=await qn("/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 a=(t.now??Date.now)(),s=Gn({deviceCode:r.device_code,userCode:r.user_code,url:r.verification_uri_complete,expiresAt:a+Math.min(Pr(r.expires_in,600),3600)*1e3,intervalMs:Math.max(1,Pr(r.interval,5))*1e3},t,a);if(!s)throw new Error("Vulcan answered with a sign-in this tool does not recognise; update the tool and try again.");return s}var zn=2e4;async function jr(e,t,n={}){let r=n.now??Date.now,a=n.sleep??(u=>new Promise(d=>setTimeout(d,u))),s=r()+t,i=e.intervalMs,o=null;for(;;){if(r()>=e.expiresAt)return{status:"expired"};try{let{status:u,body:d}=await qn("/api/agent/device/token",{device_code:e.deviceCode},n,zn);if(u===200&&typeof d.license_token=="string")return{status:"signed_in",token:d.license_token,expiresAt:String(d.expires_at??"")};if(u===403&&typeof d.code=="string")return{status:d.code==="not_entitled"?"free_account":"pro_ended"};if(d.error==="access_denied")return{status:"denied"};if(d.error==="expired_token"||d.error==="invalid_grant"||d.error==="invalid_request")return{status:"expired"};if(d.error==="slow_down")i=Math.min(Math.max(i+5e3,Pr(d.interval,0)*1e3),6e4);else if(u>=500)o=typeof d.error=="string"&&d.error!=="server_error"?d.error:`Vulcan could not finish sign-in (HTTP ${u}); it will retry.`;else{if(d.error!=="authorization_pending")return{status:"error",message:typeof d.error=="string"?d.error:`Vulcan sign-in failed (HTTP ${u}).`};o=null}}catch(u){o=u.message}if(r()+i>=e.expiresAt)return{status:"expired"};if(r()+i+zn>s)return o?{status:"error",message:o}:{status:"pending"};await a(i)}}async function Kn(e,t={}){return cr(e.workspace,t)}async function Xn(e,t){return lr(e.workspace,t)}import Zn from"fs";import Ce from"path";import{fileURLToPath as co}from"url";var lo=Ce.dirname(co(import.meta.url));function uo(){let e=[],t=lo;for(let s=0;s<6;s+=1){e.push(t);let i=Ce.dirname(t);if(i===t)break;t=i}e.push(process.cwd());let n=[];for(let s of e)n.push({directory:Ce.join(s,"wasm"),context:"helper-root"},{directory:Ce.join(s,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:Ce.join(s,"web","dist","wasm"),context:"rust-hem-runner"},{directory:Ce.join(s,"web","dist"),context:"rust-hem-runner"},{directory:Ce.join(s,"web","pkg"),context:"rust-hem-runner"},{directory:Ce.join(s,"apps","web","public","launch"),context:"vulcan-website"});let r=[],a=new Set;for(let s of n){let i=Ce.join(s.directory,"wasm_wrapper.js");if(a.has(i))continue;a.add(i),r.push(i);let o=Ce.join(s.directory,"wasm_wrapper_bg.wasm");if(Zn.existsSync(i)&&Zn.existsSync(o))return s}throw new Error(`WASM files not found. Tried:
18
+ `+r.map(s=>` - ${s}`).join(`
19
19
  `)+`
20
- Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var xt=null;async function He(){if(xt)return xt;try{let{directory:e,context:t}=oo();return console.error(`[WASM] Loading from ${t}: ${e}`),xt=await _t(e),console.error(`[WASM] Initialized successfully from ${t}`),xt}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function Gn(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 or(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 io}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_${io()}`;return er(r,{...t,job_id:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{gate:n,processBatchConfig:async(...i)=>{let o=await He().catch(d=>{throw new Error(`WASM initialization failed: ${d.message}`)});if(!o.processBatchConfig)throw new Error("WASM process_batch_config function not available");return ht(r),o.processBatchConfig(...i)}})}async function At(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 fr(e.workspace,t,{calculateMetricsFromParsedData:n.calculateMetricsFromParsedData})}async function Tr(e,t){return cr(e.workspace,t)}async function Rt(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 co}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 lo(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(o){if(o.code!=="ENOENT")throw new Error(`Could not update ${r}: ${o.message}. Fix or remove it, then sign in again.`)}let i=`${r}.${co()}.tmp`;try{await Be.writeFile(i,`${JSON.stringify({...a,license_token:t},null,2)}
21
- `,{mode:384}),await Be.rename(i,r)}catch(o){throw await Be.rm(i,{force:!0}),o}return n}async function aa(e,t,n){let s=(ta.get(e)??Promise.resolve()).catch(()=>{}).then(()=>uo(e,t,n));return ta.set(e,s),s}async function uo(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 Et(r);return a?await fo(e,t,n,r,a):ra(await Pt(r,await Pr("Vulcan MCP helper")))}catch(s){return{status:"error",message:s.message}}}async function fo(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 i=e.license_token;e.license_token=a.token;let o=await n();if(!o.pro)return e.license_token=i,{status:"error",message:`Signed in, but the access Vulcan issued does not unlock this helper's Pro tools: ${o.detail}`};let d;try{d=await lo(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:at};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:at};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 jt=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."),st=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")},mo=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 po=[{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.
20
+ Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var Rt=null;async function qe(){if(Rt)return Rt;try{let{directory:e,context:t}=uo();return console.error(`[WASM] Loading from ${t}: ${e}`),Rt=await _t(e),console.error(`[WASM] Initialized successfully from ${t}`),Rt}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function Yn(e,t){let n;try{n=await qe()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return ur(e.workspace,t,{validateSnippetJs:n.validateSnippetJs})}async function Tr(e,t,n){return nr(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{},{gate:n})}import{randomUUID as mo}from"crypto";async function Mr(e,t,n){let{workspace:r}=e,{config_name:a}=t;if(!a)throw new Error("config_name is required");let s=t.job_id||`mcp_${mo()}`;return ar(r,{...t,job_id:s,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{gate:n,processBatchConfig:async(...i)=>{let o=await qe().catch(u=>{throw new Error(`WASM initialization failed: ${u.message}`)});if(!o.processBatchConfig)throw new Error("WASM process_batch_config function not available");return ht(r),o.processBatchConfig(...i)}})}async function At(e,t={}){return sr(e.workspace,t)}async function $r(e,t){let n;try{n=await qe()}catch(r){let a=r;throw new Error(`WASM initialization failed: ${a.message}`)}if(!n.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return _r(e.workspace,t,{calculateMetricsFromParsedData:n.calculateMetricsFromParsedData})}async function Or(e,t){return dr(e.workspace,t)}async function jt(e,t){return Je(e.workspace,t)}async function Qn(e,t){let{workspace:n}=e,{csv_path:r,output_path:a}=t;if(!r)throw new Error("csv_path is required");return ir({workspace:n,csvPath:r,outputPath:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import ea from"path";async function ta(e,t){return hr({csvPath:ea.isAbsolute(t.csv_path)?t.csv_path:ea.join(e.workspace,t.csv_path),failOn:t.fail_on,workspace:e.workspace})}import ra from"path";async function na(e,t){return wr({csvPath:ra.isAbsolute(t.csv_path)?t.csv_path:ra.join(e.workspace,t.csv_path),mode:t.mode,workspace:e.workspace})}import aa from"path";async function sa(e,t){return yr({csvPath:aa.isAbsolute(t.csv_path)?t.csv_path:aa.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,workspace:e.workspace})}import{randomUUID as fo}from"crypto";import Ve from"fs/promises";import Fr from"path";var oa=new WeakMap;function ia(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 ca(e){return e.configPath??Fr.join(e.workspace,"vulcan-mcp-config.json")}async function po(e,t){let n=ca(e),r=n,a=await Ve.realpath(n).catch(()=>null);a&&(await Ve.lstat(n)).isSymbolicLink()&&(Fr.basename(a)==="vulcan-mcp-config.json"?r=a:await Ve.rm(n));let s={};try{s=JSON.parse(await Ve.readFile(r,"utf8"))}catch(o){if(o.code!=="ENOENT")throw new Error(`Could not update ${r}: ${o.message}. Fix or remove it, then sign in again.`)}let i=`${r}.${fo()}.tmp`;try{await Ve.writeFile(i,`${JSON.stringify({...s,license_token:t},null,2)}
21
+ `,{mode:384}),await Ve.rename(i,r)}catch(o){throw await Ve.rm(i,{force:!0}),o}return n}async function la(e,t,n){let a=(oa.get(e)??Promise.resolve()).catch(()=>{}).then(()=>_o(e,t,n));return oa.set(e,a),a}async function _o(e,t,n){let r=`mcp:${Fr.resolve(ca(e))}`;try{let a=await n();if(a.pro)return await $e(r).catch(()=>{}),{status:"signed_in",detail:a.detail};let s=await Pt(r);return s?await go(e,t,n,r,s):ia(await xt(r,await Ar("Vulcan MCP helper")))}catch(a){return{status:"error",message:a.message}}}async function go(e,t,n,r,a){let s=await jr(a,(t.wait_seconds??40)*1e3);switch(s.status){case"pending":return ia(a);case"signed_in":{await $e(r);let i=e.license_token;e.license_token=s.token;let o=await n();if(!o.pro)return e.license_token=i,{status:"error",message:`Signed in, but the access Vulcan issued does not unlock this helper's Pro tools: ${o.detail}`};let u;try{u=await po(e,s.token)}catch(d){return{status:"signed_in",detail:`Vulcan Pro tools are unlocked for this session, but the token could not be saved: ${d.message} Call vulcan_sign_in again after a restart.`,expires_at:s.expiresAt}}return e.configPath=u,{status:"signed_in",detail:"Vulcan Pro tools are unlocked.",expires_at:s.expiresAt,config_path:u,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 $e(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:at};case"pro_ended":return await $e(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:at};case"denied":return await $e(r),{status:"denied",message:"The user declined the sign-in. Call vulcan_sign_in to start again."};case"expired":return await $e(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:s.message}}}var Tt=S.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."),st=S.string().describe("Batch configuration name (with or without .json)"),Nr={target_manifest:S.string().optional().describe("Optional offline override: local HEM target bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:S.string().optional().describe("Expected SHA-256 of target_manifest; required with it")},ho=S.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]]}})),S.record(S.string(),S.array(S.string())));var wo=[{name:"vulcan_sign_in",title:"Sign in to Vulcan",description:`Sign this helper in to the user's Vulcan account, to unlock the Pro tools their account includes. Free tools need no sign-in.
22
22
 
23
- 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.
23
+ Two steps. The first call returns sign_in_url and a code: show both to the user in your reply straight away, before any other tool call, so they can open the link, sign in and approve. Then call vulcan_sign_in again: it waits up to wait_seconds for their approval and saves the access token in the workspace's vulcan-mcp-config.json. The code survives a restart of this helper. Call it again to renew when Pro tools report the access has expired.`,input:{wait_seconds:S.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)=>la(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.
24
24
 
25
25
  Use this before creating batch configurations. Example: category="base_json" lists the base models.
26
- 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 ot.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.
26
+ See also: vulcan_view_parameter.`,input:{category:S.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 Kn(e,t),geometry_csvs:await ot.readdir(Oe.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.
27
27
 
28
- 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
+ Example: category="heat_source_wet", parameter_id="hp". See also: vulcan_list_parameters.`,input:{category:S.string().describe('Parameter category (e.g. "heat_source_wet", "controls", "base_json")'),parameter_id:S.string().describe("Parameter ID (filename without .json)")},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Xn(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.
29
29
 
30
- 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)=>Gn(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.
30
+ See also: vulcan_view_parameter to read an existing snippet first.`,input:{category:S.string().describe('Parameter category (e.g. "heat_source_wet", "controls")'),parameter_id:S.string().describe("Parameter ID (filename without .json)"),content:S.record(S.string(),S.unknown()).describe("Parameter JSON object"),markdown_content:S.string().optional().describe("Optional markdown documentation for the parameter")},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t)=>Yn(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
31
 
32
32
  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.
33
33
 
34
- ${Ue}
35
- 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:mo.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.
34
+ ${ze}
35
+ See also: vulcan_list_parameters, vulcan_run_batch.`,input:{config_name:S.string().describe("Configuration name (saved as input/batch_configs/{config_name}.json)"),base_model:S.string().describe("Base model filename (without .json)"),weather_file:S.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:S.string().optional().describe('Model wrapper (e.g. "fhs_compliance", "fhs_assumptions", "passthrough"; a HEM:EPC model takes "epc_quick" or "epc_full")'),parameters:ho.describe("Object mapping category to an array of parameter IDs"),...Nr},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t,n)=>Tr(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.
36
36
 
37
37
  Unpinned batches run on the bundled engine. A batch from a pinned model runs its saved HEM target in Google Chrome (install it separately); the first use downloads and verifies the target. Long Python runs are expected; read progress with vulcan_get_batch_status.
38
38
 
39
- ${Ue}
40
- See also: vulcan_create_batch_config, vulcan_get_batch_status.`,input:{config_name:st,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.
39
+ ${ze}
40
+ See also: vulcan_create_batch_config, vulcan_get_batch_status.`,input:{config_name:st,job_id:S.string().optional().describe("Optional job ID (defaults to mcp_{uuid})"),...Nr},plan:"free",readOnly:!1,workspaceLayout:!0,run:(e,t,n)=>Mr(e,t,n)},{name:"vulcan_get_batch_status",title:"Get batch status",description:`Status, progress, pass/fail counts and warnings for a batch run.
41
41
 
42
- Status is queued, running, completed or error; not_run when the config has no recorded run; unknown (with the reason) when the files cannot tell. Give job_id (from vulcan_run_batch) or config_name (reads that config's latest run, from the app or this helper).`,input:{job_id: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 At(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.
42
+ Status is queued, running, completed or error; not_run when the config has no recorded run; unknown (with the reason) when the files cannot tell. Give job_id (from vulcan_run_batch) or config_name (reads that config's latest run, from the app or this helper).`,input:{job_id:S.string().optional().describe("Job ID returned by vulcan_run_batch"),config_name:S.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 At(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.
43
43
 
44
44
  Cost metrics need tariff_file_path and tariff_column_index (a CSV with 17,520 half-hourly rows). Models with results only from an earlier run, or whose last run failed, are listed apart (earlier_run_models, failed_models); read the warnings before presenting results as current.
45
45
 
46
46
  Free: metrics for one model without cost or tariffs. Comparing models and cost metrics need Vulcan Pro.
47
- See also: vulcan_list_batch_models, vulcan_list_csv_columns.`,input:{config_name:st,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:st,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:st},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Rt(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.
47
+ See also: vulcan_list_batch_models, vulcan_list_csv_columns.`,input:{config_name:st,model_names:S.array(S.string()).describe("Model names to calculate metrics for (from vulcan_list_batch_models)"),metric_definitions:S.array(S.object({id:S.string().optional(),name:S.string().optional(),column:S.string().optional().describe("Result column name (from vulcan_list_csv_columns)"),function:S.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:S.string().optional(),threshold:S.number().optional()})).describe("Metric definitions"),time_range:S.object({start:S.number().optional(),end:S.number().optional()}).optional().describe("Optional timestep range"),tariff_file_path:S.string().optional().describe("Tariff CSV path (relative to the workspace, or absolute). Required for cost metrics."),tariff_column_index:S.number().optional().describe("Zero-based tariff column index. Required for cost metrics.")},plan:async(e,t)=>kr(t),readOnly:!0,workspaceLayout:!0,run:(e,t)=>$r(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:st,model_name:S.string().describe('Model name (e.g. "scenario_1_0")')},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>Or(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:st},plan:"free",readOnly:!0,workspaceLayout:!0,run:(e,t)=>jt(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.
48
48
 
49
- 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:jt,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. ${nt}`),defaults_path:k.unknown().optional().describe(`Removed. ${nt}`)},plan:"free",readOnly:!1,run:async(e,{schema_path:t,defaults_path:n,...r})=>{if(t!==void 0||n!==void 0)throw new Error(nt);let s=await zn(e,{...r,csv_path:await Tt(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:jt,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 Tt(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:jt,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 Tt(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:jt,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 Tt(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.
49
+ 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:Tt,output_path:S.string().optional().describe("Output JSON path (default input/batch_parameters/base_json/{csv name}.json)"),...Nr,schema_path:S.unknown().optional().describe(`Removed. ${nt}`),defaults_path:S.unknown().optional().describe(`Removed. ${nt}`)},plan:"free",readOnly:!1,run:async(e,{schema_path:t,defaults_path:n,...r})=>{if(t!==void 0||n!==void 0)throw new Error(nt);let a=await Qn(e,{...r,csv_path:await Mt(e,r.csv_path)});if(!a.ok)throw new Error(a.error??"Conversion failed");return a}},{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:Tt,fail_on:S.enum(["none","critical","warning"]).optional().describe("Which findings fail the check (default critical)")},plan:"free",readOnly:!0,run:async(e,t)=>Ir(await ta(e,{...t,csv_path:await Mt(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:Tt,mode:S.enum(["summary","json","csv-section"]).optional().describe("Output mode (default summary)")},plan:"free",readOnly:!0,run:async(e,t)=>Ir(await na(e,{...t,csv_path:await Mt(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:Tt,include_auto:S.boolean().optional().describe("Also validate the automatic thermal-bridge proposals"),mode:S.enum(["summary","json"]).optional().describe("Output mode (default summary)")},plan:"free",readOnly:!0,run:async(e,t)=>Ir(await sa(e,{...t,csv_path:await Mt(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.
50
50
 
51
51
  Free runs use a model saved by the current Vulcan app (pinned to a HEM version), with its reference weather; Google Chrome is needed and the first use downloads the target. If the run outlasts wait_seconds, the result gives config_name: read it later with vulcan_get_batch_status and vulcan_calculate_metrics.
52
52
 
53
- ${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)}`,i;try{i=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(!i.success)return{config_name:a,status:"not_created",...i};let o=await Rr(e,{config_name:a},n);if(o.status!=="started")return{config_name:a,...o};let d=Date.now()+(t.wait_seconds??45)*1e3,u=await At(e,{config_name:a});for(;(u.status==="queued"||u.status==="running")&&Date.now()<d;)await new Promise($=>setTimeout($,2e3)),u=await At(e,{config_name:a});if(u.status!=="completed")return{config_name:a,job_id:o.job_id,status:u.status,progress:u.progress,error:u.error,next:`Check again with vulcan_get_batch_status (config_name "${a}"), then vulcan_calculate_metrics.`};let f=await Rt(e,{config_name:a}),p=f.models[0],g=p?.name,_=await St(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 _o(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 ot.access(Me.join(e.workspace,b)).then(()=>!0,()=>!1);return{config_name:a,job_id:o.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"?ia[V]??null:R.get(V)??null})),...C.unavailable.length||_.unsupported.length?{unavailable:[...C.unavailable,..._.unsupported]}:{},...g?{}:{note:f.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:st},plan:"pro",readOnly:!0,workspaceLayout:!0,run:async(e,t)=>{let n=await Rt(e,t),r=await St(e.workspace),s=n.models.length>0?await sa(e,t.config_name,n.models.map(o=>o.name),r.metrics):{metrics:[],unavailable:[]},a=r.metrics.map((o,d)=>({key:o.id??`metric_${d+1}`,name:o.name})),i=n.models.map(o=>({model:o.name,values:Object.fromEntries(a.map(d=>[d.key,s.metrics.find(u=>u.model_name===o.name&&(u.id===d.key||u.name===d.name))?.value??null]))}));return{config_name:t.config_name,columns:a,rows:i,...s.unavailable.length||r.unsupported.length?{unavailable:[...s.unavailable,...r.unsupported]}:{},...n.failed_models?.length?{failed_models:n.failed_models}:{},...n.earlier_run_models?.length?{earlier_run_models:n.earlier_run_models}:{},...n.latest_run_unknown?{latest_run_unknown:n.latest_run_unknown}:{},...r.cost_metrics.length?{cost_metrics_not_run:r.cost_metrics,cost_note:"Cost needs a tariff: use vulcan_calculate_metrics."}:{}}}}],ia={dwelling_emission_rate:"kgCO2e/m2/yr",dwelling_primary_energy_rate:"kWh/m2/yr",dwelling_fabric_energy_efficiency:"kWh/m2/yr"};async function _o(e){let t;try{t=JSON.parse(await ot.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:ia[`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 Tt(e,t){let n=await ot.readdir(Me.join(e.workspace,"input","base_models")).then(i=>i.filter(o=>o.toLowerCase().endsWith(".csv")).sort().map(o=>`input/base_models/${o}`)).catch(()=>[]),r=n.length?`Geometry CSVs in this workspace: ${n.join(", ")}.`:"This workspace has no geometry CSVs in input/base_models.";if(t===void 0){if(n.length===1)return n[0];throw new Error(`Give csv_path. ${r}`)}let s=Me.isAbsolute(t)?t:Me.join(e.workspace,t);if(!(await ot.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 i of r)try{let o=await jr(e,{config_name:t,model_names:n,metric_definitions:[i]});s.push(...o.metrics)}catch(o){a.push({name:i.name??i.column??"metric",reason:o.message})}return{metrics:s,unavailable:a}}function 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 oa(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 po)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 i=await n(t);if(!i.pro)return oa(r.name,a,i)}}try{return ca(await r.run(t,s,vr(()=>n(t)),()=>n(t)))}catch(a){if(!(a instanceof Je))throw a;return oa(r.name,a.requirement,{pro:!1,detail:a.accessDetail})}})}var qe=Lr.version,vo=`Vulcan tools for Home Energy Model (HEM) workspaces. Everything runs on this machine; models and results are not sent to Vulcan.
53
+ ${ze} Cost metrics need Vulcan Pro and a tariff (vulcan_calculate_metrics).`,input:{base_model:S.string().describe("Base model filename in input/batch_parameters/base_json (without .json)"),wrapper:S.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:S.string().optional().describe("EPW filename; a weather choice needs Vulcan Pro"),wait_seconds:S.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 Kt(e.workspace,t.base_model),a=new Date().toISOString().replace(/\D/g,"").slice(0,14),s=`agent_run_${t.base_model}_${a}_${Math.random().toString(36).slice(2,6)}`,i;try{i=await Tr(e,{config_name:s,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(!i.success)return{config_name:s,status:"not_created",...i};let o=await Mr(e,{config_name:s},n);if(o.status!=="started")return{config_name:s,...o};let u=Date.now()+(t.wait_seconds??45)*1e3,d=await At(e,{config_name:s});for(;(d.status==="queued"||d.status==="running")&&Date.now()<u;)await new Promise($=>setTimeout($,2e3)),d=await At(e,{config_name:s});if(d.status!=="completed")return{config_name:s,job_id:o.job_id,status:d.status,progress:d.progress,error:d.error,next:`Check again with vulcan_get_batch_status (config_name "${s}"), then vulcan_calculate_metrics.`};let m=await jt(e,{config_name:s}),_=m.models[0],g=_?.name,f=await kt(e.workspace),v=g?await ua(e,s,[g],f.metrics):{metrics:[],unavailable:[]},A=g?new Map((await Or(e,{config_name:s,model_name:g}).catch(()=>({columns:[]}))).columns.map($=>[$.name,$.unit])):new Map,I=_?.csv_path?await yo(Oe.join(Oe.dirname(Oe.resolve(e.workspace,_.csv_path)),"fhs_compliance_report.json")):void 0,C=`input/base_models/${t.base_model}.csv`,x=await ot.access(Oe.join(e.workspace,C)).then(()=>!0,()=>!1);return{config_name:s,job_id:o.job_id,status:"completed",model:g,...x?{source:`${C} (the model's pinned source; edit this CSV, not base_json/${t.base_model}.json, to change what runs)`}:{},...I?{fhs_compliance:I}:{},metrics:v.metrics.map(({name:$,column:V,function:E,value:W})=>({name:$,column:V,function:E,value:W,unit:E==="compliance"?ma[V]??null:A.get(V)??null})),...v.unavailable.length||f.unsupported.length?{unavailable:[...v.unavailable,...f.unsupported]}:{},...g?{}:{note:m.latest_run_unknown??"The run completed but listed no current model; see vulcan_list_batch_models."},...f.metrics.length===0?{metrics_note:"This workspace has no default metric templates; list columns with vulcan_list_csv_columns and use vulcan_calculate_metrics."}:{},...f.cost_metrics.length>0?{cost_metrics_not_run:f.cost_metrics,cost_note:"Cost metrics need a tariff and Vulcan Pro."}:{}}}},{name:"vulcan_size_heating",title:"Size the heating",description:`Check if the heat pump or boiler and the radiators of one model are big enough, with the same verdicts and numbers as the Sizing block in the Vulcan app. The check uses the design heat loss of each zone at the coldest hour of the pinned Bedford weather. Nothing is sent to Vulcan's servers; the first use downloads the model's HEM target.
54
+
55
+ Returns status "sized" with each heat source and heating system, or status "unavailable" with the reason (for example, a HEM version that cannot calculate the design heat loss).`,input:{base_model:S.string().describe("Base model filename in input/batch_parameters/base_json (without .json)")},plan:"free",readOnly:!0,workspaceLayout:!0,run:async(e,t)=>rr({workspace:e.workspace,baseModel:t.base_model})},{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:st},plan:"pro",readOnly:!0,workspaceLayout:!0,run:async(e,t)=>{let n=await jt(e,t),r=await kt(e.workspace),a=n.models.length>0?await ua(e,t.config_name,n.models.map(o=>o.name),r.metrics):{metrics:[],unavailable:[]},s=r.metrics.map((o,u)=>({key:o.id??`metric_${u+1}`,name:o.name})),i=n.models.map(o=>({model:o.name,values:Object.fromEntries(s.map(u=>[u.key,a.metrics.find(d=>d.model_name===o.name&&(d.id===u.key||d.name===u.name))?.value??null]))}));return{config_name:t.config_name,columns:s,rows:i,...a.unavailable.length||r.unsupported.length?{unavailable:[...a.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."}:{}}}}],ma={dwelling_emission_rate:"kgCO2e/m2/yr",dwelling_primary_energy_rate:"kWh/m2/yr",dwelling_fabric_energy_efficiency:"kWh/m2/yr"};async function yo(e){let t;try{t=JSON.parse(await ot.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:ma[`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 Mt(e,t){let n=await ot.readdir(Oe.join(e.workspace,"input","base_models")).then(i=>i.filter(o=>o.toLowerCase().endsWith(".csv")).sort().map(o=>`input/base_models/${o}`)).catch(()=>[]),r=n.length?`Geometry CSVs in this workspace: ${n.join(", ")}.`:"This workspace has no geometry CSVs in input/base_models.";if(t===void 0){if(n.length===1)return n[0];throw new Error(`Give csv_path. ${r}`)}let a=Oe.isAbsolute(t)?t:Oe.join(e.workspace,t);if(!(await ot.stat(a).catch(()=>{}))?.isFile())throw new Error(`No geometry CSV at ${t}. ${r}`);return t}function Ir(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 ua(e,t,n,r){let a=[],s=[];for(let i of r)try{let o=await $r(e,{config_name:t,model_names:n,metric_definitions:[i]});a.push(...o.metrics)}catch(o){s.push({name:i.name??i.column??"metric",reason:o.message})}return{metrics:a,unavailable:s}}function fa(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 da(e,t,n){return fa(Er(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 pa(e,t,n=zr){for(let r of wo)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:r.input,annotations:{title:r.title,readOnlyHint:r.readOnly,openWorldHint:!1}},async a=>{if(r.workspaceLayout&&await or(t.workspace),r.plan!=="free"){let s=r.plan==="pro"?{reason:"This tool needs Vulcan Pro."}:await r.plan(t,a);if(s){let i=await n(t);if(!i.pro)return da(r.name,s,i)}}try{return fa(await r.run(t,a,Sr(()=>n(t)),()=>n(t)))}catch(s){if(!(s instanceof Ue))throw s;return da(r.name,s.requirement,{pro:!1,detail:s.accessDetail})}})}var Ge=Vr.version,ko=`Vulcan tools for Home Energy Model (HEM) workspaces. Everything runs on this machine; models and results are not sent to Vulcan.
54
56
  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.
55
- Vulcan Pro (https://usevulcan.app/join) adds scenario batches, weather and parameter variations, model comparison and cost metrics. A Pro tool called without Pro returns status "requires_pro" with what is missing; tell the user rather than retrying.`;function fa(e){let t=new ho({name:"vulcan-mcp-helper",version:qe},{instructions:vo});return la(t,e),bo(t),t}function bo(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 ma(e){console.error(`[MCP Helper] v${qe}; workspace: ${e.workspace}`),console.error(e.configPath?`[MCP Helper] Config: ${e.configPath}`:"[MCP Helper] No config file: Free tools only.")}async function pa(e={}){let t=await Bt(e);ma(t),await fa(t).connect(new wo)}async function _a(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.");ma(r);let a=ua(),i=go({origin:!0,methods:["GET","OPTIONS"],credentials:!1});a.post("/mcp",ua.raw({type:"application/json",limit:"10mb"}),async(o,d)=>{try{await Ur(o.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(o.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 f=fa(r),p=new yo({sessionIdGenerator:void 0,enableJsonResponse:!0});d.on("close",()=>{p.close(),f.close()});try{await f.connect(p),await p.handleRequest(o,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",i,(o,d)=>{d.json({status:"running",port:n,version:qe,name:"vulcan-mcp-helper"})}),a.get("/helper/status",i,(o,d)=>{d.json({running:!0,port:n,version:qe,mcpReady:!0})}),a.listen(n,"127.0.0.1",()=>{console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${n}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${n}/health`)})}Number(process.versions.node.split(".")[0])<20&&(console.error(`vulcan-mcp-helper requires Node >=20.0.0; current Node is ${process.versions.node}.`),process.exit(1));var So=`Usage: vulcan-mcp-helper --stdio [--workspace <dir>] [--config <path>]
57
+ 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 ha(e){let t=new bo({name:"vulcan-mcp-helper",version:Ge},{instructions:ko});return pa(t,e),Eo(t),t}function Eo(e){let t=e.server,n=t._oninitialize?.bind(e.server);if(!n)return;t.removeRequestHandler("initialize");let r=ga.extend({params:ga.shape.params.partial().optional().transform((a={})=>({protocolVersion:a.protocolVersion||"2024-11-05",capabilities:a.capabilities||{},clientInfo:a.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});t.setRequestHandler(r,a=>n(a))}function wa(e){console.error(`[MCP Helper] v${Ge}; workspace: ${e.workspace}`),console.error(e.configPath?`[MCP Helper] Config: ${e.configPath}`:"[MCP Helper] No config file: Free tools only.")}async function ya(e={}){let t=await Dt(e);wa(t),await ha(t).connect(new Co)}async function va(e={},t){let n=t||parseInt(process.env.HELPER_PORT||"5000",10),r=await Dt(e),a=r.license_token;if(!a)throw new Error("HTTP mode needs a Vulcan Pro access config (license_token), used as its Bearer credential. Run with --stdio for Free use.");wa(r);let s=_a(),i=vo({origin:!0,methods:["GET","OPTIONS"],credentials:!1});s.post("/mcp",_a.raw({type:"application/json",limit:"10mb"}),async(o,u)=>{try{await qr(o.headers.authorization,a)}catch(g){let f=g.message;console.error(`[MCP Helper] Rejected MCP request: ${f}`),u.set("WWW-Authenticate",'Bearer realm="vulcan-mcp"').status(401).json({jsonrpc:"2.0",error:{code:-32001,message:`Unauthorized: ${f}`},id:null});return}let d;try{d=JSON.parse(o.body.toString("utf-8"))}catch(g){u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:g.message},id:null});return}let m=ha(r),_=new So({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{_.close(),m.close()});try{await m.connect(_),await _.handleRequest(o,u,d)}catch(g){let f=g;console.error(`[MCP Helper] MCP request failed: ${f.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:f.message},id:d?.id??null})}}),s.get("/health",i,(o,u)=>{u.json({status:"running",port:n,version:Ge,name:"vulcan-mcp-helper"})}),s.get("/helper/status",i,(o,u)=>{u.json({running:!0,port:n,version:Ge,mcpReady:!0})}),s.listen(n,"127.0.0.1",()=>{console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${n}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${n}/health`)})}Number(process.versions.node.split(".")[0])<20&&(console.error(`vulcan-mcp-helper requires Node >=20.0.0; current Node is ${process.versions.node}.`),process.exit(1));var xo=`Usage: vulcan-mcp-helper --stdio [--workspace <dir>] [--config <path>]
56
58
  vulcan-mcp-helper [--config <path>] [--port <port>]
57
59
 
58
60
  Vulcan tools for Home Energy Model workspaces. Everything runs on this machine.
@@ -67,7 +69,7 @@ Vulcan tools for Home Energy Model workspaces. Everything runs on this machine.
67
69
  --help, -h Show this help.
68
70
 
69
71
  Claude Code: claude mcp add vulcan -- npx -y @vulcan-energy/mcp-helper --stdio --workspace /path/to/workspace
70
- Setup guide: https://usevulcan.app/docs/vulcan-mcp-server-guide`;async function ko(){let{values:e}=Co({options:{stdio:{type:"boolean"},workspace:{type:"string"},config:{type:"string"},port:{type:"string"},version:{type:"boolean",short:"v"},help:{type:"boolean",short:"h"}}});if(e.help){console.log(So);return}if(e.version){console.log(qe);return}let t={configPath:e.config,workspace:e.workspace};if(e.stdio){if(e.port)throw new Error("--port applies to HTTP mode, not --stdio");await pa(t);return}let n;if(e.port!==void 0&&(n=Number.parseInt(e.port,10),!Number.isInteger(n)||n<1||n>65535))throw new Error(`Invalid port: ${e.port}`);await _a(t,n)}ko().catch(e=>{console.error(`Error: ${e.message}`),process.exit(1)});
72
+ Setup guide: https://usevulcan.app/docs/vulcan-mcp-server-guide`;async function Ro(){let{values:e}=Po({options:{stdio:{type:"boolean"},workspace:{type:"string"},config:{type:"string"},port:{type:"string"},version:{type:"boolean",short:"v"},help:{type:"boolean",short:"h"}}});if(e.help){console.log(xo);return}if(e.version){console.log(Ge);return}let t={configPath:e.config,workspace:e.workspace};if(e.stdio){if(e.port)throw new Error("--port applies to HTTP mode, not --stdio");await ya(t);return}let n;if(e.port!==void 0&&(n=Number.parseInt(e.port,10),!Number.isInteger(n)||n<1||n>65535))throw new Error(`Invalid port: ${e.port}`);await va(t,n)}Ro().catch(e=>{console.error(`Error: ${e.message}`),process.exit(1)});
71
73
  /*! Bundled license information:
72
74
 
73
75
  papaparse/papaparse.js: