@vulcan-energy/mcp-helper 0.1.8 → 0.2.2

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