@vulcan-energy/mcp-helper 0.1.8 → 0.2.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.
package/dist/server.js CHANGED
@@ -1,2411 +1,54 @@
1
- // src/server.ts
2
- import express from "express";
3
- import cors from "cors";
4
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
6
- import {
7
- ListToolsRequestSchema,
8
- CallToolRequestSchema,
9
- InitializeRequestSchema
10
- } from "@modelcontextprotocol/sdk/types.js";
11
-
12
- // src/engine/workspace.ts
13
- import fs from "fs/promises";
14
- import path from "path";
15
- import { jwtVerify, importSPKI } from "jose";
16
-
17
- // src/engine/licenseKeys.ts
18
- var MCP_PUBLIC_KEYS = [
19
- `-----BEGIN PUBLIC KEY-----
1
+ var dn=Object.create;var zt=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty;var hn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var gn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of fn(t))!_n.call(e,a)&&a!==r&&zt(e,a,{get:()=>t[a],enumerable:!(n=mn(t,a))||n.enumerable});return e};var wn=(e,t,r)=>(r=e!=null?dn(pn(e)):{},yn(t||!e||!e.__esModule?zt(r,"default",{value:e,enumerable:!0}):r,e));var rr=gn((_t,ht)=>{"use strict";(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof ht=="object"&&typeof _t<"u"?ht.exports=t():e.Papa=t()})(_t,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function r(){var i=t.URL||t.webkitURL||null,l=e.toString();return s.BLOB_URL||(s.BLOB_URL=i.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",l,")();"],{type:"text/javascript"})))}var n=!t.document&&!!t.postMessage,a=t.IS_PAPA_WORKER||!1,o={},c=0,s={};if(s.parse=u,s.unparse=m,s.RECORD_SEP="",s.UNIT_SEP="",s.BYTE_ORDER_MARK="\uFEFF",s.BAD_DELIMITERS=["\r",`
2
+ `,'"',s.BYTE_ORDER_MARK],s.WORKERS_SUPPORTED=!n&&!!t.Worker,s.NODE_STREAM_INPUT=1,s.LocalChunkSize=1024*1024*10,s.RemoteChunkSize=1024*1024*5,s.DefaultDelimiter=",",s.Parser=N,s.ParserHandle=Z,s.NetworkStreamer=g,s.FileStreamer=h,s.StringStreamer=S,s.ReadableStreamStreamer=w,typeof PAPA_BROWSER_CONTEXT>"u"&&(s.DuplexStreamStreamer=T),t.jQuery){var d=t.jQuery;d.fn.parse=function(i){var l=i.config||{},f=[];return this.each(function(E){var v=d(this).prop("tagName").toUpperCase()==="INPUT"&&d(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!v||!this.files||this.files.length===0)return!0;for(var O=0;O<this.files.length;O++)f.push({file:this.files[O],inputElem:this,instanceConfig:d.extend({},l)})}),y(),this;function y(){if(f.length===0){$(i.complete)&&i.complete();return}var E=f[0];if($(i.before)){var v=i.before(E.file,E.inputElem);if(typeof v=="object")if(v.action==="abort"){b("AbortError",E.file,E.inputElem,v.reason);return}else if(v.action==="skip"){R();return}else typeof v.config=="object"&&(E.instanceConfig=d.extend(E.instanceConfig,v.config));else if(v==="skip"){R();return}}var O=E.instanceConfig.complete;E.instanceConfig.complete=function(D){$(O)&&O(D,E.file,E.inputElem),R()},s.parse(E.file,E.instanceConfig)}function b(E,v,O,D){$(i.error)&&i.error({name:E},v,O,D)}function R(){f.splice(0,1),y()}}}a&&(t.onmessage=fe);function u(i,l){l=l||{};var f=l.dynamicTyping||!1;if($(f)&&(l.dynamicTypingFunction=f,f={}),l.dynamicTyping=f,l.transform=$(l.transform)?l.transform:!1,l.worker&&s.WORKERS_SUPPORTED){var y=ne();y.userStep=l.step,y.userChunk=l.chunk,y.userComplete=l.complete,y.userError=l.error,l.step=$(l.step),l.chunk=$(l.chunk),l.complete=$(l.complete),l.error=$(l.error),delete l.worker,y.postMessage({input:i,config:l,workerId:y.id});return}var b=null;if(i===s.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return b=new T(l),b.getStream();return typeof i=="string"?(i=R(i),l.download?b=new g(l):b=new S(l)):i.readable===!0&&$(i.read)&&$(i.on)?b=new w(l):(t.File&&i instanceof File||i instanceof Object)&&(b=new h(l)),b.stream(i);function R(E){return E.charCodeAt(0)===65279?E.slice(1):E}}function m(i,l){var f=!1,y=!0,b=",",R=`\r
3
+ `,E='"',v=E+E,O=!1,D=null,G=!1;ie();var A=new RegExp(q(E),"g");if(typeof i=="string"&&(i=JSON.parse(i)),Array.isArray(i)){if(!i.length||Array.isArray(i[0]))return P(null,i,O);if(typeof i[0]=="object")return P(D||Object.keys(i[0]),i,O)}else if(typeof i=="object")return typeof i.data=="string"&&(i.data=JSON.parse(i.data)),Array.isArray(i.data)&&(i.fields||(i.fields=i.meta&&i.meta.fields||D),i.fields||(i.fields=Array.isArray(i.data[0])?i.fields:typeof i.data[0]=="object"?Object.keys(i.data[0]):[]),!Array.isArray(i.data[0])&&typeof i.data[0]!="object"&&(i.data=[i.data])),P(i.fields||[],i.data||[],O);throw new Error("Unable to serialize unrecognized input");function ie(){if(typeof l=="object"){if(typeof l.delimiter=="string"&&!s.BAD_DELIMITERS.filter(function(F){return l.delimiter.indexOf(F)!==-1}).length&&(b=l.delimiter),(typeof l.quotes=="boolean"||typeof l.quotes=="function"||Array.isArray(l.quotes))&&(f=l.quotes),(typeof l.skipEmptyLines=="boolean"||typeof l.skipEmptyLines=="string")&&(O=l.skipEmptyLines),typeof l.newline=="string"&&(R=l.newline),typeof l.quoteChar=="string"&&(E=l.quoteChar),typeof l.header=="boolean"&&(y=l.header),Array.isArray(l.columns)){if(l.columns.length===0)throw new Error("Option columns is empty");D=l.columns}l.escapeChar!==void 0&&(v=l.escapeChar+E),l.escapeFormulae instanceof RegExp?G=l.escapeFormulae:typeof l.escapeFormulae=="boolean"&&l.escapeFormulae&&(G=/^[=+\-@\t\r].*$/)}}function P(F,B,H){var z="";typeof F=="string"&&(F=JSON.parse(F)),typeof B=="string"&&(B=JSON.parse(B));var le=Array.isArray(F)&&F.length>0,Q=!Array.isArray(B[0]);if(le&&y){for(var me=0;me<F.length;me++)me>0&&(z+=b),z+=j(F[me],me);B.length>0&&(z+=R)}for(var L=0;L<B.length;L++){var Se=le?F.length:B[L].length,pe=!1,k=le?Object.keys(B[L]).length===0:B[L].length===0;if(H&&!le&&(pe=H==="greedy"?B[L].join("").trim()==="":B[L].length===1&&B[L][0].length===0),H==="greedy"&&le){for(var x=[],M=0;M<Se;M++){var V=Q?F[M]:M;x.push(B[L][V])}pe=x.join("").trim()===""}if(!pe){for(var C=0;C<Se;C++){C>0&&!k&&(z+=b);var W=le&&Q?F[C]:C;z+=j(B[L][W],C)}L<B.length-1&&(!H||Se>0&&!k)&&(z+=R)}}return z}function j(F,B){if(typeof F>"u"||F===null)return"";if(F.constructor===Date)return JSON.stringify(F).slice(1,25);var H=!1;G&&typeof F=="string"&&G.test(F)&&(F="'"+F,H=!0);var z=F.toString().replace(A,v);return H=H||f===!0||typeof f=="function"&&f(F,B)||Array.isArray(f)&&f[B]||Re(z,s.BAD_DELIMITERS)||z.indexOf(b)>-1||z.charAt(0)===" "||z.charAt(z.length-1)===" ",H?E+z+E:z}function Re(F,B){for(var H=0;H<B.length;H++)if(F.indexOf(B[H])>-1)return!0;return!1}}function p(i){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},l.call(this,i),this.parseChunk=function(f,y){let b=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&b>0){let G=this._config.newline;if(!G){let ie=this._config.quoteChar||'"';G=this._handle.guessLineEndings(f,ie)}f=[...f.split(G).slice(b)].join(G)}if(this.isFirstChunk&&$(this._config.beforeFirstChunk)){var R=this._config.beforeFirstChunk(f);R!==void 0&&(f=R)}this.isFirstChunk=!1,this._halted=!1;var E=this._partialLine+f;this._partialLine="";var v=this._handle.parse(E,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var O=v.meta.cursor;this._finished||(this._partialLine=E.substring(O-this._baseIndex),this._baseIndex=O),v&&v.data&&(this._rowCount+=v.data.length);var D=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(a)t.postMessage({results:v,workerId:s.WORKER_ID,finished:D});else if($(this._config.chunk)&&!y){if(this._config.chunk(v,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}v=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(v.data),this._completeResults.errors=this._completeResults.errors.concat(v.errors),this._completeResults.meta=v.meta),!this._completed&&D&&$(this._config.complete)&&(!v||!v.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!D&&(!v||!v.meta.paused)&&this._nextChunk(),v},this._sendError=function(f){$(this._config.error)?this._config.error(f):a&&this._config.error&&t.postMessage({workerId:s.WORKER_ID,error:f,finished:!1})};function l(f){var y=de(f);y.chunkSize=parseInt(y.chunkSize),!f.step&&!f.chunk&&(y.chunkSize=null),this._handle=new Z(y),this._handle.streamer=this,this._config=y}}function g(i){i=i||{},i.chunkSize||(i.chunkSize=s.RemoteChunkSize),p.call(this,i);var l;n?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(y){this._input=y,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(l=new XMLHttpRequest,this._config.withCredentials&&(l.withCredentials=this._config.withCredentials),n||(l.onload=I(this._chunkLoaded,this),l.onerror=I(this._chunkError,this)),l.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var y=this._config.downloadRequestHeaders;for(var b in y)l.setRequestHeader(b,y[b])}if(this._config.chunkSize){var R=this._start+this._config.chunkSize-1;l.setRequestHeader("Range","bytes="+this._start+"-"+R)}try{l.send(this._config.downloadRequestBody)}catch(E){this._chunkError(E.message)}n&&l.status===0&&this._chunkError()},this._chunkLoaded=function(){if(l.readyState===4){if(l.status<200||l.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:l.responseText.length,this._finished=!this._config.chunkSize||this._start>=f(l),this.parseChunk(l.responseText)}},this._chunkError=function(y){var b=l.statusText||y;this._sendError(new Error(b))};function f(y){var b=y.getResponseHeader("Content-Range");return b===null?-1:parseInt(b.substring(b.lastIndexOf("/")+1))}}g.prototype=Object.create(p.prototype),g.prototype.constructor=g;function h(i){i=i||{},i.chunkSize||(i.chunkSize=s.LocalChunkSize),p.call(this,i);var l,f,y=typeof FileReader<"u";this.stream=function(b){this._input=b,f=b.slice||b.webkitSlice||b.mozSlice,y?(l=new FileReader,l.onload=I(this._chunkLoaded,this),l.onerror=I(this._chunkError,this)):l=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var b=this._input;if(this._config.chunkSize){var R=Math.min(this._start+this._config.chunkSize,this._input.size);b=f.call(b,this._start,R)}var E=l.readAsText(b,this._config.encoding);y||this._chunkLoaded({target:{result:E}})},this._chunkLoaded=function(b){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(b.target.result)},this._chunkError=function(){this._sendError(l.error)}}h.prototype=Object.create(p.prototype),h.prototype.constructor=h;function S(i){i=i||{},p.call(this,i);var l;this.stream=function(f){return l=f,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var f=this._config.chunkSize,y;return f?(y=l.substring(0,f),l=l.substring(f)):(y=l,l=""),this._finished=!l,this.parseChunk(y)}}}S.prototype=Object.create(S.prototype),S.prototype.constructor=S;function w(i){i=i||{},p.call(this,i);var l=[],f=!0,y=!1;this.pause=function(){p.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){p.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(b){this._input=b,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){y&&l.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),l.length?this.parseChunk(l.shift()):f=!0},this._streamData=I(function(b){try{l.push(typeof b=="string"?b:b.toString(this._config.encoding)),f&&(f=!1,this._checkIsFinished(),this.parseChunk(l.shift()))}catch(R){this._streamError(R)}},this),this._streamError=I(function(b){this._streamCleanUp(),this._sendError(b)},this),this._streamEnd=I(function(){this._streamCleanUp(),y=!0,this._streamData("")},this),this._streamCleanUp=I(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}w.prototype=Object.create(p.prototype),w.prototype.constructor=w;function T(i){var l=hn("stream").Duplex,f=de(i),y=!0,b=!1,R=[],E=null;this._onCsvData=function(v){var O=v.data;!E.push(O)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){E.push(null)},f.step=I(this._onCsvData,this),f.complete=I(this._onCsvComplete,this),p.call(this,f),this._nextChunk=function(){b&&R.length===1&&(this._finished=!0),R.length?R.shift()():y=!0},this._addToParseQueue=function(v,O){R.push(I(function(){if(this.parseChunk(typeof v=="string"?v:v.toString(f.encoding)),$(O))return O()},this)),y&&(y=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(v,O,D){this._addToParseQueue(v,D)},this._onWriteComplete=function(){b=!0,this._addToParseQueue("")},this.getStream=function(){return E},E=new l({readableObjectMode:!0,decodeStrings:!1,read:I(this._onRead,this),write:I(this._onWrite,this)}),E.once("finish",I(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(T.prototype=Object.create(p.prototype),T.prototype.constructor=T);function Z(i){var l=Math.pow(2,53),f=-l,y=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,b=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,R=this,E=0,v=0,O,D,G=!1,A=!1,ie,P=[],j={data:[],errors:[],meta:{}};if($(i.step)){var Re=i.step;i.step=function(k){if(j=k,z())H();else{if(H(),j.data.length===0)return;E+=k.data.length,i.preview&&E>i.preview?D.abort():(j.data=j.data[0],Re(j,R))}}}this.parse=function(k,x,M){var V=i.quoteChar||'"';if(i.newline||(i.newline=this.guessLineEndings(k,V)),ie=!1,i.delimiter)$(i.delimiter)&&(i.delimiter=i.delimiter(k),j.meta.delimiter=i.delimiter);else{var C=Se(k,i.newline,i.skipEmptyLines,i.comments,i.delimitersToGuess);C.successful?i.delimiter=C.bestDelimiter:(ie=!0,i.delimiter=s.DefaultDelimiter),j.meta.delimiter=i.delimiter}var W=de(i);return i.preview&&i.header&&W.preview++,O=k,D=new N(W),j=D.parse(O,x,M),H(),G?{meta:{paused:!0}}:j||{meta:{paused:!1}}},this.paused=function(){return G},this.pause=function(){G=!0,D.abort(),O=$(i.chunk)?"":O.substring(D.getCharIndex())},this.resume=function(){R.streamer._halted?(G=!1,R.streamer.parseChunk(O,!0)):setTimeout(R.resume,3)},this.aborted=function(){return A},this.abort=function(){A=!0,D.abort(),j.meta.aborted=!0,$(i.complete)&&i.complete(j),O=""},this.guessLineEndings=function(k,x){k=k.substring(0,1024*1024);var M=new RegExp(q(x)+"([^]*?)"+q(x),"gm");k=k.replace(M,"");var V=k.split("\r"),C=k.split(`
4
+ `),W=C.length>1&&C[0].length<V[0].length;if(V.length===1||W)return`
5
+ `;for(var ee=0,X=0;X<V.length;X++)V[X][0]===`
6
+ `&&ee++;return ee>=V.length/2?`\r
7
+ `:"\r"};function F(k){return i.skipEmptyLines==="greedy"?k.join("").trim()==="":k.length===1&&k[0].length===0}function B(k){if(y.test(k)){var x=parseFloat(k);if(x>f&&x<l)return!0}return!1}function H(){return j&&ie&&(pe("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+s.DefaultDelimiter+"'"),ie=!1),i.skipEmptyLines&&(j.data=j.data.filter(function(k){return!F(k)})),z()&&le(),L()}function z(){return i.header&&P.length===0}function le(){if(!j)return;function k(M,V){$(i.transformHeader)&&(M=i.transformHeader(M,V)),P.push(M)}if(Array.isArray(j.data[0])){for(var x=0;z()&&x<j.data.length;x++)j.data[x].forEach(k);j.data.splice(0,1)}else j.data.forEach(k)}function Q(k){return i.dynamicTypingFunction&&i.dynamicTyping[k]===void 0&&(i.dynamicTyping[k]=i.dynamicTypingFunction(k)),(i.dynamicTyping[k]||i.dynamicTyping)===!0}function me(k,x){return Q(k)?x==="true"||x==="TRUE"?!0:x==="false"||x==="FALSE"?!1:B(x)?parseFloat(x):b.test(x)?new Date(x):x===""?null:x:x}function L(){if(!j||!i.header&&!i.dynamicTyping&&!i.transform)return j;function k(M,V){var C=i.header?{}:[],W;for(W=0;W<M.length;W++){var ee=W,X=M[W];i.header&&(ee=W>=P.length?"__parsed_extra":P[W]),i.transform&&(X=i.transform(X,ee)),X=me(ee,X),ee==="__parsed_extra"?(C[ee]=C[ee]||[],C[ee].push(X)):C[ee]=X}return i.header&&(W>P.length?pe("FieldMismatch","TooManyFields","Too many fields: expected "+P.length+" fields but parsed "+W,v+V):W<P.length&&pe("FieldMismatch","TooFewFields","Too few fields: expected "+P.length+" fields but parsed "+W,v+V)),C}var x=1;return!j.data.length||Array.isArray(j.data[0])?(j.data=j.data.map(k),x=j.data.length):j.data=k(j.data,0),i.header&&j.meta&&(j.meta.fields=P),v+=x,j}function Se(k,x,M,V,C){var W,ee,X,je;C=C||[","," ","|",";",s.RECORD_SEP,s.UNIT_SEP];for(var Ee=0;Ee<C.length;Ee++){var Be=C[Ee],Me=0,ke=0,ae=0;X=void 0;for(var ye=new N({comments:V,delimiter:Be,newline:x,preview:10}).parse(k),te=0;te<ye.data.length;te++){if(M&&F(ye.data[te])){ae++;continue}var ce=ye.data[te].length;if(ke+=ce,typeof X>"u"){X=ce;continue}else ce>0&&(Me+=Math.abs(ce-X),X=ce)}ye.data.length>0&&(ke/=ye.data.length-ae),(typeof ee>"u"||Me<=ee)&&(typeof je>"u"||ke>je)&&ke>1.99&&(ee=Me,W=Be,je=ke)}return i.delimiter=W,{successful:!!W,bestDelimiter:W}}function pe(k,x,M,V){var C={type:k,code:x,message:M};V!==void 0&&(C.row=V),j.errors.push(C)}}function q(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(i){i=i||{};var l=i.delimiter,f=i.newline,y=i.comments,b=i.step,R=i.preview,E=i.fastMode,v,O=null,D=!1;i.quoteChar===void 0||i.quoteChar===null?v='"':v=i.quoteChar;var G=v;if(i.escapeChar!==void 0&&(G=i.escapeChar),(typeof l!="string"||s.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),y===l)throw new Error("Comment character same as delimiter");y===!0?y="#":(typeof y!="string"||s.BAD_DELIMITERS.indexOf(y)>-1)&&(y=!1),f!==`
8
+ `&&f!=="\r"&&f!==`\r
9
+ `&&(f=`
10
+ `);var A=0,ie=!1;this.parse=function(P,j,Re){if(typeof P!="string")throw new Error("Input must be a string");var F=P.length,B=l.length,H=f.length,z=y.length,le=$(b);A=0;var Q=[],me=[],L=[],Se=0;if(!P)return ae();if(E||E!==!1&&P.indexOf(v)===-1){for(var pe=P.split(f),k=0;k<pe.length;k++){if(L=pe[k],A+=L.length,k!==pe.length-1)A+=f.length;else if(Re)return ae();if(!(y&&L.substring(0,z)===y)){if(le){if(Q=[],Ee(L.split(l)),ye(),ie)return ae()}else Ee(L.split(l));if(R&&k>=R)return Q=Q.slice(0,R),ae(!0)}}return ae()}for(var x=P.indexOf(l,A),M=P.indexOf(f,A),V=new RegExp(q(G)+q(v),"g"),C=P.indexOf(v,A);;){if(P[A]===v){for(C=A,A++;;){if(C=P.indexOf(v,C+1),C===-1)return Re||me.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:Q.length,index:A}),Me();if(C===F-1){var W=P.substring(A,C).replace(V,v);return Me(W)}if(v===G&&P[C+1]===G){C++;continue}if(!(v!==G&&C!==0&&P[C-1]===G)){x!==-1&&x<C+1&&(x=P.indexOf(l,C+1)),M!==-1&&M<C+1&&(M=P.indexOf(f,C+1));var ee=M===-1?x:Math.min(x,M),X=Be(ee);if(P.substr(C+1+X,B)===l){L.push(P.substring(A,C).replace(V,v)),A=C+1+X+B,P[C+1+X+B]!==v&&(C=P.indexOf(v,A)),x=P.indexOf(l,A),M=P.indexOf(f,A);break}var je=Be(M);if(P.substring(C+1+je,C+1+je+H)===f){if(L.push(P.substring(A,C).replace(V,v)),ke(C+1+je+H),x=P.indexOf(l,A),C=P.indexOf(v,A),le&&(ye(),ie))return ae();if(R&&Q.length>=R)return ae(!0);break}me.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:Q.length,index:A}),C++}}continue}if(y&&L.length===0&&P.substring(A,A+z)===y){if(M===-1)return ae();A=M+H,M=P.indexOf(f,A),x=P.indexOf(l,A);continue}if(x!==-1&&(x<M||M===-1)){L.push(P.substring(A,x)),A=x+B,x=P.indexOf(l,A);continue}if(M!==-1){if(L.push(P.substring(A,M)),ke(M+H),le&&(ye(),ie))return ae();if(R&&Q.length>=R)return ae(!0);continue}break}return Me();function Ee(te){Q.push(te),Se=A}function Be(te){var ce=0;if(te!==-1){var Pe=P.substring(C+1,te);Pe&&Pe.trim()===""&&(ce=Pe.length)}return ce}function Me(te){return Re||(typeof te>"u"&&(te=P.substring(A)),L.push(te),A=F,Ee(L),le&&ye()),ae()}function ke(te){A=te,Ee(L),L=[],M=P.indexOf(f,A)}function ae(te){if(i.header&&!j&&Q.length&&!D){let ce=Q[0],Pe=Object.create(null),ot=new Set(ce),qt=!1;for(let Te=0;Te<ce.length;Te++){let we=ce[Te];if($(i.transformHeader)&&(we=i.transformHeader(we,Te)),!Pe[we])Pe[we]=1,ce[Te]=we;else{let Le,Ht=Pe[we];do Le=`${we}_${Ht}`,Ht++;while(ot.has(Le));ot.add(Le),ce[Te]=Le,Pe[we]++,qt=!0,O===null&&(O={}),O[Le]=we}ot.add(we)}qt&&console.warn("Duplicate headers found and renamed."),D=!0}return{data:Q,errors:me,meta:{delimiter:l,linebreak:f,aborted:ie,truncated:!!te,cursor:Se+(j||0),renamedHeaders:O}}}function ye(){b(ae()),Q=[],me=[]}},this.abort=function(){ie=!0},this.getCharIndex=function(){return A}}function ne(){if(!s.WORKERS_SUPPORTED)return!1;var i=r(),l=new t.Worker(i);return l.onmessage=Y,l.id=c++,o[l.id]=l,l}function Y(i){var l=i.data,f=o[l.workerId],y=!1;if(l.error)f.userError(l.error,l.file);else if(l.results&&l.results.data){var b=function(){y=!0,K(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},R={abort:b,pause:ue,resume:ue};if($(f.userStep)){for(var E=0;E<l.results.data.length&&(f.userStep({data:l.results.data[E],errors:l.results.errors,meta:l.results.meta},R),!y);E++);delete l.results}else $(f.userChunk)&&(f.userChunk(l.results,R,l.file),delete l.results)}l.finished&&!y&&K(l.workerId,l.results)}function K(i,l){var f=o[i];$(f.userComplete)&&f.userComplete(l),f.terminate(),delete o[i]}function ue(){throw new Error("Not implemented.")}function fe(i){var l=i.data;if(typeof s.WORKER_ID>"u"&&l&&(s.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:s.WORKER_ID,results:s.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var f=s.parse(l.input,l.config);f&&t.postMessage({workerId:s.WORKER_ID,results:f,finished:!0})}}function de(i){if(typeof i!="object"||i===null)return i;var l=Array.isArray(i)?[]:{};for(var f in i)l[f]=de(i[f]);return l}function I(i,l){return function(){i.apply(l,arguments)}}function $(i){return typeof i=="function"}return s})});import cn from"express";import ln from"cors";import{Server as Wa}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Da}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as Va,CallToolRequestSchema as Ja,InitializeRequestSchema as un}from"@modelcontextprotocol/sdk/types.js";import ft from"fs/promises";import Oe from"path";var Gt=Object.freeze(["mcp","analyst"]);function it(e){return typeof e=="string"&&Gt.includes(e)}var He="https://usevulcan.app",ct="vulcan-local-tools",ze=1,lt=10080*60,ut=300,J=class extends Error{code;constructor(t,r){super(r),this.name="CapabilityTokenError",this.code=t}};var Kt=Object.freeze([`-----BEGIN PUBLIC KEY-----
20
11
  MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
21
- -----END PUBLIC KEY-----`
22
- ];
23
-
24
- // src/engine/workspace.ts
25
- var WARNING_WINDOW_SECONDS = 3 * 24 * 60 * 60;
26
- var CLOCK_SKEW_TOLERANCE_SECONDS = 300;
27
- async function readConfig(configPath) {
28
- let resolvedPath = configPath;
29
- if (!resolvedPath) {
30
- const workspace = process.env.VULCAN_WORKSPACE;
31
- if (workspace) {
32
- resolvedPath = path.join(workspace, "vulcan-mcp-config.json");
33
- } else {
34
- resolvedPath = path.join(process.cwd(), "vulcan-mcp-config.json");
35
- }
36
- }
37
- resolvedPath = path.resolve(resolvedPath);
38
- let configContent;
39
- try {
40
- configContent = await fs.readFile(resolvedPath, "utf-8");
41
- } catch (error) {
42
- const err = error;
43
- throw new Error(`Config file not found: ${resolvedPath}. Please generate it from Vulcan \u2192 Integrations \u2192 MCP.`);
44
- }
45
- let config;
46
- try {
47
- config = JSON.parse(configContent);
48
- } catch (error) {
49
- const err = error;
50
- throw new Error(`Invalid JSON in config file: ${err.message}`);
51
- }
52
- if (!config.workspace) {
53
- throw new Error("Config file missing required field: workspace");
54
- }
55
- if (!config.license_token || typeof config.license_token !== "string") {
56
- throw new Error('Your Vulcan MCP token is missing. Open Vulcan \u2192 Integrations \u2192 MCP and click "Generate config".');
57
- }
58
- const workspacePath = path.resolve(path.dirname(resolvedPath), config.workspace);
59
- try {
60
- await fs.access(workspacePath);
61
- } catch (error) {
62
- throw new Error(`Workspace directory not found: ${workspacePath}`);
63
- }
64
- const batchParamsDir = path.join(workspacePath, "input", "batch_parameters");
65
- try {
66
- await fs.access(batchParamsDir);
67
- } catch (error) {
68
- throw new Error(`Workspace missing required directory: ${batchParamsDir}. MCP only supports folder (FSA) workspaces backed by the real filesystem.`);
69
- }
70
- const { payload } = await verifyLicenseToken(config.license_token);
71
- const nowSeconds = Math.floor(Date.now() / 1e3);
72
- const exp = payload.exp;
73
- if (exp - nowSeconds < WARNING_WINDOW_SECONDS) {
74
- console.error(
75
- '[MCP Helper] Warning: Your Vulcan MCP token will expire soon. Open Vulcan \u2192 Integrations \u2192 MCP and click "Refresh token" to avoid interruptions.'
76
- );
77
- }
78
- return {
79
- workspace: workspacePath,
80
- license_token: config.license_token,
81
- configPath: resolvedPath
82
- };
83
- }
84
- async function verifyLicenseToken(token) {
85
- const nowSeconds = Math.floor(Date.now() / 1e3);
86
- let lastError;
87
- for (const pem of MCP_PUBLIC_KEYS) {
88
- try {
89
- const key = await importSPKI(pem, "EdDSA");
90
- const { payload } = await jwtVerify(token, key, { algorithms: ["EdDSA"] });
91
- const claims = payload;
92
- if (!claims.token_id || !claims.user_id || !Array.isArray(claims.entitlements)) {
93
- throw new Error("MCP license token missing required claims");
94
- }
95
- if (!claims.entitlements.includes("mcp")) {
96
- throw new Error('MCP license token missing "mcp" entitlement');
97
- }
98
- const iat = claims.iat;
99
- const exp = claims.exp;
100
- if (typeof iat !== "number" || typeof exp !== "number") {
101
- throw new Error("MCP license token missing iat/exp claims");
102
- }
103
- if (nowSeconds < iat - CLOCK_SKEW_TOLERANCE_SECONDS) {
104
- console.error(
105
- "[MCP Helper] System clock appears to be too far behind the token issue time."
106
- );
107
- throw new Error("clock skew too large");
108
- }
109
- if (nowSeconds > exp) {
110
- console.error(
111
- "[MCP Helper] MCP license token expired at",
112
- new Date(exp * 1e3).toISOString()
113
- );
114
- throw new Error("token expired");
115
- }
116
- return { payload: claims };
117
- } catch (err) {
118
- lastError = err;
119
- }
120
- }
121
- const message = lastError instanceof Error && lastError.message.includes("expired") ? 'Your Vulcan MCP token has expired. Open Vulcan \u2192 Integrations \u2192 MCP and click "Refresh token" to continue.' : "Your Vulcan MCP token is invalid or was signed with an unknown key. Please refresh your token in Vulcan \u2192 Integrations \u2192 MCP.";
122
- throw new Error(message);
123
- }
124
-
125
- // src/engine/requestAuth.ts
126
- import { timingSafeEqual } from "crypto";
127
- function extractBearerToken(header) {
128
- if (typeof header !== "string") {
129
- throw new Error("MCP request Bearer token is required");
130
- }
131
- const match = /^Bearer[\t ]+([^\t ]+)$/i.exec(header.trim());
132
- if (!match?.[1]) {
133
- throw new Error("MCP request Bearer token is required");
134
- }
135
- return match[1];
136
- }
137
- function tokensMatch(candidate, expected) {
138
- const candidateBytes = Buffer.from(candidate);
139
- const expectedBytes = Buffer.from(expected);
140
- return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
141
- }
142
- async function authorizeMcpRequest(authorizationHeader, expectedToken, verify = verifyLicenseToken) {
143
- const candidate = extractBearerToken(authorizationHeader);
144
- if (!tokensMatch(candidate, expectedToken)) {
145
- throw new Error("MCP request Bearer token is invalid");
146
- }
147
- await verify(candidate);
148
- }
149
-
150
- // src/engine/wasm.ts
151
- import fs2 from "fs";
152
- import path2 from "path";
153
- import { fileURLToPath } from "url";
154
- import { pathToFileURL } from "url";
155
- var __filename = fileURLToPath(import.meta.url);
156
- var __dirname = path2.dirname(__filename);
157
- var consoleRedirected = false;
158
- function redirectConsoleToStderr() {
159
- if (consoleRedirected) {
160
- return;
161
- }
162
- const originalConsole = globalThis.console || console;
163
- if (!originalConsole) {
164
- return;
165
- }
166
- const errorLogger = typeof originalConsole.error === "function" ? originalConsole.error.bind(originalConsole) : (...args) => {
167
- process.stderr.write(args.map(String).join(" ") + "\n");
168
- };
169
- const patchedConsole = originalConsole;
170
- patchedConsole.log = (...args) => errorLogger(...args);
171
- globalThis.console = patchedConsole;
172
- consoleRedirected = true;
173
- }
174
- redirectConsoleToStderr();
175
- function resolveWasmPaths() {
176
- const roots = [];
177
- let current = __dirname;
178
- for (let depth = 0; depth < 6; depth += 1) {
179
- roots.push(current);
180
- const parent = path2.dirname(current);
181
- if (parent === current) break;
182
- current = parent;
183
- }
184
- roots.push(process.cwd());
185
- const candidates = [];
186
- for (const root of roots) {
187
- candidates.push(
188
- { directory: path2.join(root, "wasm"), context: "helper-root" },
189
- { directory: path2.join(root, "vulcan-mcp-server", "wasm"), context: "helper-dist" },
190
- { directory: path2.join(root, "web", "dist", "wasm"), context: "rust-hem-runner" },
191
- { directory: path2.join(root, "web", "dist"), context: "rust-hem-runner" },
192
- { directory: path2.join(root, "web", "pkg"), context: "rust-hem-runner" },
193
- { directory: path2.join(root, "apps", "web", "public", "launch"), context: "vulcan-website" }
194
- );
195
- }
196
- const tried = [];
197
- const seen = /* @__PURE__ */ new Set();
198
- for (const candidate of candidates) {
199
- const jsPath = path2.join(candidate.directory, "wasm_wrapper.js");
200
- if (seen.has(jsPath)) continue;
201
- seen.add(jsPath);
202
- tried.push(jsPath);
203
- const wasmPath = path2.join(candidate.directory, "wasm_wrapper_bg.wasm");
204
- if (fs2.existsSync(jsPath) && fs2.existsSync(wasmPath)) {
205
- return { jsPath, wasmPath, context: candidate.context };
206
- }
207
- }
208
- throw new Error(
209
- `WASM files not found. Tried:
210
- ` + tried.map((candidate) => ` - ${candidate}`).join("\n") + `
211
- Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`
212
- );
213
- }
214
- var wasmModule = null;
215
- var wasmInitialized = false;
216
- var currentWorkspace = process.cwd();
217
- async function initWasm() {
218
- if (wasmInitialized && wasmModule) {
219
- return wasmModule;
220
- }
221
- try {
222
- const { jsPath, wasmPath, context } = resolveWasmPaths();
223
- console.error(`[WASM] Loading from ${context}: ${jsPath}`);
224
- const global = globalThis;
225
- if (!global.self) {
226
- global.self = globalThis;
227
- }
228
- if (!global.window) {
229
- global.window = globalThis;
230
- }
231
- if (typeof global.addEventListener !== "function") {
232
- global.addEventListener = () => {
233
- };
234
- }
235
- if (typeof global.postMessage !== "function") {
236
- global.postMessage = () => {
237
- };
238
- }
239
- if (typeof global.self.addEventListener !== "function") {
240
- global.self.addEventListener = () => {
241
- };
242
- }
243
- if (typeof global.self.postMessage !== "function") {
244
- global.self.postMessage = () => {
245
- };
246
- }
247
- if (typeof global.Worker !== "function") {
248
- global.Worker = class {
249
- constructor() {
250
- }
251
- addEventListener() {
252
- }
253
- postMessage() {
254
- }
255
- terminate() {
256
- }
257
- };
258
- }
259
- globalThis.write_file = (p, content) => {
260
- const abs = path2.isAbsolute(p) ? p : path2.resolve(currentWorkspace, p);
261
- try {
262
- fs2.mkdirSync(path2.dirname(abs), { recursive: true });
263
- fs2.writeFileSync(abs, content);
264
- return true;
265
- } catch (error) {
266
- const err = error;
267
- console.error(`[FS Bridge] write_file failed for ${abs}:`, err.message);
268
- return false;
269
- }
270
- };
271
- globalThis.read_file = (p) => {
272
- const abs = path2.isAbsolute(p) ? p : path2.resolve(currentWorkspace, p);
273
- try {
274
- return fs2.readFileSync(abs, "utf8");
275
- } catch (error) {
276
- const err = error;
277
- console.error(`[FS Bridge] read_file failed for ${abs}:`, err.message);
278
- throw error;
279
- }
280
- };
281
- globalThis.file_exists = (p) => {
282
- try {
283
- const abs = path2.isAbsolute(p) ? p : path2.resolve(currentWorkspace, p);
284
- return fs2.existsSync(abs);
285
- } catch {
286
- return false;
287
- }
288
- };
289
- globalThis.create_dir_all = (p) => {
290
- const abs = path2.isAbsolute(p) ? p : path2.resolve(currentWorkspace, p);
291
- try {
292
- fs2.mkdirSync(abs, { recursive: true });
293
- return true;
294
- } catch (error) {
295
- const err = error;
296
- console.error(`[FS Bridge] create_dir_all failed for ${abs}:`, err.message);
297
- return false;
298
- }
299
- };
300
- globalThis.list_dir = (p) => {
301
- const abs = path2.isAbsolute(p) ? p : path2.resolve(currentWorkspace, p);
302
- try {
303
- return fs2.readdirSync(abs);
304
- } catch (error) {
305
- const err = error;
306
- console.error(`[FS Bridge] list_dir failed for ${abs}:`, err.message);
307
- return [];
308
- }
309
- };
310
- const originalFetch = globalThis.fetch;
311
- globalThis.fetch = async (url, options) => {
312
- if (typeof url === "string" && url.startsWith("file://")) {
313
- const filePath = fileURLToPath(url);
314
- try {
315
- const content = fs2.readFileSync(filePath);
316
- if (typeof Response !== "undefined") {
317
- return new Response(content, {
318
- status: 200,
319
- statusText: "OK",
320
- headers: { "Content-Type": "application/javascript" }
321
- });
322
- } else {
323
- return {
324
- ok: true,
325
- status: 200,
326
- statusText: "OK",
327
- async text() {
328
- return content.toString();
329
- },
330
- async arrayBuffer() {
331
- return content.buffer;
332
- },
333
- headers: /* @__PURE__ */ new Map([["Content-Type", "application/javascript"]])
334
- };
335
- }
336
- } catch (error) {
337
- if (typeof Response !== "undefined") {
338
- return new Response(null, {
339
- status: 404,
340
- statusText: "Not Found"
341
- });
342
- } else {
343
- return {
344
- ok: false,
345
- status: 404,
346
- statusText: "Not Found",
347
- async text() {
348
- return "";
349
- },
350
- async arrayBuffer() {
351
- return new ArrayBuffer(0);
352
- },
353
- headers: /* @__PURE__ */ new Map()
354
- };
355
- }
356
- }
357
- }
358
- if (originalFetch) {
359
- return originalFetch(url, options);
360
- }
361
- throw new Error("fetch not available for non-file URLs");
362
- };
363
- const wasmModuleUrl = pathToFileURL(jsPath).href;
364
- wasmModule = await import(wasmModuleUrl);
365
- if (wasmModule.initSync) {
366
- const wasmBytes = fs2.readFileSync(wasmPath);
367
- wasmModule.initSync({ module: wasmBytes });
368
- } else {
369
- throw new Error("WASM module does not have initSync - this should not happen with wasm-pack build");
370
- }
371
- if (wasmModule.setup_panic_hook) {
372
- wasmModule.setup_panic_hook();
373
- }
374
- wasmInitialized = true;
375
- console.error(`[WASM] Initialized successfully from ${context}`);
376
- return wasmModule;
377
- } catch (error) {
378
- console.error("[WASM] Initialization failed:", error);
379
- wasmModule = null;
380
- wasmInitialized = false;
381
- const err = error;
382
- throw new Error(`WASM initialization failed: ${err.message}`);
383
- }
384
- }
385
- function getWasmModule() {
386
- if (!wasmModule || !wasmInitialized) {
387
- throw new Error("WASM module not initialized. Call initWasm() first.");
388
- }
389
- return wasmModule;
390
- }
391
- function setWorkspace(workspace) {
392
- currentWorkspace = workspace;
393
- }
394
-
395
- // src/tools/index.ts
396
- import { z } from "zod";
397
-
398
- // ../packages/workspace-tools/src/batchConfig.ts
399
- import fs3 from "fs/promises";
400
- import path3 from "path";
401
- function validateBatchConfigStructure(config) {
402
- const errors = [];
403
- const warnings = [];
404
- if (!config || typeof config !== "object") {
405
- return { valid: false, errors: ["Config must be an object"], warnings: [] };
406
- }
407
- const scenarios = Object.keys(config);
408
- if (scenarios.length === 0) {
409
- errors.push("Config must have at least one scenario");
410
- }
411
- for (const [scenarioName, scenarioValue] of Object.entries(config)) {
412
- if (!scenarioValue || typeof scenarioValue !== "object") {
413
- errors.push(`Scenario '${scenarioName}' must be an object`);
414
- continue;
415
- }
416
- const scenario = scenarioValue;
417
- if (!Array.isArray(scenario.base_json)) {
418
- errors.push(`Scenario '${scenarioName}' is missing required 'base_json' field (must be array)`);
419
- } else if (scenario.base_json.length !== 1) {
420
- errors.push(`Scenario '${scenarioName}' must have exactly one base_json (found ${scenario.base_json.length})`);
421
- }
422
- const hasWeatherFiles = Boolean(scenario.weather_file || scenario.weather_files);
423
- const hasExternalConditions = Boolean(scenario.external_conditions);
424
- if (hasWeatherFiles) {
425
- const weatherField = scenario.weather_file || scenario.weather_files;
426
- if (Array.isArray(weatherField)) {
427
- if (weatherField.length > 1) {
428
- errors.push(`Scenario '${scenarioName}' must have at most one weather_file (found ${weatherField.length})`);
429
- }
430
- } else {
431
- errors.push(`Scenario '${scenarioName}' weather_file/weather_files must be an array`);
432
- }
433
- }
434
- if (hasExternalConditions && !Array.isArray(scenario.external_conditions)) {
435
- errors.push(`Scenario '${scenarioName}' external_conditions must be an array`);
436
- }
437
- if (!hasWeatherFiles && !hasExternalConditions) {
438
- errors.push(`Scenario '${scenarioName}' must have either 'weather_files' or 'external_conditions'`);
439
- }
440
- if (hasWeatherFiles && hasExternalConditions) {
441
- warnings.push(`Scenario '${scenarioName}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);
442
- }
443
- for (const [category, values] of Object.entries(scenario)) {
444
- if (!Array.isArray(values)) {
445
- errors.push(`Scenario '${scenarioName}': '${category}' must be an array`);
446
- }
447
- }
448
- }
449
- return {
450
- valid: errors.length === 0,
451
- errors,
452
- warnings
453
- };
454
- }
455
- function calculatePermutations(config) {
456
- try {
457
- if (!config || typeof config !== "object") return null;
458
- let totalPermutations = 0;
459
- for (const scenarioValue of Object.values(config)) {
460
- if (!scenarioValue || typeof scenarioValue !== "object") continue;
461
- const scenario = scenarioValue;
462
- let scenarioPermutations = 1;
463
- for (const values of Object.values(scenario)) {
464
- if (Array.isArray(values)) {
465
- scenarioPermutations *= values.length;
466
- }
467
- }
468
- totalPermutations += scenarioPermutations;
469
- }
470
- return totalPermutations;
471
- } catch {
472
- return null;
473
- }
474
- }
475
- async function validateParameterFilesExist(workspace, config) {
476
- const errors = [];
477
- const missingFiles = [];
478
- if (!config || typeof config !== "object") {
479
- return {
480
- valid: false,
481
- errors: ["Config must be an object"],
482
- missingFiles
483
- };
484
- }
485
- for (const [scenarioName, scenarioValue] of Object.entries(config)) {
486
- if (!scenarioValue || typeof scenarioValue !== "object") continue;
487
- const scenario = scenarioValue;
488
- for (const [category, values] of Object.entries(scenario)) {
489
- if (!Array.isArray(values)) continue;
490
- if (category === "weather_file" || category === "weather_files") continue;
491
- for (const paramId of values) {
492
- const paramPath = path3.join(
493
- workspace,
494
- "input",
495
- "batch_parameters",
496
- category,
497
- `${String(paramId)}.json`
498
- );
499
- try {
500
- await fs3.access(paramPath);
501
- } catch {
502
- missingFiles.push({
503
- scenario: scenarioName,
504
- category,
505
- parameter: String(paramId),
506
- path: paramPath
507
- });
508
- errors.push(`Scenario '${scenarioName}': Parameter '${String(paramId)}' in category '${category}' not found at ${paramPath}`);
509
- }
510
- }
511
- }
512
- }
513
- return {
514
- valid: errors.length === 0,
515
- errors,
516
- missingFiles
517
- };
518
- }
519
-
520
- // ../packages/workspace-tools/src/batches.ts
521
- import { randomUUID } from "crypto";
522
- import fs4 from "fs/promises";
523
- import path4 from "path";
524
- async function createBatchConfig(workspace, args) {
525
- const { config_name, base_model, weather_file, wrapper, parameters } = args;
526
- if (!config_name) {
527
- throw new Error("config_name is required");
528
- }
529
- if (!base_model) {
530
- throw new Error("base_model is required");
531
- }
532
- if (!weather_file) {
533
- throw new Error("weather_file is required");
534
- }
535
- if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
536
- throw new Error("parameters is required and must be an object mapping category to parameter IDs array");
537
- }
538
- const normalizedParameters = normalizeParameterSelections(parameters);
539
- const batchConfig = {
540
- scenario_1: {
541
- base_json: [base_model],
542
- weather_files: [weather_file],
543
- ...wrapper ? { model_wrappers: [wrapper] } : {},
544
- ...normalizedParameters
545
- }
546
- };
547
- const structureValidation = validateBatchConfigStructure(batchConfig);
548
- if (!structureValidation.valid) {
549
- return {
550
- success: false,
551
- valid: false,
552
- errors: structureValidation.errors,
553
- warnings: structureValidation.warnings,
554
- message: `Config validation failed: ${structureValidation.errors.join("; ")}`
555
- };
556
- }
557
- const permutations = calculatePermutations(batchConfig);
558
- if (permutations === null) {
559
- return {
560
- success: false,
561
- valid: false,
562
- errors: ["Failed to calculate permutations"],
563
- message: "Failed to calculate permutations for batch config"
564
- };
565
- }
566
- if (permutations > 500) {
567
- return {
568
- success: false,
569
- valid: false,
570
- errors: [`Total permutations (${permutations}) exceeds maximum of 500`],
571
- message: `Config would generate ${permutations} permutations, which exceeds the limit of 500`
572
- };
573
- }
574
- const fileValidation = await validateParameterFilesExist(workspace, batchConfig);
575
- if (!fileValidation.valid) {
576
- return {
577
- success: false,
578
- valid: false,
579
- errors: fileValidation.errors,
580
- missingFiles: fileValidation.missingFiles,
581
- message: `Some parameter files are missing: ${fileValidation.errors.slice(0, 3).join("; ")}${fileValidation.errors.length > 3 ? "..." : ""}`
582
- };
583
- }
584
- const baseModelPath = path4.join(
585
- workspace,
586
- "input",
587
- "batch_parameters",
588
- "base_json",
589
- `${base_model}.json`
590
- );
591
- try {
592
- await fs4.access(baseModelPath);
593
- } catch {
594
- return {
595
- success: false,
596
- valid: false,
597
- errors: [`Base model '${base_model}' not found at ${baseModelPath}`],
598
- message: `Base model file not found: ${base_model}`
599
- };
600
- }
601
- const weatherFilePath = path4.join(
602
- workspace,
603
- "input",
604
- "batch_parameters",
605
- "weather_files",
606
- weather_file.endsWith(".epw") ? weather_file : `${weather_file}.epw`
607
- );
608
- try {
609
- await fs4.access(weatherFilePath);
610
- } catch {
611
- return {
612
- success: false,
613
- valid: false,
614
- errors: [`Weather file '${weather_file}' not found at ${weatherFilePath}`],
615
- message: `Weather file not found: ${weather_file}`
616
- };
617
- }
618
- const configDir = path4.join(workspace, "input", "batch_configs");
619
- await fs4.mkdir(configDir, { recursive: true });
620
- const configFileName = config_name.endsWith(".json") ? config_name : `${config_name}.json`;
621
- const configPath = path4.join(configDir, configFileName);
622
- try {
623
- await fs4.access(configPath);
624
- return {
625
- success: false,
626
- valid: false,
627
- errors: [`Config file '${configFileName}' already exists`],
628
- message: "Config file already exists. Use a different name or delete the existing file first."
629
- };
630
- } catch {
631
- }
632
- await fs4.writeFile(configPath, JSON.stringify(batchConfig, null, 2), "utf8");
633
- return {
634
- success: true,
635
- valid: true,
636
- message: `Batch config '${config_name}' created successfully`,
637
- config_path: configPath,
638
- permutations,
639
- structure: batchConfig
640
- };
641
- }
642
- async function runBatch(workspace, args, deps) {
643
- const { config_name, job_id } = args;
644
- if (!config_name) {
645
- throw new Error("config_name is required");
646
- }
647
- const finalJobId = job_id || deps.generateJobId?.() || `mcp_${randomUUID()}`;
648
- const configFileName = config_name.endsWith(".json") ? config_name : `${config_name}.json`;
649
- const configPath = path4.join(workspace, "input", "batch_configs", configFileName);
650
- let configContent;
651
- try {
652
- configContent = await fs4.readFile(configPath, "utf8");
653
- } catch (error) {
654
- const err = error;
655
- if (err.code === "ENOENT") {
656
- throw new Error(`Batch config '${config_name}' not found at ${configPath}`);
657
- }
658
- throw new Error(`Failed to read config file: ${err.message}`);
659
- }
660
- const outputDir = path4.join(workspace, "output");
661
- await fs4.mkdir(outputDir, { recursive: true });
662
- try {
663
- const resultJson = deps.processBatchConfig(
664
- configContent,
665
- workspace,
666
- outputDir,
667
- config_name.replace(/\.json$/, ""),
668
- finalJobId
669
- );
670
- const result = JSON.parse(resultJson);
671
- if (result.error) {
672
- return {
673
- job_id: finalJobId,
674
- status: "error",
675
- message: `Batch execution failed: ${result.error}`,
676
- error: result.error
677
- };
678
- }
679
- return {
680
- job_id: finalJobId,
681
- status: "started",
682
- message: "Batch execution started successfully",
683
- config_name,
684
- output_dir: outputDir
685
- };
686
- } catch (error) {
687
- const err = error;
688
- return {
689
- job_id: finalJobId,
690
- status: "error",
691
- message: `Failed to start batch execution: ${err.message}`,
692
- error: err.message
693
- };
694
- }
695
- }
696
- async function getBatchStatus(workspace, args = {}) {
697
- let { job_id, config_name } = args;
698
- if (config_name && !job_id) {
699
- const outputDir2 = path4.join(workspace, "output");
700
- const cleanConfigName = config_name.replace(/\.json$/, "");
701
- try {
702
- const files = await fs4.readdir(outputDir2);
703
- const progressFiles = files.filter((file) => file.startsWith("progress_") && file.endsWith(".json")).map((file) => ({
704
- name: file,
705
- jobId: file.replace("progress_", "").replace(".json", ""),
706
- path: path4.join(outputDir2, file),
707
- isMcp: file.startsWith("progress_mcp_")
708
- }));
709
- const filesWithStats = await Promise.all(
710
- progressFiles.map(async (file) => {
711
- try {
712
- const stat = await fs4.stat(file.path);
713
- return { ...file, mtime: stat.mtime };
714
- } catch {
715
- return { ...file, mtime: /* @__PURE__ */ new Date(0) };
716
- }
717
- })
718
- );
719
- filesWithStats.sort((a, b) => {
720
- if (a.isMcp && !b.isMcp) return -1;
721
- if (!a.isMcp && b.isMcp) return 1;
722
- return b.mtime.getTime() - a.mtime.getTime();
723
- });
724
- if (filesWithStats[0]) {
725
- job_id = filesWithStats[0].jobId;
726
- }
727
- } catch (error2) {
728
- console.warn(`Failed to find job_id for config_name '${config_name}': ${error2.message}`);
729
- }
730
- if (!job_id) {
731
- return {
732
- config_name: cleanConfigName,
733
- status: "queued",
734
- progress: 0,
735
- passes: 0,
736
- failures: 0,
737
- output_dir: path4.join(workspace, "output"),
738
- error: null,
739
- batch_progress: void 0,
740
- sim_progress: void 0
741
- };
742
- }
743
- }
744
- if (!job_id) {
745
- throw new Error("Either job_id or config_name is required");
746
- }
747
- const outputDir = path4.join(workspace, "output");
748
- const progressPath = path4.join(outputDir, `progress_${job_id}.json`);
749
- const simProgressPath = path4.join(outputDir, `sim_progress_${job_id}.json`);
750
- let batchProgress = null;
751
- let simProgress = null;
752
- try {
753
- batchProgress = JSON.parse(await fs4.readFile(progressPath, "utf8"));
754
- } catch (error2) {
755
- const err = error2;
756
- if (err.code !== "ENOENT") {
757
- console.warn(`Failed to read batch progress: ${err.message}`);
758
- }
759
- }
760
- try {
761
- simProgress = JSON.parse(await fs4.readFile(simProgressPath, "utf8"));
762
- } catch (error2) {
763
- const err = error2;
764
- if (err.code !== "ENOENT") {
765
- console.warn(`Failed to read simulation progress: ${err.message}`);
766
- }
767
- }
768
- let status = "queued";
769
- let progress = 0;
770
- let passes = 0;
771
- let failures = 0;
772
- let error = null;
773
- if (batchProgress) {
774
- if (isBatchStatus(batchProgress.status)) {
775
- status = batchProgress.status;
776
- } else if (typeof batchProgress.percentage === "number") {
777
- progress = batchProgress.percentage;
778
- status = progress >= 100 ? "completed" : "running";
779
- } else if (typeof batchProgress.current_combination === "number" && typeof batchProgress.total_combinations === "number") {
780
- progress = Math.round(
781
- batchProgress.current_combination / batchProgress.total_combinations * 100
782
- );
783
- status = progress >= 100 ? "completed" : "running";
784
- }
785
- if (typeof batchProgress.error === "string") {
786
- error = batchProgress.error;
787
- status = "error";
788
- }
789
- }
790
- if (simProgress) {
791
- if (isBatchStatus(simProgress.status)) {
792
- status = simProgress.status;
793
- }
794
- if (typeof simProgress.passes === "number") {
795
- passes = simProgress.passes;
796
- }
797
- if (typeof simProgress.failures === "number") {
798
- failures = simProgress.failures;
799
- }
800
- if (typeof simProgress.error === "string") {
801
- error = simProgress.error;
802
- status = "error";
803
- }
804
- }
805
- if (!batchProgress && !simProgress) {
806
- const jobOutputDir = path4.join(outputDir, job_id);
807
- try {
808
- const entries = await fs4.readdir(jobOutputDir);
809
- status = entries.length > 0 ? "completed" : "queued";
810
- progress = entries.length > 0 ? 100 : 0;
811
- } catch {
812
- status = "queued";
813
- }
814
- }
815
- return {
816
- job_id,
817
- ...config_name ? { config_name: config_name.replace(/\.json$/, "") } : {},
818
- status,
819
- progress,
820
- passes,
821
- failures,
822
- output_dir: outputDir,
823
- error,
824
- batch_progress: batchProgress,
825
- sim_progress: simProgress
826
- };
827
- }
828
- function normalizeParameterSelections(parameters) {
829
- return Object.fromEntries(
830
- Object.entries(parameters).map(([category, values]) => [
831
- category,
832
- Array.isArray(values) ? values.map(String) : [String(values)]
833
- ])
834
- );
835
- }
836
- function isBatchStatus(value) {
837
- return value === "queued" || value === "running" || value === "completed" || value === "error";
838
- }
839
-
840
- // ../packages/workspace-tools/src/defaults.ts
841
- import fs5 from "fs/promises";
842
- import path5 from "path";
843
- var DEFAULT_DEFAULTS_PATH = "input/defaults/defaults_template.json";
844
- var LEGACY_DEFAULT_DEFAULTS_PATH = "input/batch_parameters/base_json/defaults_template.json";
845
- var LEGACY_SUFFIX = "batch_parameters/base_json/defaults_template.json";
846
- var CANONICAL_SUFFIX = "defaults/defaults_template.json";
847
- function parseCsvDefaultsPath(csvContent) {
848
- const head = csvContent.split("\n").slice(0, 50);
849
- const metaLine = head.find((line) => /^DefaultsPath,/i.test(line.trim()));
850
- if (!metaLine) return null;
851
- const parts = parseCsvLine(metaLine);
852
- const parsed = (parts[1] || "").trim();
853
- return parsed || null;
854
- }
855
- function isLegacyDefaultsTemplatePath(value) {
856
- const normalized = value.trim().replace(/\\/g, "/");
857
- return normalized === LEGACY_DEFAULT_DEFAULTS_PATH || normalized.endsWith("/batch_parameters/base_json/defaults_template.json");
858
- }
859
- function defaultsReadPathAttempts(workspaceRelativePath) {
860
- const trimmed = workspaceRelativePath.trim();
861
- if (!trimmed) return [];
862
- if (!isLegacyDefaultsTemplatePath(trimmed)) return [trimmed];
863
- const normalized = trimmed.replace(/\\/g, "/");
864
- const suffixIndex = normalized.lastIndexOf(LEGACY_SUFFIX);
865
- const canonical = suffixIndex >= 0 ? `${normalized.slice(0, suffixIndex)}${CANONICAL_SUFFIX}` : DEFAULT_DEFAULTS_PATH;
866
- return [canonical, trimmed];
867
- }
868
- async function loadDefaultsForCsv(args) {
869
- const explicitDefaultsPath = (args.explicitDefaultsPath ?? "").trim();
870
- const declaredDefaultsPath = explicitDefaultsPath || parseCsvDefaultsPath(args.csvContent);
871
- if (declaredDefaultsPath) {
872
- const attempts = defaultsReadPathAttempts(declaredDefaultsPath);
873
- let lastError;
874
- for (const relativePath of attempts) {
875
- const absolutePath = path5.isAbsolute(relativePath) ? relativePath : path5.join(args.workspace, relativePath);
876
- try {
877
- return {
878
- defaultsJson: await fs5.readFile(absolutePath, "utf8"),
879
- source: explicitDefaultsPath ? `custom: ${relativePath}` : `CSV metadata: ${relativePath}`,
880
- path: absolutePath
881
- };
882
- } catch (error) {
883
- lastError = error;
884
- }
885
- }
886
- const message = lastError instanceof Error ? lastError.message : String(lastError);
887
- throw new Error(
888
- `Could not read defaults file "${declaredDefaultsPath}". Conversion was aborted instead of silently substituting the standard defaults template. ${message}`
889
- );
890
- }
891
- for (const relativePath of [
892
- DEFAULT_DEFAULTS_PATH,
893
- LEGACY_DEFAULT_DEFAULTS_PATH,
894
- "defaults_template.json"
895
- ]) {
896
- const absolutePath = path5.join(args.workspace, relativePath);
897
- try {
898
- return {
899
- defaultsJson: await fs5.readFile(absolutePath, "utf8"),
900
- source: "legacy fallback: standard defaults template",
901
- path: absolutePath
902
- };
903
- } catch {
904
- }
905
- }
906
- throw new Error(
907
- `Defaults file not found. Tried ${DEFAULT_DEFAULTS_PATH}, ${LEGACY_DEFAULT_DEFAULTS_PATH}, defaults_template.json`
908
- );
909
- }
910
- function parseCsvLine(line) {
911
- const result = [];
912
- let current = "";
913
- let inQuotes = false;
914
- for (let i = 0; i < line.length; i += 1) {
915
- const ch = line[i];
916
- if (inQuotes) {
917
- if (ch === '"') {
918
- if (line[i + 1] === '"') {
919
- current += '"';
920
- i += 1;
921
- } else {
922
- inQuotes = false;
923
- }
924
- } else {
925
- current += ch;
926
- }
927
- } else if (ch === '"') {
928
- inQuotes = true;
929
- } else if (ch === ",") {
930
- result.push(current);
931
- current = "";
932
- } else {
933
- current += ch;
934
- }
935
- }
936
- result.push(current);
937
- return result;
938
- }
939
-
940
- // ../packages/workspace-tools/src/geometryCsv.ts
941
- import crypto from "crypto";
942
- import fs8 from "fs/promises";
943
- import path8 from "path";
944
-
945
- // ../packages/workspace-tools/src/repo.ts
946
- import fs6 from "fs";
947
- import path6 from "path";
948
- import { fileURLToPath as fileURLToPath2 } from "url";
949
- function findRepoRoot(start = process.cwd()) {
950
- let current = path6.resolve(start);
951
- if (fs6.existsSync(current) && fs6.statSync(current).isFile()) {
952
- current = path6.dirname(current);
953
- }
954
- while (true) {
955
- if (fs6.existsSync(path6.join(current, "package.json")) && fs6.existsSync(path6.join(current, "hem-batch-core")) && fs6.existsSync(path6.join(current, "web"))) {
956
- return current;
957
- }
958
- const parent = path6.dirname(current);
959
- if (parent === current) {
960
- break;
961
- }
962
- current = parent;
963
- }
964
- const moduleDir = path6.dirname(fileURLToPath2(import.meta.url));
965
- return path6.resolve(moduleDir, "..", "..", "..");
966
- }
967
-
968
- // ../packages/workspace-tools/src/schema.ts
969
- import fs7 from "fs/promises";
970
- import path7 from "path";
971
- function parseSchemaModeFromCsv(csvContent) {
972
- let complianceValidationEnabled = false;
973
- let metadataSchemaMode = null;
974
- for (const rawLine of csvContent.split("\n").slice(0, 80)) {
975
- const line = rawLine.trim();
976
- if (/^ComplianceValidationEnabled,/i.test(line)) {
977
- const value = parseCsvLine2(line)[1]?.trim().toUpperCase();
978
- complianceValidationEnabled = value === "TRUE";
979
- continue;
980
- }
981
- if (/^SchemaProfile,/i.test(line)) {
982
- const value = parseCsvLine2(line)[1]?.trim().toLowerCase();
983
- if (value === "ecaas_input_fhs") metadataSchemaMode = "ecaas_input_fhs";
984
- if (value === "input_fhs") metadataSchemaMode = "input_fhs";
985
- if (value === "input_core") metadataSchemaMode = "input_core";
986
- }
987
- }
988
- if (metadataSchemaMode) return metadataSchemaMode;
989
- return complianceValidationEnabled ? "input_fhs" : "input_core";
990
- }
991
- async function loadSchemaForCsv(args) {
992
- const mode = parseSchemaModeFromCsv(args.csvContent);
993
- if (args.explicitSchemaPath) {
994
- const schemaPath = path7.isAbsolute(args.explicitSchemaPath) ? args.explicitSchemaPath : path7.resolve(args.workspace ?? process.cwd(), args.explicitSchemaPath);
995
- return {
996
- mode,
997
- source: schemaPath,
998
- schemaJson: await fs7.readFile(schemaPath, "utf8")
999
- };
1000
- }
1001
- const candidates = schemaCandidatePaths({
1002
- mode,
1003
- repoRoot: args.repoRoot,
1004
- workspace: args.workspace
1005
- });
1006
- const tried = [];
1007
- for (const schemaPath of candidates) {
1008
- tried.push(schemaPath);
1009
- try {
1010
- return {
1011
- mode,
1012
- source: schemaPath,
1013
- schemaJson: await fs7.readFile(schemaPath, "utf8")
1014
- };
1015
- } catch {
1016
- }
1017
- }
1018
- throw new Error(`Schema file not found for ${mode}. Tried: ${tried.join(", ")}`);
1019
- }
1020
- function schemaCandidatePaths(args) {
1021
- const candidates = [];
1022
- if (args.repoRoot) {
1023
- candidates.push(path7.join(args.repoRoot, ...repoSchemaPathSegments(args.mode)));
1024
- }
1025
- if (args.workspace) {
1026
- const workspaceSegments = workspaceSchemaCandidateSegments(args.mode);
1027
- candidates.push(...workspaceSegments.map((segments) => path7.join(args.workspace, ...segments)));
1028
- }
1029
- return [...new Set(candidates)];
1030
- }
1031
- function repoSchemaPathSegments(mode) {
1032
- switch (mode) {
1033
- case "input_core":
1034
- return ["hem_engine_upstream", "schemas", "core-input.schema.json"];
1035
- case "input_fhs":
1036
- return ["hem_fhs_upstream", "schema", "input_fhs.schema.json"];
1037
- case "ecaas_input_fhs":
1038
- return ["schemas", "ecaas_input_fhs.schema.json"];
1039
- }
1040
- }
1041
- function workspaceSchemaCandidateSegments(mode) {
1042
- switch (mode) {
1043
- case "input_core":
1044
- return [
1045
- ["input_core.schema.json"],
1046
- ["hem_engine_upstream", "schemas", "core-input.schema.json"],
1047
- ["core-input.schema.json"],
1048
- ["schemas", "core-input.schema.json"],
1049
- ["input.schema.json"]
1050
- ];
1051
- case "input_fhs":
1052
- return [
1053
- ["input_fhs.schema.json"],
1054
- ["hem_fhs_upstream", "schema", "input_fhs.schema.json"],
1055
- ["schema", "input_fhs.schema.json"],
1056
- ["schemas", "input_fhs.schema.json"]
1057
- ];
1058
- case "ecaas_input_fhs":
1059
- return [
1060
- ["ecaas_input_fhs.schema.json"],
1061
- ["schemas", "ecaas_input_fhs.schema.json"]
1062
- ];
1063
- }
1064
- }
1065
- function parseCsvLine2(line) {
1066
- const result = [];
1067
- let current = "";
1068
- let inQuotes = false;
1069
- for (let i = 0; i < line.length; i += 1) {
1070
- const ch = line[i];
1071
- if (inQuotes) {
1072
- if (ch === '"') {
1073
- if (line[i + 1] === '"') {
1074
- current += '"';
1075
- i += 1;
1076
- } else {
1077
- inQuotes = false;
1078
- }
1079
- } else {
1080
- current += ch;
1081
- }
1082
- } else if (ch === '"') {
1083
- inQuotes = true;
1084
- } else if (ch === ",") {
1085
- result.push(current);
1086
- current = "";
1087
- } else {
1088
- current += ch;
1089
- }
1090
- }
1091
- result.push(current);
1092
- return result;
1093
- }
1094
-
1095
- // ../packages/workspace-tools/src/geometryCsv.ts
1096
- async function convertGeometryCsvWithPolicy(args) {
1097
- const { workspace, csvContent, schemaJson, defaultsPath, deps } = args;
1098
- const defaults = await loadDefaultsForCsv({
1099
- workspace,
1100
- csvContent,
1101
- explicitDefaultsPath: defaultsPath
1102
- });
1103
- let resultJson;
1104
- try {
1105
- resultJson = deps.convertGeometryCsvToJson(
1106
- csvContent,
1107
- schemaJson,
1108
- defaults.defaultsJson
1109
- );
1110
- } catch (error) {
1111
- const err = error;
1112
- return {
1113
- ok: false,
1114
- error: `WASM conversion failed: ${err.message}`,
1115
- defaults_source: defaults.source,
1116
- defaults_path: defaults.path
1117
- };
1118
- }
1119
- if (!resultJson || typeof resultJson !== "string") {
1120
- return {
1121
- ok: false,
1122
- error: "WASM returned empty or invalid result",
1123
- defaults_source: defaults.source,
1124
- defaults_path: defaults.path
1125
- };
1126
- }
1127
- const result = parseConversionEnvelope(resultJson);
1128
- if (!result.ok || result.json === void 0 || result.json === null) {
1129
- return {
1130
- ok: false,
1131
- validation: result.validation,
1132
- error: result.error || "WASM conversion returned invalid result",
1133
- defaults_source: defaults.source,
1134
- defaults_path: defaults.path
1135
- };
1136
- }
1137
- return {
1138
- ok: true,
1139
- json: result.json,
1140
- validation: result.validation,
1141
- defaults_source: defaults.source,
1142
- defaults_path: defaults.path
1143
- };
1144
- }
1145
- async function mergeGeometryCsvToJson(options) {
1146
- const { workspace, csvPath, outputPath, schemaPath, defaultsPath, repoRoot, deps } = options;
1147
- const csvAbsPath = path8.isAbsolute(csvPath) ? csvPath : path8.join(workspace, csvPath);
1148
- let csvContent;
1149
- try {
1150
- csvContent = await fs8.readFile(csvAbsPath, "utf8");
1151
- } catch (error) {
1152
- const err = error;
1153
- if (err.code === "ENOENT") {
1154
- throw new Error(`CSV file not found at ${csvAbsPath}`);
1155
- }
1156
- throw new Error(`Failed to read CSV file: ${err.message}`);
1157
- }
1158
- const schema = await loadSchemaForCsv({
1159
- repoRoot: repoRoot ?? findRepoRoot(workspace),
1160
- workspace,
1161
- csvContent,
1162
- explicitSchemaPath: schemaPath
1163
- });
1164
- const conversion = await convertGeometryCsvWithPolicy({
1165
- workspace,
1166
- csvContent,
1167
- schemaJson: schema.schemaJson,
1168
- defaultsPath,
1169
- deps
1170
- });
1171
- if (!conversion.ok || conversion.json === void 0 || conversion.json === null) {
1172
- return {
1173
- ok: false,
1174
- validation: conversion.validation,
1175
- error: conversion.error || "WASM conversion returned invalid result",
1176
- defaults_source: conversion.defaults_source,
1177
- schema_source: schema.source
1178
- };
1179
- }
1180
- const outputAbsPath = outputPath ? path8.isAbsolute(outputPath) ? outputPath : path8.join(workspace, outputPath) : defaultJsonOutputPath(workspace, csvAbsPath);
1181
- await fs8.mkdir(path8.dirname(outputAbsPath), { recursive: true });
1182
- try {
1183
- await fs8.writeFile(outputAbsPath, JSON.stringify(conversion.json, null, 2), "utf8");
1184
- } catch (error) {
1185
- const err = error;
1186
- return {
1187
- ok: false,
1188
- validation: conversion.validation,
1189
- error: `Failed to write JSON file: ${err.message}`,
1190
- defaults_source: conversion.defaults_source,
1191
- schema_source: schema.source
1192
- };
1193
- }
1194
- return {
1195
- ok: true,
1196
- json_path: path8.relative(workspace, outputAbsPath),
1197
- validation: conversion.validation,
1198
- defaults_source: conversion.defaults_source,
1199
- schema_source: schema.source
1200
- };
1201
- }
1202
- function parseConversionEnvelope(resultJson) {
1203
- try {
1204
- return JSON.parse(resultJson);
1205
- } catch (error) {
1206
- const err = error;
1207
- return {
1208
- ok: false,
1209
- error: `WASM returned invalid JSON: ${err.message}`
1210
- };
1211
- }
1212
- }
1213
- function defaultJsonOutputPath(workspace, csvAbsPath) {
1214
- const csvBasename = path8.basename(csvAbsPath, path8.extname(csvAbsPath));
1215
- return path8.join(
1216
- workspace,
1217
- "input",
1218
- "batch_parameters",
1219
- "base_json",
1220
- `${csvBasename}.json`
1221
- );
1222
- }
1223
-
1224
- // ../packages/workspace-tools/src/parameters.ts
1225
- import fs9 from "fs/promises";
1226
- import path9 from "path";
1227
- async function listParameters(workspace, args = {}) {
1228
- const { category: filterCategory } = args;
1229
- const batchParamsDir = path9.join(workspace, "input", "batch_parameters");
1230
- const entries = await fs9.readdir(batchParamsDir, { withFileTypes: true });
1231
- const catalog = {};
1232
- for (const entry of entries) {
1233
- if (!entry.isDirectory()) continue;
1234
- const categoryName = entry.name;
1235
- if (filterCategory && categoryName !== filterCategory) continue;
1236
- const categoryPath = path9.join(batchParamsDir, categoryName);
1237
- const categoryFiles = await fs9.readdir(categoryPath);
1238
- const parameters = [];
1239
- for (const file of categoryFiles) {
1240
- if (!file.endsWith(".json")) continue;
1241
- const parameterId = file.replace(/\.json$/, "");
1242
- const filePath = path9.join(categoryPath, file);
1243
- try {
1244
- const content = await fs9.readFile(filePath, "utf8");
1245
- const json = JSON.parse(content);
1246
- parameters.push({
1247
- id: parameterId,
1248
- name: typeof json.name === "string" ? json.name : parameterId,
1249
- description: typeof json.description === "string" ? json.description : "",
1250
- category: categoryName
1251
- });
1252
- } catch (error) {
1253
- const err = error;
1254
- console.error(`Failed to parse ${filePath}: ${err.message}`);
1255
- }
1256
- }
1257
- if (parameters.length > 0) {
1258
- catalog[categoryName] = {
1259
- category: categoryName,
1260
- parameters: parameters.sort((a, b) => a.name.localeCompare(b.name))
1261
- };
1262
- }
1263
- }
1264
- return {
1265
- catalog,
1266
- total_categories: Object.keys(catalog).length,
1267
- total_parameters: Object.values(catalog).reduce(
1268
- (sum, category) => sum + category.parameters.length,
1269
- 0
1270
- )
1271
- };
1272
- }
1273
- async function viewParameter(workspace, args) {
1274
- const { category, parameter_id } = args;
1275
- if (!category) {
1276
- throw new Error("category is required");
1277
- }
1278
- if (!parameter_id) {
1279
- throw new Error("parameter_id is required");
1280
- }
1281
- const paramDir = path9.join(workspace, "input", "batch_parameters", category);
1282
- const jsonPath = path9.join(paramDir, `${parameter_id}.json`);
1283
- const markdownPath = path9.join(paramDir, `${parameter_id}.md`);
1284
- let jsonContent;
1285
- try {
1286
- const content = await fs9.readFile(jsonPath, "utf8");
1287
- jsonContent = JSON.parse(content);
1288
- } catch (error) {
1289
- const err = error;
1290
- if (err.code === "ENOENT") {
1291
- throw new Error(`Parameter '${parameter_id}' not found in category '${category}'`);
1292
- }
1293
- throw new Error(`Failed to read parameter JSON: ${err.message}`);
1294
- }
1295
- let markdownContent = null;
1296
- try {
1297
- markdownContent = await fs9.readFile(markdownPath, "utf8");
1298
- } catch (error) {
1299
- const err = error;
1300
- if (err.code !== "ENOENT") {
1301
- console.warn(`Failed to read markdown file: ${err.message}`);
1302
- }
1303
- }
1304
- return {
1305
- category,
1306
- parameter_id,
1307
- json: jsonContent,
1308
- markdown: markdownContent,
1309
- has_markdown: markdownContent !== null
1310
- };
1311
- }
1312
- async function saveParameter(workspace, args, deps) {
1313
- const { category, parameter_id, content, markdown_content } = args;
1314
- if (!category) {
1315
- throw new Error("category is required");
1316
- }
1317
- if (!parameter_id) {
1318
- throw new Error("parameter_id is required");
1319
- }
1320
- if (content === void 0 || content === null || content === "") {
1321
- throw new Error("content is required");
1322
- }
1323
- const jsonContent = parseContent(content);
1324
- const [schema, baseline, simplifiedExample] = await Promise.all([
1325
- loadSnippetSchema(workspace),
1326
- loadBaseline(workspace),
1327
- loadSimplifiedExample(workspace, category)
1328
- ]);
1329
- const validationResult = deps.validateSnippetJs(
1330
- category,
1331
- JSON.stringify(jsonContent),
1332
- JSON.stringify(schema),
1333
- JSON.stringify(baseline),
1334
- simplifiedExample ? JSON.stringify(simplifiedExample) : null
1335
- );
1336
- const validation = JSON.parse(validationResult);
1337
- if (!validation.ok) {
1338
- const errors = (validation.errors ?? []).map(
1339
- (error) => typeof error === "string" ? error : error.message || String(error)
1340
- );
1341
- return {
1342
- success: false,
1343
- valid: false,
1344
- errors,
1345
- message: `Validation failed: ${errors.join("; ")}`
1346
- };
1347
- }
1348
- const paramDir = path9.join(workspace, "input", "batch_parameters", category);
1349
- await fs9.mkdir(paramDir, { recursive: true });
1350
- const jsonPath = path9.join(paramDir, `${parameter_id}.json`);
1351
- await fs9.writeFile(jsonPath, JSON.stringify(jsonContent, null, 2), "utf8");
1352
- let markdownPath = null;
1353
- if (markdown_content) {
1354
- markdownPath = path9.join(paramDir, `${parameter_id}.md`);
1355
- await fs9.writeFile(markdownPath, markdown_content, "utf8");
1356
- }
1357
- return {
1358
- success: true,
1359
- valid: true,
1360
- errors: [],
1361
- message: `Parameter '${parameter_id}' saved successfully in category '${category}'`,
1362
- paths: {
1363
- json: jsonPath,
1364
- markdown: markdownPath
1365
- }
1366
- };
1367
- }
1368
- function parseContent(content) {
1369
- if (typeof content !== "string") {
1370
- return content;
1371
- }
1372
- try {
1373
- return JSON.parse(content);
1374
- } catch (error) {
1375
- throw new Error(`Invalid JSON syntax: ${error.message}`);
1376
- }
1377
- }
1378
- async function loadSnippetSchema(workspace) {
1379
- const schemaPaths = [
1380
- path9.join(workspace, "input_core.schema.json"),
1381
- path9.join(workspace, "hem_engine_upstream", "schemas", "core-input.schema.json"),
1382
- path9.join(workspace, "core-input.schema.json"),
1383
- path9.join(workspace, "schemas", "core-input.schema.json"),
1384
- path9.join(workspace, "input.schema.json")
1385
- ];
1386
- for (const schemaPath of schemaPaths) {
1387
- try {
1388
- return JSON.parse(await fs9.readFile(schemaPath, "utf8"));
1389
- } catch {
1390
- }
1391
- }
1392
- throw new Error(`Schema file not found. Tried: ${schemaPaths.join(", ")}`);
1393
- }
1394
- async function loadBaseline(workspace) {
1395
- const baselinePath = path9.join(
1396
- workspace,
1397
- "input",
1398
- "batch_parameters",
1399
- "base_json",
1400
- "demo_hp_annual.json"
1401
- );
1402
- try {
1403
- return JSON.parse(await fs9.readFile(baselinePath, "utf8"));
1404
- } catch (error) {
1405
- const err = error;
1406
- throw new Error(`Baseline model not found at ${baselinePath}: ${err.message}`);
1407
- }
1408
- }
1409
- async function loadSimplifiedExample(workspace, category) {
1410
- if (category !== "simplified_fabric") {
1411
- return null;
1412
- }
1413
- const examplePaths = [
1414
- path9.join(
1415
- workspace,
1416
- "input",
1417
- "batch_parameters",
1418
- "simplified_fabric",
1419
- "good_insulation_compliance.json"
1420
- ),
1421
- path9.join(
1422
- workspace,
1423
- "input",
1424
- "batch_parameters",
1425
- "simplified_fabric",
1426
- "compliance_example.json"
1427
- )
1428
- ];
1429
- for (const examplePath of examplePaths) {
1430
- try {
1431
- return JSON.parse(await fs9.readFile(examplePath, "utf8"));
1432
- } catch {
1433
- }
1434
- }
1435
- return null;
1436
- }
1437
-
1438
- // ../packages/workspace-tools/src/metrics.ts
1439
- import fs10 from "fs/promises";
1440
- import path10 from "path";
1441
- var CONDITIONAL_FUNCS = /* @__PURE__ */ new Set(["sumif", "averageif", "countif"]);
1442
- var VALID_COMPARATORS = /* @__PURE__ */ new Set([">=", "<=", ">", "<", "="]);
1443
- async function calculateMetrics(workspace, args, deps) {
1444
- const {
1445
- config_name,
1446
- model_names,
1447
- metric_definitions,
1448
- time_range,
1449
- tariff_file_path,
1450
- tariff_column_index
1451
- } = args;
1452
- if (!config_name) {
1453
- throw new Error("config_name is required");
1454
- }
1455
- if (!model_names || !Array.isArray(model_names) || model_names.length === 0) {
1456
- throw new Error("model_names is required and must be a non-empty array");
1457
- }
1458
- if (!metric_definitions || !Array.isArray(metric_definitions) || metric_definitions.length === 0) {
1459
- throw new Error("metric_definitions is required and must be a non-empty array");
1460
- }
1461
- const outputDir = path10.join(workspace, "output");
1462
- const cleanConfigName = config_name.replace(/\.json$/, "");
1463
- const { encodedMetrics, metadata: metricMetadata } = formatMetricDefinitions(metric_definitions);
1464
- const hasCostMetric = metricMetadata.some(
1465
- (metric) => metric.function.toLowerCase() === "cost"
1466
- );
1467
- if (hasCostMetric && (!tariff_file_path || tariff_column_index === void 0)) {
1468
- throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");
1469
- }
1470
- let tariffJson;
1471
- if (tariff_file_path && tariff_column_index !== void 0) {
1472
- const tariffRates = await loadTariffData(tariff_file_path, tariff_column_index, workspace);
1473
- tariffJson = JSON.stringify(tariffRates);
1474
- }
1475
- const allResults = [];
1476
- for (const modelName of model_names) {
1477
- const { csvPath, csvContent } = await readModelCsv({
1478
- outputDir,
1479
- cleanConfigName,
1480
- modelName
1481
- });
1482
- try {
1483
- const coreResultsData = parseCoreResults(csvContent, modelName, config_name);
1484
- if (coreResultsData.timestamps.length === 0) {
1485
- throw new Error(`No timestamps found in CSV for model ${modelName}`);
1486
- }
1487
- if (Object.keys(coreResultsData.columns).length === 0) {
1488
- throw new Error(`No columns found in CSV for model ${modelName}`);
1489
- }
1490
- const missingColumns = missingMetricColumns(coreResultsData, encodedMetrics, metricMetadata);
1491
- if (missingColumns.length > 0) {
1492
- const availableColumns = Object.keys(coreResultsData.columns).slice(0, 10);
1493
- throw new Error(
1494
- `Columns not found in CSV: ${missingColumns.join(", ")}. Available columns: ${availableColumns.join(", ")}...`
1495
- );
1496
- }
1497
- const resultJson = deps.calculateMetricsFromParsedData(
1498
- JSON.stringify(coreResultsData),
1499
- JSON.stringify(encodedMetrics),
1500
- time_range ? JSON.stringify(time_range) : void 0,
1501
- tariffJson
1502
- );
1503
- if (!resultJson || typeof resultJson !== "string") {
1504
- throw new Error(`WASM returned invalid result: ${typeof resultJson}`);
1505
- }
1506
- const results = JSON.parse(resultJson);
1507
- if (!Array.isArray(results)) {
1508
- throw new Error(`WASM returned non-array result: ${typeof results}`);
1509
- }
1510
- results.forEach((result, index) => {
1511
- const meta = metricMetadata[index];
1512
- const [resultColumn = result.name, resultFunction = "sum"] = result.name.split("|");
1513
- allResults.push({
1514
- id: meta?.id || result.name,
1515
- name: meta?.name || result.name,
1516
- column: meta?.column || resultColumn,
1517
- function: meta?.function || resultFunction,
1518
- comparator: meta?.comparator,
1519
- threshold: meta?.threshold,
1520
- value: result.value,
1521
- model_name: modelName
1522
- });
1523
- });
1524
- } catch (error) {
1525
- const err = error;
1526
- if (err.code === "ENOENT") {
1527
- console.warn(`CSV file not found for model ${modelName}: ${csvPath}`);
1528
- continue;
1529
- }
1530
- throw new Error(`Failed to process model ${modelName}: ${err.message}`);
1531
- }
1532
- }
1533
- return {
1534
- metrics: allResults,
1535
- total_models: model_names.length,
1536
- total_metrics: allResults.length
1537
- };
1538
- }
1539
- function parseCoreResults(csvContent, modelName, configName) {
1540
- const lines = csvContent.split("\n").filter((line) => line.trim());
1541
- if (lines.length < 2) {
1542
- throw new Error("CSV must have at least headers and units rows");
1543
- }
1544
- const headers = (lines[0] ?? "").split(",").map((header) => header.trim());
1545
- const units = (lines[1] ?? "").split(",").map((unit) => unit.trim());
1546
- const timestamps = [];
1547
- const columnsMap = {};
1548
- const columnOrder = [];
1549
- const columnUnits = [];
1550
- for (let i = 1; i < headers.length; i += 1) {
1551
- const header = headers[i];
1552
- if (!header) continue;
1553
- columnsMap[header] = [];
1554
- columnOrder.push(header);
1555
- columnUnits.push(i < units.length ? units[i] || "" : "");
1556
- }
1557
- for (let rowIndex = 2; rowIndex < lines.length; rowIndex += 1) {
1558
- const row = (lines[rowIndex] ?? "").split(",").map((value) => value.trim());
1559
- if (row.length === 0 || row.length === 1 && !row[0]) continue;
1560
- const tsValue = row[0];
1561
- if (!tsValue) continue;
1562
- const timestep = Number.parseInt(tsValue, 10);
1563
- if (Number.isNaN(timestep) || timestep < 0) continue;
1564
- timestamps.push(timestep);
1565
- for (let colIndex = 1; colIndex < headers.length && colIndex < row.length; colIndex += 1) {
1566
- const header = headers[colIndex];
1567
- if (!header || !columnsMap[header]) continue;
1568
- const rowValue = row[colIndex];
1569
- if (rowValue === void 0) continue;
1570
- const value = Number.parseFloat(rowValue);
1571
- columnsMap[header].push(Number.isNaN(value) ? 0 : value);
1572
- }
1573
- }
1574
- return {
1575
- timestamps,
1576
- columns: columnsMap,
1577
- column_order: columnOrder,
1578
- column_units: columnUnits,
1579
- metadata: {
1580
- model_name: modelName,
1581
- config_name: configName.replace(/\.json$/, ""),
1582
- total_points: timestamps.length,
1583
- sample_rate: 1800
1584
- },
1585
- dwelling_emission_rate: null,
1586
- dwelling_primary_energy_rate: null,
1587
- dwelling_fabric_energy_efficiency: null
1588
- };
1589
- }
1590
- function buildFunctionSegment(definition) {
1591
- const rawFunction = (definition.function || definition.type || "sum").toString();
1592
- const normalized = rawFunction.toLowerCase();
1593
- if (normalized === "cost") {
1594
- return "cost";
1595
- }
1596
- if (!CONDITIONAL_FUNCS.has(normalized)) {
1597
- return normalized;
1598
- }
1599
- const comparator = definition.comparator || ">=";
1600
- if (!VALID_COMPARATORS.has(comparator)) {
1601
- throw new Error(
1602
- `Invalid comparator "${comparator}" for ${rawFunction}. Use one of ${Array.from(VALID_COMPARATORS).join(", ")}`
1603
- );
1604
- }
1605
- if (definition.threshold === void 0 || definition.threshold === null || Number.isNaN(Number(definition.threshold))) {
1606
- throw new Error(`threshold is required for ${rawFunction} metrics`);
1607
- }
1608
- return `${normalized}${comparator}${definition.threshold}`;
1609
- }
1610
- function formatMetricDefinitions(metricDefinitions) {
1611
- const encodedMetrics = [];
1612
- const metadata = [];
1613
- metricDefinitions.forEach((definition, index) => {
1614
- if (typeof definition === "string") {
1615
- const encoded2 = definition.includes("|") ? definition : `${definition}|sum`;
1616
- const [column2 = definition, fn = "sum"] = encoded2.split("|");
1617
- encodedMetrics.push({ name: encoded2 });
1618
- metadata.push({
1619
- id: definition,
1620
- name: definition,
1621
- column: column2,
1622
- function: fn,
1623
- isCompliance: fn.toLowerCase() === "compliance"
1624
- });
1625
- return;
1626
- }
1627
- const column = definition.column || (definition.name?.includes("|") ? definition.name.split("|")[0] : definition.name);
1628
- if (!column) {
1629
- throw new Error(`Metric definition at index ${index} missing column or name. Got: ${JSON.stringify(definition)}`);
1630
- }
1631
- const functionSegment = definition.name?.includes("|") && !definition.function ? definition.name.split("|")[1] || "sum" : buildFunctionSegment(definition);
1632
- const encoded = `${column}|${functionSegment}`;
1633
- encodedMetrics.push({ name: encoded });
1634
- metadata.push({
1635
- id: definition.id || definition.metric_id || `${column}_${functionSegment}`,
1636
- name: definition.name || definition.id || column,
1637
- column,
1638
- function: functionSegment,
1639
- comparator: definition.comparator,
1640
- threshold: definition.threshold,
1641
- isCompliance: functionSegment.toLowerCase() === "compliance"
1642
- });
1643
- });
1644
- return { encodedMetrics, metadata };
1645
- }
1646
- async function loadTariffData(tariffFilePath, columnIndex, workspacePath) {
1647
- const resolvedPath = path10.isAbsolute(tariffFilePath) ? tariffFilePath : path10.resolve(workspacePath, tariffFilePath);
1648
- const csvContent = await fs10.readFile(resolvedPath, "utf8").catch((error) => {
1649
- throw new Error(`Failed to read tariff file: ${resolvedPath}. Error: ${error.message}`);
1650
- });
1651
- const lines = csvContent.split("\n").filter((line) => line.trim());
1652
- if (lines.length === 0) {
1653
- throw new Error(`Tariff file is empty: ${resolvedPath}`);
1654
- }
1655
- const rates = [];
1656
- for (let i = 1; i < lines.length; i += 1) {
1657
- const columns = (lines[i] ?? "").split(",").map((column) => column.trim().replace(/"/g, ""));
1658
- if (columnIndex >= columns.length) {
1659
- throw new Error(`Column index ${columnIndex} not found in record ${i} with ${columns.length} columns`);
1660
- }
1661
- const raw = columns[columnIndex];
1662
- if (raw === void 0) {
1663
- throw new Error(`Column index ${columnIndex} is undefined in record ${i}`);
1664
- }
1665
- const parsed = Number.parseFloat(raw);
1666
- if (Number.isNaN(parsed)) {
1667
- throw new Error(`Could not parse '${raw}' as number in row ${i + 1}, column ${columnIndex + 1}`);
1668
- }
1669
- rates.push(parsed);
1670
- }
1671
- if (rates.length !== 17520) {
1672
- throw new Error(`Tariff must contain 17,520 rows (found ${rates.length})`);
1673
- }
1674
- return rates;
1675
- }
1676
- async function readModelCsv(args) {
1677
- const { outputDir, cleanConfigName, modelName } = args;
1678
- const candidates = [
1679
- path10.join(outputDir, cleanConfigName, `${modelName}__core__results.csv`),
1680
- path10.join(outputDir, cleanConfigName, `${modelName}__results.csv`)
1681
- ];
1682
- try {
1683
- const files = await fs10.readdir(outputDir);
1684
- const resultDirs = files.filter((file) => file.startsWith(`result_${cleanConfigName}_`));
1685
- for (const resultDir of resultDirs) {
1686
- candidates.push(path10.join(outputDir, resultDir, `${modelName}__core__results.csv`));
1687
- candidates.push(path10.join(outputDir, resultDir, `${modelName}__results.csv`));
1688
- }
1689
- } catch {
1690
- }
1691
- for (const csvPath of candidates) {
1692
- try {
1693
- return {
1694
- csvPath,
1695
- csvContent: await fs10.readFile(csvPath, "utf8")
1696
- };
1697
- } catch {
1698
- }
1699
- }
1700
- throw new Error(`CSV file not found for model ${modelName}. Tried: ${candidates.join(", ")}`);
1701
- }
1702
- function missingMetricColumns(coreResultsData, encodedMetrics, metricMetadata) {
1703
- const missingColumns = [];
1704
- encodedMetrics.forEach((metric, index) => {
1705
- const columnName = metric.name.split("|")[0];
1706
- if (!columnName) {
1707
- throw new Error(`Invalid metric name format: ${metric.name}`);
1708
- }
1709
- if (metricMetadata[index]?.isCompliance) {
1710
- return;
1711
- }
1712
- if (!coreResultsData.columns[columnName]) {
1713
- missingColumns.push(columnName);
1714
- }
1715
- });
1716
- return missingColumns;
1717
- }
1718
-
1719
- // ../packages/workspace-tools/src/results.ts
1720
- import fs11 from "fs/promises";
1721
- import path11 from "path";
1722
- async function listBatchModels(workspace, args) {
1723
- const outputDir = path11.join(workspace, "output");
1724
- const cleanConfigName = cleanConfigStem(args.config_name);
1725
- const models = [];
1726
- const modelNamesSet = /* @__PURE__ */ new Set();
1727
- try {
1728
- const configOutputDir = path11.join(outputDir, cleanConfigName);
1729
- if (await pathExists(configOutputDir)) {
1730
- await collectModelResultFiles(configOutputDir, models, modelNamesSet);
1731
- }
1732
- const filesInOutputDir = await fs11.readdir(outputDir);
1733
- const resultDirs = filesInOutputDir.filter(
1734
- (file) => file.startsWith(`result_${cleanConfigName}_`)
1735
- );
1736
- for (const resultDir of resultDirs) {
1737
- const resultDirPath = path11.join(outputDir, resultDir);
1738
- try {
1739
- await collectModelResultFiles(resultDirPath, models, modelNamesSet);
1740
- } catch (error) {
1741
- console.warn(
1742
- `Failed to read result directory ${resultDir}: ${error.message}`
1743
- );
1744
- }
1745
- }
1746
- models.sort((a, b) => a.name.localeCompare(b.name));
1747
- return {
1748
- config_name: cleanConfigName,
1749
- models,
1750
- total_models: models.length,
1751
- output_dir: outputDir
1752
- };
1753
- } catch (error) {
1754
- return {
1755
- config_name: cleanConfigName,
1756
- models: [],
1757
- total_models: 0,
1758
- output_dir: outputDir,
1759
- error: `Failed to list models: ${error.message}`
1760
- };
1761
- }
1762
- }
1763
- async function listCsvColumns(workspace, args) {
1764
- const outputDir = path11.join(workspace, "output");
1765
- const cleanConfigName = cleanConfigStem(args.config_name);
1766
- const potentialCsvPaths = [
1767
- path11.join(outputDir, cleanConfigName, `${args.model_name}__core__results.csv`),
1768
- path11.join(outputDir, cleanConfigName, `${args.model_name}__results.csv`)
1769
- ];
1770
- try {
1771
- const filesInOutputDir = await fs11.readdir(outputDir);
1772
- const resultDirs = filesInOutputDir.filter(
1773
- (file) => file.startsWith(`result_${cleanConfigName}_`)
1774
- );
1775
- for (const resultDir of resultDirs) {
1776
- potentialCsvPaths.push(
1777
- path11.join(outputDir, resultDir, `${args.model_name}__core__results.csv`)
1778
- );
1779
- potentialCsvPaths.push(
1780
- path11.join(outputDir, resultDir, `${args.model_name}__results.csv`)
1781
- );
1782
- }
1783
- } catch {
1784
- }
1785
- let csvPath;
1786
- let csvContent;
1787
- for (const candidatePath of potentialCsvPaths) {
1788
- if (!await pathExists(candidatePath)) continue;
1789
- csvPath = candidatePath;
1790
- try {
1791
- csvContent = await fs11.readFile(csvPath, "utf8");
1792
- break;
1793
- } catch (error) {
1794
- console.warn(`Failed to read CSV from ${candidatePath}: ${error.message}`);
1795
- }
1796
- }
1797
- if (!csvContent || !csvPath) {
1798
- return {
1799
- config_name: cleanConfigName,
1800
- model_name: args.model_name,
1801
- columns: [],
1802
- total_columns: 0,
1803
- error: `CSV file not found for model ${args.model_name}. Tried: ${potentialCsvPaths.join(", ")}`
1804
- };
1805
- }
1806
- const lines = csvContent.split("\n").filter((line) => line.trim());
1807
- if (lines.length < 2) {
1808
- return {
1809
- config_name: cleanConfigName,
1810
- model_name: args.model_name,
1811
- columns: [],
1812
- total_columns: 0,
1813
- csv_path: csvPath,
1814
- error: "CSV must have at least headers and units rows"
1815
- };
1816
- }
1817
- const headers = parseCsvLine3(lines[0] ?? "").map((header) => header.trim());
1818
- const units = parseCsvLine3(lines[1] ?? "").map((unit) => unit.trim());
1819
- const columns = [];
1820
- for (let i = 1; i < headers.length; i += 1) {
1821
- const header = headers[i];
1822
- const unit = i < units.length ? units[i] : "";
1823
- if (!header) continue;
1824
- columns.push({
1825
- name: header,
1826
- unit: unit || "",
1827
- index: i - 1
1828
- });
1829
- }
1830
- return {
1831
- config_name: cleanConfigName,
1832
- model_name: args.model_name,
1833
- columns,
1834
- total_columns: columns.length,
1835
- csv_path: csvPath
1836
- };
1837
- }
1838
- async function collectModelResultFiles(resultDirPath, models, modelNamesSet) {
1839
- const files = await fs11.readdir(resultDirPath);
1840
- for (const file of files) {
1841
- const match = file.match(/^(.+?)__(?:core__)?results\.csv$/);
1842
- if (!match?.[1]) continue;
1843
- const modelName = match[1];
1844
- if (modelNamesSet.has(modelName)) continue;
1845
- modelNamesSet.add(modelName);
1846
- models.push({
1847
- name: modelName,
1848
- csv_path: path11.join(resultDirPath, file),
1849
- has_results: true
1850
- });
1851
- }
1852
- }
1853
- function cleanConfigStem(configName) {
1854
- return configName.replace(/\.json$/, "");
1855
- }
1856
- async function pathExists(filePath) {
1857
- try {
1858
- await fs11.access(filePath);
1859
- return true;
1860
- } catch {
1861
- return false;
1862
- }
1863
- }
1864
- function parseCsvLine3(line) {
1865
- const result = [];
1866
- let current = "";
1867
- let inQuotes = false;
1868
- for (let i = 0; i < line.length; i += 1) {
1869
- const ch = line[i];
1870
- if (inQuotes) {
1871
- if (ch === '"') {
1872
- if (line[i + 1] === '"') {
1873
- current += '"';
1874
- i += 1;
1875
- } else {
1876
- inQuotes = false;
1877
- }
1878
- } else {
1879
- current += ch;
1880
- }
1881
- } else if (ch === '"') {
1882
- inQuotes = true;
1883
- } else if (ch === ",") {
1884
- result.push(current);
1885
- current = "";
1886
- } else {
1887
- current += ch;
1888
- }
1889
- }
1890
- result.push(current);
1891
- return result;
1892
- }
1893
-
1894
- // ../packages/workspace-tools/src/validation.ts
1895
- import { spawn } from "child_process";
1896
- import path12 from "path";
1897
- async function validateGeometryCsv(args) {
1898
- const repoRoot = resolveRepoRoot(args);
1899
- const failOn = args.failOn ?? "critical";
1900
- const csvPath = path12.resolve(args.csvPath);
1901
- const run = await runCommand(args, "npm", [
1902
- "run",
1903
- "--silent",
1904
- "validate:geometry-csv",
1905
- "--",
1906
- csvPath,
1907
- "--json",
1908
- `--fail-on=${failOn}`
1909
- ]);
1910
- const parsed = parseJsonStdout(run);
1911
- const parsedRecord = isRecord(parsed) ? parsed : void 0;
1912
- return {
1913
- ok: run.exitCode === 0 && parsedRecord !== void 0,
1914
- command: "geometry validate",
1915
- csv_path: csvPath,
1916
- repo_root: repoRoot,
1917
- fail_on: failOn,
1918
- exit_code: run.exitCode,
1919
- signal: run.signal,
1920
- stdout: run.stdout,
1921
- stderr: run.stderr,
1922
- parsed: parsedRecord,
1923
- counts: isRecord(parsedRecord?.counts) ? parsedRecord.counts : void 0,
1924
- critical_issues: Array.isArray(parsedRecord?.criticalIssues) ? parsedRecord.criticalIssues : void 0,
1925
- warnings: Array.isArray(parsedRecord?.warnings) ? parsedRecord.warnings : void 0,
1926
- missing_elements: Array.isArray(parsedRecord?.missingElements) ? parsedRecord.missingElements : void 0,
1927
- error: parsedRecord === void 0 ? jsonParseError(run) : void 0
1928
- };
1929
- }
1930
- async function generateAutoThermalBridges(args) {
1931
- const repoRoot = resolveRepoRoot(args);
1932
- const mode = args.mode ?? "summary";
1933
- const csvPath = path12.resolve(args.csvPath);
1934
- const run = await runCommand(args, "npx", [
1935
- "vite-node",
1936
- "scripts/auto-tb-cli.ts",
1937
- csvPath,
1938
- modeFlag(mode)
1939
- ]);
1940
- const parsed = mode === "json" ? parseJsonStdout(run) : void 0;
1941
- return {
1942
- ok: run.exitCode === 0 && (mode !== "json" || parsed !== void 0),
1943
- command: "thermal-bridges auto",
1944
- csv_path: csvPath,
1945
- repo_root: repoRoot,
1946
- mode,
1947
- exit_code: run.exitCode,
1948
- signal: run.signal,
1949
- stdout: run.stdout,
1950
- stderr: run.stderr,
1951
- parsed,
1952
- proposal_count: Array.isArray(parsed) ? parsed.length : void 0,
1953
- error: mode === "json" && parsed === void 0 ? jsonParseError(run) : void 0
1954
- };
1955
- }
1956
- async function validateThermalBridges(args) {
1957
- const repoRoot = resolveRepoRoot(args);
1958
- const mode = args.mode ?? "summary";
1959
- const includeAuto = args.includeAuto === true;
1960
- const csvPath = path12.resolve(args.csvPath);
1961
- const scriptArgs = [
1962
- "vite-node",
1963
- "scripts/validate-tb-cli.ts",
1964
- csvPath,
1965
- ...includeAuto ? ["--with-auto"] : [],
1966
- modeFlag(mode)
1967
- ];
1968
- const run = await runCommand(args, "npx", scriptArgs);
1969
- const parsed = mode === "json" ? parseJsonStdout(run) : void 0;
1970
- const parsedRecord = isRecord(parsed) ? parsed : void 0;
1971
- return {
1972
- ok: run.exitCode === 0 && (mode !== "json" || parsedRecord !== void 0),
1973
- command: "thermal-bridges validate",
1974
- csv_path: csvPath,
1975
- repo_root: repoRoot,
1976
- include_auto: includeAuto,
1977
- mode,
1978
- exit_code: run.exitCode,
1979
- signal: run.signal,
1980
- stdout: run.stdout,
1981
- stderr: run.stderr,
1982
- parsed: parsedRecord,
1983
- issue_count: typeof parsedRecord?.issueCount === "number" ? parsedRecord.issueCount : void 0,
1984
- thermal_bridge_linear_rows: typeof parsedRecord?.thermalBridgeLinearRows === "number" ? parsedRecord.thermalBridgeLinearRows : void 0,
1985
- error: mode === "json" && parsedRecord === void 0 ? jsonParseError(run) : void 0
1986
- };
1987
- }
1988
- function resolveRepoRoot(args) {
1989
- return path12.resolve(args.repoRoot ?? findRepoRoot(args.csvPath));
1990
- }
1991
- async function runCommand(args, command, commandArgs) {
1992
- const repoRoot = resolveRepoRoot(args);
1993
- const runner = args.runner ?? defaultCommandRunner;
1994
- return runner(command, commandArgs, { cwd: repoRoot });
1995
- }
1996
- function modeFlag(mode) {
1997
- return `--${mode}`;
1998
- }
1999
- function parseJsonStdout(run) {
2000
- try {
2001
- return JSON.parse(run.stdout);
2002
- } catch {
2003
- return void 0;
2004
- }
2005
- }
2006
- function jsonParseError(run) {
2007
- const suffix = run.stderr.trim() ? ` stderr: ${run.stderr.trim()}` : "";
2008
- return `Expected JSON output from validation CLI.${suffix}`;
2009
- }
2010
- function isRecord(value) {
2011
- return typeof value === "object" && value !== null && !Array.isArray(value);
2012
- }
2013
- var defaultCommandRunner = (command, args, options) => new Promise((resolve, reject) => {
2014
- const child = spawn(command, [...args], {
2015
- cwd: options.cwd,
2016
- shell: false,
2017
- stdio: ["ignore", "pipe", "pipe"]
2018
- });
2019
- let stdout = "";
2020
- let stderr = "";
2021
- child.stdout.setEncoding("utf8");
2022
- child.stderr.setEncoding("utf8");
2023
- child.stdout.on("data", (chunk) => {
2024
- stdout += chunk;
2025
- });
2026
- child.stderr.on("data", (chunk) => {
2027
- stderr += chunk;
2028
- });
2029
- child.on("error", reject);
2030
- child.on("close", (exitCode, signal) => {
2031
- resolve({ exitCode, signal, stdout, stderr });
2032
- });
2033
- });
2034
-
2035
- // src/tools/listParameters.ts
2036
- async function listParameters2(config, args = {}) {
2037
- return listParameters(config.workspace, args);
2038
- }
2039
-
2040
- // src/tools/viewParameter.ts
2041
- async function viewParameter2(config, args) {
2042
- return viewParameter(config.workspace, args);
2043
- }
2044
-
2045
- // src/tools/saveParameter.ts
2046
- async function saveParameter2(config, args) {
2047
- let wasm;
2048
- try {
2049
- await initWasm();
2050
- wasm = getWasmModule();
2051
- } catch (error) {
2052
- const err = error;
2053
- throw new Error(`WASM initialization failed: ${err.message}`);
2054
- }
2055
- if (!wasm.validate_snippet_js) {
2056
- throw new Error("WASM validate_snippet_js function not available");
2057
- }
2058
- return saveParameter(config.workspace, args, {
2059
- validateSnippetJs: wasm.validate_snippet_js.bind(wasm)
2060
- });
2061
- }
2062
-
2063
- // src/tools/createBatchConfig.ts
2064
- async function createBatchConfig2(config, args) {
2065
- return createBatchConfig(config.workspace, args);
2066
- }
2067
-
2068
- // src/tools/runBatch.ts
2069
- import { randomUUID as randomUUID2 } from "crypto";
2070
- async function runBatch2(config, args) {
2071
- const { workspace } = config;
2072
- const { config_name } = args;
2073
- if (!config_name) {
2074
- throw new Error("config_name is required");
2075
- }
2076
- const finalJobId = args.job_id || `mcp_${randomUUID2()}`;
2077
- let wasm;
2078
- try {
2079
- await initWasm();
2080
- wasm = getWasmModule();
2081
- } catch (error) {
2082
- const err = error;
2083
- return {
2084
- job_id: finalJobId,
2085
- status: "error",
2086
- message: `WASM initialization failed: ${err.message}`,
2087
- error: err.message
2088
- };
2089
- }
2090
- if (!wasm.process_batch_config) {
2091
- return {
2092
- job_id: finalJobId,
2093
- status: "error",
2094
- message: "WASM process_batch_config function not available",
2095
- error: "WASM function missing"
2096
- };
2097
- }
2098
- setWorkspace(workspace);
2099
- return runBatch(workspace, { ...args, job_id: finalJobId }, {
2100
- processBatchConfig: wasm.process_batch_config.bind(wasm)
2101
- });
2102
- }
2103
-
2104
- // src/tools/getBatchStatus.ts
2105
- async function getBatchStatus2(config, args = {}) {
2106
- return getBatchStatus(config.workspace, args);
2107
- }
2108
-
2109
- // src/tools/calculateMetrics.ts
2110
- async function calculateMetrics2(config, args) {
2111
- let wasm;
2112
- try {
2113
- await initWasm();
2114
- wasm = getWasmModule();
2115
- } catch (error) {
2116
- const err = error;
2117
- throw new Error(`WASM initialization failed: ${err.message}`);
2118
- }
2119
- if (!wasm.calculate_metrics_from_parsed_data) {
2120
- throw new Error("WASM calculate_metrics_from_parsed_data function not available");
2121
- }
2122
- return calculateMetrics(config.workspace, args, {
2123
- calculateMetricsFromParsedData: wasm.calculate_metrics_from_parsed_data.bind(wasm)
2124
- });
2125
- }
2126
-
2127
- // src/tools/listCsvColumns.ts
2128
- async function listCsvColumns2(config, args) {
2129
- return listCsvColumns(config.workspace, args);
2130
- }
2131
-
2132
- // src/tools/listBatchModels.ts
2133
- async function listBatchModels2(config, args) {
2134
- return listBatchModels(config.workspace, args);
2135
- }
2136
-
2137
- // src/tools/mergeCsvToJson.ts
2138
- async function mergeCsvToJson(config, args) {
2139
- const { workspace } = config;
2140
- const { csv_path, output_path, schema_path, defaults_path } = args;
2141
- if (!csv_path) {
2142
- throw new Error("csv_path is required");
2143
- }
2144
- let wasm;
2145
- try {
2146
- await initWasm();
2147
- wasm = getWasmModule();
2148
- } catch (error) {
2149
- const err = error;
2150
- return {
2151
- ok: false,
2152
- error: `WASM initialization failed: ${err.message}`
2153
- };
2154
- }
2155
- if (!wasm.convert_geometry_csv_to_json) {
2156
- return {
2157
- ok: false,
2158
- error: "WASM convert_geometry_csv_to_json function not available"
2159
- };
2160
- }
2161
- setWorkspace(workspace);
2162
- return mergeGeometryCsvToJson({
2163
- workspace,
2164
- csvPath: csv_path,
2165
- outputPath: output_path,
2166
- schemaPath: schema_path,
2167
- defaultsPath: defaults_path,
2168
- deps: {
2169
- convertGeometryCsvToJson: wasm.convert_geometry_csv_to_json.bind(wasm)
2170
- }
2171
- });
2172
- }
2173
-
2174
- // src/tools/validateGeometryCsv.ts
2175
- import path13 from "path";
2176
- async function validateGeometryCsv2(config, args) {
2177
- return validateGeometryCsv({
2178
- csvPath: path13.isAbsolute(args.csv_path) ? args.csv_path : path13.join(config.workspace, args.csv_path),
2179
- failOn: args.fail_on,
2180
- repoRoot: process.cwd()
2181
- });
2182
- }
2183
-
2184
- // src/tools/autoThermalBridges.ts
2185
- import path14 from "path";
2186
- async function generateAutoThermalBridges2(config, args) {
2187
- return generateAutoThermalBridges({
2188
- csvPath: path14.isAbsolute(args.csv_path) ? args.csv_path : path14.join(config.workspace, args.csv_path),
2189
- mode: args.mode,
2190
- repoRoot: process.cwd()
2191
- });
2192
- }
2193
-
2194
- // src/tools/validateThermalBridges.ts
2195
- import path15 from "path";
2196
- async function validateThermalBridges2(config, args) {
2197
- return validateThermalBridges({
2198
- csvPath: path15.isAbsolute(args.csv_path) ? args.csv_path : path15.join(config.workspace, args.csv_path),
2199
- includeAuto: args.include_auto,
2200
- mode: args.mode,
2201
- repoRoot: process.cwd()
2202
- });
2203
- }
2204
-
2205
- // src/tools/index.ts
2206
- var toolSchemas = {
2207
- vulcan_list_parameters: z.object({
2208
- category: z.string().optional().describe('Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")')
2209
- }),
2210
- vulcan_view_parameter: z.object({
2211
- category: z.string().describe('Parameter category (e.g., "heat_source_wet", "controls", "base_json")'),
2212
- parameter_id: z.string().describe("Parameter ID (filename without .json extension)")
2213
- }),
2214
- vulcan_save_parameter: z.object({
2215
- category: z.string().describe('Parameter category (e.g., "heat_source_wet", "controls")'),
2216
- parameter_id: z.string().describe("Parameter ID (filename without .json extension)"),
2217
- content: z.record(z.string(), z.any()).describe("Parameter JSON content (must be valid JSON object)"),
2218
- markdown_content: z.string().optional().describe("Optional markdown documentation for the parameter")
2219
- }),
2220
- vulcan_create_batch_config: z.object({
2221
- config_name: z.string().describe("Configuration name (will be saved as {config_name}.json)"),
2222
- base_model: z.string().describe("Base model filename (without .json extension)"),
2223
- weather_file: z.string().describe("Weather file name (with or without .epw extension)"),
2224
- wrapper: z.string().optional().describe('Optional model wrapper (e.g., "fhs_compliance", "passthrough")'),
2225
- parameters: z.preprocess((params) => {
2226
- if (!params || typeof params !== "object" || Array.isArray(params)) {
2227
- return params;
2228
- }
2229
- return Object.fromEntries(
2230
- Object.entries(params).map(([key, value]) => {
2231
- if (typeof value === "string") {
2232
- try {
2233
- const parsed = JSON.parse(value);
2234
- return [key, Array.isArray(parsed) ? parsed : [parsed]];
2235
- } catch {
2236
- return [key, [value]];
2237
- }
2238
- }
2239
- return [key, Array.isArray(value) ? value : [value]];
2240
- })
2241
- );
2242
- }, z.record(z.string(), z.array(z.string()))).describe("Object mapping category to array of parameter IDs")
2243
- }),
2244
- vulcan_run_batch: z.object({
2245
- config_name: z.string().describe("Configuration name (with or without .json extension)"),
2246
- job_id: z.string().optional().describe("Optional custom job ID (defaults to mcp_{uuid})")
2247
- }),
2248
- vulcan_get_batch_status: z.object({
2249
- job_id: z.string().optional().describe("Job ID returned from vulcan_run_batch"),
2250
- config_name: z.string().optional().describe("Configuration name (alternative to job_id, since config names are unique)")
2251
- }).refine((data) => data.job_id || data.config_name, {
2252
- message: "Either job_id or config_name must be provided"
2253
- }),
2254
- vulcan_calculate_metrics: z.object({
2255
- config_name: z.string().describe("Configuration name (with or without .json extension)"),
2256
- model_names: z.array(z.string()).describe("Array of model names to calculate metrics for"),
2257
- metric_definitions: z.array(z.object({
2258
- id: z.string().optional(),
2259
- name: z.string().optional(),
2260
- column: z.string().optional(),
2261
- function: z.enum(["sum", "average", "peak", "min", "cost", "sumIf", "averageIf", "countIf"]).optional(),
2262
- comparator: z.string().optional(),
2263
- threshold: z.number().optional()
2264
- })).describe("Array of metric definitions"),
2265
- time_range: z.object({
2266
- start: z.number().optional(),
2267
- end: z.number().optional()
2268
- }).optional().describe("Optional time range filter"),
2269
- tariff_file_path: z.string().optional().describe("Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."),
2270
- tariff_column_index: z.number().optional().describe("Zero-based index of tariff column in CSV. Required for cost metrics.")
2271
- }),
2272
- vulcan_list_csv_columns: z.object({
2273
- config_name: z.string().describe("Configuration name (with or without .json extension)"),
2274
- model_name: z.string().describe('Model name (e.g., "scenario_1_0")')
2275
- }),
2276
- vulcan_list_batch_models: z.object({
2277
- config_name: z.string().describe("Configuration name (with or without .json extension)")
2278
- }),
2279
- vulcan_merge_csv_to_json: z.object({
2280
- csv_path: z.string().describe("Path to CSV file (relative to workspace or absolute)"),
2281
- output_path: z.string().optional().describe("Optional: output JSON path (defaults to input/batch_parameters/base_json/{csv_filename}.json)"),
2282
- schema_path: z.string().optional().describe("Optional: custom schema path (defaults to the core schema with workspace fallbacks)"),
2283
- defaults_path: z.string().optional().describe("Optional: custom defaults path. Declared paths must load; standard defaults are used only for legacy CSVs without DefaultsPath.")
2284
- }),
2285
- vulcan_validate_geometry_csv: z.object({
2286
- csv_path: z.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),
2287
- fail_on: z.enum(["none", "critical", "warning"]).optional().describe("Validation exit policy for the wrapped CLI. Defaults to critical.")
2288
- }),
2289
- vulcan_auto_thermal_bridges: z.object({
2290
- csv_path: z.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),
2291
- mode: z.enum(["summary", "json", "csv-section"]).optional().describe("Wrapped auto-TB CLI output mode. Defaults to summary.")
2292
- }),
2293
- vulcan_validate_thermal_bridges: z.object({
2294
- csv_path: z.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),
2295
- include_auto: z.boolean().optional().describe("Also synthesize auto-TB proposals before validation."),
2296
- mode: z.enum(["summary", "json"]).optional().describe("Wrapped TB validation CLI output mode. Defaults to summary.")
2297
- })
2298
- };
2299
- var toolDefinitions = [
2300
- {
2301
- name: "vulcan_list_parameters",
2302
- description: `List available parameter categories and their JSON snippets.
12
+ -----END PUBLIC KEY-----`]);import{compactVerify as vn,importSPKI as bn}from"jose";var Xt="EdDSA";async function mt(e,t){let r=e.trim();if(!r)throw new J("empty","Vulcan access token is empty.");let n=t.publicKeys??Kt,a=t.now??(()=>new Date),o=Math.floor(a().getTime()/1e3),c=await Cn(r,n),s=Sn(c);if(s.iss!==He)throw new J("wrong_issuer",`Vulcan access token was issued by ${s.iss}, not ${He}.`);if(s.aud!==ct)throw new J("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(s.entitlement_schema_version!==ze)throw new J("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${s.entitlement_schema_version}, but this build understands version ${ze}. Update your Vulcan tools.`);if(!s.capabilities.includes(t.capability))throw new J("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(s.exp-s.iat>lt)throw new J("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(o<s.iat-ut)throw new J("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let d=o>s.exp;if(d&&!t.allowExpired)throw new J("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:s,expired:d,expiresAt:new Date(s.exp*1e3),expiresInSeconds:s.exp-o}}async function Cn(e,t){for(let r of t)try{let n=await bn(r,Xt),{payload:a}=await vn(e,n,{algorithms:[Xt]});return a}catch{}throw new J("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function Sn(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new J("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new J("malformed","Vulcan access token payload is not an object.");let r=t,n=Ie(r,"iss"),a=Ie(r,"aud"),o=Ie(r,"sub"),c=Ie(r,"org"),s=Ie(r,"jti"),d=dt(r,"iat"),u=dt(r,"exp"),m=dt(r,"entitlement_schema_version");if(!Array.isArray(r.capabilities))throw new J("malformed","Vulcan access token must include a capabilities array.");let p=[];for(let g of r.capabilities){if(!it(g))throw new J("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(g)}.`);p.push(g)}if(p.length===0)throw new J("malformed","Vulcan access token grants no capabilities.");if(u<=d)throw new J("malformed","Vulcan access token expires no later than it was issued.");return{iss:n,aud:a,sub:o,org:c,jti:s,capabilities:Object.freeze(p),entitlement_schema_version:m,iat:d,exp:u}}function Ie(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new J("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return r}function dt(e,t){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new J("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return r}var En="mcp",kn=2880*60;async function Yt(e){let t=e;if(!t){let u=process.env.VULCAN_WORKSPACE;u?t=Oe.join(u,"vulcan-mcp-config.json"):t=Oe.join(process.cwd(),"vulcan-mcp-config.json")}t=Oe.resolve(t);let r;try{r=await ft.readFile(t,"utf-8")}catch(u){let m=u;throw new Error(`Config file not found: ${t}. Please generate it from Vulcan \u2192 Integrations \u2192 MCP.`)}let n;try{n=JSON.parse(r)}catch(u){let m=u;throw new Error(`Invalid JSON in config file: ${m.message}`)}if(!n.workspace)throw new Error("Config file missing required field: workspace");if(!n.license_token||typeof n.license_token!="string")throw new Error('Your Vulcan MCP token is missing. Open Vulcan \u2192 Integrations \u2192 MCP and click "Generate config".');let a=Oe.resolve(Oe.dirname(t),n.workspace);try{await ft.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}let o=Oe.join(a,"input","batch_parameters");try{await ft.access(o)}catch{throw new Error(`Workspace missing required directory: ${o}. MCP only supports folder (FSA) workspaces backed by the real filesystem.`)}let{payload:c}=await pt(n.license_token),s=Math.floor(Date.now()/1e3),d=c.exp-s;if(d<kn){let u=Math.max(1,Math.round(d/3600));console.error(`[MCP Helper] Warning: your Vulcan access config expires in about ${u} hour(s). Open Vulcan -> Profile -> Integrations and click "Generate Config File" to avoid interruption.`)}return{workspace:a,license_token:n.license_token,configPath:t}}async function pt(e,t={}){try{let{claims:r}=await mt(e,{capability:En,now:t.now,publicKeys:t.publicKeys});return{payload:r}}catch(r){throw new Error(Pn(r))}}function Pn(e){if(!(e instanceof J))return e instanceof Error?e.message:String(e);switch(e.code){case"missing_capability":return"This Vulcan access config does not include MCP. MCP requires a Vulcan Pro seat; open Vulcan -> Profile -> Integrations and generate a new config.";case"expired":return'Your Vulcan access config has expired. Open Vulcan -> Profile -> Integrations and click "Generate Config File" to continue.';case"unsupported_schema_version":return'This Vulcan access config was issued for a newer version of the Vulcan tools. Update the helper with "npm install -g @vulcan-energy/mcp-helper@latest".';case"lifetime_exceeded":return"This Vulcan access config declares a longer lifetime than Vulcan issues and was refused. Generate a new config.";case"clock_behind":return"This system clock is too far behind the access config issue time. Correct the clock, then restart the helper.";case"wrong_audience":case"wrong_issuer":return'This access config was not issued for local Vulcan tools. Open Vulcan -> Profile -> Integrations and click "Generate Config File".';default:return'Your Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and click "Generate Config File".'}}import{timingSafeEqual as xn}from"crypto";function An(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 Rn(e,t){let r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&xn(r,n)}async function Zt(e,t,r=pt){let n=An(e);if(!Rn(n,t))throw new Error("MCP request Bearer token is invalid");await r(n)}import{z as _}from"zod";import jn from"fs/promises";import Mn from"path";function Qt(e,t={}){let r=[],n=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&r.push("Config must have at least one scenario");for(let[o,c]of Object.entries(e)){if(!c||typeof c!="object"){r.push(`Scenario '${o}' must be an object`);continue}let s=c;Array.isArray(s.base_json)?s.base_json.length!==1&&r.push(`Scenario '${o}' must have exactly one base_json (found ${s.base_json.length})`):r.push(`Scenario '${o}' is missing required 'base_json' field (must be array)`);let d=!!(s.weather_file||s.weather_files),u=!!s.external_conditions;if(d){let m=s.weather_file||s.weather_files;Array.isArray(m)?m.length>1&&r.push(`Scenario '${o}' must have at most one weather_file (found ${m.length})`):r.push(`Scenario '${o}' weather_file/weather_files must be an array`)}u&&!Array.isArray(s.external_conditions)&&r.push(`Scenario '${o}' external_conditions must be an array`),t.requireWeather!==!1&&!d&&!u&&r.push(`Scenario '${o}' must have either 'weather_files' or 'external_conditions'`),d&&u&&n.push(`Scenario '${o}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,p]of Object.entries(s))Array.isArray(p)||r.push(`Scenario '${o}': '${m}' must be an array`)}return{valid:r.length===0,errors:r,warnings:n}}function er(e){try{if(!e||typeof e!="object")return null;let t=0;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let n=r,a=1;for(let o of Object.values(n))Array.isArray(o)&&(a*=o.length);t+=a}return t}catch{return null}}async function tr(e,t){let r=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:n};for(let[a,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let c=o;for(let[s,d]of Object.entries(c))if(Array.isArray(d)&&!(s==="weather_file"||s==="weather_files"))for(let u of d){let m=Mn.join(e,"input","batch_parameters",s,`${String(u)}.json`);try{await jn.access(m)}catch{n.push({scenario:a,category:s,parameter:String(u),path:m}),r.push(`Scenario '${a}': Parameter '${String(u)}' in category '${s}' not found at ${m}`)}}}return{valid:r.length===0,errors:r,missingFiles:n}}import{readFile as br}from"fs/promises";import{join as Cr}from"path";var Tn=wn(rr(),1),On=Object.defineProperty,Fn=Object.getOwnPropertyNames,$n=(e,t)=>function(){return e&&(t=(0,e[Fn(e)[0]])(e=0)),t},Nn=(e,t)=>{for(var r in t)On(e,r,{get:t[r],enumerable:!0})},Bn={};Nn(Bn,{configureWasm:()=>Ln,getRuntimeApiUrl:()=>Hn,getRuntimeWasmVariant:()=>Jn,getVersionedWasmAssetPaths:()=>wt,getVersionedWasmJsUrl:()=>cr,getWasmAssetPaths:()=>ir,getWasmBaseUrl:()=>yt,getWasmBinaryUrl:()=>lr,getWasmJsUrl:()=>mr,getWasmRayonThreadCount:()=>ar,getWasmVariant:()=>or,getWasmVersionInfo:()=>Ge,getWasmVersionJsonUrl:()=>sr,getWasmWasmUrl:()=>fr,initializeWasmRayonThreadPool:()=>Vn});function Ln(e={}){e.baseUrl&&(ur=In(e.baseUrl)),typeof e.preferHashed=="boolean"&&(dr=e.preferHashed)}function nr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function In(e){return e.replace(/\/+$/,"")||"/"}function Wn(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Dn(){let e=nr();if(e){if(Wn(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function yt(){return ur||Dn()}function ar(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Vn(e){let t=e,r=We.get(t);if(r)return r;let n=e.initialize_rayon_thread_pool;if(typeof n!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>n(ar())).then(()=>{});return We.set(t,a),a.catch(()=>{We.get(t)===a&&We.delete(t)}),a}function sr(){return`${yt()}/wasm_version.json`}async function Ge(){try{let e=await fetch(sr(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function or(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function Jn(){return or(await Ge())}function Un(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function qn(e){let t=Un(),n=!!((dr??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(n?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(n?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function ir(e){let t=yt(),r=e===void 0?await Ge():e,{jsFilename:n,wasmFilename:a}=qn(r);return{jsPath:`${t}/${n}`,wasmPath:`${t}/${a}`}}async function wt(){let e=await Ge(),{jsPath:t,wasmPath:r}=await ir(e),n=e?.build_id||e?.sha256||e?.timestamp;if(!n)return{jsPath:t,wasmPath:r,versionInfo:e};let a=`v=${encodeURIComponent(String(n))}`;return{jsPath:`${t}?${a}`,wasmPath:`${r}?${a}`,versionInfo:e}}async function cr(){let{jsPath:e}=await wt();return e}async function lr(){let{wasmPath:e}=await wt();return e}function Hn(e){let t=nr();return t?new URL(e,t.origin).toString():e}var We,ur,dr,mr,fr,pr=$n({"src/wasmPath.ts"(){We=new WeakMap,mr=cr,fr=lr}});async function _r(e,t){let r=`${t}/target-run.json`;if(!await e.fileExists(r))return null;let n=JSON.parse(await e.readFile(r));if(n?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(n.files)||!n.files.length||n.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(n.files)}async function hr(e,t){let r=await _r(e,t),n=await e.listFiles(t,{withKind:!0});return r===null?n:n.filter(a=>r.has(typeof a=="string"?a:a.name))}async function gr(e,t){let r=t.lastIndexOf("/"),n=await _r(e,t.slice(0,r));return(n===null||n.has(t.slice(r+1)))&&await e.fileExists(t)}function vt(e,t){let r=e.map(n=>typeof n=="string"?n:n.name).filter(n=>n.endsWith(".csv")?t==="results_heat_source_wet"?n.includes("__results_heat_source_wet__"):t==="results_emitters"?n.includes("__results_emitters_"):n.endsWith(`__${t}.csv`):!1).sort((n,a)=>n.localeCompare(a));return r.find(n=>/(?:^|__)FHS__/.test(n))??r.find(n=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(n))}pr();function zn(e){return e.startsWith("__")}function yr(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,r])=>!zn(t)&&!!r&&typeof r=="object"&&!Array.isArray(r)).map(([t,r])=>({name:t,value:r}))}function Gn(){try{let r=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(r&&gt(r))return r;let n=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(n&&gt(n))return n;let o=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(o&&gt(o))return o}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function gt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var us=Gn();pr();import wr from"fs/promises";import bt from"path";var Ct="input/defaults/defaults_template.json",St="input/batch_parameters/base_json/defaults_template.json",Kn="batch_parameters/base_json/defaults_template.json",Xn="defaults/defaults_template.json";function Yn(e){let r=e.split(`
13
+ `).slice(0,50).find(o=>/^DefaultsPath,/i.test(o.trim()));return r&&(Ke(r)[1]||"").trim()||null}function Zn(e){let t=e.trim().replace(/\\/g,"/");return t===St||t.endsWith("/batch_parameters/base_json/defaults_template.json")}function Qn(e){let t=e.trim();if(!t)return[];if(!Zn(t))return[t];let r=t.replace(/\\/g,"/"),n=r.lastIndexOf(Kn);return[n>=0?`${r.slice(0,n)}${Xn}`:Ct,t]}async function vr(e){let t=(e.explicitDefaultsPath??"").trim(),r=t||Yn(e.csvContent);if(r){let n=Qn(r),a;for(let c of n){let s=bt.isAbsolute(c)?c:bt.join(e.workspace,c);try{return{defaultsJson:await wr.readFile(s,"utf8"),source:t?`custom: ${c}`:`CSV metadata: ${c}`,path:s}}catch(d){a=d}}let o=a instanceof Error?a.message:String(a);throw new Error(`Could not read defaults file "${r}". Conversion was aborted instead of silently substituting the standard defaults template. ${o}`)}for(let n of[Ct,St,"defaults_template.json"]){let a=bt.join(e.workspace,n);try{return{defaultsJson:await wr.readFile(a,"utf8"),source:"legacy fallback: standard defaults template",path:a}}catch{}}throw new Error(`Defaults file not found. Tried ${Ct}, ${St}, defaults_template.json`)}function Ke(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}function Et(e,t=!1){let r="",n=1,a,o=[];for(let c of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!c.trim())continue;let s=Ke(c).map(u=>u.trim());if(s[0]=s[0]?.replace(/^#\s*/,"")??"",s[0]&&s.slice(1).every(u=>!u)){r=s[0],a=void 0;continue}if(r==="Metadata"){if(s[0]==="TargetBundleId"&&s[1]&&!t)return`CSV pins TargetBundleId '${s[1]}'. Merge it with vulcan_merge_csv_to_json, which prepares it with its pinned target; the installed legacy converter cannot substitute that bundle.`;s[0]==="VulcanCsvVersion"&&(n=Number(s[1]));continue}if(r!=="Non-Exposed Elements")continue;if(!a){a=s;continue}let d=Object.fromEntries(a.map((u,m)=>[u,s[m]??""]));d.Type==="BuildingElementPartyWall"&&o.push(d)}if(!Number.isInteger(n)||n<1||n>3)return`Unsupported or invalid VulcanCsvVersion '${n}'; supported versions are 1, 2 and 3.`;for(let c of o){let s={};if(c.extra_json)try{s=JSON.parse(c.extra_json)}catch{return`Invalid extra_json for party wall '${c.Name||"unnamed"}'; resolve it before finalizing CSV version 3.`}let d=!!c.u_value||s&&Object.hasOwn(s,"u_value"),u=c.u_value?Number(c.u_value):s?.u_value,m=n<3&&typeof s?.u_value_interpreted_value=="number"&&s.u_value_interpreted_value!==u,p=n>=3&&s?.u_value_interpretation!=="whole_wall"&&s?.u_value_interpretation!=="half_construction";if(d&&(p||m))return`E_CSV_MIGRATION: Party wall '${c.Name||"unnamed"}' has unresolved legacy U-value meaning. Explicitly select whole_wall or half_construction before finalizing CSV version 3.`}}function Fe(e){let t=!1,r;for(let n of e.replace(/^\uFEFF/,"").split(/\r?\n/)){if(!n.trim())continue;let a=Ke(n).map(o=>o.trim());if(a[0]=a[0]?.replace(/^#\s*/,"")??"",a[0]&&a.slice(1).every(o=>!o)){t=a[0]==="Metadata";continue}if(t&&a[0]==="TargetBundleId"&&a[1]){if(r)throw new Error("CSV contains conflicting TargetBundleId metadata");r=a[1]}}return r}async function Xe(e,t){let r=new Set;for(let{value:n}of yr(t))if(Array.isArray(n.base_json))for(let a of n.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");r.add(await ea(e,a))}if(r.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...r][0]}async function ea(e,t){try{let r=JSON.parse(await br(Cr(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof r.targetBundleId!="string"||!r.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return r.targetBundleId}catch(r){if(r.code!=="ENOENT")throw r}try{return Fe(await br(Cr(e,"input/base_models",`${t}.csv`),"utf8"))}catch(r){if(r.code==="ENOENT")return;throw r}}async function kt(e,t){let r;try{r=await Xe(e,t)}catch(n){return n.message}if(r)return`This batch's base models pin HEM target '${r}'. Create the batch with vulcan_create_batch_config to capture its exact __hem source/snippet snapshot; a legacy batch cannot substitute the installed Rust runner.`}import{fork as ta}from"child_process";import{resolve as ra}from"path";import{access as na}from"fs/promises";import{fileURLToPath as Sr}from"url";var De=async e=>{let t=!!(e.targetManifestPath||e.targetManifestSha256);if(t&&(!e.targetManifestPath||!/^[a-f0-9]{64}$/.test(e.targetManifestSha256??"")))throw new Error("Supply both target_manifest and target_manifest_sha256 for an offline bundle, or neither to download the verified pinned target.");if(!t&&!e.targetBundleId)throw new Error("No HEM target identified. Save the source CSV with its TargetBundleId pin; installed legacy WASM cannot substitute it.");for(let r of["./hem-target-runtime/browser-adapter.mjs","../hem-target-runtime/browser-adapter.mjs"]){let n=new URL(r,import.meta.url);try{await na(Sr(n))}catch{continue}let a=t?{...e,manifestPath:ra(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{...e};if(e.operation==="batch")return aa(Sr(n),a);let{runTargetBrowser:o}=await import(n.href);return o(a)}throw new Error("Target browser assets are not installed. Build the local target CLI assets or install a helper release including them.")};function aa(e,t){return new Promise((r,n)=>{let a=ta(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),o=setTimeout(()=>{a.kill(),n(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",c=>{clearTimeout(o),n(c)}),a.once("exit",c=>{clearTimeout(o),n(new Error(`Target batch stopped before startup (${c})`))}),a.once("message",c=>{clearTimeout(o),c.started?(a.unref(),r({status:"started"})):(a.kill(),n(new Error(c.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as sa}from"crypto";import se from"fs/promises";import oe from"path";async function Pt(e,t,r={},n={}){let{config_name:a,base_model:o,weather_file:c,wrapper:s,parameters:d}=t;if(!a)throw new Error("config_name is required");if(!o)throw new Error("base_model is required");if(!d||typeof d!="object"||Array.isArray(d))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let u=oa(d),m={base_json:[o],...s?{model_wrappers:[s]}:{},...u},p=await Xe(e,{scenario_1:m}),g=!!(t.targetManifestPath||t.targetManifestSha256||p);if(!c&&!g)throw new Error("weather_file is required");if(g&&(!/^[a-zA-Z0-9_. -]+$/.test(a)||a===".."))throw new Error("Invalid target config name");c&&(m.weather_files=[g&&!c.endsWith(".epw")?`${c}.epw`:c]);let h={scenario_1:m},S=Qt(h,{requireWeather:!g});if(!S.valid)return{success:!1,valid:!1,errors:S.errors,warnings:S.warnings,message:`Config validation failed: ${S.errors.join("; ")}`};let w=er(h);if(w===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let T=r.maxPermutations??500;if(!Number.isSafeInteger(T)||T<1)throw new Error("maxPermutations must be a positive integer");if(w>T)return{success:!1,valid:!1,errors:[`Total permutations (${w}) exceeds maximum of ${T}`],message:`Config would generate ${w} permutations, which exceeds the limit of ${T}`};let Z=h;if(g){let Y=await(n.runTarget??De)({workspace:e,operation:"snapshot",config:h,targetBundleId:p,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});Z={...h,__hem:Y}}else{let Y=await tr(e,h);if(!Y.valid)return{success:!1,valid:!1,errors:Y.errors,missingFiles:Y.missingFiles,message:`Some parameter files are missing: ${Y.errors.slice(0,3).join("; ")}${Y.errors.length>3?"...":""}`};let K=oe.join(e,"input","batch_parameters","base_json",`${o}.json`);try{await se.access(K)}catch{return{success:!1,valid:!1,errors:[`Base model '${o}' not found at ${K}`],message:`Base model file not found: ${o}`}}let ue=oe.join(e,"input","batch_parameters","weather_files",c.endsWith(".epw")?c:`${c}.epw`);try{await se.access(ue)}catch{return{success:!1,valid:!1,errors:[`Weather file '${c}' not found at ${ue}`],message:`Weather file not found: ${c}`}}}let q=oe.join(e,"input","batch_configs");if(g){let Y=await se.realpath(e);for(let K of["input","batch_configs"])if(Y=oe.join(Y,K),await se.mkdir(Y).catch(ue=>{if(ue.code!=="EEXIST")throw ue}),await se.realpath(Y)!==Y)throw new Error("Target config directory is a symlink")}else await se.mkdir(q,{recursive:!0});let N=a.endsWith(".json")?a:`${a}.json`,ne=oe.join(q,N);try{return await se.access(ne),{success:!1,valid:!1,errors:[`Config file '${N}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await se.writeFile(ne,JSON.stringify(Z,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:ne,permutations:w,structure:h}}async function Ye(e,t,r){let{config_name:n,job_id:a}=t;if(!n)throw new Error("config_name is required");let o=a||r.generateJobId?.()||`mcp_${sa()}`,c=n.endsWith(".json")?n:`${n}.json`,s=oe.join(e,"input","batch_configs",c),d;try{d=await se.readFile(s,"utf8")}catch(g){let h=g;throw h.code==="ENOENT"?new Error(`Batch config '${n}' not found at ${s}`):new Error(`Failed to read config file: ${h.message}`)}let u=JSON.parse(d);if(u&&typeof u=="object"&&("__hem"in u||"targetBundleId"in u)){let g=u.__hem;if(!g){let h="This batch names a HEM target but has no saved __hem source snapshot. Re-save the batch in the app (or create it with vulcan_create_batch_config).";return{job_id:o,status:"error",message:h,error:h}}try{return await(r.runTarget??De)({workspace:e,operation:"batch",config:u,targetBundleId:g.targetBundleId,configName:n.replace(/\.json$/,""),jobId:o,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:o,status:"started",config_name:n,output_dir:oe.join(e,"output"),message:"Exact target batch started. Read progress with vulcan_get_batch_status; runtime provenance is stored with outputs."}}catch(h){let S=h.message;return{job_id:o,status:"error",message:S,error:S}}}let m=await kt(e,u);if(m)return{job_id:o,status:"error",message:m,error:m};if(t.targetManifestPath||t.targetManifestSha256){let g="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:o,status:"error",message:g,error:g}}let p=oe.join(e,"output");await se.mkdir(p,{recursive:!0});try{let g=await r.processBatchConfig(d,e,p,n.replace(/\.json$/,""),o),h=JSON.parse(g);return h.error?{job_id:o,status:"error",message:`Batch execution failed: ${h.error}`,error:h.error}:{job_id:o,status:"started",message:"Batch execution started successfully",config_name:n,output_dir:p}}catch(g){let h=g;return{job_id:o,status:"error",message:`Failed to start batch execution: ${h.message}`,error:h.message}}}async function xt(e,t={}){let{job_id:r,config_name:n}=t;if(n&&!r){let S=oe.join(e,"output"),w=n.replace(/\.json$/,"");try{let Z=(await se.readdir(S)).filter(N=>N.startsWith("progress_")&&N.endsWith(".json")).map(N=>({name:N,jobId:N.replace("progress_","").replace(".json",""),path:oe.join(S,N),isMcp:N.startsWith("progress_mcp_")})),q=await Promise.all(Z.map(async N=>{try{let ne=await se.stat(N.path);return{...N,mtime:ne.mtime}}catch{return{...N,mtime:new Date(0)}}}));q.sort((N,ne)=>N.isMcp&&!ne.isMcp?-1:!N.isMcp&&ne.isMcp?1:ne.mtime.getTime()-N.mtime.getTime()),q[0]&&(r=q[0].jobId)}catch(T){console.warn(`Failed to find job_id for config_name '${n}': ${T.message}`)}if(!r)return{config_name:w,status:"queued",progress:0,passes:0,failures:0,output_dir:oe.join(e,"output"),error:null,batch_progress:void 0,sim_progress:void 0}}if(!r)throw new Error("Either job_id or config_name is required");let a=oe.join(e,"output"),o=oe.join(a,`progress_${r}.json`),c=oe.join(a,`sim_progress_${r}.json`),s=null,d=null;try{s=JSON.parse(await se.readFile(o,"utf8"))}catch(S){let w=S;w.code!=="ENOENT"&&console.warn(`Failed to read batch progress: ${w.message}`)}try{d=JSON.parse(await se.readFile(c,"utf8"))}catch(S){let w=S;w.code!=="ENOENT"&&console.warn(`Failed to read simulation progress: ${w.message}`)}let u="queued",m=0,p=0,g=0,h=null;if(s&&(Er(s.status)?u=s.status:typeof s.percentage=="number"?(m=s.percentage,u=m>=100?"completed":"running"):typeof s.current_combination=="number"&&typeof s.total_combinations=="number"&&(m=Math.round(s.current_combination/s.total_combinations*100),u=m>=100?"completed":"running"),typeof s.percentage=="number"&&(m=s.percentage),typeof s.error=="string"&&(h=s.error,u="error")),d&&!s?.targetBundleId&&(Er(d.status)&&(u=d.status),typeof d.passes=="number"&&(p=d.passes),typeof d.failures=="number"&&(g=d.failures),typeof d.error=="string"&&(h=d.error,u="error")),!s&&!d){let S=oe.join(a,r);try{let w=await se.readdir(S);u=w.length>0?"completed":"queued",m=w.length>0?100:0}catch{u="queued"}}return{job_id:r,...n?{config_name:n.replace(/\.json$/,"")}:{},status:u,progress:m,passes:p,failures:g,output_dir:a,error:h,batch_progress:s,sim_progress:s?.targetBundleId?null:d}}function oa(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Array.isArray(r)?r.map(String):[String(r)]]))}function Er(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import qs from"crypto";import be from"fs/promises";import U from"path";import Ve from"fs";import xe from"path";import{fileURLToPath as ia}from"url";function Ze(e=process.cwd()){let t=xe.resolve(e);for(Ve.existsSync(t)&&Ve.statSync(t).isFile()&&(t=xe.dirname(t));;){if(Ve.existsSync(xe.join(t,"package.json"))&&Ve.existsSync(xe.join(t,"hem-batch-core"))&&Ve.existsSync(xe.join(t,"web")))return t;let n=xe.dirname(t);if(n===t)break;t=n}let r=xe.dirname(ia(import.meta.url));return xe.resolve(r,"..","..","..")}import kr from"fs/promises";import Qe from"path";function ca(e){let t=!1,r=null;for(let n of e.split(`
14
+ `).slice(0,80)){let a=n.trim();if(/^ComplianceValidationEnabled,/i.test(a)){t=Pr(a)[1]?.trim().toUpperCase()==="TRUE";continue}if(/^SchemaProfile,/i.test(a)){let o=Pr(a)[1]?.trim().toLowerCase();o==="ecaas_input_fhs"&&(r="ecaas_input_fhs"),o==="input_fhs"&&(r="input_fhs"),o==="input_core"&&(r="input_core")}}return r||(t?"input_fhs":"input_core")}async function xr(e){let t=ca(e.csvContent);if(e.explicitSchemaPath){let a=Qe.isAbsolute(e.explicitSchemaPath)?e.explicitSchemaPath:Qe.resolve(e.workspace??process.cwd(),e.explicitSchemaPath);return{mode:t,source:a,schemaJson:await kr.readFile(a,"utf8")}}let r=la({mode:t,repoRoot:e.repoRoot,workspace:e.workspace}),n=[];for(let a of r){n.push(a);try{return{mode:t,source:a,schemaJson:await kr.readFile(a,"utf8")}}catch{}}throw new Error(`Schema file not found for ${t}. Tried: ${n.join(", ")}`)}function la(e){let t=[];if(e.repoRoot&&t.push(Qe.join(e.repoRoot,...ua(e.mode))),e.workspace){let r=da(e.mode);t.push(...r.map(n=>Qe.join(e.workspace,...n)))}return[...new Set(t)]}function ua(e){switch(e){case"input_core":return["hem_engine_upstream","schemas","core-input.schema.json"];case"input_fhs":return["hem_fhs_upstream","schema","input_fhs.schema.json"];case"ecaas_input_fhs":return["schemas","ecaas_input_fhs.schema.json"]}}function da(e){switch(e){case"input_core":return[["input_core.schema.json"],["hem_engine_upstream","schemas","core-input.schema.json"],["core-input.schema.json"],["schemas","core-input.schema.json"],["input.schema.json"]];case"input_fhs":return[["input_fhs.schema.json"],["hem_fhs_upstream","schema","input_fhs.schema.json"],["schema","input_fhs.schema.json"],["schemas","input_fhs.schema.json"]];case"ecaas_input_fhs":return[["ecaas_input_fhs.schema.json"],["schemas","ecaas_input_fhs.schema.json"]]}}function Pr(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}import ve from"fs";import _e from"path";import{pathToFileURL as ma}from"url";var Ar=new Map,Rr=!1,At=process.cwd(),Mr=!1;async function Rt(e){let t=Ar.get(e);if(t)return t;fa();let r=_e.join(e,"wasm_wrapper.js"),n=_e.join(e,"wasm_wrapper_bg.wasm"),a=_e.join(e,"wasm_version.json");if(!ve.existsSync(r)||!ve.existsSync(n))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(ma(r).href);if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:ve.readFileSync(n)}),o.setup_panic_hook?.(),typeof o.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let c={convertGeometryCsvToJson:o.convert_geometry_csv_to_json.bind(o),validateSnippetJs:o.validate_snippet_js?.bind(o),processBatchConfig:o.process_batch_config?.bind(o),calculateMetricsFromParsedData:o.calculate_metrics_from_parsed_data?.bind(o),setWorkspace:$e,metadata:{source:r,wasm_path:n,wasm_version:ha(a),build_stamp:Ue(o.build_stamp),build_info:ga(o.get_build_info),runtime_origin_descriptor:Ue(o.runtime_origin_descriptor),hem_core_version:Ue(o.metadata_hem_core_version),fhs_wrapper_version:Ue(o.metadata_fhs_wrapper_version)}};return Ar.set(e,c),c}function $e(e,t={}){At=_e.resolve(e),Mr=t.confineToWorkspace===!0}function fa(){pa(),_a();let e=globalThis;e.self||(e.self=globalThis),e.window||(e.window=globalThis),typeof e.addEventListener!="function"&&(e.addEventListener=()=>{}),typeof e.postMessage!="function"&&(e.postMessage=()=>{});let t=e.self;typeof t.addEventListener!="function"&&(t.addEventListener=()=>{}),typeof t.postMessage!="function"&&(t.postMessage=()=>{}),typeof e.Worker!="function"&&(e.Worker=class{addEventListener(){}postMessage(){}terminate(){}}),e.write_file=(r,n)=>{let a=Je(r);try{return ve.mkdirSync(_e.dirname(a),{recursive:!0}),ve.writeFileSync(a,n),!0}catch(o){return console.error(`[FS Bridge] write_file failed for ${a}:`,o.message),!1}},e.read_file=r=>{let n=Je(r);return ve.readFileSync(n,"utf8")},e.file_exists=r=>{let n=Je(r);return ve.existsSync(n)},e.create_dir_all=r=>{let n=Je(r);try{return ve.mkdirSync(n,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${n}:`,a.message),!1}},e.list_dir=r=>{let n=Je(r);try{return ve.readdirSync(n)}catch{return[]}}}function Je(e){let t=_e.isAbsolute(e)?_e.resolve(e):_e.resolve(At,e);if(Mr){let r=_e.relative(At,t);if(r===".."||r.startsWith(`..${_e.sep}`)||_e.isAbsolute(r))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function pa(){if(Rr)return;let e=console.error.bind(console);console.log=(...t)=>{let r=t[0];typeof r=="string"&&r.startsWith("[WASM]")||e(...t)},Rr=!0}var jr=!1;function _a(){if(jr)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,r)=>{let n=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(n.startsWith("file:")&&n.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,r)}),jr=!0}function ha(e){try{return JSON.parse(ve.readFileSync(e,"utf8"))}catch{return}}function Ue(e){return typeof e!="function"?void 0:e()||void 0}function ga(e){let t=Ue(e);if(t)try{return JSON.parse(t)}catch{return t}}async function Fr(e){let{workspace:t,csvContent:r,schemaJson:n,defaultsPath:a,deps:o}=e,c=Et(r);if(c)return{ok:!1,error:c};let s=await vr({workspace:t,csvContent:r,explicitDefaultsPath:a}),d;try{d=await o.convertGeometryCsvToJson(r,n,s.defaultsJson)}catch(m){return{ok:!1,error:`WASM conversion failed: ${m.message}`,defaults_source:s.source,defaults_path:s.path}}if(!d||typeof d!="string")return{ok:!1,error:"WASM returned empty or invalid result",defaults_source:s.source,defaults_path:s.path};let u=ya(d);return!u.ok||u.json===void 0||u.json===null?{ok:!1,validation:u.validation,error:u.error||"WASM conversion returned invalid result",defaults_source:s.source,defaults_path:s.path}:{ok:!0,json:u.json,validation:u.validation,defaults_source:s.source,defaults_path:s.path}}async function et(e){let{workspace:t,csvPath:r,outputPath:n,schemaPath:a,defaultsPath:o,repoRoot:c,deps:s}=e,d=U.isAbsolute(r)?r:U.join(t,r),u;try{u=await be.readFile(d,"utf8")}catch(w){let T=w;throw T.code==="ENOENT"?new Error(`CSV file not found at ${d}`):new Error(`Failed to read CSV file: ${T.message}`)}let m=Fe(u),p=Et(u,!!m);if(p)return{ok:!1,error:p};if(m){if(a||o)return{ok:!1,error:"Pinned target preparation uses its matching schema/defaults. Keep authored DefaultsPath in the CSV; custom schema/default overrides cannot replace bundle artifacts."};try{let w=await(s.runTarget??De)({workspace:t,operation:"prepare",csv:u,targetBundleId:m,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),T=n?U.resolve(t,n):Tr(t,d);if(U.extname(T)!==".json")throw new Error("Prepared target output must have a .json extension");return await $r(t,T),await Or(t,U.join(t,"input/base_models",U.basename(T,".json")+".target.json"),JSON.stringify({targetBundleId:m,validation:w.validation,schema_omissions:w.schema_omissions,readiness:"wrapper_input"})),await Or(t,T,JSON.stringify(w.model,null,2)),{ok:!0,json_path:U.relative(t,T),validation:w.validation,schema_source:`target:${m}`,defaults_source:`target:${m}`}}catch(w){return{ok:!1,error:w.message}}}if(e.targetManifestPath||e.targetManifestSha256)return{ok:!1,error:"CSV has no TargetBundleId. Select and save an exact target before supplying its bundle."};let g=await xr({repoRoot:c??Ze(t),workspace:t,csvContent:u,explicitSchemaPath:a}),h=await Fr({workspace:t,csvContent:u,schemaJson:g.schemaJson,defaultsPath:o,deps:s});if(!h.ok||h.json===void 0||h.json===null)return{ok:!1,validation:h.validation,error:h.error||"WASM conversion returned invalid result",defaults_source:h.defaults_source,schema_source:g.source};let S=n?U.isAbsolute(n)?n:U.join(t,n):Tr(t,d);await be.mkdir(U.dirname(S),{recursive:!0});try{await be.writeFile(S,JSON.stringify(h.json,null,2),"utf8")}catch(w){let T=w;return{ok:!1,validation:h.validation,error:`Failed to write JSON file: ${T.message}`,defaults_source:h.defaults_source,schema_source:g.source}}return{ok:!0,json_path:U.relative(t,S),validation:h.validation,defaults_source:h.defaults_source,schema_source:g.source}}function ya(e){try{return JSON.parse(e)}catch(t){return{ok:!1,error:`WASM returned invalid JSON: ${t.message}`}}}function Tr(e,t){let r=U.basename(t,U.extname(t));return U.join(e,"input","batch_parameters","base_json",`${r}.json`)}async function $r(e,t){let r=await be.realpath(e),n=U.relative(U.resolve(e),t);if(!n||n===".."||n.startsWith(`..${U.sep}`)||U.isAbsolute(n))throw new Error("Target preparation output must stay within the workspace");let a=U.join(r,n),o=r;for(let c of U.relative(r,U.dirname(a)).split(U.sep).filter(Boolean))if(o=U.join(o,c),await be.mkdir(o).catch(s=>{if(s.code!=="EEXIST")throw s}),await be.realpath(o)!==o)throw new Error("Target preparation output directory is a symlink");try{if(await be.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(c){if(c.code!=="ENOENT")throw c}return a}async function Or(e,t,r){let n=await $r(e,t),a=await be.open(n,"wx").catch(async o=>{if(o.code!=="EEXIST")throw o;if(await be.realpath(n)!==n)throw new Error("Target preparation output is a symlink");return be.open(n,"w")});try{await a.writeFile(r)}finally{await a.close()}}import he from"fs/promises";import re from"path";async function jt(e,t={}){let{category:r}=t,n=re.join(e,"input","batch_parameters"),a=await he.readdir(n,{withFileTypes:!0}),o={};for(let c of a){if(!c.isDirectory())continue;let s=c.name;if(r&&s!==r)continue;let d=re.join(n,s),u=await he.readdir(d),m=[];for(let p of u){if(!p.endsWith(".json"))continue;let g=p.replace(/\.json$/,""),h=re.join(d,p);try{let S=await he.readFile(h,"utf8"),w=JSON.parse(S);m.push({id:g,name:typeof w.name=="string"?w.name:g,description:typeof w.description=="string"?w.description:"",category:s})}catch(S){console.error(`Failed to parse ${h}: ${S.message}`)}}m.length>0&&(o[s]={category:s,parameters:m.sort((p,g)=>p.name.localeCompare(g.name))})}return{catalog:o,total_categories:Object.keys(o).length,total_parameters:Object.values(o).reduce((c,s)=>c+s.parameters.length,0)}}async function Mt(e,t){let{category:r,parameter_id:n}=t;if(!r)throw new Error("category is required");if(!n)throw new Error("parameter_id is required");let a=re.join(e,"input","batch_parameters",r),o=re.join(a,`${n}.json`),c=re.join(a,`${n}.md`),s;try{let u=await he.readFile(o,"utf8");s=JSON.parse(u)}catch(u){let m=u;throw m.code==="ENOENT"?new Error(`Parameter '${n}' not found in category '${r}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let d=null;try{d=await he.readFile(c,"utf8")}catch(u){let m=u;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:r,parameter_id:n,json:s,markdown:d,has_markdown:d!==null}}async function Tt(e,t,r){let{category:n,parameter_id:a,content:o,markdown_content:c}=t;if(!n)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(o==null||o==="")throw new Error("content is required");let s=wa(o),[d,u,m]=await Promise.all([va(e),ba(e),Ca(e,n)]),p=r.validateSnippetJs(n,JSON.stringify(s),JSON.stringify(d),JSON.stringify(u),m?JSON.stringify(m):null),g=JSON.parse(p);if(!g.ok){let T=(g.errors??[]).map(Z=>typeof Z=="string"?Z:Z.message||String(Z));return{success:!1,valid:!1,errors:T,message:`Validation failed: ${T.join("; ")}`}}let h=re.join(e,"input","batch_parameters",n);await he.mkdir(h,{recursive:!0});let S=re.join(h,`${a}.json`);await he.writeFile(S,JSON.stringify(s,null,2),"utf8");let w=null;return c&&(w=re.join(h,`${a}.md`),await he.writeFile(w,c,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${n}'`,paths:{json:S,markdown:w}}}function wa(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}async function va(e){let t=[re.join(e,"input_core.schema.json"),re.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),re.join(e,"core-input.schema.json"),re.join(e,"schemas","core-input.schema.json"),re.join(e,"input.schema.json")];for(let r of t)try{return JSON.parse(await he.readFile(r,"utf8"))}catch{}throw new Error(`Schema file not found. Tried: ${t.join(", ")}`)}async function ba(e){let t=re.join(e,"input","batch_parameters","base_json","demo_hp_annual.json");try{return JSON.parse(await he.readFile(t,"utf8"))}catch(r){let n=r;throw new Error(`Baseline model not found at ${t}: ${n.message}`)}}async function Ca(e,t){if(t!=="simplified_fabric")return null;let r=[re.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),re.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let n of r)try{return JSON.parse(await he.readFile(n,"utf8"))}catch{}return null}import $t from"fs/promises";import rt from"path";import qe from"fs/promises";import tt from"path";async function Ne(e,t){let r=tt.join(e,"output"),n=Lr(t.config_name),a=[],o=new Set;try{let c=tt.join(r,n);await Ir(c)&&await Nr(c,a,o);let d=(await qe.readdir(r)).filter(u=>u.startsWith(`result_${n}_`));for(let u of d){let m=tt.join(r,u);try{await Nr(m,a,o,u.slice(`result_${n}_`.length))}catch(p){console.warn(`Failed to read result directory ${u}: ${p.message}`)}}return a.sort((u,m)=>u.name.localeCompare(m.name)),{config_name:n,models:a,total_models:a.length,output_dir:r}}catch(c){return{config_name:n,models:[],total_models:0,output_dir:r,error:`Failed to list models: ${c.message}`}}}async function Ot(e,t){let r=Lr(t.config_name),n=await Ne(e,{config_name:r}),a=n.models.find(m=>m.name===t.model_name)?.csv_path;if(!a)return{config_name:r,model_name:t.model_name,columns:[],total_columns:0,error:n.error??`No completed actual-dwelling CSV found for model ${t.model_name}`};let c=(await qe.readFile(a,"utf8")).split(`
15
+ `).filter(m=>m.trim());if(c.length<2)return{config_name:r,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let s=Br(c[0]??"").map(m=>m.trim()),d=Br(c[1]??"").map(m=>m.trim()),u=[];for(let m=1;m<s.length;m+=1){let p=s[m],g=m<d.length?d[m]:"";p&&u.push({name:p,unit:g||"",index:m-1})}return{config_name:r,model_name:t.model_name,columns:u,total_columns:u.length,csv_path:a}}var Ft={fileExists:Ir,readFile:e=>qe.readFile(e,"utf8"),listFiles:e=>qe.readdir(e)};async function Nr(e,t,r,n){let o=(await hr(Ft,e)).map(s=>typeof s=="string"?s:s.name),c=(s,d)=>{r.has(s)||(r.add(s),t.push({name:s,csv_path:tt.join(e,d),has_results:!0}))};if(n){let s=vt(o,"results");s&&c(n,s);return}for(let s of o){if(!vt([s],"results"))continue;let d=s.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);d?.[1]&&c(d[1],s)}}function Lr(e){return e.replace(/\.json$/,"")}async function Ir(e){try{return await qe.access(e),!0}catch{return!1}}function Br(e){let t=[],r="",n=!1;for(let a=0;a<e.length;a+=1){let o=e[a];n?o==='"'?e[a+1]==='"'?(r+='"',a+=1):n=!1:r+=o:o==='"'?n=!0:o===","?(t.push(r),r=""):r+=o}return t.push(r),t}var Sa=new Set(["sumif","averageif","countif"]),Wr=new Set([">=","<=",">","<","="]);async function Nt(e,t,r){let{config_name:n,model_names:a,metric_definitions:o,time_range:c,tariff_file_path:s,tariff_column_index:d}=t;if(!n)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!o||!Array.isArray(o)||o.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let u=n.replace(/\.json$/,""),{encodedMetrics:m,metadata:p}=Pa(o);if(p.some(w=>w.function.toLowerCase()==="cost")&&(!s||d===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let h;if(s&&d!==void 0){let w=await xa(s,d,e);h=JSON.stringify(w)}let S=[];for(let w of a){let{csvPath:T,csvContent:Z}=await Aa({workspace:e,cleanConfigName:u,modelName:w});try{let q=Ea(Z,w,n);if(p.some(K=>K.isCompliance)){let K=rt.join(rt.dirname(T),"fhs_compliance_report.json");if(!await gr(Ft,K))throw new Error("Completed FHS compliance report is unavailable");let ue=JSON.parse(await $t.readFile(K,"utf8")),fe=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let de of fe){let I=ue[de];q[de]=typeof I=="number"&&Number.isFinite(I)?I:null}for(let de of p.filter(I=>I.isCompliance)){let I=fe.find($=>$===de.column);if(!I||q[I]===null)throw new Error(`Completed FHS compliance rate '${de.column}' is unavailable`)}}if(q.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${w}`);if(Object.keys(q.columns).length===0)throw new Error(`No columns found in CSV for model ${w}`);let N=Ra(q,m,p);if(N.length>0){let K=Object.keys(q.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${N.join(", ")}. Available columns: ${K.join(", ")}...`)}let ne=r.calculateMetricsFromParsedData(JSON.stringify(q),JSON.stringify(m),c?JSON.stringify(c):void 0,h);if(!ne||typeof ne!="string")throw new Error(`WASM returned invalid result: ${typeof ne}`);let Y=JSON.parse(ne);if(!Array.isArray(Y))throw new Error(`WASM returned non-array result: ${typeof Y}`);Y.forEach((K,ue)=>{let fe=p[ue],[de=K.name,I="sum"]=K.name.split("|");S.push({id:fe?.id||K.name,name:fe?.name||K.name,column:fe?.column||de,function:fe?.function||I,comparator:fe?.comparator,threshold:fe?.threshold,value:K.value,model_name:w})})}catch(q){let N=q;if(N.code==="ENOENT"){console.warn(`CSV file not found for model ${w}: ${T}`);continue}throw new Error(`Failed to process model ${w}: ${N.message}`)}}return{metrics:S,total_models:a.length,total_metrics:S.length}}function Ea(e,t,r){let n=e.split(`
16
+ `).filter(m=>m.trim());if(n.length<2)throw new Error("CSV must have at least headers and units rows");let a=(n[0]??"").split(",").map(m=>m.trim()),o=(n[1]??"").split(",").map(m=>m.trim()),c=[],s={},d=[],u=[];for(let m=1;m<a.length;m+=1){let p=a[m];p&&(s[p]=[],d.push(p),u.push(m<o.length&&o[m]||""))}for(let m=2;m<n.length;m+=1){let p=(n[m]??"").split(",").map(S=>S.trim());if(p.length===0||p.length===1&&!p[0])continue;let g=p[0];if(!g)continue;let h=Number.parseInt(g,10);if(!(Number.isNaN(h)||h<0)){c.push(h);for(let S=1;S<a.length&&S<p.length;S+=1){let w=a[S];if(!w||!s[w])continue;let T=p[S];if(T===void 0)continue;let Z=Number.parseFloat(T);s[w].push(Number.isNaN(Z)?0:Z)}}}return{timestamps:c,columns:s,column_order:d,column_units:u,metadata:{model_name:t,config_name:r.replace(/\.json$/,""),total_points:c.length,sample_rate:1800},dwelling_emission_rate:null,dwelling_primary_energy_rate:null,dwelling_fabric_energy_efficiency:null}}function ka(e){let t=(e.function||e.type||"sum").toString(),r=t.toLowerCase();if(r==="cost")return"cost";if(!Sa.has(r))return r;let n=e.comparator||">=";if(!Wr.has(n))throw new Error(`Invalid comparator "${n}" for ${t}. Use one of ${Array.from(Wr).join(", ")}`);if(e.threshold===void 0||e.threshold===null||Number.isNaN(Number(e.threshold)))throw new Error(`threshold is required for ${t} metrics`);return`${r}${n}${e.threshold}`}function Pa(e){let t=[],r=[];return e.forEach((n,a)=>{if(typeof n=="string"){let d=n.includes("|")?n:`${n}|sum`,[u=n,m="sum"]=d.split("|");t.push({name:d}),r.push({id:n,name:n,column:u,function:m,isCompliance:m.toLowerCase()==="compliance"});return}let o=n.column||(n.name?.includes("|")?n.name.split("|")[0]:n.name);if(!o)throw new Error(`Metric definition at index ${a} missing column or name. Got: ${JSON.stringify(n)}`);let c=n.name?.includes("|")&&!n.function?n.name.split("|")[1]||"sum":ka(n),s=`${o}|${c}`;t.push({name:s}),r.push({id:n.id||n.metric_id||`${o}_${c}`,name:n.name||n.id||o,column:o,function:c,comparator:n.comparator,threshold:n.threshold,isCompliance:c.toLowerCase()==="compliance"})}),{encodedMetrics:t,metadata:r}}async function xa(e,t,r){let n=rt.isAbsolute(e)?e:rt.resolve(r,e),o=(await $t.readFile(n,"utf8").catch(s=>{throw new Error(`Failed to read tariff file: ${n}. Error: ${s.message}`)})).split(`
17
+ `).filter(s=>s.trim());if(o.length===0)throw new Error(`Tariff file is empty: ${n}`);let c=[];for(let s=1;s<o.length;s+=1){let d=(o[s]??"").split(",").map(p=>p.trim().replace(/"/g,""));if(t>=d.length)throw new Error(`Column index ${t} not found in record ${s} with ${d.length} columns`);let u=d[t];if(u===void 0)throw new Error(`Column index ${t} is undefined in record ${s}`);let m=Number.parseFloat(u);if(Number.isNaN(m))throw new Error(`Could not parse '${u}' as number in row ${s+1}, column ${t+1}`);c.push(m)}if(c.length!==17520)throw new Error(`Tariff must contain 17,520 rows (found ${c.length})`);return c}async function Aa(e){let{workspace:t,cleanConfigName:r,modelName:n}=e,a=await Ne(t,{config_name:r}),o=a.models.find(c=>c.name===n)?.csv_path;if(!o)throw new Error(a.error??`No completed actual-dwelling CSV found for model ${n}`);return{csvPath:o,csvContent:await $t.readFile(o,"utf8")}}function Ra(e,t,r){let n=[];return t.forEach((a,o)=>{let c=a.name.split("|")[0];if(!c)throw new Error(`Invalid metric name format: ${a.name}`);r[o]?.isCompliance||e.columns[c]||n.push(c)}),n}import{spawn as ja}from"child_process";import nt from"path";var Lt=["vite-node","community/apps/cli/src/cli.ts"];async function It(e){let t=at(e),r=e.failOn??"critical",n=nt.resolve(e.csvPath),a=await Vt(e,"npx",[...Lt,"check",n,"--json",`--fail-on=${r}`]),o=Jt(a),c=Bt(o)?o:void 0;return{ok:a.exitCode===0&&c!==void 0,command:"geometry validate",csv_path:n,repo_root:t,fail_on:r,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:c,counts:Bt(c?.counts)?c.counts:void 0,critical_issues:Array.isArray(c?.criticalIssues)?c.criticalIssues:void 0,warnings:Array.isArray(c?.warnings)?c.warnings:void 0,missing_elements:Array.isArray(c?.missingElements)?c.missingElements:void 0,error:c===void 0?Ut(a):void 0}}async function Wt(e){let t=at(e),r=e.mode??"summary",n=nt.resolve(e.csvPath),a=await Vt(e,"npx",[...Lt,"thermal-bridges",n,Dr(r)]),o=r==="json"?Jt(a):void 0;return{ok:a.exitCode===0&&(r!=="json"||o!==void 0),command:"thermal-bridges auto",csv_path:n,repo_root:t,mode:r,exit_code:a.exitCode,signal:a.signal,stdout:a.stdout,stderr:a.stderr,parsed:o,proposal_count:Array.isArray(o)?o.length:void 0,error:r==="json"&&o===void 0?Ut(a):void 0}}async function Dt(e){let t=at(e),r=e.mode??"summary",n=e.includeAuto===!0,a=nt.resolve(e.csvPath),o=[...Lt,"thermal-bridges",a,"--validate",...n?["--with-auto"]:[],Dr(r)],c=await Vt(e,"npx",o),s=r==="json"?Jt(c):void 0,d=Bt(s)?s:void 0;return{ok:c.exitCode===0&&(r!=="json"||d!==void 0),command:"thermal-bridges validate",csv_path:a,repo_root:t,include_auto:n,mode:r,exit_code:c.exitCode,signal:c.signal,stdout:c.stdout,stderr:c.stderr,parsed:d,issue_count:typeof d?.issueCount=="number"?d.issueCount:void 0,thermal_bridge_linear_rows:typeof d?.thermalBridgeLinearRows=="number"?d.thermalBridgeLinearRows:void 0,error:r==="json"&&d===void 0?Ut(c):void 0}}function at(e){return nt.resolve(e.repoRoot??Ze(e.csvPath))}async function Vt(e,t,r){let n=at(e);return(e.runner??Ma)(t,r,{cwd:n})}function Dr(e){return`--${e}`}function Jt(e){try{return JSON.parse(e.stdout)}catch{return}}function Ut(e){return`Expected JSON output from validation CLI.${e.stderr.trim()?` stderr: ${e.stderr.trim()}`:""}`}function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ma=(e,t,r)=>new Promise((n,a)=>{let o=ja(e,[...t],{cwd:r.cwd,shell:!1,stdio:["ignore","pipe","pipe"]}),c="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",d=>{c+=d}),o.stderr.on("data",d=>{s+=d}),o.on("error",a),o.on("close",(d,u)=>{n({exitCode:d,signal:u,stdout:c,stderr:s})})});async function Vr(e,t={}){return jt(e.workspace,t)}async function Jr(e,t){return Mt(e.workspace,t)}import Ur from"fs";import Ce from"path";import{fileURLToPath as Ta}from"url";var Oa=Ce.dirname(Ta(import.meta.url));function Fa(){let e=[],t=Oa;for(let o=0;o<6;o+=1){e.push(t);let c=Ce.dirname(t);if(c===t)break;t=c}e.push(process.cwd());let r=[];for(let o of e)r.push({directory:Ce.join(o,"wasm"),context:"helper-root"},{directory:Ce.join(o,"vulcan-mcp-server","wasm"),context:"helper-dist"},{directory:Ce.join(o,"web","dist","wasm"),context:"rust-hem-runner"},{directory:Ce.join(o,"web","dist"),context:"rust-hem-runner"},{directory:Ce.join(o,"web","pkg"),context:"rust-hem-runner"},{directory:Ce.join(o,"apps","web","public","launch"),context:"vulcan-website"});let n=[],a=new Set;for(let o of r){let c=Ce.join(o.directory,"wasm_wrapper.js");if(a.has(c))continue;a.add(c),n.push(c);let s=Ce.join(o.directory,"wasm_wrapper_bg.wasm");if(Ur.existsSync(c)&&Ur.existsSync(s))return o}throw new Error(`WASM files not found. Tried:
18
+ `+n.map(o=>` - ${o}`).join(`
19
+ `)+`
20
+ Please ensure WASM is built (run: scripts/deploy-wasm.sh --update)`)}var st=null;async function Ae(){if(st)return st;try{let{directory:e,context:t}=Fa();return console.error(`[WASM] Loading from ${t}: ${e}`),st=await Rt(e),console.error(`[WASM] Initialized successfully from ${t}`),st}catch(e){throw console.error("[WASM] Initialization failed:",e),new Error(`WASM initialization failed: ${e.message}`)}}async function qr(e,t){let r;try{r=await Ae()}catch(n){let a=n;throw new Error(`WASM initialization failed: ${a.message}`)}if(!r.validateSnippetJs)throw new Error("WASM validate_snippet_js function not available");return Tt(e.workspace,t,{validateSnippetJs:r.validateSnippetJs})}async function Hr(e,t){return Pt(e.workspace,{...t,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256})}import{randomUUID as $a}from"crypto";import Na from"fs/promises";import Ba from"path";async function zr(e,t){let{workspace:r}=e,{config_name:n}=t;if(!n)throw new Error("config_name is required");let a=t.job_id||`mcp_${$a()}`,o=Ba.join(r,"input","batch_configs",n.endsWith(".json")?n:`${n}.json`),c=await Na.readFile(o,"utf8").then(u=>JSON.parse(u),()=>{});if(!!(c&&typeof c=="object"&&("__hem"in c||"targetBundleId"in c))||t.target_manifest||t.target_manifest_sha256)return Ye(r,{...t,job_id:a,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256},{processBatchConfig:()=>{throw new Error("Pinned execution cannot use legacy WASM")}});let d;try{d=await Ae()}catch(u){let m=u;return{job_id:a,status:"error",message:`WASM initialization failed: ${m.message}`,error:m.message}}return d.processBatchConfig?($e(r),Ye(r,{...t,job_id:a},{processBatchConfig:d.processBatchConfig})):{job_id:a,status:"error",message:"WASM process_batch_config function not available",error:"WASM function missing"}}async function Gr(e,t={}){return xt(e.workspace,t)}async function Kr(e,t){let r;try{r=await Ae()}catch(n){let a=n;throw new Error(`WASM initialization failed: ${a.message}`)}if(!r.calculateMetricsFromParsedData)throw new Error("WASM calculate_metrics_from_parsed_data function not available");return Nt(e.workspace,t,{calculateMetricsFromParsedData:r.calculateMetricsFromParsedData})}async function Xr(e,t){return Ot(e.workspace,t)}async function Yr(e,t){return Ne(e.workspace,t)}import La from"fs/promises";import Ia from"path";async function Zr(e,t){let{workspace:r}=e,{csv_path:n,output_path:a,schema_path:o,defaults_path:c}=t;if(!n)throw new Error("csv_path is required");let s=await La.readFile(Ia.resolve(r,n),"utf8").catch(()=>{});if(s!==void 0&&!!Fe(s)||t.target_manifest||t.target_manifest_sha256)return et({workspace:r,csvPath:n,outputPath:a,schemaPath:o,defaultsPath:c,targetManifestPath:t.target_manifest,targetManifestSha256:t.target_manifest_sha256,deps:{convertGeometryCsvToJson:()=>{throw new Error("Pinned preparation cannot use legacy WASM")}}});let u;try{u=await Ae()}catch(m){return{ok:!1,error:`WASM initialization failed: ${m.message}`}}return $e(r),et({workspace:r,csvPath:n,outputPath:a,schemaPath:o,defaultsPath:c,deps:{convertGeometryCsvToJson:u.convertGeometryCsvToJson}})}import Qr from"path";async function en(e,t){return It({csvPath:Qr.isAbsolute(t.csv_path)?t.csv_path:Qr.join(e.workspace,t.csv_path),failOn:t.fail_on,repoRoot:process.cwd()})}import tn from"path";async function rn(e,t){return Wt({csvPath:tn.isAbsolute(t.csv_path)?t.csv_path:tn.join(e.workspace,t.csv_path),mode:t.mode,repoRoot:process.cwd()})}import nn from"path";async function an(e,t){return Dt({csvPath:nn.isAbsolute(t.csv_path)?t.csv_path:nn.join(e.workspace,t.csv_path),includeAuto:t.include_auto,mode:t.mode,repoRoot:process.cwd()})}var ge={vulcan_list_parameters:_.object({category:_.string().optional().describe('Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")')}),vulcan_view_parameter:_.object({category:_.string().describe('Parameter category (e.g., "heat_source_wet", "controls", "base_json")'),parameter_id:_.string().describe("Parameter ID (filename without .json extension)")}),vulcan_save_parameter:_.object({category:_.string().describe('Parameter category (e.g., "heat_source_wet", "controls")'),parameter_id:_.string().describe("Parameter ID (filename without .json extension)"),content:_.record(_.string(),_.any()).describe("Parameter JSON content (must be valid JSON object)"),markdown_content:_.string().optional().describe("Optional markdown documentation for the parameter")}),vulcan_create_batch_config:_.object({config_name:_.string().describe("Configuration name (will be saved as {config_name}.json)"),base_model:_.string().describe("Base model filename (without .json extension)"),weather_file:_.string().optional().describe("EPW filename in batch_parameters/weather_files (extension optional); required for unpinned models, optional for pinned models (omit for reference weather)"),target_manifest:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned models otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it"),wrapper:_.string().optional().describe('Optional model wrapper (e.g., "fhs_compliance", "passthrough")'),parameters:_.preprocess(e=>!e||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r=="string")try{let n=JSON.parse(r);return[t,Array.isArray(n)?n:[n]]}catch{return[t,[r]]}return[t,Array.isArray(r)?r:[r]]})),_.record(_.string(),_.array(_.string()))).describe("Object mapping category to array of parameter IDs")}),vulcan_run_batch:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),job_id:_.string().optional().describe("Optional custom job ID (defaults to mcp_{uuid})"),target_manifest:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned batches otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_get_batch_status:_.object({job_id:_.string().optional().describe("Job ID returned from vulcan_run_batch"),config_name:_.string().optional().describe("Configuration name (alternative to job_id, since config names are unique)")}).refine(e=>e.job_id||e.config_name,{message:"Either job_id or config_name must be provided"}),vulcan_calculate_metrics:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),model_names:_.array(_.string()).describe("Array of model names to calculate metrics for"),metric_definitions:_.array(_.object({id:_.string().optional(),name:_.string().optional(),column:_.string().optional(),function:_.enum(["sum","average","peak","min","cost","sumIf","averageIf","countIf"]).optional(),comparator:_.string().optional(),threshold:_.number().optional()})).describe("Array of metric definitions"),time_range:_.object({start:_.number().optional(),end:_.number().optional()}).optional().describe("Optional time range filter"),tariff_file_path:_.string().optional().describe("Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."),tariff_column_index:_.number().optional().describe("Zero-based index of tariff column in CSV. Required for cost metrics.")}),vulcan_list_csv_columns:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)"),model_name:_.string().describe('Model name (e.g., "scenario_1_0")')}),vulcan_list_batch_models:_.object({config_name:_.string().describe("Configuration name (with or without .json extension)")}),vulcan_merge_csv_to_json:_.object({csv_path:_.string().describe("Path to CSV file (relative to workspace or absolute)"),output_path:_.string().optional().describe("Optional: output JSON path (defaults to input/batch_parameters/base_json/{csv_filename}.json)"),schema_path:_.string().optional().describe("Optional: custom schema path (defaults to the core schema with workspace fallbacks)"),defaults_path:_.string().optional().describe("Optional: custom defaults path. Declared paths must load; standard defaults are used only for legacy CSVs without DefaultsPath."),target_manifest:_.string().optional().describe("Optional offline override: local bundle manifest path; pinned CSVs otherwise download their verified target"),target_manifest_sha256:_.string().optional().describe("Expected SHA-256 of target_manifest; required with it")}),vulcan_validate_geometry_csv:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),fail_on:_.enum(["none","critical","warning"]).optional().describe("Validation exit policy for the wrapped CLI. Defaults to critical.")}),vulcan_auto_thermal_bridges:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),mode:_.enum(["summary","json","csv-section"]).optional().describe("Wrapped auto-TB CLI output mode. Defaults to summary.")}),vulcan_validate_thermal_bridges:_.object({csv_path:_.string().describe("Path to geometry CSV file (relative to workspace or absolute)"),include_auto:_.boolean().optional().describe("Also synthesize auto-TB proposals before validation."),mode:_.enum(["summary","json"]).optional().describe("Wrapped TB validation CLI output mode. Defaults to summary.")})},sn=[{name:"vulcan_list_parameters",description:`List available parameter categories and their JSON snippets.
2303
21
 
2304
22
  Use this to discover what parameters are available before creating batch configurations.
2305
23
  Returns a catalog of all categories (e.g., base_json, heat_source_wet, controls) and their parameters.
2306
24
 
2307
25
  Example: Call with category='base_json' to see all base models available.
2308
- See also: vulcan_view_parameter to see details of a specific parameter.`,
2309
- inputSchema: {
2310
- type: "object",
2311
- properties: {
2312
- category: {
2313
- type: "string",
2314
- description: 'Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")'
2315
- }
2316
- }
2317
- }
2318
- },
2319
- {
2320
- name: "vulcan_view_parameter",
2321
- description: `View a specific parameter JSON snippet and its markdown documentation.
26
+ See also: vulcan_view_parameter to see details of a specific parameter.`,inputSchema:{type:"object",properties:{category:{type:"string",description:'Optional: filter by category name (e.g., "base_json", "heat_source_wet", "controls")'}}}},{name:"vulcan_view_parameter",description:`View a specific parameter JSON snippet and its markdown documentation.
2322
27
 
2323
28
  Use this to see the full content of a parameter after discovering it with vulcan_list_parameters.
2324
29
  Returns both the JSON content and optional markdown documentation if available.
2325
30
 
2326
31
  Example: View the "hp" parameter in "heat_source_wet" category to see heat pump configuration.
2327
- See also: vulcan_list_parameters to discover available parameters.`,
2328
- inputSchema: {
2329
- type: "object",
2330
- required: ["category", "parameter_id"],
2331
- properties: {
2332
- category: { type: "string" },
2333
- parameter_id: { type: "string" }
2334
- }
2335
- }
2336
- },
2337
- {
2338
- name: "vulcan_save_parameter",
2339
- description: `Create or edit a parameter JSON snippet with validation.
32
+ See also: vulcan_list_parameters to discover available parameters.`,inputSchema:{type:"object",required:["category","parameter_id"],properties:{category:{type:"string"},parameter_id:{type:"string"}}}},{name:"vulcan_save_parameter",description:`Create or edit a parameter JSON snippet with validation.
2340
33
 
2341
34
  Use this to create new parameters or modify existing ones. The parameter will be validated
2342
35
  against the schema and baseline model before saving. Validation ensures the parameter is
2343
36
  compatible with the HEM engine.
2344
37
 
2345
38
  Example: Create a new heat pump configuration or modify an existing control schedule.
2346
- See also: vulcan_view_parameter to view existing parameters before editing.`,
2347
- inputSchema: {
2348
- type: "object",
2349
- required: ["category", "parameter_id", "content"],
2350
- properties: {
2351
- category: { type: "string" },
2352
- parameter_id: { type: "string" },
2353
- content: { type: "object" },
2354
- markdown_content: { type: "string" }
2355
- }
2356
- }
2357
- },
2358
- {
2359
- name: "vulcan_create_batch_config",
2360
- description: `Create a batch configuration with base model, weather file, wrapper, and parameters.
39
+ See also: vulcan_view_parameter to view existing parameters before editing.`,inputSchema:{type:"object",required:["category","parameter_id","content"],properties:{category:{type:"string"},parameter_id:{type:"string"},content:{type:"object"},markdown_content:{type:"string"}}}},{name:"vulcan_create_batch_config",description:`Create a batch configuration with base model, weather file, wrapper, and parameters.
2361
40
 
2362
41
  Use this to create a batch simulation configuration that can be executed with vulcan_run_batch.
2363
- The config defines which parameters to combine in a batch run. All parameter files must exist.
42
+ The config defines which parameters to combine in a batch run. All parameter files must exist. A base model whose CSV pins a HEM target (TargetBundleId) captures its exact source/snippet snapshot through that target: the first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python) and needs Google Chrome installed. weather_file is required only for unpinned models; omit it for a pinned model's reference weather. target_manifest plus target_manifest_sha256 are an optional offline override.
2364
43
 
2365
44
  Example: Create a config comparing different insulation levels with a heat pump system.
2366
- See also: vulcan_list_parameters to discover available parameters, vulcan_run_batch to execute.`,
2367
- inputSchema: {
2368
- type: "object",
2369
- required: ["config_name", "base_model", "weather_file", "parameters"],
2370
- properties: {
2371
- config_name: { type: "string" },
2372
- base_model: { type: "string" },
2373
- weather_file: { type: "string" },
2374
- wrapper: { type: "string" },
2375
- parameters: {
2376
- type: "object",
2377
- additionalProperties: {
2378
- oneOf: [
2379
- { type: "array", items: { type: "string" } },
2380
- { type: "string" }
2381
- // Allow strings that will be parsed to arrays
2382
- ]
2383
- }
2384
- }
2385
- }
2386
- }
2387
- },
2388
- {
2389
- name: "vulcan_run_batch",
2390
- description: `Run a batch simulation configuration asynchronously.
45
+ See also: vulcan_list_parameters to discover available parameters, vulcan_run_batch to execute.`,inputSchema:{type:"object",required:["config_name","base_model","parameters"],properties:{config_name:{type:"string"},base_model:{type:"string"},weather_file:{type:"string",description:"EPW filename (extension optional); required for unpinned models, optional for pinned models"},target_manifest:{type:"string",description:"Optional offline override: local bundle manifest path"},target_manifest_sha256:{type:"string",description:"Expected SHA-256 of target_manifest; required with it"},wrapper:{type:"string"},parameters:{type:"object",additionalProperties:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}}}},{name:"vulcan_run_batch",description:`Run a batch simulation configuration asynchronously.
2391
46
 
2392
47
  Use this to execute a batch configuration created with vulcan_create_batch_config.
2393
- The simulation runs in the background and progress can be checked with vulcan_get_batch_status.
48
+ Unpinned batches run on the installed engine. A batch created from a pinned model runs its saved HEM target in Google Chrome (install it separately): the first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python), execution runs in the background, and vulcan_get_batch_status reads download and calculation progress. Long Python calculation duration is expected. target_manifest plus target_manifest_sha256 are an optional offline override.
2394
49
 
2395
50
  Example: Run a batch config named "insulation_test" to execute all parameter combinations.
2396
- See also: vulcan_get_batch_status to check progress, vulcan_create_batch_config to create configs.`,
2397
- inputSchema: {
2398
- type: "object",
2399
- required: ["config_name"],
2400
- properties: {
2401
- config_name: { type: "string" },
2402
- job_id: { type: "string" }
2403
- }
2404
- }
2405
- },
2406
- {
2407
- name: "vulcan_get_batch_status",
2408
- description: `Get the status, progress, and results summary of a batch run.
51
+ See also: vulcan_get_batch_status to check progress, vulcan_create_batch_config to create configs.`,inputSchema:{type:"object",required:["config_name"],properties:{config_name:{type:"string"},job_id:{type:"string"},target_manifest:{type:"string",description:"Optional offline override: local bundle manifest path"},target_manifest_sha256:{type:"string",description:"Expected SHA-256 of target_manifest; required with it"}}}},{name:"vulcan_get_batch_status",description:`Get the status, progress, and results summary of a batch run.
2409
52
 
2410
53
  Use this to check the progress of a batch simulation started with vulcan_run_batch.
2411
54
  Returns current status (queued/running/completed/error), progress percentage, and pass/fail counts.
@@ -2413,18 +56,7 @@ Returns current status (queued/running/completed/error), progress percentage, an
2413
56
  You can provide either job_id (returned from vulcan_run_batch) or config_name (since config names are unique).
2414
57
 
2415
58
  Example: Check status using config_name "my_batch_config" or job_id "mcp_abc123".
2416
- See also: vulcan_run_batch to start a batch, vulcan_calculate_metrics to analyze results.`,
2417
- inputSchema: {
2418
- type: "object",
2419
- properties: {
2420
- job_id: { type: "string", description: "Job ID returned from vulcan_run_batch" },
2421
- config_name: { type: "string", description: "Configuration name (alternative to job_id)" }
2422
- }
2423
- }
2424
- },
2425
- {
2426
- name: "vulcan_calculate_metrics",
2427
- description: `Calculate metrics by aggregating columns from simulation results.
59
+ See also: vulcan_run_batch to start a batch, vulcan_calculate_metrics to analyze results.`,inputSchema:{type:"object",properties:{job_id:{type:"string",description:"Job ID returned from vulcan_run_batch"},config_name:{type:"string",description:"Configuration name (alternative to job_id)"}}}},{name:"vulcan_calculate_metrics",description:`Calculate metrics by aggregating columns from simulation results.
2428
60
 
2429
61
  Use this to compute metrics (sum, average, peak, min, cost) from CSV result files after a batch run.
2430
62
  Supports time range filtering and conditional metrics (sumIf, averageIf).
@@ -2434,71 +66,19 @@ Tariff file must be CSV with 17,520 rows (half-hourly for a full year).
2434
66
 
2435
67
  Example: Calculate total electricity consumption and peak demand for all models in a batch.
2436
68
  Example with tariff: Calculate cost using Octopus Agile rates from input/tariff_data_structured/Octopus.csv, column index 2.
2437
- See also: vulcan_get_batch_status to check if batch is complete, vulcan_run_batch to start batch.`,
2438
- inputSchema: {
2439
- type: "object",
2440
- required: ["config_name", "model_names", "metric_definitions"],
2441
- properties: {
2442
- config_name: { type: "string" },
2443
- model_names: { type: "array", items: { type: "string" } },
2444
- metric_definitions: { type: "array" },
2445
- time_range: {
2446
- type: "object",
2447
- description: "Optional time range filter (start and end timesteps)",
2448
- properties: {
2449
- start: { type: "number" },
2450
- end: { type: "number" }
2451
- }
2452
- },
2453
- tariff_file_path: {
2454
- type: "string",
2455
- description: "Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."
2456
- },
2457
- tariff_column_index: {
2458
- type: "number",
2459
- description: "Zero-based index of tariff column in CSV. Required for cost metrics."
2460
- }
2461
- }
2462
- }
2463
- },
2464
- {
2465
- name: "vulcan_list_csv_columns",
2466
- description: `List available columns from a CSV result file.
69
+ See also: vulcan_get_batch_status to check if batch is complete, vulcan_run_batch to start batch.`,inputSchema:{type:"object",required:["config_name","model_names","metric_definitions"],properties:{config_name:{type:"string"},model_names:{type:"array",items:{type:"string"}},metric_definitions:{type:"array"},time_range:{type:"object",description:"Optional time range filter (start and end timesteps)",properties:{start:{type:"number"},end:{type:"number"}}},tariff_file_path:{type:"string",description:"Path to tariff CSV file (relative to workspace or absolute). Required for cost metrics."},tariff_column_index:{type:"number",description:"Zero-based index of tariff column in CSV. Required for cost metrics."}}}},{name:"vulcan_list_csv_columns",description:`List available columns from a CSV result file.
2467
70
 
2468
71
  Use this to discover what columns are available in a model's results before calculating metrics.
2469
72
  Returns column names, units, and their indices.
2470
73
 
2471
74
  Example: List columns for model "scenario_1_0" in config "my_batch" to see available data columns.
2472
- See also: vulcan_list_batch_models to get model names, vulcan_calculate_metrics to compute metrics.`,
2473
- inputSchema: {
2474
- type: "object",
2475
- required: ["config_name", "model_name"],
2476
- properties: {
2477
- config_name: { type: "string" },
2478
- model_name: { type: "string" }
2479
- }
2480
- }
2481
- },
2482
- {
2483
- name: "vulcan_list_batch_models",
2484
- description: `List all model names from a completed batch run.
75
+ See also: vulcan_list_batch_models to get model names, vulcan_calculate_metrics to compute metrics.`,inputSchema:{type:"object",required:["config_name","model_name"],properties:{config_name:{type:"string"},model_name:{type:"string"}}}},{name:"vulcan_list_batch_models",description:`List all model names from a completed batch run.
2485
76
 
2486
77
  Use this to discover which models were generated by a batch run, so you can use them in vulcan_calculate_metrics.
2487
78
  Returns all model names that have result CSV files.
2488
79
 
2489
80
  Example: List models from config "my_batch" to get ["scenario_1_0", "scenario_1_1", ...].
2490
- See also: vulcan_get_batch_status to check if batch is complete, vulcan_calculate_metrics to analyze results.`,
2491
- inputSchema: {
2492
- type: "object",
2493
- required: ["config_name"],
2494
- properties: {
2495
- config_name: { type: "string" }
2496
- }
2497
- }
2498
- },
2499
- {
2500
- name: "vulcan_merge_csv_to_json",
2501
- description: `Convert a geometry CSV file to JSON format using WASM conversion.
81
+ See also: vulcan_get_batch_status to check if batch is complete, vulcan_calculate_metrics to analyze results.`,inputSchema:{type:"object",required:["config_name"],properties:{config_name:{type:"string"}}}},{name:"vulcan_merge_csv_to_json",description:`Convert a geometry CSV file to JSON format using WASM conversion.
2502
82
 
2503
83
  This tool performs the same conversion as the geometry canvas save operation:
2504
84
  - Parses CSV geometry data
@@ -2511,334 +91,35 @@ the CSV file to specify its own defaults template path in the metadata section.
2511
91
  If a CSV declares DefaultsPath, that file must load; the standard defaults template
2512
92
  is used only for legacy CSVs with no DefaultsPath row.
2513
93
 
94
+ A CSV saved by the current app pins a HEM target (TargetBundleId) and is prepared by that
95
+ target's own schema, defaults and converter in Google Chrome (install it separately). The
96
+ first use downloads and verifies the target (about 12 MB for Rust, 75 MB for Python) into
97
+ ~/.cache/vulcan/hem-targets. target_manifest plus target_manifest_sha256 are an optional
98
+ offline override.
99
+
2514
100
  Example: Convert input/base_models/my_model.csv to JSON.
2515
- See also: vulcan_list_parameters to see available base models.`,
2516
- inputSchema: {
2517
- type: "object",
2518
- required: ["csv_path"],
2519
- properties: {
2520
- csv_path: { type: "string" },
2521
- output_path: { type: "string" },
2522
- schema_path: { type: "string" },
2523
- defaults_path: { type: "string" }
2524
- }
2525
- }
2526
- },
2527
- {
2528
- name: "vulcan_validate_geometry_csv",
2529
- description: `Validate a geometry CSV through the existing Vulcan geometry validator CLI.
101
+ See also: vulcan_list_parameters to see available base models.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},output_path:{type:"string"},schema_path:{type:"string"},defaults_path:{type:"string"},target_manifest:{type:"string",description:"Optional offline override: local bundle manifest path"},target_manifest_sha256:{type:"string",description:"Expected SHA-256 of target_manifest; required with it"}}}},{name:"vulcan_validate_geometry_csv",description:`Validate a geometry CSV through the existing Vulcan geometry validator CLI.
2530
102
 
2531
103
  This wraps npm run validate:geometry-csv and reuses the same pure web validators used by
2532
104
  Build Geometry. It reports element, zone, global, missing-element, and Part F findings
2533
105
  without reimplementing validation logic in MCP.
2534
106
 
2535
- Example: Validate input/base_models/H283_target.csv before merging or running batches.`,
2536
- inputSchema: {
2537
- type: "object",
2538
- required: ["csv_path"],
2539
- properties: {
2540
- csv_path: { type: "string" },
2541
- fail_on: { type: "string", enum: ["none", "critical", "warning"] }
2542
- }
2543
- }
2544
- },
2545
- {
2546
- name: "vulcan_auto_thermal_bridges",
2547
- description: `Generate auto thermal-bridge proposals through the existing Vulcan auto-TB CLI.
107
+ Example: Validate input/base_models/H283_target.csv before merging or running batches.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},fail_on:{type:"string",enum:["none","critical","warning"]}}}},{name:"vulcan_auto_thermal_bridges",description:`Generate auto thermal-bridge proposals through the existing Vulcan auto-TB CLI.
2548
108
 
2549
- This wraps scripts/auto-tb-cli.ts and reuses the web app's per-junction thermal-bridge
109
+ This wraps the Community CLI's thermal-bridges command and reuses the web app's per-junction thermal-bridge
2550
110
  proposal pipeline. Use mode=json for structured proposals, summary for a compact table,
2551
- or csv-section for a pasteable Thermal Bridging Elements CSV section.`,
2552
- inputSchema: {
2553
- type: "object",
2554
- required: ["csv_path"],
2555
- properties: {
2556
- csv_path: { type: "string" },
2557
- mode: { type: "string", enum: ["summary", "json", "csv-section"] }
2558
- }
2559
- }
2560
- },
2561
- {
2562
- name: "vulcan_validate_thermal_bridges",
2563
- description: `Validate ThermalBridgeLinear rows through the existing Vulcan TB validation CLI.
111
+ or csv-section for a pasteable Thermal Bridging Elements CSV section.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},mode:{type:"string",enum:["summary","json","csv-section"]}}}},{name:"vulcan_validate_thermal_bridges",description:`Validate ThermalBridgeLinear rows through the existing Vulcan TB validation CLI.
2564
112
 
2565
- This wraps scripts/validate-tb-cli.ts and reuses findLinearThermalBridgeIssues plus
113
+ This wraps the Community CLI's thermal-bridges --validate command and reuses findLinearThermalBridgeIssues plus
2566
114
  validateElementCore. Set include_auto=true to validate existing CSV rows plus synthesized
2567
- auto-TB proposals without mutating the CSV.`,
2568
- inputSchema: {
2569
- type: "object",
2570
- required: ["csv_path"],
2571
- properties: {
2572
- csv_path: { type: "string" },
2573
- include_auto: { type: "boolean" },
2574
- mode: { type: "string", enum: ["summary", "json"] }
2575
- }
2576
- }
2577
- }
2578
- ];
2579
- async function handleToolCall(name, args, config) {
2580
- switch (name) {
2581
- case "vulcan_list_parameters": {
2582
- const params = toolSchemas.vulcan_list_parameters.parse(args);
2583
- return await listParameters2(config, params);
2584
- }
2585
- case "vulcan_view_parameter": {
2586
- const params = toolSchemas.vulcan_view_parameter.parse(args);
2587
- return await viewParameter2(config, params);
2588
- }
2589
- case "vulcan_save_parameter": {
2590
- const { category, parameter_id, content, markdown_content } = args || {};
2591
- if (!category || typeof category !== "string") {
2592
- throw new Error("category is required and must be a string");
2593
- }
2594
- if (!parameter_id || typeof parameter_id !== "string") {
2595
- throw new Error("parameter_id is required and must be a string");
2596
- }
2597
- if (!content || typeof content !== "object" || Array.isArray(content)) {
2598
- throw new Error("content is required and must be a JSON object");
2599
- }
2600
- const saveParams = {
2601
- category,
2602
- parameter_id,
2603
- content,
2604
- ...markdown_content ? { markdown_content } : {}
2605
- };
2606
- return await saveParameter2(config, saveParams);
2607
- }
2608
- case "vulcan_create_batch_config": {
2609
- const { config_name, base_model, weather_file, wrapper, parameters } = args || {};
2610
- if (!config_name || typeof config_name !== "string") {
2611
- throw new Error("config_name is required and must be a string");
2612
- }
2613
- if (!base_model || typeof base_model !== "string") {
2614
- throw new Error("base_model is required and must be a string");
2615
- }
2616
- if (!weather_file || typeof weather_file !== "string") {
2617
- throw new Error("weather_file is required and must be a string");
2618
- }
2619
- let parsedParameters = {};
2620
- if (parameters) {
2621
- if (typeof parameters !== "object" || Array.isArray(parameters)) {
2622
- throw new Error("parameters must be an object mapping category to array of parameter IDs");
2623
- }
2624
- parsedParameters = Object.fromEntries(
2625
- Object.entries(parameters).map(([key, value]) => {
2626
- if (typeof value === "string") {
2627
- try {
2628
- const parsed = JSON.parse(value);
2629
- return [key, Array.isArray(parsed) ? parsed : [parsed]];
2630
- } catch {
2631
- return [key, [value]];
2632
- }
2633
- }
2634
- return [key, Array.isArray(value) ? value : [value]];
2635
- })
2636
- );
2637
- }
2638
- const createParams = {
2639
- config_name,
2640
- base_model,
2641
- weather_file,
2642
- ...wrapper ? { wrapper } : {},
2643
- parameters: parsedParameters
2644
- };
2645
- return await createBatchConfig2(config, createParams);
2646
- }
2647
- case "vulcan_run_batch": {
2648
- const params = toolSchemas.vulcan_run_batch.parse(args);
2649
- return await runBatch2(config, params);
2650
- }
2651
- case "vulcan_get_batch_status": {
2652
- const params = toolSchemas.vulcan_get_batch_status.parse(args);
2653
- return await getBatchStatus2(config, params);
2654
- }
2655
- case "vulcan_calculate_metrics": {
2656
- const params = toolSchemas.vulcan_calculate_metrics.parse(args);
2657
- return await calculateMetrics2(config, params);
2658
- }
2659
- case "vulcan_list_csv_columns": {
2660
- const params = toolSchemas.vulcan_list_csv_columns.parse(args);
2661
- return await listCsvColumns2(config, params);
2662
- }
2663
- case "vulcan_list_batch_models": {
2664
- const params = toolSchemas.vulcan_list_batch_models.parse(args);
2665
- return await listBatchModels2(config, params);
2666
- }
2667
- case "vulcan_merge_csv_to_json": {
2668
- const params = toolSchemas.vulcan_merge_csv_to_json.parse(args);
2669
- return await mergeCsvToJson(config, params);
2670
- }
2671
- case "vulcan_validate_geometry_csv": {
2672
- const params = toolSchemas.vulcan_validate_geometry_csv.parse(args);
2673
- return await validateGeometryCsv2(config, params);
2674
- }
2675
- case "vulcan_auto_thermal_bridges": {
2676
- const params = toolSchemas.vulcan_auto_thermal_bridges.parse(args);
2677
- return await generateAutoThermalBridges2(config, params);
2678
- }
2679
- case "vulcan_validate_thermal_bridges": {
2680
- const params = toolSchemas.vulcan_validate_thermal_bridges.parse(args);
2681
- return await validateThermalBridges2(config, params);
2682
- }
2683
- default:
2684
- throw new Error(`Unknown tool: ${name}`);
2685
- }
2686
- }
2687
-
2688
- // src/server.ts
2689
- async function startServer(configPath, port) {
2690
- const httpPort = port || parseInt(process.env.HELPER_PORT || "5000", 10);
2691
- let config;
2692
- try {
2693
- config = await readConfig(configPath);
2694
- console.error(`[MCP Helper] Config loaded from: ${config.configPath}`);
2695
- console.error(`[MCP Helper] Workspace: ${config.workspace}`);
2696
- } catch (error) {
2697
- const err = error;
2698
- console.error(`[MCP Helper] Failed to load config: ${err.message}`);
2699
- process.exit(1);
2700
- }
2701
- try {
2702
- await initWasm();
2703
- console.error("[MCP Helper] WASM initialized");
2704
- } catch (error) {
2705
- const err = error;
2706
- console.error(`[MCP Helper] WASM initialization failed: ${err.message}`);
2707
- process.exit(1);
2708
- }
2709
- const app = express();
2710
- const corsOptions = {
2711
- origin: true,
2712
- // Allow all origins (localhost, 127.0.0.1, etc.)
2713
- methods: ["GET", "OPTIONS"],
2714
- credentials: false
2715
- };
2716
- const mcpServer = new Server(
2717
- {
2718
- name: "vulcan-mcp-helper",
2719
- version: "0.1.0"
2720
- },
2721
- {
2722
- capabilities: {
2723
- tools: {}
2724
- }
2725
- }
2726
- );
2727
- const originalOnInitialize = mcpServer._oninitialize?.bind(mcpServer);
2728
- if (originalOnInitialize) {
2729
- mcpServer.removeRequestHandler("initialize");
2730
- const LegacyInitializeSchema = InitializeRequestSchema.extend({
2731
- params: InitializeRequestSchema.shape.params.partial().transform((params = {}) => ({
2732
- protocolVersion: params.protocolVersion || "2024-11-05",
2733
- capabilities: params.capabilities || {},
2734
- clientInfo: params.clientInfo || { name: "unknown-client", version: "0.0.0" }
2735
- }))
2736
- });
2737
- mcpServer.setRequestHandler(LegacyInitializeSchema, (request) => originalOnInitialize(request));
2738
- }
2739
- mcpServer.setRequestHandler(ListToolsRequestSchema, async () => {
2740
- return { tools: toolDefinitions };
2741
- });
2742
- mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
2743
- const { name, arguments: toolArgs } = request.params;
2744
- console.error(`[MCP Helper] Tool call: ${name}`);
2745
- try {
2746
- const result = await handleToolCall(name, toolArgs, config);
2747
- return {
2748
- content: [
2749
- {
2750
- type: "text",
2751
- text: JSON.stringify(result, null, 2)
2752
- }
2753
- ]
2754
- };
2755
- } catch (error) {
2756
- const err = error;
2757
- console.error(`[MCP Helper] Tool call failed: ${err.message}`);
2758
- throw err;
2759
- }
2760
- });
2761
- app.post("/mcp", express.raw({ type: "application/json", limit: "10mb" }), async (req, res) => {
2762
- try {
2763
- await authorizeMcpRequest(req.headers.authorization, config.license_token);
2764
- } catch {
2765
- console.error("[MCP Helper] Rejected unauthorized MCP request");
2766
- res.set("WWW-Authenticate", 'Bearer realm="vulcan-mcp"').status(401).json({
2767
- jsonrpc: "2.0",
2768
- error: {
2769
- code: -32001,
2770
- message: "Unauthorized"
2771
- },
2772
- id: null
2773
- });
2774
- return;
2775
- }
2776
- let requestBody;
2777
- try {
2778
- const bodyText = req.body.toString("utf-8");
2779
- requestBody = JSON.parse(bodyText);
2780
- } catch (error) {
2781
- const err = error;
2782
- res.status(400).json({
2783
- jsonrpc: "2.0",
2784
- error: {
2785
- code: -32700,
2786
- message: "Parse error",
2787
- data: err.message
2788
- },
2789
- id: null
2790
- });
2791
- return;
2792
- }
2793
- const transport = new StreamableHTTPServerTransport({
2794
- sessionIdGenerator: void 0,
2795
- enableJsonResponse: true
2796
- });
2797
- res.on("close", () => {
2798
- transport.close();
2799
- });
2800
- try {
2801
- await mcpServer.connect(transport);
2802
- await transport.handleRequest(req, res, requestBody);
2803
- } catch (error) {
2804
- const err = error;
2805
- console.error(`[MCP Helper] MCP request failed: ${err.message}`);
2806
- if (!res.headersSent) {
2807
- res.status(500).json({
2808
- jsonrpc: "2.0",
2809
- error: {
2810
- code: -32603,
2811
- message: "Internal server error",
2812
- data: err.message
2813
- },
2814
- id: requestBody?.id || null
2815
- });
2816
- }
2817
- }
2818
- });
2819
- app.get("/health", cors(corsOptions), (req, res) => {
2820
- res.json({
2821
- status: "running",
2822
- port: httpPort,
2823
- version: "0.1.0",
2824
- name: "vulcan-mcp-helper"
2825
- });
2826
- });
2827
- app.get("/helper/status", cors(corsOptions), (req, res) => {
2828
- res.json({
2829
- running: true,
2830
- port: httpPort,
2831
- version: "0.1.0",
2832
- mcpReady: true
2833
- });
2834
- });
2835
- app.listen(httpPort, "127.0.0.1", () => {
2836
- console.error(`[MCP Helper] Server running on http://127.0.0.1:${httpPort}`);
2837
- console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${httpPort}/mcp`);
2838
- console.error(`[MCP Helper] Health check: http://127.0.0.1:${httpPort}/health`);
2839
- console.error(`[MCP Helper] Status API: http://127.0.0.1:${httpPort}/helper/status`);
2840
- });
2841
- }
2842
- export {
2843
- startServer
2844
- };
115
+ auto-TB proposals without mutating the CSV.`,inputSchema:{type:"object",required:["csv_path"],properties:{csv_path:{type:"string"},include_auto:{type:"boolean"},mode:{type:"string",enum:["summary","json"]}}}}];async function on(e,t,r){switch(e){case"vulcan_list_parameters":{let n=ge.vulcan_list_parameters.parse(t);return await Vr(r,n)}case"vulcan_view_parameter":{let n=ge.vulcan_view_parameter.parse(t);return await Jr(r,n)}case"vulcan_save_parameter":{let{category:n,parameter_id:a,content:o,markdown_content:c}=t||{};if(!n||typeof n!="string")throw new Error("category is required and must be a string");if(!a||typeof a!="string")throw new Error("parameter_id is required and must be a string");if(!o||typeof o!="object"||Array.isArray(o))throw new Error("content is required and must be a JSON object");let s={category:n,parameter_id:a,content:o,...c?{markdown_content:c}:{}};return await qr(r,s)}case"vulcan_create_batch_config":{let{config_name:n,base_model:a,weather_file:o,wrapper:c,parameters:s,target_manifest:d,target_manifest_sha256:u}=t||{};if(!n||typeof n!="string")throw new Error("config_name is required and must be a string");if(!a||typeof a!="string")throw new Error("base_model is required and must be a string");if(o!==void 0&&typeof o!="string")throw new Error("weather_file must be a string");let m={};if(s){if(typeof s!="object"||Array.isArray(s))throw new Error("parameters must be an object mapping category to array of parameter IDs");m=Object.fromEntries(Object.entries(s).map(([g,h])=>{if(typeof h=="string")try{let S=JSON.parse(h);return[g,Array.isArray(S)?S:[S]]}catch{return[g,[h]]}return[g,Array.isArray(h)?h:[h]]}))}let p={config_name:n,base_model:a,weather_file:o,...c?{wrapper:c}:{},parameters:m,target_manifest:d,target_manifest_sha256:u};return await Hr(r,p)}case"vulcan_run_batch":{let n=ge.vulcan_run_batch.parse(t);return await zr(r,n)}case"vulcan_get_batch_status":{let n=ge.vulcan_get_batch_status.parse(t);return await Gr(r,n)}case"vulcan_calculate_metrics":{let n=ge.vulcan_calculate_metrics.parse(t);return await Kr(r,n)}case"vulcan_list_csv_columns":{let n=ge.vulcan_list_csv_columns.parse(t);return await Xr(r,n)}case"vulcan_list_batch_models":{let n=ge.vulcan_list_batch_models.parse(t);return await Yr(r,n)}case"vulcan_merge_csv_to_json":{let n=ge.vulcan_merge_csv_to_json.parse(t);return await Zr(r,n)}case"vulcan_validate_geometry_csv":{let n=ge.vulcan_validate_geometry_csv.parse(t);return await en(r,n)}case"vulcan_auto_thermal_bridges":{let n=ge.vulcan_auto_thermal_bridges.parse(t);return await rn(r,n)}case"vulcan_validate_thermal_bridges":{let n=ge.vulcan_validate_thermal_bridges.parse(t);return await an(r,n)}default:throw new Error(`Unknown tool: ${e}`)}}async function Di(e,t){let r=t||parseInt(process.env.HELPER_PORT||"5000",10),n;try{n=await Yt(e),console.error(`[MCP Helper] Config loaded from: ${n.configPath}`),console.error(`[MCP Helper] Workspace: ${n.workspace}`)}catch(d){console.error(`[MCP Helper] Failed to load config: ${d.message}`),process.exit(1)}let a=cn(),o={origin:!0,methods:["GET","OPTIONS"],credentials:!1},c=new Wa({name:"vulcan-mcp-helper",version:"0.1.0"},{capabilities:{tools:{}}}),s=c._oninitialize?.bind(c);if(s){c.removeRequestHandler("initialize");let d=un.extend({params:un.shape.params.partial().transform((u={})=>({protocolVersion:u.protocolVersion||"2024-11-05",capabilities:u.capabilities||{},clientInfo:u.clientInfo||{name:"unknown-client",version:"0.0.0"}}))});c.setRequestHandler(d,u=>s(u))}c.setRequestHandler(Va,async()=>({tools:sn})),c.setRequestHandler(Ja,async d=>{let{name:u,arguments:m}=d.params;console.error(`[MCP Helper] Tool call: ${u}`);try{let p=await on(u,m,n);return{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}catch(p){let g=p;throw console.error(`[MCP Helper] Tool call failed: ${g.message}`),g}}),a.post("/mcp",cn.raw({type:"application/json",limit:"10mb"}),async(d,u)=>{try{await Zt(d.headers.authorization,n.license_token)}catch{console.error("[MCP Helper] Rejected unauthorized MCP request"),u.set("WWW-Authenticate",'Bearer realm="vulcan-mcp"').status(401).json({jsonrpc:"2.0",error:{code:-32001,message:"Unauthorized"},id:null});return}let m;try{let g=d.body.toString("utf-8");m=JSON.parse(g)}catch(g){let h=g;u.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:h.message},id:null});return}let p=new Da({sessionIdGenerator:void 0,enableJsonResponse:!0});u.on("close",()=>{p.close()});try{await c.connect(p),await p.handleRequest(d,u,m)}catch(g){let h=g;console.error(`[MCP Helper] MCP request failed: ${h.message}`),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:h.message},id:m?.id||null})}}),a.get("/health",ln(o),(d,u)=>{u.json({status:"running",port:r,version:"0.1.0",name:"vulcan-mcp-helper"})}),a.get("/helper/status",ln(o),(d,u)=>{u.json({running:!0,port:r,version:"0.1.0",mcpReady:!0})}),a.listen(r,"127.0.0.1",()=>{console.error(`[MCP Helper] Server running on http://127.0.0.1:${r}`),console.error(`[MCP Helper] MCP endpoint: http://127.0.0.1:${r}/mcp`),console.error(`[MCP Helper] Health check: http://127.0.0.1:${r}/health`),console.error(`[MCP Helper] Status API: http://127.0.0.1:${r}/helper/status`)})}export{Di as startServer};
116
+ /*! Bundled license information:
117
+
118
+ papaparse/papaparse.js:
119
+ (* @license
120
+ Papa Parse
121
+ v5.5.3
122
+ https://github.com/mholt/PapaParse
123
+ License: MIT
124
+ *)
125
+ */