@vulcan-energy/mcp-helper 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/vulcan-mcp-helper.js +1 -1
- package/dist/hem-target-runtime/python-worker.mjs +1 -1
- package/dist/hem-target-runtime/rust-worker.mjs +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/wasm/wasm_version.json +10 -10
- package/wasm/wasm_wrapper.js +27 -6
- package/wasm/wasm_wrapper_bg.wasm +0 -0
|
@@ -8,7 +8,7 @@ var ba=Object.create;var Dr=Object.defineProperty;var Ca=Object.getOwnPropertyDe
|
|
|
8
8
|
`:"\r"};function D(P){return c.skipEmptyLines==="greedy"?P.join("").trim()==="":P.length===1&&P[0].length===0}function J(P){if(h.test(P)){var j=parseFloat(P);if(j>p&&j<l)return!0}return!1}function Z(){return N&&le&&(ge("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&(N.data=N.data.filter(function(P){return!D(P)})),Y()&&me(),H()}function Y(){return c.header&&R.length===0}function me(){if(!N)return;function P(L,G){M(c.transformHeader)&&(L=c.transformHeader(L,G)),R.push(L)}if(Array.isArray(N.data[0])){for(var j=0;Y()&&j<N.data.length;j++)N.data[j].forEach(P);N.data.splice(0,1)}else N.data.forEach(P)}function se(P){return c.dynamicTypingFunction&&c.dynamicTyping[P]===void 0&&(c.dynamicTyping[P]=c.dynamicTypingFunction(P)),(c.dynamicTyping[P]||c.dynamicTyping)===!0}function pe(P,j){return se(P)?j==="true"||j==="TRUE"?!0:j==="false"||j==="FALSE"?!1:J(j)?parseFloat(j):w.test(j)?new Date(j):j===""?null:j:j}function H(){if(!N||!c.header&&!c.dynamicTyping&&!c.transform)return N;function P(L,G){var k=c.header?{}:[],z;for(z=0;z<L.length;z++){var oe=z,te=L[z];c.header&&(oe=z>=R.length?"__parsed_extra":R[z]),c.transform&&(te=c.transform(te,oe)),te=pe(oe,te),oe==="__parsed_extra"?(k[oe]=k[oe]||[],k[oe].push(te)):k[oe]=te}return c.header&&(z>R.length?ge("FieldMismatch","TooManyFields","Too many fields: expected "+R.length+" fields but parsed "+z,y+G):z<R.length&&ge("FieldMismatch","TooFewFields","Too few fields: expected "+R.length+" fields but parsed "+z,y+G)),k}var j=1;return!N.data.length||Array.isArray(N.data[0])?(N.data=N.data.map(P),j=N.data.length):N.data=P(N.data,0),c.header&&N.meta&&(N.meta.fields=R),y+=j,N}function ke(P,j,L,G,k){var z,oe,te,Ne;k=k||[","," ","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var Ee=0;Ee<k.length;Ee++){var Ke=k[Ee],Ie=0,Pe=0,ce=0;te=void 0;for(var ve=new $({comments:G,delimiter:Ke,newline:j,preview:10}).parse(P),ie=0;ie<ve.data.length;ie++){if(L&&D(ve.data[ie])){ce++;continue}var ue=ve.data[ie].length;if(Pe+=ue,typeof te>"u"){te=ue;continue}else ue>0&&(Ie+=Math.abs(ue-te),te=ue)}ve.data.length>0&&(Pe/=ve.data.length-ce),(typeof oe>"u"||Ie<=oe)&&(typeof Ne>"u"||Pe>Ne)&&Pe>1.99&&(oe=Ie,z=Ke,Ne=Pe)}return c.delimiter=z,{successful:!!z,bestDelimiter:z}}function ge(P,j,L,G){var k={type:P,code:j,message:L};G!==void 0&&(k.row=G),N.errors.push(k)}}function x(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(c){c=c||{};var l=c.delimiter,p=c.newline,h=c.comments,w=c.step,O=c.preview,b=c.fastMode,y,B=null,q=!1;c.quoteChar===void 0||c.quoteChar===null?y='"':y=c.quoteChar;var ee=y;if(c.escapeChar!==void 0&&(ee=c.escapeChar),(typeof l!="string"||o.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),h===l)throw new Error("Comment character same as delimiter");h===!0?h="#":(typeof h!="string"||o.BAD_DELIMITERS.indexOf(h)>-1)&&(h=!1),p!==`
|
|
9
9
|
`&&p!=="\r"&&p!==`\r
|
|
10
10
|
`&&(p=`
|
|
11
|
-
`);var F=0,le=!1;this.parse=function(R,N,Fe){if(typeof R!="string")throw new Error("Input must be a string");var D=R.length,J=l.length,Z=p.length,Y=h.length,me=M(w);F=0;var se=[],pe=[],H=[],ke=0;if(!R)return ce();if(b||b!==!1&&R.indexOf(y)===-1){for(var ge=R.split(p),P=0;P<ge.length;P++){if(H=ge[P],F+=H.length,P!==ge.length-1)F+=p.length;else if(Fe)return ce();if(!(h&&H.substring(0,Y)===h)){if(me){if(se=[],Ee(H.split(l)),ve(),le)return ce()}else Ee(H.split(l));if(O&&P>=O)return se=se.slice(0,O),ce(!0)}}return ce()}for(var j=R.indexOf(l,F),L=R.indexOf(p,F),G=new RegExp(x(ee)+x(y),"g"),k=R.indexOf(y,F);;){if(R[F]===y){for(k=F,F++;;){if(k=R.indexOf(y,k+1),k===-1)return Fe||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),Ie();if(k===D-1){var z=R.substring(F,k).replace(G,y);return Ie(z)}if(y===ee&&R[k+1]===ee){k++;continue}if(!(y!==ee&&k!==0&&R[k-1]===ee)){j!==-1&&j<k+1&&(j=R.indexOf(l,k+1)),L!==-1&&L<k+1&&(L=R.indexOf(p,k+1));var oe=L===-1?j:Math.min(j,L),te=Ke(oe);if(R.substr(k+1+te,J)===l){H.push(R.substring(F,k).replace(G,y)),F=k+1+te+J,R[k+1+te+J]!==y&&(k=R.indexOf(y,F)),j=R.indexOf(l,F),L=R.indexOf(p,F);break}var Ne=Ke(L);if(R.substring(k+1+Ne,k+1+Ne+Z)===p){if(H.push(R.substring(F,k).replace(G,y)),Pe(k+1+Ne+Z),j=R.indexOf(l,F),k=R.indexOf(y,F),me&&(ve(),le))return ce();if(O&&se.length>=O)return ce(!0);break}pe.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:se.length,index:F}),k++}}continue}if(h&&H.length===0&&R.substring(F,F+Y)===h){if(L===-1)return ce();F=L+Z,L=R.indexOf(p,F),j=R.indexOf(l,F);continue}if(j!==-1&&(j<L||L===-1)){H.push(R.substring(F,j)),F=j+J,j=R.indexOf(l,F);continue}if(L!==-1){if(H.push(R.substring(F,L)),Pe(L+Z),me&&(ve(),le))return ce();if(O&&se.length>=O)return ce(!0);continue}break}return Ie();function Ee(ie){se.push(ie),ke=F}function Ke(ie){var ue=0;if(ie!==-1){var xe=R.substring(k+1,ie);xe&&xe.trim()===""&&(ue=xe.length)}return ue}function Ie(ie){return Fe||(typeof ie>"u"&&(ie=R.substring(F)),H.push(ie),F=D,Ee(H),me&&ve()),ce()}function Pe(ie){F=ie,Ee(H),H=[],L=R.indexOf(p,F)}function ce(ie){if(c.header&&!N&&se.length&&!q){let ue=se[0],xe=Object.create(null),$t=new Set(ue),Lr=!1;for(let We=0;We<ue.length;We++){let be=ue[We];if(M(c.transformHeader)&&(be=c.transformHeader(be,We)),!xe[be])xe[be]=1,ue[We]=be;else{let Xe,Br=xe[be];do Xe=`${be}_${Br}`,Br++;while($t.has(Xe));$t.add(Xe),ue[We]=Xe,xe[be]++,Lr=!0,B===null&&(B={}),B[Xe]=be}$t.add(be)}Lr&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:p,aborted:le,truncated:!!ie,cursor:ke+(N||0),renamedHeaders:B}}}function ve(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function V(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=E,l.id=i++,s[l.id]=l,l}function E(c){var l=c.data,p=s[l.workerId],h=!1;if(l.error)p.userError(l.error,l.file);else if(l.results&&l.results.data){var w=function(){h=!0,W(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},O={abort:w,pause:Q,resume:Q};if(M(p.userStep)){for(var b=0;b<l.results.data.length&&(p.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},O),!h);b++);delete l.results}else M(p.userChunk)&&(p.userChunk(l.results,O,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var p=s[c];M(p.userComplete)&&p.userComplete(l),p.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Se(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var p=o.parse(l.input,l.config);p&&t.postMessage({workerId:o.WORKER_ID,results:p,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=ae(c[p]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return o})});import{parseArgs as Po}from"util";import _a from"express";import vo from"cors";import{McpServer as bo}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Co}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as So}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ga}from"@modelcontextprotocol/sdk/types.js";var Vr={name:"@vulcan-energy/mcp-helper",version:"0.3.
|
|
11
|
+
`);var F=0,le=!1;this.parse=function(R,N,Fe){if(typeof R!="string")throw new Error("Input must be a string");var D=R.length,J=l.length,Z=p.length,Y=h.length,me=M(w);F=0;var se=[],pe=[],H=[],ke=0;if(!R)return ce();if(b||b!==!1&&R.indexOf(y)===-1){for(var ge=R.split(p),P=0;P<ge.length;P++){if(H=ge[P],F+=H.length,P!==ge.length-1)F+=p.length;else if(Fe)return ce();if(!(h&&H.substring(0,Y)===h)){if(me){if(se=[],Ee(H.split(l)),ve(),le)return ce()}else Ee(H.split(l));if(O&&P>=O)return se=se.slice(0,O),ce(!0)}}return ce()}for(var j=R.indexOf(l,F),L=R.indexOf(p,F),G=new RegExp(x(ee)+x(y),"g"),k=R.indexOf(y,F);;){if(R[F]===y){for(k=F,F++;;){if(k=R.indexOf(y,k+1),k===-1)return Fe||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),Ie();if(k===D-1){var z=R.substring(F,k).replace(G,y);return Ie(z)}if(y===ee&&R[k+1]===ee){k++;continue}if(!(y!==ee&&k!==0&&R[k-1]===ee)){j!==-1&&j<k+1&&(j=R.indexOf(l,k+1)),L!==-1&&L<k+1&&(L=R.indexOf(p,k+1));var oe=L===-1?j:Math.min(j,L),te=Ke(oe);if(R.substr(k+1+te,J)===l){H.push(R.substring(F,k).replace(G,y)),F=k+1+te+J,R[k+1+te+J]!==y&&(k=R.indexOf(y,F)),j=R.indexOf(l,F),L=R.indexOf(p,F);break}var Ne=Ke(L);if(R.substring(k+1+Ne,k+1+Ne+Z)===p){if(H.push(R.substring(F,k).replace(G,y)),Pe(k+1+Ne+Z),j=R.indexOf(l,F),k=R.indexOf(y,F),me&&(ve(),le))return ce();if(O&&se.length>=O)return ce(!0);break}pe.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:se.length,index:F}),k++}}continue}if(h&&H.length===0&&R.substring(F,F+Y)===h){if(L===-1)return ce();F=L+Z,L=R.indexOf(p,F),j=R.indexOf(l,F);continue}if(j!==-1&&(j<L||L===-1)){H.push(R.substring(F,j)),F=j+J,j=R.indexOf(l,F);continue}if(L!==-1){if(H.push(R.substring(F,L)),Pe(L+Z),me&&(ve(),le))return ce();if(O&&se.length>=O)return ce(!0);continue}break}return Ie();function Ee(ie){se.push(ie),ke=F}function Ke(ie){var ue=0;if(ie!==-1){var xe=R.substring(k+1,ie);xe&&xe.trim()===""&&(ue=xe.length)}return ue}function Ie(ie){return Fe||(typeof ie>"u"&&(ie=R.substring(F)),H.push(ie),F=D,Ee(H),me&&ve()),ce()}function Pe(ie){F=ie,Ee(H),H=[],L=R.indexOf(p,F)}function ce(ie){if(c.header&&!N&&se.length&&!q){let ue=se[0],xe=Object.create(null),$t=new Set(ue),Lr=!1;for(let We=0;We<ue.length;We++){let be=ue[We];if(M(c.transformHeader)&&(be=c.transformHeader(be,We)),!xe[be])xe[be]=1,ue[We]=be;else{let Xe,Br=xe[be];do Xe=`${be}_${Br}`,Br++;while($t.has(Xe));$t.add(Xe),ue[We]=Xe,xe[be]++,Lr=!0,B===null&&(B={}),B[Xe]=be}$t.add(be)}Lr&&console.warn("Duplicate headers found and renamed."),q=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:p,aborted:le,truncated:!!ie,cursor:ke+(N||0),renamedHeaders:B}}}function ve(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function V(){if(!o.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=E,l.id=i++,s[l.id]=l,l}function E(c){var l=c.data,p=s[l.workerId],h=!1;if(l.error)p.userError(l.error,l.file);else if(l.results&&l.results.data){var w=function(){h=!0,W(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},O={abort:w,pause:Q,resume:Q};if(M(p.userStep)){for(var b=0;b<l.results.data.length&&(p.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},O),!h);b++);delete l.results}else M(p.userChunk)&&(p.userChunk(l.results,O,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var p=s[c];M(p.userComplete)&&p.userComplete(l),p.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Se(c){var l=c.data;if(typeof o.WORKER_ID>"u"&&l&&(o.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:o.WORKER_ID,results:o.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var p=o.parse(l.input,l.config);p&&t.postMessage({workerId:o.WORKER_ID,results:p,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=ae(c[p]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return o})});import{parseArgs as Po}from"util";import _a from"express";import vo from"cors";import{McpServer as bo}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Co}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as So}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ga}from"@modelcontextprotocol/sdk/types.js";var Vr={name:"@vulcan-energy/mcp-helper",version:"0.3.3",description:"Vulcan Home Energy Model tools for AI assistants over MCP (Claude Code, Codex, Claude Desktop, Cursor). Runs locally; Free tools need no account.",repository:{type:"git",url:"git+https://github.com/baziyer/rust-hem-runner.git",directory:"vulcan-mcp-server"},type:"module",main:"./dist/server.js",types:"./dist/server.d.ts",bin:{"vulcan-mcp-helper":"dist/bin/vulcan-mcp-helper.js"},scripts:{build:"tsup --config tsup.config.ts",dev:"tsx watch bin/vulcan-mcp-helper.ts",start:"node dist/bin/vulcan-mcp-helper.js",prepublishOnly:"npm run build && npm run clean",clean:"echo 'Package is ready for publishing'",test:"node --import tsx --test src/engine/requestAuth.test.ts src/engine/licenseToken.test.ts src/engine/config.test.ts src/tools/registry.test.ts src/tools/signIn.test.ts"},keywords:["claude","codex","energy-modeling","future-homes-standard","hem","home-energy-model","mcp","model-context-protocol","vulcan"],author:"",license:"UNLICENSED",dependencies:{"@modelcontextprotocol/sdk":"^1.32.2","@vulcan-energy/community-cli":"^0.1.0",cors:"^2.8.5",express:"^4.18.2",jose:"^6.1.2","playwright-core":"^1.59.1",zod:"^4.1.12"},devDependencies:{"@types/cors":"^2.8.17","@types/express":"^4.17.21","@types/node":"^20.10.0",tsup:"^8.5.0",tsx:"^4.7.0",typescript:"^5.3.3"},engines:{node:">=20.0.0"},files:["dist/","wasm/","schemas/","package.json","README.md","LICENSE","THIRD_PARTY_NOTICES.md"]};import Ur from"fs/promises";import Ye from"path";var Wr=Object.freeze(["mcp","analyst"]);function Ot(e){return typeof e=="string"&&Wr.includes(e)}var it="https://usevulcan.app",Ft="vulcan-local-tools",ct=1,Nt=10080*60,It=300,K=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var Jr=Object.freeze([`-----BEGIN PUBLIC KEY-----
|
|
12
12
|
MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
|
|
13
13
|
-----END PUBLIC KEY-----`]);import{compactVerify as Ta,importSPKI as Ma}from"jose";var Hr="EdDSA";async function Bt(e,t){let n=e.trim();if(!n)throw new K("empty","Vulcan access token is empty.");let r=t.publicKeys??Jr,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),i=await $a(n,r),o=Oa(i);if(o.iss!==it)throw new K("wrong_issuer",`Vulcan access token was issued by ${o.iss}, not ${it}.`);if(o.aud!==Ft)throw new K("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(o.entitlement_schema_version!==ct)throw new K("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${o.entitlement_schema_version}, but this build understands version ${ct}. Update your Vulcan tools.`);if(!o.capabilities.includes(t.capability))throw new K("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(o.exp-o.iat>Nt)throw new K("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(s<o.iat-It)throw new K("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let u=s>o.exp;if(u&&!t.allowExpired)throw new K("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:o,expired:u,expiresAt:new Date(o.exp*1e3),expiresInSeconds:o.exp-s}}async function $a(e,t){for(let n of t)try{let r=await Ma(n,Hr),{payload:a}=await Ta(e,r,{algorithms:[Hr]});return a}catch{}throw new K("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function Oa(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new K("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new K("malformed","Vulcan access token payload is not an object.");let n=t,r=Ze(n,"iss"),a=Ze(n,"aud"),s=Ze(n,"sub"),i=Ze(n,"org"),o=Ze(n,"jti"),u=Lt(n,"iat"),d=Lt(n,"exp"),m=Lt(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new K("malformed","Vulcan access token must include a capabilities array.");let _=[];for(let g of n.capabilities){if(!Ot(g))throw new K("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(g)}.`);_.push(g)}if(_.length===0)throw new K("malformed","Vulcan access token grants no capabilities.");if(d<=u)throw new K("malformed","Vulcan access token expires no later than it was issued.");return{iss:r,aud:a,sub:s,org:i,jti:o,capabilities:Object.freeze(_),entitlement_schema_version:m,iat:u,exp:d}}function Ze(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new K("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function Lt(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new K("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return n}var Fa="mcp",Na=2880*60;async function Dt(e={}){let t=Ye.resolve(e.workspace??process.env.VULCAN_WORKSPACE??process.cwd()),n=Ye.resolve(e.configPath??Ye.join(t,"vulcan-mcp-config.json")),r;try{r=await Ur.readFile(n,"utf-8")}catch{if(e.configPath)throw new Error(`Config file not found: ${n}. Generate one in Vulcan \u2192 Profile \u2192 Integrations \u2192 MCP, or omit --config to run Free.`)}let a=t,s;if(r!==void 0){let i;try{i=JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in config file ${n}: ${o.message}`)}if(i.workspace!==void 0){if(typeof i.workspace!="string")throw new Error("Config field workspace must be a string");a=Ye.resolve(Ye.dirname(n),i.workspace)}if(i.license_token!==void 0){if(typeof i.license_token!="string"||!i.license_token)throw new Error("Config field license_token must be a non-empty string");s=i.license_token}}try{await Ur.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}if(s){let{payload:i}=await lt(s,{allowExpired:!0}),o=i.exp-Math.floor(Date.now()/1e3);if(o<=0)console.error("[MCP Helper] Your Vulcan Pro access has expired: Free tools work; ask your assistant to sign in again (vulcan_sign_in) to renew.");else if(o<Na){let u=Math.max(1,Math.round(o/3600));console.error(`[MCP Helper] Warning: your Vulcan access expires in about ${u} hour(s). Ask your assistant to sign in again (vulcan_sign_in), or open Vulcan -> Profile -> Integrations and click "Generate Config File".`)}}return{workspace:a,...s?{license_token:s}:{},...r!==void 0?{configPath:n}:{}}}async function zr(e,t={}){if(!e.license_token)return{pro:!1,detail:"No Vulcan Pro access config is set; Free tools only."};try{return await lt(e.license_token,t),{pro:!0,detail:"Vulcan Pro access config is valid."}}catch(n){return{pro:!1,detail:n.message}}}async function lt(e,t={}){try{let{claims:n}=await Bt(e,{capability:Fa,now:t.now,publicKeys:t.publicKeys,allowExpired:t.allowExpired});return{payload:n}}catch(n){throw new Error(Ia(n))}}function Ia(e){if(!(e instanceof K))return e instanceof Error?e.message:String(e);switch(e.code){case"missing_capability":return"This Vulcan access config does not include MCP. MCP requires a Vulcan Pro seat; open Vulcan -> Profile -> Integrations and generate a new config.";case"expired":return'Your Vulcan access config has expired. Call vulcan_sign_in to renew it, or open Vulcan -> Profile -> Integrations and click "Generate Config File".';case"unsupported_schema_version":return'This Vulcan access config was issued for a newer version of the Vulcan tools. Update the helper with "npm install -g @vulcan-energy/mcp-helper@latest".';case"lifetime_exceeded":return"This Vulcan access config declares a longer lifetime than Vulcan issues and was refused. Generate a new config.";case"clock_behind":return"This system clock is too far behind the access config issue time. Correct the clock, then restart the helper.";case"wrong_audience":case"wrong_issuer":return'This access config was not issued for local Vulcan tools. Open Vulcan -> Profile -> Integrations and click "Generate Config File".';default:return'Your Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and click "Generate Config File".'}}import{timingSafeEqual as La}from"crypto";function Ba(e){if(typeof e!="string")throw new Error("MCP request Bearer token is required");let t=/^Bearer[\t ]+([^\t ]+)$/i.exec(e.trim());if(!t?.[1])throw new Error("MCP request Bearer token is required");return t[1]}function Da(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&La(n,r)}async function qr(e,t,n=lt){let r=Ba(e);if(!Da(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as S}from"zod";import ot from"fs/promises";import Oe from"path";import Va from"fs/promises";import Wa from"path";function Gr(e,t={}){let n=[],r=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&n.push("Config must have at least one scenario");for(let[s,i]of Object.entries(e)){if(!i||typeof i!="object"){n.push(`Scenario '${s}' must be an object`);continue}let o=i;Array.isArray(o.base_json)?o.base_json.length!==1&&n.push(`Scenario '${s}' must have exactly one base_json (found ${o.base_json.length})`):n.push(`Scenario '${s}' is missing required 'base_json' field (must be array)`);let u=!!(o.weather_file||o.weather_files),d=!!o.external_conditions;if(u){let m=o.weather_file||o.weather_files;Array.isArray(m)?m.length>1&&n.push(`Scenario '${s}' must have at most one weather_file (found ${m.length})`):n.push(`Scenario '${s}' weather_file/weather_files must be an array`)}d&&!Array.isArray(o.external_conditions)&&n.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!u&&!d&&n.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),u&&d&&r.push(`Scenario '${s}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,_]of Object.entries(o))Array.isArray(_)||n.push(`Scenario '${s}': '${m}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function Kr(e){try{if(!e||typeof e!="object")return null;let t=0;for(let n of Object.values(e)){if(!n||typeof n!="object")continue;let r=n,a=1;for(let s of Object.values(r))Array.isArray(s)&&(a*=s.length);t+=a}return t}catch{return null}}async function Xr(e,t){let n=[],r=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:r};for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let i=s;for(let[o,u]of Object.entries(i))if(Array.isArray(u)&&!(o==="weather_file"||o==="weather_files"))for(let d of u){let m=Wa.join(e,"input","batch_parameters",o,`${String(d)}.json`);try{await Va.access(m)}catch{r.push({scenario:a,category:o,parameter:String(d),path:m}),n.push(`Scenario '${a}': Parameter '${String(d)}' in category '${o}' not found at ${m}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as hs,readFile as wn}from"fs/promises";import{join as yn}from"path";import{fileURLToPath as ws}from"url";var Ja=Aa(Zr(),1),Ha=Object.defineProperty,Ua=Object.getOwnPropertyNames,za=(e,t)=>function(){return e&&(t=(0,e[Ua(e)[0]])(e=0)),t},qa=(e,t)=>{for(var n in t)Ha(e,n,{get:t[n],enumerable:!0})},Ga={};qa(Ga,{configureWasm:()=>Ka,getRuntimeApiUrl:()=>ns,getRuntimeWasmVariant:()=>es,getVersionedWasmAssetPaths:()=>Ut,getVersionedWasmJsUrl:()=>nn,getWasmAssetPaths:()=>rn,getWasmBaseUrl:()=>Ht,getWasmBinaryUrl:()=>an,getWasmJsUrl:()=>cn,getWasmRayonThreadCount:()=>Qr,getWasmVariant:()=>tn,getWasmVersionInfo:()=>ut,getWasmVersionJsonUrl:()=>en,getWasmWasmUrl:()=>ln,initializeWasmRayonThreadPool:()=>Qa});function Ka(e={}){e.baseUrl&&(sn=Xa(e.baseUrl)),typeof e.preferHashed=="boolean"&&(on=e.preferHashed)}function Yr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function Xa(e){return e.replace(/\/+$/,"")||"/"}function Za(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Ya(){let e=Yr();if(e){if(Za(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Ht(){return sn||Ya()}function Qr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Qa(e){let t=e,n=Qe.get(t);if(n)return n;let r=e.initialize_rayon_thread_pool;if(typeof r!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>r(Qr())).then(()=>{});return Qe.set(t,a),a.catch(()=>{Qe.get(t)===a&&Qe.delete(t)}),a}function en(){return`${Ht()}/wasm_version.json`}async function ut(){try{let e=await fetch(en(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function tn(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function es(){return tn(await ut())}function ts(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function rs(e){let t=ts(),r=!!((on??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(r?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(r?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function rn(e){let t=Ht(),n=e===void 0?await ut():e,{jsFilename:r,wasmFilename:a}=rs(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${a}`}}async function Ut(){let e=await ut(),{jsPath:t,wasmPath:n}=await rn(e),r=e?.build_id||e?.sha256||e?.timestamp;if(!r)return{jsPath:t,wasmPath:n,versionInfo:e};let a=`v=${encodeURIComponent(String(r))}`;return{jsPath:`${t}?${a}`,wasmPath:`${n}?${a}`,versionInfo:e}}async function nn(){let{jsPath:e}=await Ut();return e}async function an(){let{wasmPath:e}=await Ut();return e}function ns(e){let t=Yr();return t?new URL(e,t.origin).toString():e}var Qe,sn,on,cn,ln,un=za({"src/wasmPath.ts"(){Qe=new WeakMap,cn=nn,ln=an}});async function dn(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return null;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(r.files)||!r.files.length||r.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(r.files)}async function mn(e,t){let n=await dn(e,t),r=await e.listFiles(t,{withKind:!0});return n===null?r:r.filter(a=>n.has(typeof a=="string"?a:a.name))}async function fn(e,t){let n=t.lastIndexOf("/"),r=await dn(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}async function pn(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return t;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);let a=r.archive??t;if(typeof a!="string"||a!==t&&!a.startsWith(`${t}/`)||a.split("/").some(s=>!s||s==="."||s==="..")||a.includes("\\"))throw new Error(`Invalid target result archive: ${t}`);return a}function zt(e){let t=new Map;for(let{run:i,startedAt:o,fileTime:u}of e){if(o!==void 0&&Number.isNaN(Date.parse(o)))throw new Error(`Run ${i} records an invalid start time: ${o}`);let d=t.get(i);t.set(i,{run:i,startedAt:d?.startedAt??o,fileTime:Math.max(d?.fileTime??u,u)})}let n=(i,o)=>{let u=`Runs ${i.run} and ${o.run} have the same time, so the helper cannot tell which run is newest. Run the config again.`;if(i.startedAt!==void 0&&o.startedAt!==void 0)return Date.parse(i.startedAt)-Date.parse(o.startedAt)||u;if(i.startedAt===void 0&&o.startedAt===void 0)return i.fileTime-o.fileTime||u;let[d,m]=i.startedAt===void 0?[o,i]:[i,o];return m.fileTime<Date.parse(d.startedAt)?d===i?1:-1:`The workspace holds a run recorded by an older version of Vulcan, which did not record when a run started (${m.run}). Its files are dated after run ${d.run} started, so they may have been copied, and the helper cannot tell which run is newest. Run the config again.`},r=[...t.values()],a=r.map(i=>r.filter(o=>o!==i).map(o=>n(i,o))),s=r.find((i,o)=>a[o].every(u=>typeof u=="number"&&u>0));return s||!r.length?s:{unknown:a.flat().find(i=>typeof i=="string")}}function qt(e,t){let n=e.map(r=>typeof r=="string"?r:r.name).filter(r=>r.endsWith(".csv")?t==="results_heat_source_wet"?r.includes("__results_heat_source_wet__"):t==="results_emitters"?r.includes("__results_emitters_"):r.endsWith(`__${t}.csv`):!1).sort((r,a)=>r.localeCompare(a));return n.find(r=>/(?:^|__)FHS__/.test(r))??n.find(r=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(r))}un();function _n(e){return e.startsWith("__")}function dt(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!_n(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function as(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function ss(e){let t=as(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function mt(e,t){let n=[];for(let r of dt(t)){let a=ss(r.value);for(let s=0;s<a;s+=1)n.push(`result_${e}_${r.name}_${s}`)}return n}function Gt(e){return Math.floor(e/1e3)}function os(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function is(e){return e==="failure_context.json"}function gn(e){return os(e)||is(e)}var cs=["fhs_assumptions","fhs_compliance"];var ls=[...cs,"epc_quick","epc_full"];function us(e){return ls.some(t=>t===e)}var ds=new Set(["base_json","model_wrappers","weather_files","external_conditions"]);function he(e,t,n){return{category:e,selections:[...t],message:n}}function ms(e){let t=0;for(let n of e){let r=1;for(let a of Object.values(n.parameters))a.length>0&&(r*=a.length);t+=r}return t}function fs(e){let t=[],n=e.scenarios[0];e.scenarios.length!==1&&t.push(he("scenarios",e.scenarios.slice(1).map(d=>d.name),"Free configurations contain exactly one scenario."));let r=n?.parameters??{},a=r.base_json??[];a.length!==1&&t.push(he("base_json",a.slice(1),"Free configurations contain exactly one base model."));let s=r.model_wrappers??[],i=s.findIndex(us),o=s.filter((d,m)=>m!==i);(s.length!==1||i!==0)&&t.push(he("model_wrappers",o,"Free configurations use exactly one model wrapper: fhs_assumptions, fhs_compliance, epc_quick or epc_full."));for(let d of["weather_files","external_conditions"]){let m=r[d]??[];m.length>0&&t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")}.`))}for(let[d,m]of Object.entries(r))ds.has(d)||m.length===0||t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")} parameters.`));let u=ms(e.scenarios);return u!==1&&t.push(he("permutations",[String(u)],"Free configurations compute exactly one permutation.")),{isFree:t.length===0,violations:t}}function ps(e,t){return _n(e)||e==="targetBundleId"&&typeof t=="string"}function _s(e){return!e||typeof e!="object"?!1:Object.values(e).some(t=>Object.values(t??{}).some(n=>Array.isArray(n)?n.length>0:!!n))}function hn(e){if(!e||typeof e!="object"||Array.isArray(e))return{isFree:!1,violations:[he("config",[],"A batch configuration must be a JSON object.")]};let t=[],n=[];for(let[i,o]of Object.entries(e)){if(ps(i,o))continue;if(!o||typeof o!="object"||Array.isArray(o)){t.push(he("config",[i],`Unrecognised batch configuration entry '${i}'.`));continue}let u={};for(let[d,m]of Object.entries(o))d==="zone_allocations"?_s(m)&&t.push(he("zone_allocations",[i],"Free configurations do not use per-zone selections.")):Array.isArray(m)?u[d]=m.map(String):t.push(he(d,[i],`'${d}' in '${i}' must be a list of selections.`));n.push({name:i,parameters:u})}let r=e.__hem;(!r||typeof r!="object"||Array.isArray(r))&&t.push(he("target",[],"Free runs use a model saved by the current Vulcan app, pinned to a HEM version."));let s=[...fs({scenarios:n}).violations,...t];return{isFree:s.length===0,violations:s}}function gs(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&Jt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&Jt(r))return r;let s=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(s&&Jt(s))return s}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function Jt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var Xo=gs();un();var ft;async function pt(e){return ft??=vn(),(await ft).csvTarget(e)}async function Kt(e,t){let n=await Le(e,{scenario_1:{base_json:[t]}});return n?(ft??=vn(),(await ft).singleRunWrapper(n)):"fhs_compliance"}async function vn(){for(let e of["./hem-target-runtime/preparation.mjs","../hem-target-runtime/preparation.mjs"]){let t=new URL(e,import.meta.url);try{await hs(ws(t))}catch{continue}return import(t.href)}throw new Error("The target CSV reader is not installed. Build the local target CLI assets or install a helper release including them.")}async function Le(e,t){let n=new Set;for(let{value:r}of dt(t))if(Array.isArray(r.base_json))for(let a of r.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");n.add(await ys(e,a))}if(n.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...n][0]}async function ys(e,t){try{return await pt(await wn(yn(e,"input/base_models",`${t}.csv`),"utf8"))}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await wn(yn(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof n.targetBundleId!="string"||!n.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return n.targetBundleId}catch(n){if(n.code==="ENOENT")return;throw n}}async function Xt(e,t){if(dt(t).some(({value:r})=>Array.isArray(r.heating_profiles)&&r.heating_profiles.length))return"Heating profiles require a saved, pinned HEM target batch; the legacy runner cannot apply post-FHS controls.";let n;try{n=await Le(e,t)}catch(r){return r.message}if(n)return`This batch has no saved __hem snapshot. Its base models use HEM target '${n}' (a Geometry CSV with no TargetBundleId uses Rust a7). Create the batch again with vulcan_create_batch_config, or open it in Create Scenarios in the Vulcan app and save it. Either step saves its exact __hem source and snippet snapshot. The installed legacy runner cannot run it.`}import{fork as Rs}from"child_process";import{join as Qt,resolve as As}from"path";import{access as js,readFile as er}from"fs/promises";import{fileURLToPath as tr}from"url";import{createHash as bs}from"crypto";import et from"fs";import Re from"path";import{fileURLToPath as vs}from"url";function Zt(e=process.cwd()){let t=Re.resolve(e);for(et.existsSync(t)&&et.statSync(t).isFile()&&(t=Re.dirname(t));;){if(et.existsSync(Re.join(t,"package.json"))&&et.existsSync(Re.join(t,"hem-batch-core"))&&et.existsSync(Re.join(t,"web")))return t;let r=Re.dirname(t);if(r===t)break;t=r}let n=Re.dirname(vs(import.meta.url));return Re.resolve(n,"..","..","..")}import we from"fs";import de from"path";import{fileURLToPath as di,pathToFileURL as Cs}from"url";var bn=new Map,Cn=!1,Yt=process.cwd(),En=!1;async function _t(e,t){let n=t?`${e}?verified`:e,r=bn.get(n);if(r)return r;Ss();let a=de.join(e,"wasm_wrapper.js"),s=de.join(e,"wasm_wrapper_bg.wasm"),i=de.join(e,"wasm_version.json");if(!we.existsSync(a)||!we.existsSync(s))throw new Error(`Browser WASM artifact not found in ${e}`);let o=await import(Cs(a).href+(t?"?verified":""));if(typeof o.initSync!="function")throw new Error("WASM module is missing initSync");if(o.initSync({module:t??we.readFileSync(s)}),o.setup_panic_hook?.(),typeof o.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let u={convertGeometryCsvToJson:o.convert_geometry_csv_to_json.bind(o),validateSnippetJs:o.validate_snippet_js?.bind(o),processBatchConfig:o.process_batch_config?.bind(o),calculateMetricsFromParsedData:o.calculate_metrics_from_parsed_data?.bind(o),setWorkspace:ht,prepareTargetScenario:o.prepare_target_scenario?.bind(o),metadata:{source:a,wasm_path:s,wasm_version:Ps(i),build_stamp:rt(o.build_stamp),build_info:xs(o.get_build_info),runtime_origin_descriptor:rt(o.runtime_origin_descriptor),hem_core_version:rt(o.metadata_hem_core_version),fhs_wrapper_version:rt(o.metadata_fhs_wrapper_version)}};return bn.set(n,u),u}var Sn=new Map;async function gt(e,t){let n=Sn.get(e);if(n)return n;let r=u=>{try{return we.readFileSync(de.join(e,u))}catch{throw new Error(`The package WASM is incomplete: ${de.join(e,u)} is missing. ${t}`)}},a=JSON.parse(r("wasm_version.json").toString("utf8"));for(let u of["js_sha256","sha256"])if(!a[u])throw new Error(`${de.join(e,"wasm_version.json")} has no ${u}. ${t}`);let s=u=>bs("sha256").update(u).digest("hex"),i=r("wasm_wrapper_bg.wasm");if(s(r("wasm_wrapper.js"))!==a.js_sha256||s(i)!==a.sha256)throw new Error(`The WASM in ${e} does not match its wasm_version.json. ${t}`);let o={...await _t(e,i),versionInfo:a};return Sn.set(e,o),o}function ht(e,t={}){Yt=de.resolve(e),En=t.confineToWorkspace===!0}function Ss(){ks(),Es();let e=globalThis;e.self||(e.self=globalThis),e.window||(e.window=globalThis),typeof e.addEventListener!="function"&&(e.addEventListener=()=>{}),typeof e.postMessage!="function"&&(e.postMessage=()=>{});let t=e.self;typeof t.addEventListener!="function"&&(t.addEventListener=()=>{}),typeof t.postMessage!="function"&&(t.postMessage=()=>{}),typeof e.Worker!="function"&&(e.Worker=class{addEventListener(){}postMessage(){}terminate(){}}),e.write_file=(n,r)=>{let a=tt(n);try{return we.mkdirSync(de.dirname(a),{recursive:!0}),we.writeFileSync(a,r),!0}catch(s){return console.error(`[FS Bridge] write_file failed for ${a}:`,s.message),!1}},e.read_file=n=>{let r=tt(n);return we.readFileSync(r,"utf8")},e.file_exists=n=>{let r=tt(n);return we.existsSync(r)},e.create_dir_all=n=>{let r=tt(n);try{return we.mkdirSync(r,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${r}:`,a.message),!1}},e.list_dir=n=>{let r=tt(n);try{return we.readdirSync(r)}catch{return[]}}}function tt(e){let t=de.isAbsolute(e)?de.resolve(e):de.resolve(Yt,e);if(En){let n=de.relative(Yt,t);if(n===".."||n.startsWith(`..${de.sep}`)||de.isAbsolute(n))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function ks(){if(Cn)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},Cn=!0}var kn=!1;function Es(){if(kn)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,n)=>{let r=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(r.startsWith("file:")&&r.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,n)}),kn=!0}function Ps(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function rt(e){return typeof e!="function"?void 0:e()||void 0}function xs(e){let t=rt(e);if(t)try{return JSON.parse(t)}catch{return t}}var Be=async e=>{let t=!!(e.targetManifestPath||e.targetManifestSha256);if(t&&(!e.targetManifestPath||!/^[a-f0-9]{64}$/.test(e.targetManifestSha256??"")))throw new Error("Supply both target_manifest and target_manifest_sha256 for an offline bundle, or neither to download the verified pinned target.");if(!t&&!e.targetBundleId)throw new Error("No HEM target identified. Save the source CSV with its TargetBundleId pin; installed legacy WASM cannot substitute it.");let n=await Pn(),r=t?{targetBundleId:e.targetBundleId,manifestPath:As(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{targetBundleId:e.targetBundleId};if(e.operation==="snapshot")return n.adapter.snapshotTarget({workspace:e.workspace,config:e.config,...r});let a=e.wasmDir??n.wasmDir,s=e.wasmRemedy??"Reinstall the package.";if(e.operation==="batch"){let m={workspace:e.workspace,config:e.config,configName:e.configName,jobId:e.jobId,...r,wasmDir:a,wasmRemedy:s};return e.foreground?n.adapter.runTargetBrowser(m,{loadPackageWasm:gt}):Ts(n.adapterPath,m)}if(typeof e.csv!="string")throw new Error("CSV source required");let i=await n.adapter.workspaceReader(e.workspace),{manifest:o,text:u}=await n.adapter.readPreparationBundle(r),d=await gt(a,s);return n.preparation.prepareCsv({csv:e.csv,manifest:o,text:u,converter:{prepare_target_scenario:d.prepareTargetScenario},read:i})};async function rr(e){let{workspace:t,baseModel:n}=e,r=await Le(t,{scenario_1:{base_json:[n]}});if(!r)return{status:"unavailable",reason:`${n} is not pinned to a HEM version. Re-save it in the current Vulcan app, or convert its geometry CSV with vulcan_merge_csv_to_json.`};let a=await Pn(),s=a.preparation.heatingSizingUnavailable(r);if(s)return{status:"unavailable",reason:s};let i=await er(Qt(t,"input/base_models",`${n}.csv`),"utf8").catch(_=>{if(_.code!=="ENOENT")throw _}),o=i===void 0?{model:JSON.parse(await er(Qt(t,"input/batch_parameters/base_json",`${n}.json`),"utf8")),validation:JSON.parse(await er(Qt(t,"input/base_models",`${n}.target.json`),"utf8")).validation}:await Be({...e,operation:"prepare",csv:i,targetBundleId:r}),u=o.validation?.errors??[];if(u.length)return{status:"unavailable",reason:"Fix the model errors to size the heating.",errors:u.map(_=>_.message)};if(!Object.keys(o.model.SpaceHeatSystem??{}).length)return{status:"unavailable",reason:"The model has no space heating system to size."};let d=await a.adapter.resolveReleaseBundle(r),m=await a.adapter.loadDesignHeatLossTarget(d.manifestPath,d.manifestSha256);return m.reason?{status:"unavailable",reason:m.reason}:a.preparation.sizeTargetHeating(m.module,JSON.stringify(o.model))}async function Pn(){for(let e of["./hem-target-runtime/","../hem-target-runtime/"]){let t=new URL(e,import.meta.url),n=new URL("browser-adapter.mjs",t);try{await js(tr(n))}catch{continue}let[r,a]=await Promise.all([import(n.href),import(new URL("preparation.mjs",t).href)]);return{adapter:r,preparation:a,adapterPath:tr(n),wasmDir:tr(new URL("../../wasm/",t))}}throw new Error("Target assets are not installed. Build the local target CLI assets or install a helper release including them.")}function Ts(e,t){return new Promise((n,r)=>{let a=Rs(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),s=setTimeout(()=>{a.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",i=>{clearTimeout(s),r(i)}),a.once("exit",i=>{clearTimeout(s),r(new Error(`Target batch stopped before startup (${i})`))}),a.once("message",i=>{clearTimeout(s),i.started?(a.unref(),n({status:"started"})):(a.kill(),r(new Error(i.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as Ms}from"crypto";import re from"fs/promises";import U from"path";async function nr(e,t,n={},r={}){let{config_name:a,base_model:s,weather_file:i,wrapper:o,parameters:u}=t;if(!a)throw new Error("config_name is required");if(De(a),!s)throw new Error("base_model is required");if(!u||typeof u!="object"||Array.isArray(u))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let d=$s(u),m={base_json:[s],...o?{model_wrappers:[o]}:{},...d},_=await Le(e,{scenario_1:m}),g=!!(t.targetManifestPath||t.targetManifestSha256||_);if(!i&&!g)throw new Error("weather_file is required");i&&(m.weather_files=[g&&!i.endsWith(".epw")?`${i}.epw`:i]);let f={scenario_1:m};await r.gate?.(g?{...f,__hem:{}}:f);let v=Gr(f,{requireWeather:!g});if(!v.valid)return{success:!1,valid:!1,errors:v.errors,warnings:v.warnings,message:`Config validation failed: ${v.errors.join("; ")}`};let A=Kr(f);if(A===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let I=n.maxPermutations??500;if(!Number.isSafeInteger(I)||I<1)throw new Error("maxPermutations must be a positive integer");if(A>I)return{success:!1,valid:!1,errors:[`Total permutations (${A}) exceeds maximum of ${I}`],message:`Config would generate ${A} permutations, which exceeds the limit of ${I}`};let C=f;if(g){let E=await(r.runTarget??Be)({workspace:e,operation:"snapshot",config:f,targetBundleId:_,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});C={...f,__hem:E}}else{let E=await Xr(e,f);if(!E.valid)return{success:!1,valid:!1,errors:E.errors,missingFiles:E.missingFiles,message:`Some parameter files are missing: ${E.errors.slice(0,3).join("; ")}${E.errors.length>3?"...":""}`};let W=U.join(e,"input","batch_parameters","base_json",`${s}.json`);try{await re.access(W)}catch{return{success:!1,valid:!1,errors:[`Base model '${s}' not found at ${W}`],message:`Base model file not found: ${s}`}}let Q=U.join(e,"input","batch_parameters","weather_files",i.endsWith(".epw")?i:`${i}.epw`);try{await re.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${i}' not found at ${Q}`],message:`Weather file not found: ${i}`}}}await r.gate?.(C);let x=U.join(e,"input","batch_configs");if(g){let E=await re.realpath(e);for(let W of["input","batch_configs"])if(E=U.join(E,W),await re.mkdir(E).catch(Q=>{if(Q.code!=="EEXIST")throw Q}),await re.realpath(E)!==E)throw new Error("Target config directory is a symlink")}else await re.mkdir(x,{recursive:!0});let $=a.endsWith(".json")?a:`${a}.json`,V=U.join(x,$);try{return await re.access(V),{success:!1,valid:!1,errors:[`Config file '${$}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await re.writeFile(V,JSON.stringify(C,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:V,permutations:A,structure:f}}async function ar(e,t,n){let{config_name:r,job_id:a}=t;if(!r)throw new Error("config_name is required");let s=a||n.generateJobId?.()||`mcp_${Ms()}`;De(r);let i=r.endsWith(".json")?r:`${r}.json`,o=U.join(e,"input","batch_configs",i),u;try{u=await re.readFile(o,"utf8")}catch(g){let f=g;throw f.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${o}`):new Error(`Failed to read config file: ${f.message}`)}let d=JSON.parse(u);if(await n.gate?.(d),d&&typeof d=="object"&&("__hem"in d||"targetBundleId"in d)){let g=d.__hem;if(!g){let f="This batch names a HEM target but has no saved __hem source snapshot. Re-save the batch in the app (or create it with vulcan_create_batch_config).";return{job_id:s,status:"error",message:f,error:f}}try{return await(n.runTarget??Be)({workspace:e,operation:"batch",config:d,targetBundleId:g.targetBundleId,configName:r.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:r,output_dir:U.join(e,"output"),message:"Exact target batch started. Read progress with batch status (MCP: vulcan_get_batch_status; Analyst: vulcan-analyst batch status); runtime provenance is stored with outputs."}}catch(f){let v=f.message;return{job_id:s,status:"error",message:v,error:v}}}let m=await Xt(e,d);if(m)return{job_id:s,status:"error",message:m,error:m};if(t.targetManifestPath||t.targetManifestSha256){let g="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:s,status:"error",message:g,error:g}}let _=U.join(e,"output");await re.mkdir(_,{recursive:!0});try{let g=await n.processBatchConfig(u,e,_,r.replace(/\.json$/,""),s),f=JSON.parse(g);return f.error?{job_id:s,status:"error",message:`Batch execution failed: ${f.error}`,error:f.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:_}}catch(g){let f=g;return{job_id:s,status:"error",message:`Failed to start batch execution: ${f.message}`,error:f.message}}}async function sr(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,"");r&&De(r);let a=U.join(e,"output"),s;if(r&&!n){if(s=await wt(e,r),!s.jobId){let x=s.error!==void 0?"error":s.unknown?"unknown":"not_run",$=s.error??s.unknown??s.changed??`Batch config '${r}' has no recorded run. A legacy engine run records its config only in its result folders: pass the job_id from vulcan_run_batch instead.`;return{config_name:r,status:x,progress:0,passes:0,failures:0,output_dir:a,error:$,...An(s.warnings)}}n=s.jobId}if(!n)throw new Error("Either job_id or config_name is required");if(/[\\/]/.test(n)||n==="."||n==="..")throw new Error(`Invalid job_id '${n}': a job id is a plain name, as vulcan_run_batch returns it`);let i=s?.warnings??[],o=U.join(a,`progress_${n}.json`),u=U.join(a,`sim_progress_${n}.json`),d=await Ae(o,i),m=await Ae(u,i),_=await Mn(a,n,i);if(!s&&_.config){let x=await wt(e,_.config);i.push(...x.warnings),x.jobId===n&&(s=x),r??=_.config}let g=_.records>0||typeof d?.targetBundleId=="string",f="queued",v=0,A=0,I=0,C=null;if(d?(jn(d.status)?f=d.status:typeof d.percentage=="number"?(v=d.percentage,f=v>=100?"completed":"running"):typeof d.current_combination=="number"&&typeof d.total_combinations=="number"&&(v=Math.round(d.current_combination/d.total_combinations*100),f=v>=100?"completed":"running"),typeof d.percentage=="number"&&(v=d.percentage),typeof d.error=="string"&&(C=d.error,f="error")):_.records&&(_.stopped?(f="error",C=_.stopped):s?.expected!==void 0&&_.passes===s.expected?(f="completed",v=100):(f="unknown",C=`Job ${n} has finished ${_.passes} of ${s?.expected??"an unknown number of"} scenarios and recorded no failure. The app writes no progress file, so the helper cannot tell whether the run is still going or has stopped; check the app.`)),_.records&&({passes:A,failures:I}=_),s?.error!==void 0&&(C=s.error,f="error"),m&&!g&&(jn(m.status)&&(f=m.status),typeof m.passes=="number"&&(A=m.passes),typeof m.failures=="number"&&(I=m.failures),typeof m.error=="string"&&(C=m.error,f="error")),!d&&!m&&!_.records){let x=U.join(a,n);try{let $=await re.readdir(x);f=$.length>0?"completed":"queued",v=$.length>0?100:0}catch($){throw $.code!=="ENOENT"?$:new Error(`Job ${n} does not exist in this workspace: ${a} holds no progress file, run record or folder for it.`)}}return{job_id:n,...r?{config_name:r}:{},status:f,progress:v,passes:A,failures:I,output_dir:a,error:C,batch_progress:d??null,sim_progress:g?null:m??null,...An(i)}}async function wt(e,t){let n=U.join(e,"output"),r=[],a=[],s=async T=>(await re.stat(T)).mtimeMs,i=T=>typeof T.startedAt=="string"?T.startedAt:void 0;for(let T of await re.readdir(n).catch(yt)??[]){if(!T.startsWith("progress_")||!T.endsWith(".json"))continue;let M=await Ae(U.join(n,T),r),c=T.slice(9,-5);M?.config_name===t&&a.push({run:c,jobId:c,startedAt:i(M),fileTime:await s(U.join(n,T))})}De(t);let o=U.join(e,"input","batch_configs",`${t}.json`),u=await Ae(o,r),d=u?mt(t,u):[],m,_=[];for(let T of d){let M=U.join(n,T),c=await re.readdir(M,{withFileTypes:!0}).catch(yt);if(!c)continue;if(!c.some(p=>p.name==="target-run.json")){let p=c.filter(h=>h.isFile()&&gn(h.name)).map(h=>U.join(M,h.name));if(!p.length)continue;m??=`Batch config '${t}' has results in output/${T} from the legacy engine, which does not record the job that wrote them. Pass the job_id from vulcan_run_batch.`,a.push({run:xn,fileTime:Math.max(...await Promise.all(p.map(s)))});continue}let l=T.slice(`result_${t}_`.length);for(let p of c.filter(h=>h.isDirectory()))for(let h of await re.readdir(U.join(M,p.name),{withFileTypes:!0})){if(!h.isDirectory())continue;let w=U.join(M,p.name,h.name,"target-run.json"),O=r.length,b=await Ae(w,r);if(!b){r.length>O&&_.push({warning:r.at(-1),fileTime:await s(w)});continue}b.name!==l||b.kind==="overheating"||a.push({run:h.name,jobId:h.name,startedAt:i(b),fileTime:await s(w)})}}let g=U.join(n,`batch_status_${t}.json`),f=await Ae(g,r),v=f?.status==="error"||f?.status==="running",A=v?i(f):void 0,I=A===void 0?void 0:a.find(T=>T.jobId&&T.startedAt===A)?.jobId;v&&!I&&a.push({run:Rn,startedAt:A,fileTime:await s(g)});let C=u?d.length:void 0,x=a.flatMap(T=>T.startedAt===void 0?[]:[Date.parse(T.startedAt)]),$=_.find(T=>!x.length||T.fileTime>=Math.max(...x));if($)return{unknown:`The helper cannot read a run record of batch config '${t}', so it cannot tell which run is latest. ${$.warning}`,expected:C,warnings:r};if(!a.length)return{legacyCurrent:!0,expected:C,warnings:r};if(u&&Gt(await s(o))>Gt(Math.max(...a.map(T=>T.fileTime))))return{changed:`Batch config '${t}' was saved after its last run. Results from that run are earlier-run results. Run the config again.`,expected:C,warnings:r};let V=zt(a);if("unknown"in V)return{unknown:V.unknown,expected:C,warnings:r};if(V.run===xn)return{unknown:m,legacyCurrent:!0,expected:C,warnings:r};let E=f?.error_message,W=f?.status!=="error"?void 0:typeof E=="string"&&E?E:`The app recorded the run of batch config '${t}' as failed, with no reason.`;if(V.run!==Rn)return{jobId:V.run,...V.run===I?{error:W}:{},expected:C,warnings:r};if(f?.status==="running")return{unknown:`The app started a run of batch config '${t}' at ${A} and has written no scenario yet. It may still be preparing, or it stopped without recording why; check the app.`,expected:C,warnings:r};if(A!==void 0)return{error:W,expected:C,warnings:r};let Q=zt(a.filter(T=>T.jobId)),Se=Q&&"run"in Q?Q.run:void 0;return{...Se&&(await Mn(n,Se,r)).stopped?{jobId:Se}:{},error:W,expected:C,warnings:r}}var xn="legacy engine results";async function Tn(e,t){let n=[];for(let r of await re.readdir(e,{withFileTypes:!0}).catch(yt)??[])if(r.isDirectory())for(let a of await re.readdir(U.join(e,r.name),{withFileTypes:!0})){let s=U.join(e,r.name,a.name),i=a.isDirectory()?await Ae(U.join(s,"target-run.json"),[]):void 0;i?.kind==="overheating"&&!i.parentJob&&n.push({name:t,job_id:a.name,status:String(i.status),path:s})}return n}var Rn="the app's run status";async function Mn(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let a of await re.readdir(e,{withFileTypes:!0}).catch(yt)??[])if(!(!a.isDirectory()||!a.name.startsWith("result_")))for(let s of await re.readdir(U.join(e,a.name),{withFileTypes:!0})){if(!s.isDirectory())continue;let i=await Ae(U.join(e,a.name,s.name,t,"target-run.json"),n);if(!i||i.kind==="overheating")continue;r.records+=1;let o=`_${String(i.name)}`;a.name.endsWith(o)&&(r.config??=a.name.slice(7,-o.length)),i.status==="complete"?r.passes+=1:i.status==="failed"&&(r.failures+=1),(i.status==="failed"||i.status==="cancelled")&&(r.stopped??=`Scenario ${String(i.name)} ${i.status}${typeof i.error=="string"?`: ${i.error}`:""}`)}return r}async function Ae(e,t){let n;try{n=await re.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}try{return JSON.parse(n)}catch(r){t.push(`Skipped ${e}: ${r.message}`);return}}function yt(e){if(e.code!=="ENOENT")throw e}function An(e){return e.length?{warnings:e}:{}}function De(e){let t=e.endsWith(".json")?e.slice(0,-5):e;if(!t.trim()||U.basename(t)!==t||/[\\/\0]/.test(t)||t.startsWith("."))throw new Error(`Invalid batch config name: ${JSON.stringify(e)} (no path separators or leading '.')`)}function $s(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function jn(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Oi from"crypto";import je from"fs/promises";import ne from"path";import Os from"fs/promises";import On from"path";var Ti=On.join("input","base_models");async function or(e){await $n(e,"Workspace"),await $n(On.join(e,"input","batch_parameters"),"Vulcan workspace input/batch_parameters").catch(t=>{throw new Error(`${t.message}. Point the tool at a folder opened as a workspace in the Vulcan app.`)})}async function $n(e,t){try{if(!(await Os.stat(e)).isDirectory())throw new Error(`${t} is not a directory: ${e}`)}catch(n){let r=n;throw r.code==="ENOENT"?new Error(`${t} directory not found: ${e}`):r}}var nt="The schema and defaults arguments were removed. The CSV's TargetBundleId row decides the schema; a CSV with no TargetBundleId row uses HEM:FHS 1.0.0a7. The defaults are the target's own. A DefaultsPath row in the CSV must hold the same defaults.";async function ir(e){let{workspace:t,csvPath:n,outputPath:r}=e,a=ne.isAbsolute(n)?n:ne.join(t,n),s;try{s=await je.readFile(a,"utf8")}catch(o){let u=o;throw u.code==="ENOENT"?new Error(`CSV file not found at ${a}`):new Error(`Failed to read CSV file: ${u.message}`)}let i=await pt(s);try{let o=await(e.runTarget??Be)({workspace:t,operation:"prepare",csv:s,targetBundleId:i,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),u=r?ne.resolve(t,r):Fs(t,a);if(ne.extname(u)!==".json")throw new Error("Prepared target output must have a .json extension");return await Nn(t,u),await Fn(t,ne.join(t,"input/base_models",ne.basename(u,".json")+".target.json"),JSON.stringify({targetBundleId:i,validation:o.validation,schema_omissions:o.schema_omissions,readiness:"wrapper_input"})),await Fn(t,u,JSON.stringify(o.model,null,2)),{ok:!0,json_path:ne.relative(t,u),validation:o.validation,...o.schema_omissions?.length?{schema_omissions:o.schema_omissions}:{},schema_source:`target:${i}`,defaults_source:`target:${i}`,...o.notice?{notice:o.notice}:{}}}catch(o){return{ok:!1,error:o.message}}}function Fs(e,t){let n=ne.basename(t,ne.extname(t));return ne.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function Nn(e,t){let n=await je.realpath(e),r=ne.relative(ne.resolve(e),t);if(!r||r===".."||r.startsWith(`..${ne.sep}`)||ne.isAbsolute(r))throw new Error("Target preparation output must stay within the workspace");let a=ne.join(n,r),s=n;for(let i of ne.relative(n,ne.dirname(a)).split(ne.sep).filter(Boolean))if(s=ne.join(s,i),await je.mkdir(s).catch(o=>{if(o.code!=="EEXIST")throw o}),await je.realpath(s)!==s)throw new Error("Target preparation output directory is a symlink");try{if(await je.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(i){if(i.code!=="ENOENT")throw i}return a}async function Fn(e,t,n){let r=await Nn(e,t),a=await je.open(r,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await je.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return je.open(r,"w")});try{await a.writeFile(n)}finally{await a.close()}}import{fileURLToPath as Ns}from"url";import fe from"fs/promises";import X from"path";function vt(e,t){if(!e||/[\/\\\0]/.test(e)||e.startsWith("."))throw new Error(`${t} must be a plain name, without path separators or a leading '.': ${JSON.stringify(e)}`)}async function cr(e,t={}){let{category:n}=t,r=X.join(e,"input","batch_parameters"),a=await fe.readdir(r,{withFileTypes:!0}),s={};for(let i of a){if(!i.isDirectory())continue;let o=i.name;if(n&&o!==n)continue;let u=X.join(r,o),d=await fe.readdir(u),m=[];for(let _ of d){if(!_.endsWith(".json"))continue;let g=_.replace(/\.json$/,""),f=X.join(u,_);try{let v=await fe.readFile(f,"utf8"),A=JSON.parse(v);m.push({id:g,name:typeof A.name=="string"?A.name:g,description:typeof A.description=="string"?A.description:"",category:o})}catch(v){console.error(`Failed to parse ${f}: ${v.message}`)}}m.length>0&&(s[o]={category:o,parameters:m.sort((_,g)=>_.name.localeCompare(g.name))})}return{catalog:s,total_categories:Object.keys(s).length,total_parameters:Object.values(s).reduce((i,o)=>i+o.parameters.length,0)}}async function lr(e,t){let{category:n,parameter_id:r}=t;if(!n)throw new Error("category is required");if(!r)throw new Error("parameter_id is required");vt(n,"category"),vt(r,"parameter_id");let a=X.join(e,"input","batch_parameters",n),s=X.join(a,`${r}.json`),i=X.join(a,`${r}.md`),o;try{let d=await fe.readFile(s,"utf8");o=JSON.parse(d)}catch(d){let m=d;throw m.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let u=null;try{u=await fe.readFile(i,"utf8")}catch(d){let m=d;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:n,parameter_id:r,json:o,markdown:u,has_markdown:u!==null}}async function ur(e,t,n){let{category:r,parameter_id:a,content:s,markdown_content:i}=t;if(!r)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(s==null||s==="")throw new Error("content is required");if(r!==r.toLowerCase())throw new Error(`category must be lowercase, as the workspace folders are: ${JSON.stringify(r)}`);vt(r,"category"),vt(a,"parameter_id");let o=Is(s),[u,d]=await Promise.all([Vs(e),Ws(e,r)]),m=await Ds(e,Bs(u)?"input_fhs":"input_core"),_=V=>{let E=JSON.parse(n.validateSnippetJs(r,JSON.stringify(V),JSON.stringify(m),JSON.stringify(u),d?JSON.stringify(d):null));return E.ok?[]:(E.errors??[]).map(W=>typeof W=="string"?{path:"",message:W}:{path:W.path??"",message:W.message||String(W)})},g=_(o),f=g.length>0&&!Ls.has(r),v=V=>`${V.path}\0${V.message}`,A=f?new Set(_({}).map(v)):new Set,I=g.filter(V=>V.message.startsWith("Merge failed")||!A.has(v(V))).map(V=>V.message);if(I.length>0)return{success:!1,valid:!1,errors:I,message:`Validation failed: ${I.join("; ")}`};let C=X.join(e,"input","batch_parameters",r);await fe.mkdir(C,{recursive:!0});let x=X.join(C,`${a}.json`);await fe.writeFile(x,JSON.stringify(o,null,2),"utf8");let $=null;return i&&($=X.join(C,`${a}.md`),await fe.writeFile($,i,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${r}'`,paths:{json:x,markdown:$}}}function Is(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}var Ls=new Set(["model_wrappers","weather_files","external_conditions","tariff","simplified_fabric"]);function Bs(e){return!!(e&&typeof e=="object"&&("General"in e||"PartGcompliance"in e))}function In(e){return["../schemas/","../../schemas/"].map(t=>Ns(new URL(t+e,import.meta.url)))}async function Ds(e,t){let n=t==="input_fhs"?"input_fhs.schema.json":"core-input.schema.json",r=t==="input_fhs"?[X.join(e,"input_fhs.schema.json"),X.join(e,"schemas","input_fhs.schema.json"),X.join(Zt(e),"hem_fhs_upstream","schema","input_fhs.schema.json"),...In(n)]:[X.join(e,"input_core.schema.json"),X.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),X.join(e,"core-input.schema.json"),X.join(e,"schemas","core-input.schema.json"),X.join(e,"input.schema.json"),X.join(Zt(e),"hem_engine_upstream","schemas","core-input.schema.json"),...In(n)];for(let a of r)try{return JSON.parse(await fe.readFile(a,"utf8"))}catch{}throw new Error(`Schema file not found (${t}). Tried: ${r.join(", ")}`)}async function Vs(e){let t=X.join(e,"input","batch_parameters","base_json"),n=(await fe.readdir(t).catch(()=>[])).filter(o=>o.endsWith(".json")).sort(),r=new Set(await fe.readdir(X.join(e,"input","base_models")).catch(()=>[])),a=n.filter(o=>!o.startsWith("defaults_template")),s=n.includes("demo_hp_annual.json")?"demo_hp_annual.json":a.find(o=>r.has(o.replace(/\.json$/,".csv")))??a[0];if(!s)throw new Error(`No base model to validate the snippet against: add one to ${t} (convert a geometry CSV with merge-csv-to-json).`);let i=X.join(t,s);try{return JSON.parse(await fe.readFile(i,"utf8"))}catch(o){throw new Error(`Could not read base model ${i}: ${o.message}`)}}async function Ws(e,t){if(t!=="simplified_fabric")return null;let n=[X.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),X.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let r of n)try{return JSON.parse(await fe.readFile(r,"utf8"))}catch{}return null}import pr from"fs/promises";import Ct from"path";import Te from"fs/promises";import _e from"path";async function Je(e,t){let n=_e.join(e,"output"),r=Dn(t.config_name);De(r);let a=[],s=new Set,i=[],o=[],u=[];try{let d=_e.join(n,r),m=await bt(d);m&&await Ln(e,d,a,s);let _;try{_=JSON.parse(await Te.readFile(_e.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(C){if(C.code!=="ENOENT")throw C;if(!m)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let C of _===void 0?[]:mt(r,_)){let x=_e.join(n,C);if(!await bt(x))continue;let $=C.slice(`result_${r}_`.length);o.push(...await Tn(x,$));try{await Ln(e,x,a,s,$)}catch(V){let E=await Te.readFile(_e.join(x,"target-run.json"),"utf8").then(JSON.parse,()=>{});E?.status==="failed"||E?.status==="cancelled"?i.push({name:$,...typeof E.jobId=="string"?{job_id:E.jobId}:{},error:typeof E.error=="string"?E.error:`The scenario's run is recorded as ${E.status}, with no reason.`}):E?.status==="running"?u.push(`Scenario ${$} has no results yet: its run${typeof E.jobId=="string"?` (job ${E.jobId})`:""} is recorded as running.`):u.push(`Failed to read result directory ${C}: ${V.message}`)}}a.sort((C,x)=>C.name.localeCompare(x.name));let g=_===void 0?void 0:await wt(e,r),f=g?.jobId;u.push(...g?.warnings??[]),f&&g?.error!==void 0&&!i.some(C=>C.job_id===f)&&u.push(`The app recorded run ${f} of batch config '${r}' as failed after these scenarios finished: ${g.error}`);let v=g===void 0?[]:a.filter(C=>C.job_id===void 0?!g.legacyCurrent:C.job_id!==f),A=f||g?.legacyCurrent?void 0:g?.changed??g?.unknown??(g?.error!==void 0?`The latest run of batch config '${r}' failed before it wrote any scenario: ${g.error}`:void 0),I=a.filter(C=>!v.includes(C));return{config_name:r,models:I,total_models:I.length,output_dir:n,...f?{latest_job_id:f}:{},...v.length?{earlier_run_models:v}:{},...A?{latest_run_unknown:A}:{},...i.length?{failed_models:i}:{},...o.length?{overheating_runs:o}:{},...u.length?{warnings:u}:{}}}catch(d){return{config_name:r,models:[],total_models:0,output_dir:n,error:`Failed to list models: ${d.message}`}}}async function dr(e,t){let n=Dn(t.config_name),r=await Je(e,{config_name:n}),a=r.models.find(m=>m.name===t.model_name)?.csv_path;if(!a)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,error:mr(r,t.model_name)};let i=(await Te.readFile(a,"utf8")).split(`
|
|
14
14
|
`).filter(m=>m.trim());if(i.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let o=Bn(i[0]??"").map(m=>m.trim()),u=Bn(i[1]??"").map(m=>m.trim()),d=[];for(let m=1;m<o.length;m+=1){let _=o[m],g=m<u.length?u[m]:"";_&&d.push({name:_,unit:g||"",index:m-1})}return{config_name:n,model_name:t.model_name,columns:d,total_columns:d.length,csv_path:a}}function mr(e,t){let n=e.earlier_run_models?.find(r=>r.name===t);if(n){let r=e.latest_job_id?`The config's latest run is job ${e.latest_job_id}. `:e.latest_run_unknown?`${e.latest_run_unknown} `:"";return`Model ${t} has results only from ${n.job_id?`job ${n.job_id}`:"the legacy engine"}, an earlier run. ${r}They do not reflect the latest inputs: re-run the config.`}return e.error??`No completed actual-dwelling CSV found for model ${t}`}var fr={fileExists:bt,readFile:e=>Te.readFile(e,"utf8"),listFiles:e=>Te.readdir(e)};async function Ln(e,t,n,r,a){let s={fileExists:f=>bt(_e.join(e,f)),readFile:f=>Te.readFile(_e.join(e,f),"utf8")},i=_e.relative(e,t).split(_e.sep).join("/"),o=_e.join(e,await pn(s,i)),d=(await mn(fr,o)).map(f=>typeof f=="string"?f:f.name),m=await Te.readFile(_e.join(o,"target-run.json"),"utf8").then(JSON.parse,()=>{}),_=typeof m?.jobId=="string"?m.jobId:void 0,g=(f,v)=>{r.has(f)||(r.add(f),n.push({name:f,csv_path:_e.join(o,v),has_results:!0,..._?{job_id:_}:{}}))};if(a){let f=qt(d,"results");f&&g(a,f);return}for(let f of d){if(!qt([f],"results"))continue;let v=f.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);v?.[1]&&g(v[1],f)}}function Dn(e){return e.replace(/\.json$/,"")}async function bt(e){try{return await Te.access(e),!0}catch{return!1}}function Bn(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}var Js=new Set(["sumif","averageif","countif"]),Vn=new Set([">=","<=",">","<","="]);async function _r(e,t,n){let{config_name:r,model_names:a,metric_definitions:s,time_range:i,tariff_file_path:o,tariff_column_index:u}=t;if(!r)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!s||!Array.isArray(s)||s.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let d=r.replace(/\.json$/,""),{encodedMetrics:m,metadata:_}=zs(s);if(_.some(x=>x.function.toLowerCase()==="cost")&&(!o||u===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let f;if(o&&u!==void 0){let x=await qs(o,u,e);f=JSON.stringify(x)}let v=[],A=await Je(e,{config_name:d}),I=[],C=[];for(let x of a){let $=A.models.find(E=>E.name===x)?.csv_path;if(!$){let E=A.earlier_run_models?.find(Q=>Q.name===x),W=A.failed_models?.find(Q=>Q.name===x);if(W)C.push({model_name:x,...W.job_id?{job_id:W.job_id}:{},error:W.error});else if(E)I.push({model_name:x,...E.job_id?{job_id:E.job_id}:{}});else throw new Error(mr(A,x));continue}let V=await pr.readFile($,"utf8");try{let E=Hs(V,x,r);if(_.some(ae=>ae.isCompliance)){let ae=Ct.join(Ct.dirname($),"fhs_compliance_report.json");if(!await fn(fr,ae))throw new Error("Completed FHS compliance report is unavailable");let T=JSON.parse(await pr.readFile(ae,"utf8")),M=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let c of M){let l=T[c];E[c]=typeof l=="number"&&Number.isFinite(l)?l:null}for(let c of _.filter(l=>l.isCompliance)){let l=M.find(p=>p===c.column);if(!l||E[l]===null)throw new Error(`Completed FHS compliance rate '${c.column}' is unavailable`)}}if(E.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${x}`);if(Object.keys(E.columns).length===0)throw new Error(`No columns found in CSV for model ${x}`);let W=Gs(E,m,_);if(W.length>0){let ae=Object.keys(E.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${W.join(", ")}. Available columns: ${ae.join(", ")}...`)}let Q=n.calculateMetricsFromParsedData(JSON.stringify(E),JSON.stringify(m),i?JSON.stringify(i):void 0,f);if(!Q||typeof Q!="string")throw new Error(`WASM returned invalid result: ${typeof Q}`);let Se=JSON.parse(Q);if(!Array.isArray(Se))throw new Error(`WASM returned non-array result: ${typeof Se}`);Se.forEach((ae,T)=>{let M=_[T],[c=ae.name,l="sum"]=ae.name.split("|");v.push({id:M?.id||ae.name,name:M?.name||ae.name,column:M?.column||c,function:M?.function||l,comparator:M?.comparator,threshold:M?.threshold,value:ae.value,model_name:x})})}catch(E){let W=E;if(W.code==="ENOENT"){console.warn(`CSV file not found for model ${x}: ${$}`);continue}throw new Error(`Failed to process model ${x}: ${W.message}`)}}return{metrics:v,total_models:a.length-I.length-C.length,total_metrics:v.length,...I.length?{earlier_run_models:I}:{},...C.length?{failed_models:C}:{},...A.latest_run_unknown?{latest_run_unknown:A.latest_run_unknown}:{},...A.warnings?{warnings:A.warnings}:{}}}function Hs(e,t,n){let r=e.split(`
|
|
@@ -2480,7 +2480,7 @@ var SECTION_LOCATIONS = {
|
|
|
2480
2480
|
fabric: "Global Settings > Fabric",
|
|
2481
2481
|
target: "Global Settings",
|
|
2482
2482
|
dwelling: "Global Settings > Dwelling details",
|
|
2483
|
-
airTightness: "Global Settings > Air
|
|
2483
|
+
airTightness: "Global Settings > Air tightness",
|
|
2484
2484
|
ventilation: "Global Settings > Ventilation environment",
|
|
2485
2485
|
thermalBridging: "Global Settings > Thermal bridging"
|
|
2486
2486
|
};
|
|
@@ -2929,7 +2929,7 @@ var SECTION_LOCATIONS = {
|
|
|
2929
2929
|
fabric: "Global Settings > Fabric",
|
|
2930
2930
|
target: "Global Settings",
|
|
2931
2931
|
dwelling: "Global Settings > Dwelling details",
|
|
2932
|
-
airTightness: "Global Settings > Air
|
|
2932
|
+
airTightness: "Global Settings > Air tightness",
|
|
2933
2933
|
ventilation: "Global Settings > Ventilation environment",
|
|
2934
2934
|
thermalBridging: "Global Settings > Thermal bridging"
|
|
2935
2935
|
};
|
package/dist/server.js
CHANGED
|
@@ -7,7 +7,7 @@ var ya=Object.create;var Dr=Object.defineProperty;var va=Object.getOwnPropertyDe
|
|
|
7
7
|
`:"\r"};function D(P){return c.skipEmptyLines==="greedy"?P.join("").trim()==="":P.length===1&&P[0].length===0}function J(P){if(h.test(P)){var j=parseFloat(P);if(j>p&&j<l)return!0}return!1}function Z(){return N&&le&&(ge("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+i.DefaultDelimiter+"'"),le=!1),c.skipEmptyLines&&(N.data=N.data.filter(function(P){return!D(P)})),Y()&&me(),U()}function Y(){return c.header&&R.length===0}function me(){if(!N)return;function P(L,q){M(c.transformHeader)&&(L=c.transformHeader(L,q)),R.push(L)}if(Array.isArray(N.data[0])){for(var j=0;Y()&&j<N.data.length;j++)N.data[j].forEach(P);N.data.splice(0,1)}else N.data.forEach(P)}function se(P){return c.dynamicTypingFunction&&c.dynamicTyping[P]===void 0&&(c.dynamicTyping[P]=c.dynamicTypingFunction(P)),(c.dynamicTyping[P]||c.dynamicTyping)===!0}function pe(P,j){return se(P)?j==="true"||j==="TRUE"?!0:j==="false"||j==="FALSE"?!1:J(j)?parseFloat(j):w.test(j)?new Date(j):j===""?null:j:j}function U(){if(!N||!c.header&&!c.dynamicTyping&&!c.transform)return N;function P(L,q){var E=c.header?{}:[],z;for(z=0;z<L.length;z++){var ie=z,te=L[z];c.header&&(ie=z>=R.length?"__parsed_extra":R[z]),c.transform&&(te=c.transform(te,ie)),te=pe(ie,te),ie==="__parsed_extra"?(E[ie]=E[ie]||[],E[ie].push(te)):E[ie]=te}return c.header&&(z>R.length?ge("FieldMismatch","TooManyFields","Too many fields: expected "+R.length+" fields but parsed "+z,y+q):z<R.length&&ge("FieldMismatch","TooFewFields","Too few fields: expected "+R.length+" fields but parsed "+z,y+q)),E}var j=1;return!N.data.length||Array.isArray(N.data[0])?(N.data=N.data.map(P),j=N.data.length):N.data=P(N.data,0),c.header&&N.meta&&(N.meta.fields=R),y+=j,N}function Ee(P,j,L,q,E){var z,ie,te,Ne;E=E||[","," ","|",";",i.RECORD_SEP,i.UNIT_SEP];for(var ke=0;ke<E.length;ke++){var qe=E[ke],Ie=0,Pe=0,ce=0;te=void 0;for(var ve=new O({comments:q,delimiter:qe,newline:j,preview:10}).parse(P),oe=0;oe<ve.data.length;oe++){if(L&&D(ve.data[oe])){ce++;continue}var ue=ve.data[oe].length;if(Pe+=ue,typeof te>"u"){te=ue;continue}else ue>0&&(Ie+=Math.abs(ue-te),te=ue)}ve.data.length>0&&(Pe/=ve.data.length-ce),(typeof ie>"u"||Ie<=ie)&&(typeof Ne>"u"||Pe>Ne)&&Pe>1.99&&(ie=Ie,z=qe,Ne=Pe)}return c.delimiter=z,{successful:!!z,bestDelimiter:z}}function ge(P,j,L,q){var E={type:P,code:j,message:L};q!==void 0&&(E.row=q),N.errors.push(E)}}function x(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function O(c){c=c||{};var l=c.delimiter,p=c.newline,h=c.comments,w=c.step,$=c.preview,b=c.fastMode,y,B=null,G=!1;c.quoteChar===void 0||c.quoteChar===null?y='"':y=c.quoteChar;var ee=y;if(c.escapeChar!==void 0&&(ee=c.escapeChar),(typeof l!="string"||i.BAD_DELIMITERS.indexOf(l)>-1)&&(l=","),h===l)throw new Error("Comment character same as delimiter");h===!0?h="#":(typeof h!="string"||i.BAD_DELIMITERS.indexOf(h)>-1)&&(h=!1),p!==`
|
|
8
8
|
`&&p!=="\r"&&p!==`\r
|
|
9
9
|
`&&(p=`
|
|
10
|
-
`);var F=0,le=!1;this.parse=function(R,N,Fe){if(typeof R!="string")throw new Error("Input must be a string");var D=R.length,J=l.length,Z=p.length,Y=h.length,me=M(w);F=0;var se=[],pe=[],U=[],Ee=0;if(!R)return ce();if(b||b!==!1&&R.indexOf(y)===-1){for(var ge=R.split(p),P=0;P<ge.length;P++){if(U=ge[P],F+=U.length,P!==ge.length-1)F+=p.length;else if(Fe)return ce();if(!(h&&U.substring(0,Y)===h)){if(me){if(se=[],ke(U.split(l)),ve(),le)return ce()}else ke(U.split(l));if($&&P>=$)return se=se.slice(0,$),ce(!0)}}return ce()}for(var j=R.indexOf(l,F),L=R.indexOf(p,F),q=new RegExp(x(ee)+x(y),"g"),E=R.indexOf(y,F);;){if(R[F]===y){for(E=F,F++;;){if(E=R.indexOf(y,E+1),E===-1)return Fe||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),Ie();if(E===D-1){var z=R.substring(F,E).replace(q,y);return Ie(z)}if(y===ee&&R[E+1]===ee){E++;continue}if(!(y!==ee&&E!==0&&R[E-1]===ee)){j!==-1&&j<E+1&&(j=R.indexOf(l,E+1)),L!==-1&&L<E+1&&(L=R.indexOf(p,E+1));var ie=L===-1?j:Math.min(j,L),te=qe(ie);if(R.substr(E+1+te,J)===l){U.push(R.substring(F,E).replace(q,y)),F=E+1+te+J,R[E+1+te+J]!==y&&(E=R.indexOf(y,F)),j=R.indexOf(l,F),L=R.indexOf(p,F);break}var Ne=qe(L);if(R.substring(E+1+Ne,E+1+Ne+Z)===p){if(U.push(R.substring(F,E).replace(q,y)),Pe(E+1+Ne+Z),j=R.indexOf(l,F),E=R.indexOf(y,F),me&&(ve(),le))return ce();if($&&se.length>=$)return ce(!0);break}pe.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:se.length,index:F}),E++}}continue}if(h&&U.length===0&&R.substring(F,F+Y)===h){if(L===-1)return ce();F=L+Z,L=R.indexOf(p,F),j=R.indexOf(l,F);continue}if(j!==-1&&(j<L||L===-1)){U.push(R.substring(F,j)),F=j+J,j=R.indexOf(l,F);continue}if(L!==-1){if(U.push(R.substring(F,L)),Pe(L+Z),me&&(ve(),le))return ce();if($&&se.length>=$)return ce(!0);continue}break}return Ie();function ke(oe){se.push(oe),Ee=F}function qe(oe){var ue=0;if(oe!==-1){var xe=R.substring(E+1,oe);xe&&xe.trim()===""&&(ue=xe.length)}return ue}function Ie(oe){return Fe||(typeof oe>"u"&&(oe=R.substring(F)),U.push(oe),F=D,ke(U),me&&ve()),ce()}function Pe(oe){F=oe,ke(U),U=[],L=R.indexOf(p,F)}function ce(oe){if(c.header&&!N&&se.length&&!G){let ue=se[0],xe=Object.create(null),Ot=new Set(ue),Lr=!1;for(let We=0;We<ue.length;We++){let be=ue[We];if(M(c.transformHeader)&&(be=c.transformHeader(be,We)),!xe[be])xe[be]=1,ue[We]=be;else{let Ke,Br=xe[be];do Ke=`${be}_${Br}`,Br++;while(Ot.has(Ke));Ot.add(Ke),ue[We]=Ke,xe[be]++,Lr=!0,B===null&&(B={}),B[Ke]=be}Ot.add(be)}Lr&&console.warn("Duplicate headers found and renamed."),G=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:p,aborted:le,truncated:!!oe,cursor:Ee+(N||0),renamedHeaders:B}}}function ve(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function V(){if(!i.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=k,l.id=o++,s[l.id]=l,l}function k(c){var l=c.data,p=s[l.workerId],h=!1;if(l.error)p.userError(l.error,l.file);else if(l.results&&l.results.data){var w=function(){h=!0,W(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},$={abort:w,pause:Q,resume:Q};if(M(p.userStep)){for(var b=0;b<l.results.data.length&&(p.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},$),!h);b++);delete l.results}else M(p.userChunk)&&(p.userChunk(l.results,$,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var p=s[c];M(p.userComplete)&&p.userComplete(l),p.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Se(c){var l=c.data;if(typeof i.WORKER_ID>"u"&&l&&(i.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:i.WORKER_ID,results:i.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var p=i.parse(l.input,l.config);p&&t.postMessage({workerId:i.WORKER_ID,results:p,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=ae(c[p]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return i})});import _a from"express";import hi from"cors";import{McpServer as wi}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as yi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as vi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ga}from"@modelcontextprotocol/sdk/types.js";var Vr={name:"@vulcan-energy/mcp-helper",version:"0.3.
|
|
10
|
+
`);var F=0,le=!1;this.parse=function(R,N,Fe){if(typeof R!="string")throw new Error("Input must be a string");var D=R.length,J=l.length,Z=p.length,Y=h.length,me=M(w);F=0;var se=[],pe=[],U=[],Ee=0;if(!R)return ce();if(b||b!==!1&&R.indexOf(y)===-1){for(var ge=R.split(p),P=0;P<ge.length;P++){if(U=ge[P],F+=U.length,P!==ge.length-1)F+=p.length;else if(Fe)return ce();if(!(h&&U.substring(0,Y)===h)){if(me){if(se=[],ke(U.split(l)),ve(),le)return ce()}else ke(U.split(l));if($&&P>=$)return se=se.slice(0,$),ce(!0)}}return ce()}for(var j=R.indexOf(l,F),L=R.indexOf(p,F),q=new RegExp(x(ee)+x(y),"g"),E=R.indexOf(y,F);;){if(R[F]===y){for(E=F,F++;;){if(E=R.indexOf(y,E+1),E===-1)return Fe||pe.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:se.length,index:F}),Ie();if(E===D-1){var z=R.substring(F,E).replace(q,y);return Ie(z)}if(y===ee&&R[E+1]===ee){E++;continue}if(!(y!==ee&&E!==0&&R[E-1]===ee)){j!==-1&&j<E+1&&(j=R.indexOf(l,E+1)),L!==-1&&L<E+1&&(L=R.indexOf(p,E+1));var ie=L===-1?j:Math.min(j,L),te=qe(ie);if(R.substr(E+1+te,J)===l){U.push(R.substring(F,E).replace(q,y)),F=E+1+te+J,R[E+1+te+J]!==y&&(E=R.indexOf(y,F)),j=R.indexOf(l,F),L=R.indexOf(p,F);break}var Ne=qe(L);if(R.substring(E+1+Ne,E+1+Ne+Z)===p){if(U.push(R.substring(F,E).replace(q,y)),Pe(E+1+Ne+Z),j=R.indexOf(l,F),E=R.indexOf(y,F),me&&(ve(),le))return ce();if($&&se.length>=$)return ce(!0);break}pe.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:se.length,index:F}),E++}}continue}if(h&&U.length===0&&R.substring(F,F+Y)===h){if(L===-1)return ce();F=L+Z,L=R.indexOf(p,F),j=R.indexOf(l,F);continue}if(j!==-1&&(j<L||L===-1)){U.push(R.substring(F,j)),F=j+J,j=R.indexOf(l,F);continue}if(L!==-1){if(U.push(R.substring(F,L)),Pe(L+Z),me&&(ve(),le))return ce();if($&&se.length>=$)return ce(!0);continue}break}return Ie();function ke(oe){se.push(oe),Ee=F}function qe(oe){var ue=0;if(oe!==-1){var xe=R.substring(E+1,oe);xe&&xe.trim()===""&&(ue=xe.length)}return ue}function Ie(oe){return Fe||(typeof oe>"u"&&(oe=R.substring(F)),U.push(oe),F=D,ke(U),me&&ve()),ce()}function Pe(oe){F=oe,ke(U),U=[],L=R.indexOf(p,F)}function ce(oe){if(c.header&&!N&&se.length&&!G){let ue=se[0],xe=Object.create(null),Ot=new Set(ue),Lr=!1;for(let We=0;We<ue.length;We++){let be=ue[We];if(M(c.transformHeader)&&(be=c.transformHeader(be,We)),!xe[be])xe[be]=1,ue[We]=be;else{let Ke,Br=xe[be];do Ke=`${be}_${Br}`,Br++;while(Ot.has(Ke));Ot.add(Ke),ue[We]=Ke,xe[be]++,Lr=!0,B===null&&(B={}),B[Ke]=be}Ot.add(be)}Lr&&console.warn("Duplicate headers found and renamed."),G=!0}return{data:se,errors:pe,meta:{delimiter:l,linebreak:p,aborted:le,truncated:!!oe,cursor:Ee+(N||0),renamedHeaders:B}}}function ve(){w(ce()),se=[],pe=[]}},this.abort=function(){le=!0},this.getCharIndex=function(){return F}}function V(){if(!i.WORKERS_SUPPORTED)return!1;var c=n(),l=new t.Worker(c);return l.onmessage=k,l.id=o++,s[l.id]=l,l}function k(c){var l=c.data,p=s[l.workerId],h=!1;if(l.error)p.userError(l.error,l.file);else if(l.results&&l.results.data){var w=function(){h=!0,W(l.workerId,{data:[],errors:[],meta:{aborted:!0}})},$={abort:w,pause:Q,resume:Q};if(M(p.userStep)){for(var b=0;b<l.results.data.length&&(p.userStep({data:l.results.data[b],errors:l.results.errors,meta:l.results.meta},$),!h);b++);delete l.results}else M(p.userChunk)&&(p.userChunk(l.results,$,l.file),delete l.results)}l.finished&&!h&&W(l.workerId,l.results)}function W(c,l){var p=s[c];M(p.userComplete)&&p.userComplete(l),p.terminate(),delete s[c]}function Q(){throw new Error("Not implemented.")}function Se(c){var l=c.data;if(typeof i.WORKER_ID>"u"&&l&&(i.WORKER_ID=l.workerId),typeof l.input=="string")t.postMessage({workerId:i.WORKER_ID,results:i.parse(l.input,l.config),finished:!0});else if(t.File&&l.input instanceof File||l.input instanceof Object){var p=i.parse(l.input,l.config);p&&t.postMessage({workerId:i.WORKER_ID,results:p,finished:!0})}}function ae(c){if(typeof c!="object"||c===null)return c;var l=Array.isArray(c)?[]:{};for(var p in c)l[p]=ae(c[p]);return l}function T(c,l){return function(){c.apply(l,arguments)}}function M(c){return typeof c=="function"}return i})});import _a from"express";import hi from"cors";import{McpServer as wi}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as yi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as vi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{InitializeRequestSchema as ga}from"@modelcontextprotocol/sdk/types.js";var Vr={name:"@vulcan-energy/mcp-helper",version:"0.3.3",description:"Vulcan Home Energy Model tools for AI assistants over MCP (Claude Code, Codex, Claude Desktop, Cursor). Runs locally; Free tools need no account.",repository:{type:"git",url:"git+https://github.com/baziyer/rust-hem-runner.git",directory:"vulcan-mcp-server"},type:"module",main:"./dist/server.js",types:"./dist/server.d.ts",bin:{"vulcan-mcp-helper":"dist/bin/vulcan-mcp-helper.js"},scripts:{build:"tsup --config tsup.config.ts",dev:"tsx watch bin/vulcan-mcp-helper.ts",start:"node dist/bin/vulcan-mcp-helper.js",prepublishOnly:"npm run build && npm run clean",clean:"echo 'Package is ready for publishing'",test:"node --import tsx --test src/engine/requestAuth.test.ts src/engine/licenseToken.test.ts src/engine/config.test.ts src/tools/registry.test.ts src/tools/signIn.test.ts"},keywords:["claude","codex","energy-modeling","future-homes-standard","hem","home-energy-model","mcp","model-context-protocol","vulcan"],author:"",license:"UNLICENSED",dependencies:{"@modelcontextprotocol/sdk":"^1.32.2","@vulcan-energy/community-cli":"^0.1.0",cors:"^2.8.5",express:"^4.18.2",jose:"^6.1.2","playwright-core":"^1.59.1",zod:"^4.1.12"},devDependencies:{"@types/cors":"^2.8.17","@types/express":"^4.17.21","@types/node":"^20.10.0",tsup:"^8.5.0",tsx:"^4.7.0",typescript:"^5.3.3"},engines:{node:">=20.0.0"},files:["dist/","wasm/","schemas/","package.json","README.md","LICENSE","THIRD_PARTY_NOTICES.md"]};import Hr from"fs/promises";import Ze from"path";var Wr=Object.freeze(["mcp","analyst"]);function $t(e){return typeof e=="string"&&Wr.includes(e)}var it="https://usevulcan.app",Ft="vulcan-local-tools",ot=1,Nt=10080*60,It=300,K=class extends Error{code;constructor(t,n){super(n),this.name="CapabilityTokenError",this.code=t}};var Jr=Object.freeze([`-----BEGIN PUBLIC KEY-----
|
|
11
11
|
MCowBQYDK2VwAyEAOmr0DweQnQ2L747vGML7l/ieYywCQzrnd39idAZ2YK4=
|
|
12
12
|
-----END PUBLIC KEY-----`]);import{compactVerify as Aa,importSPKI as ja}from"jose";var Ur="EdDSA";async function Bt(e,t){let n=e.trim();if(!n)throw new K("empty","Vulcan access token is empty.");let r=t.publicKeys??Jr,a=t.now??(()=>new Date),s=Math.floor(a().getTime()/1e3),o=await Ta(n,r),i=Ma(o);if(i.iss!==it)throw new K("wrong_issuer",`Vulcan access token was issued by ${i.iss}, not ${it}.`);if(i.aud!==Ft)throw new K("wrong_audience","Vulcan access token was not issued for local Vulcan tools.");if(i.entitlement_schema_version!==ot)throw new K("unsupported_schema_version",`Vulcan access token uses entitlement schema version ${i.entitlement_schema_version}, but this build understands version ${ot}. Update your Vulcan tools.`);if(!i.capabilities.includes(t.capability))throw new K("missing_capability",`Vulcan access token does not grant the "${t.capability}" capability.`);if(i.exp-i.iat>Nt)throw new K("lifetime_exceeded","Vulcan access token declares a longer lifetime than Vulcan issues. Generate a new access config.");if(s<i.iat-It)throw new K("clock_behind","This system clock is too far behind the token issue time. Correct the clock and try again.");let u=s>i.exp;if(u&&!t.allowExpired)throw new K("expired","Vulcan access token has expired. Open Vulcan -> Profile -> Integrations and generate a new access config.");return{claims:i,expired:u,expiresAt:new Date(i.exp*1e3),expiresInSeconds:i.exp-s}}async function Ta(e,t){for(let n of t)try{let r=await ja(n,Ur),{payload:a}=await Aa(e,r,{algorithms:[Ur]});return a}catch{}throw new K("untrusted_signature","Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and generate a new access config.")}function Ma(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new K("malformed","Vulcan access token payload is not valid JSON.")}if(!t||typeof t!="object"||Array.isArray(t))throw new K("malformed","Vulcan access token payload is not an object.");let n=t,r=Xe(n,"iss"),a=Xe(n,"aud"),s=Xe(n,"sub"),o=Xe(n,"org"),i=Xe(n,"jti"),u=Lt(n,"iat"),d=Lt(n,"exp"),m=Lt(n,"entitlement_schema_version");if(!Array.isArray(n.capabilities))throw new K("malformed","Vulcan access token must include a capabilities array.");let _=[];for(let g of n.capabilities){if(!$t(g))throw new K("malformed",`Vulcan access token lists an unrecognised capability: ${JSON.stringify(g)}.`);_.push(g)}if(_.length===0)throw new K("malformed","Vulcan access token grants no capabilities.");if(d<=u)throw new K("malformed","Vulcan access token expires no later than it was issued.");return{iss:r,aud:a,sub:s,org:o,jti:i,capabilities:Object.freeze(_),entitlement_schema_version:m,iat:u,exp:d}}function Xe(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new K("malformed",`Vulcan access token must include a non-empty "${t}" claim.`);return n}function Lt(e,t){let n=e[t];if(typeof n!="number"||!Number.isFinite(n))throw new K("malformed",`Vulcan access token must include a numeric "${t}" claim.`);return n}var Oa="mcp",$a=2880*60;async function Dt(e={}){let t=Ze.resolve(e.workspace??process.env.VULCAN_WORKSPACE??process.cwd()),n=Ze.resolve(e.configPath??Ze.join(t,"vulcan-mcp-config.json")),r;try{r=await Hr.readFile(n,"utf-8")}catch{if(e.configPath)throw new Error(`Config file not found: ${n}. Generate one in Vulcan \u2192 Profile \u2192 Integrations \u2192 MCP, or omit --config to run Free.`)}let a=t,s;if(r!==void 0){let o;try{o=JSON.parse(r)}catch(i){throw new Error(`Invalid JSON in config file ${n}: ${i.message}`)}if(o.workspace!==void 0){if(typeof o.workspace!="string")throw new Error("Config field workspace must be a string");a=Ze.resolve(Ze.dirname(n),o.workspace)}if(o.license_token!==void 0){if(typeof o.license_token!="string"||!o.license_token)throw new Error("Config field license_token must be a non-empty string");s=o.license_token}}try{await Hr.access(a)}catch{throw new Error(`Workspace directory not found: ${a}`)}if(s){let{payload:o}=await ct(s,{allowExpired:!0}),i=o.exp-Math.floor(Date.now()/1e3);if(i<=0)console.error("[MCP Helper] Your Vulcan Pro access has expired: Free tools work; ask your assistant to sign in again (vulcan_sign_in) to renew.");else if(i<$a){let u=Math.max(1,Math.round(i/3600));console.error(`[MCP Helper] Warning: your Vulcan access expires in about ${u} hour(s). Ask your assistant to sign in again (vulcan_sign_in), or open Vulcan -> Profile -> Integrations and click "Generate Config File".`)}}return{workspace:a,...s?{license_token:s}:{},...r!==void 0?{configPath:n}:{}}}async function zr(e,t={}){if(!e.license_token)return{pro:!1,detail:"No Vulcan Pro access config is set; Free tools only."};try{return await ct(e.license_token,t),{pro:!0,detail:"Vulcan Pro access config is valid."}}catch(n){return{pro:!1,detail:n.message}}}async function ct(e,t={}){try{let{claims:n}=await Bt(e,{capability:Oa,now:t.now,publicKeys:t.publicKeys,allowExpired:t.allowExpired});return{payload:n}}catch(n){throw new Error(Fa(n))}}function Fa(e){if(!(e instanceof K))return e instanceof Error?e.message:String(e);switch(e.code){case"missing_capability":return"This Vulcan access config does not include MCP. MCP requires a Vulcan Pro seat; open Vulcan -> Profile -> Integrations and generate a new config.";case"expired":return'Your Vulcan access config has expired. Call vulcan_sign_in to renew it, or open Vulcan -> Profile -> Integrations and click "Generate Config File".';case"unsupported_schema_version":return'This Vulcan access config was issued for a newer version of the Vulcan tools. Update the helper with "npm install -g @vulcan-energy/mcp-helper@latest".';case"lifetime_exceeded":return"This Vulcan access config declares a longer lifetime than Vulcan issues and was refused. Generate a new config.";case"clock_behind":return"This system clock is too far behind the access config issue time. Correct the clock, then restart the helper.";case"wrong_audience":case"wrong_issuer":return'This access config was not issued for local Vulcan tools. Open Vulcan -> Profile -> Integrations and click "Generate Config File".';default:return'Your Vulcan access config is invalid or was signed with an unknown key. Open Vulcan -> Profile -> Integrations and click "Generate Config File".'}}import{timingSafeEqual as Na}from"crypto";function Ia(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 La(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Na(n,r)}async function Gr(e,t,n=ct){let r=Ia(e);if(!La(r,t))throw new Error("MCP request Bearer token is invalid");await n(r)}import{z as S}from"zod";import st from"fs/promises";import $e from"path";import Ba from"fs/promises";import Da from"path";function qr(e,t={}){let n=[],r=[];if(!e||typeof e!="object")return{valid:!1,errors:["Config must be an object"],warnings:[]};Object.keys(e).length===0&&n.push("Config must have at least one scenario");for(let[s,o]of Object.entries(e)){if(!o||typeof o!="object"){n.push(`Scenario '${s}' must be an object`);continue}let i=o;Array.isArray(i.base_json)?i.base_json.length!==1&&n.push(`Scenario '${s}' must have exactly one base_json (found ${i.base_json.length})`):n.push(`Scenario '${s}' is missing required 'base_json' field (must be array)`);let u=!!(i.weather_file||i.weather_files),d=!!i.external_conditions;if(u){let m=i.weather_file||i.weather_files;Array.isArray(m)?m.length>1&&n.push(`Scenario '${s}' must have at most one weather_file (found ${m.length})`):n.push(`Scenario '${s}' weather_file/weather_files must be an array`)}d&&!Array.isArray(i.external_conditions)&&n.push(`Scenario '${s}' external_conditions must be an array`),t.requireWeather!==!1&&!u&&!d&&n.push(`Scenario '${s}' must have either 'weather_files' or 'external_conditions'`),u&&d&&r.push(`Scenario '${s}' has both 'weather_files' and 'external_conditions' - weather_files will take precedence`);for(let[m,_]of Object.entries(i))Array.isArray(_)||n.push(`Scenario '${s}': '${m}' must be an array`)}return{valid:n.length===0,errors:n,warnings:r}}function Kr(e){try{if(!e||typeof e!="object")return null;let t=0;for(let n of Object.values(e)){if(!n||typeof n!="object")continue;let r=n,a=1;for(let s of Object.values(r))Array.isArray(s)&&(a*=s.length);t+=a}return t}catch{return null}}async function Xr(e,t){let n=[],r=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be an object"],missingFiles:r};for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let o=s;for(let[i,u]of Object.entries(o))if(Array.isArray(u)&&!(i==="weather_file"||i==="weather_files"))for(let d of u){let m=Da.join(e,"input","batch_parameters",i,`${String(d)}.json`);try{await Ba.access(m)}catch{r.push({scenario:a,category:i,parameter:String(d),path:m}),n.push(`Scenario '${a}': Parameter '${String(d)}' in category '${i}' not found at ${m}`)}}}return{valid:n.length===0,errors:n,missingFiles:r}}import{access as _s,readFile as wn}from"fs/promises";import{join as yn}from"path";import{fileURLToPath as gs}from"url";var Va=xa(Zr(),1),Wa=Object.defineProperty,Ja=Object.getOwnPropertyNames,Ua=(e,t)=>function(){return e&&(t=(0,e[Ja(e)[0]])(e=0)),t},Ha=(e,t)=>{for(var n in t)Wa(e,n,{get:t[n],enumerable:!0})},za={};Ha(za,{configureWasm:()=>Ga,getRuntimeApiUrl:()=>ts,getRuntimeWasmVariant:()=>Ya,getVersionedWasmAssetPaths:()=>Ht,getVersionedWasmJsUrl:()=>nn,getWasmAssetPaths:()=>rn,getWasmBaseUrl:()=>Ut,getWasmBinaryUrl:()=>an,getWasmJsUrl:()=>cn,getWasmRayonThreadCount:()=>Qr,getWasmVariant:()=>tn,getWasmVersionInfo:()=>lt,getWasmVersionJsonUrl:()=>en,getWasmWasmUrl:()=>ln,initializeWasmRayonThreadPool:()=>Za});function Ga(e={}){e.baseUrl&&(sn=qa(e.baseUrl)),typeof e.preferHashed=="boolean"&&(on=e.preferHashed)}function Yr(){return typeof globalThis.location>"u"?void 0:globalThis.location}function qa(e){return e.replace(/\/+$/,"")||"/"}function Ka(e){let t=Number(e.port||0);return(e.hostname==="localhost"||e.hostname==="127.0.0.1")&&t>=5173&&t<=5179}function Xa(){let e=Yr();if(e){if(Ka(e))return"/pkg";if(e.pathname?.includes("/launch"))return"/launch"}return"/launch"}function Ut(){return sn||Xa()}function Qr(){let e=globalThis.window?.navigator.hardwareConcurrency;return Number.isFinite(e)&&e>0?Math.max(1,Math.floor(e)):4}function Za(e){let t=e,n=Ye.get(t);if(n)return n;let r=e.initialize_rayon_thread_pool;if(typeof r!="function")return Promise.reject(new Error("WASM module does not expose initialize_rayon_thread_pool"));let a=Promise.resolve().then(()=>r(Qr())).then(()=>{});return Ye.set(t,a),a.catch(()=>{Ye.get(t)===a&&Ye.delete(t)}),a}function en(){return`${Ut()}/wasm_version.json`}async function lt(){try{let e=await fetch(en(),{cache:"no-store"});return e.ok?await e.json():null}catch{return null}}function tn(e){let t=e?.variant;if(t===void 0)return"pro";if(t==="free"||t==="pro")return t;throw new Error(`Invalid WASM variant: ${String(t)}`)}async function Ya(){return tn(await lt())}function Qa(){return{jsFilename:"wasm_wrapper.js",wasmFilename:"wasm_wrapper_bg.wasm"}}function es(e){let t=Qa(),r=!!((on??!0)&&e?.hashed_js_filename&&e?.hashed_wasm_filename);return{jsFilename:(r?e?.hashed_js_filename:void 0)||e?.js_filename||t.jsFilename,wasmFilename:(r?e?.hashed_wasm_filename:void 0)||e?.wasm_filename||t.wasmFilename}}async function rn(e){let t=Ut(),n=e===void 0?await lt():e,{jsFilename:r,wasmFilename:a}=es(n);return{jsPath:`${t}/${r}`,wasmPath:`${t}/${a}`}}async function Ht(){let e=await lt(),{jsPath:t,wasmPath:n}=await rn(e),r=e?.build_id||e?.sha256||e?.timestamp;if(!r)return{jsPath:t,wasmPath:n,versionInfo:e};let a=`v=${encodeURIComponent(String(r))}`;return{jsPath:`${t}?${a}`,wasmPath:`${n}?${a}`,versionInfo:e}}async function nn(){let{jsPath:e}=await Ht();return e}async function an(){let{wasmPath:e}=await Ht();return e}function ts(e){let t=Yr();return t?new URL(e,t.origin).toString():e}var Ye,sn,on,cn,ln,un=Ua({"src/wasmPath.ts"(){Ye=new WeakMap,cn=nn,ln=an}});async function dn(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return null;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);if(!Array.isArray(r.files)||!r.files.length||r.files.some(a=>typeof a!="string"||!a||a==="."||a===".."||a.includes("/")||a.includes("\\")))throw new Error(`Invalid target result inventory: ${t}`);return new Set(r.files)}async function mn(e,t){let n=await dn(e,t),r=await e.listFiles(t,{withKind:!0});return n===null?r:r.filter(a=>n.has(typeof a=="string"?a:a.name))}async function fn(e,t){let n=t.lastIndexOf("/"),r=await dn(e,t.slice(0,n));return(r===null||r.has(t.slice(n+1)))&&await e.fileExists(t)}async function pn(e,t){let n=`${t}/target-run.json`;if(!await e.fileExists(n))return t;let r=JSON.parse(await e.readFile(n));if(r?.status!=="complete")throw new Error(`Target results are incomplete: ${t}`);let a=r.archive??t;if(typeof a!="string"||a!==t&&!a.startsWith(`${t}/`)||a.split("/").some(s=>!s||s==="."||s==="..")||a.includes("\\"))throw new Error(`Invalid target result archive: ${t}`);return a}function zt(e){let t=new Map;for(let{run:o,startedAt:i,fileTime:u}of e){if(i!==void 0&&Number.isNaN(Date.parse(i)))throw new Error(`Run ${o} records an invalid start time: ${i}`);let d=t.get(o);t.set(o,{run:o,startedAt:d?.startedAt??i,fileTime:Math.max(d?.fileTime??u,u)})}let n=(o,i)=>{let u=`Runs ${o.run} and ${i.run} have the same time, so the helper cannot tell which run is newest. Run the config again.`;if(o.startedAt!==void 0&&i.startedAt!==void 0)return Date.parse(o.startedAt)-Date.parse(i.startedAt)||u;if(o.startedAt===void 0&&i.startedAt===void 0)return o.fileTime-i.fileTime||u;let[d,m]=o.startedAt===void 0?[i,o]:[o,i];return m.fileTime<Date.parse(d.startedAt)?d===o?1:-1:`The workspace holds a run recorded by an older version of Vulcan, which did not record when a run started (${m.run}). Its files are dated after run ${d.run} started, so they may have been copied, and the helper cannot tell which run is newest. Run the config again.`},r=[...t.values()],a=r.map(o=>r.filter(i=>i!==o).map(i=>n(o,i))),s=r.find((o,i)=>a[i].every(u=>typeof u=="number"&&u>0));return s||!r.length?s:{unknown:a.flat().find(o=>typeof o=="string")}}function Gt(e,t){let n=e.map(r=>typeof r=="string"?r:r.name).filter(r=>r.endsWith(".csv")?t==="results_heat_source_wet"?r.includes("__results_heat_source_wet__"):t==="results_emitters"?r.includes("__results_emitters_"):r.endsWith(`__${t}.csv`):!1).sort((r,a)=>r.localeCompare(a));return n.find(r=>/(?:^|__)FHS__/.test(r))??n.find(r=>!/(?:^|__)FHS_(?:notional|FEE|notional_FEE|FEE_notional)__/.test(r))}un();function _n(e){return e.startsWith("__")}function ut(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).filter(([t,n])=>!_n(t)&&!!n&&typeof n=="object"&&!Array.isArray(n)).map(([t,n])=>({name:t,value:n}))}function rs(e){return Object.keys(e).sort().filter(t=>t!=="zone_allocations").map(t=>e[t]).filter(t=>Array.isArray(t)&&t.length>0)}function ns(e){let t=rs(e);return t.length===0?1:t.reduce((n,r)=>n*r.length,1)}function dt(e,t){let n=[];for(let r of ut(t)){let a=ns(r.value);for(let s=0;s<a;s+=1)n.push(`result_${e}_${r.name}_${s}`)}return n}function qt(e){return Math.floor(e/1e3)}function as(e){return e.endsWith(".csv")||e==="fhs_compliance_report.json"}function ss(e){return e==="failure_context.json"}function gn(e){return as(e)||ss(e)}var is=["fhs_assumptions","fhs_compliance"];var os=[...is,"epc_quick","epc_full"];function cs(e){return os.some(t=>t===e)}var ls=new Set(["base_json","model_wrappers","weather_files","external_conditions"]);function he(e,t,n){return{category:e,selections:[...t],message:n}}function us(e){let t=0;for(let n of e){let r=1;for(let a of Object.values(n.parameters))a.length>0&&(r*=a.length);t+=r}return t}function ds(e){let t=[],n=e.scenarios[0];e.scenarios.length!==1&&t.push(he("scenarios",e.scenarios.slice(1).map(d=>d.name),"Free configurations contain exactly one scenario."));let r=n?.parameters??{},a=r.base_json??[];a.length!==1&&t.push(he("base_json",a.slice(1),"Free configurations contain exactly one base model."));let s=r.model_wrappers??[],o=s.findIndex(cs),i=s.filter((d,m)=>m!==o);(s.length!==1||o!==0)&&t.push(he("model_wrappers",i,"Free configurations use exactly one model wrapper: fhs_assumptions, fhs_compliance, epc_quick or epc_full."));for(let d of["weather_files","external_conditions"]){let m=r[d]??[];m.length>0&&t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")}.`))}for(let[d,m]of Object.entries(r))ls.has(d)||m.length===0||t.push(he(d,m,`Free configurations do not select ${d.replace(/_/g," ")} parameters.`));let u=us(e.scenarios);return u!==1&&t.push(he("permutations",[String(u)],"Free configurations compute exactly one permutation.")),{isFree:t.length===0,violations:t}}function ms(e,t){return _n(e)||e==="targetBundleId"&&typeof t=="string"}function fs(e){return!e||typeof e!="object"?!1:Object.values(e).some(t=>Object.values(t??{}).some(n=>Array.isArray(n)?n.length>0:!!n))}function hn(e){if(!e||typeof e!="object"||Array.isArray(e))return{isFree:!1,violations:[he("config",[],"A batch configuration must be a JSON object.")]};let t=[],n=[];for(let[o,i]of Object.entries(e)){if(ms(o,i))continue;if(!i||typeof i!="object"||Array.isArray(i)){t.push(he("config",[o],`Unrecognised batch configuration entry '${o}'.`));continue}let u={};for(let[d,m]of Object.entries(i))d==="zone_allocations"?fs(m)&&t.push(he("zone_allocations",[o],"Free configurations do not use per-zone selections.")):Array.isArray(m)?u[d]=m.map(String):t.push(he(d,[o],`'${d}' in '${o}' must be a list of selections.`));n.push({name:o,parameters:u})}let r=e.__hem;(!r||typeof r!="object"||Array.isArray(r))&&t.push(he("target",[],"Free runs use a model saved by the current Vulcan app, pinned to a HEM version."));let s=[...ds({scenarios:n}).violations,...t];return{isFree:s.length===0,violations:s}}function ps(){try{let n=(typeof window<"u"?window:void 0)?.VULCAN_LOG_LEVEL;if(n&&Jt(n))return n;let r=typeof window<"u"&&window.localStorage.getItem("vulcan.logLevel")||void 0;if(r&&Jt(r))return r;let s=(globalThis?.import_meta?.env||void 0)?.VITE_LOG_LEVEL;if(s&&Jt(s))return s}catch{}return globalThis?.process?.env?.NODE_ENV!=="production"?"debug":"warn"}function Jt(e){return e==="debug"||e==="info"||e==="warn"||e==="error"}var Ui=ps();un();var mt;async function ft(e){return mt??=vn(),(await mt).csvTarget(e)}async function Kt(e,t){let n=await Le(e,{scenario_1:{base_json:[t]}});return n?(mt??=vn(),(await mt).singleRunWrapper(n)):"fhs_compliance"}async function vn(){for(let e of["./hem-target-runtime/preparation.mjs","../hem-target-runtime/preparation.mjs"]){let t=new URL(e,import.meta.url);try{await _s(gs(t))}catch{continue}return import(t.href)}throw new Error("The target CSV reader is not installed. Build the local target CLI assets or install a helper release including them.")}async function Le(e,t){let n=new Set;for(let{value:r}of ut(t))if(Array.isArray(r.base_json))for(let a of r.base_json){if(typeof a!="string"||/[\\/]/.test(a)||a==="..")throw new Error("Invalid base model name");n.add(await hs(e,a))}if(n.size>1)throw new Error("A batch cannot mix HEM targets. Create a separate batch for each target.");return[...n][0]}async function hs(e,t){try{return await ft(await wn(yn(e,"input/base_models",`${t}.csv`),"utf8"))}catch(n){if(n.code!=="ENOENT")throw n}try{let n=JSON.parse(await wn(yn(e,"input/base_models",`${t}.target.json`),"utf8"));if(typeof n.targetBundleId!="string"||!n.targetBundleId)throw new Error(`Invalid target identity for base model '${t}'`);return n.targetBundleId}catch(n){if(n.code==="ENOENT")return;throw n}}async function Xt(e,t){if(ut(t).some(({value:r})=>Array.isArray(r.heating_profiles)&&r.heating_profiles.length))return"Heating profiles require a saved, pinned HEM target batch; the legacy runner cannot apply post-FHS controls.";let n;try{n=await Le(e,t)}catch(r){return r.message}if(n)return`This batch has no saved __hem snapshot. Its base models use HEM target '${n}' (a Geometry CSV with no TargetBundleId uses Rust a7). Create the batch again with vulcan_create_batch_config, or open it in Create Scenarios in the Vulcan app and save it. Either step saves its exact __hem source and snippet snapshot. The installed legacy runner cannot run it.`}import{fork as Ps}from"child_process";import{join as Qt,resolve as xs}from"path";import{access as Rs,readFile as er}from"fs/promises";import{fileURLToPath as tr}from"url";import{createHash as ys}from"crypto";import Qe from"fs";import Re from"path";import{fileURLToPath as ws}from"url";function Zt(e=process.cwd()){let t=Re.resolve(e);for(Qe.existsSync(t)&&Qe.statSync(t).isFile()&&(t=Re.dirname(t));;){if(Qe.existsSync(Re.join(t,"package.json"))&&Qe.existsSync(Re.join(t,"hem-batch-core"))&&Qe.existsSync(Re.join(t,"web")))return t;let r=Re.dirname(t);if(r===t)break;t=r}let n=Re.dirname(ws(import.meta.url));return Re.resolve(n,"..","..","..")}import we from"fs";import de from"path";import{fileURLToPath as so,pathToFileURL as vs}from"url";var bn=new Map,Cn=!1,Yt=process.cwd(),kn=!1;async function pt(e,t){let n=t?`${e}?verified`:e,r=bn.get(n);if(r)return r;bs();let a=de.join(e,"wasm_wrapper.js"),s=de.join(e,"wasm_wrapper_bg.wasm"),o=de.join(e,"wasm_version.json");if(!we.existsSync(a)||!we.existsSync(s))throw new Error(`Browser WASM artifact not found in ${e}`);let i=await import(vs(a).href+(t?"?verified":""));if(typeof i.initSync!="function")throw new Error("WASM module is missing initSync");if(i.initSync({module:t??we.readFileSync(s)}),i.setup_panic_hook?.(),typeof i.convert_geometry_csv_to_json!="function")throw new Error("WASM module is missing convert_geometry_csv_to_json");let u={convertGeometryCsvToJson:i.convert_geometry_csv_to_json.bind(i),validateSnippetJs:i.validate_snippet_js?.bind(i),processBatchConfig:i.process_batch_config?.bind(i),calculateMetricsFromParsedData:i.calculate_metrics_from_parsed_data?.bind(i),setWorkspace:gt,prepareTargetScenario:i.prepare_target_scenario?.bind(i),metadata:{source:a,wasm_path:s,wasm_version:Es(o),build_stamp:tt(i.build_stamp),build_info:ks(i.get_build_info),runtime_origin_descriptor:tt(i.runtime_origin_descriptor),hem_core_version:tt(i.metadata_hem_core_version),fhs_wrapper_version:tt(i.metadata_fhs_wrapper_version)}};return bn.set(n,u),u}var Sn=new Map;async function _t(e,t){let n=Sn.get(e);if(n)return n;let r=u=>{try{return we.readFileSync(de.join(e,u))}catch{throw new Error(`The package WASM is incomplete: ${de.join(e,u)} is missing. ${t}`)}},a=JSON.parse(r("wasm_version.json").toString("utf8"));for(let u of["js_sha256","sha256"])if(!a[u])throw new Error(`${de.join(e,"wasm_version.json")} has no ${u}. ${t}`);let s=u=>ys("sha256").update(u).digest("hex"),o=r("wasm_wrapper_bg.wasm");if(s(r("wasm_wrapper.js"))!==a.js_sha256||s(o)!==a.sha256)throw new Error(`The WASM in ${e} does not match its wasm_version.json. ${t}`);let i={...await pt(e,o),versionInfo:a};return Sn.set(e,i),i}function gt(e,t={}){Yt=de.resolve(e),kn=t.confineToWorkspace===!0}function bs(){Cs(),Ss();let e=globalThis;e.self||(e.self=globalThis),e.window||(e.window=globalThis),typeof e.addEventListener!="function"&&(e.addEventListener=()=>{}),typeof e.postMessage!="function"&&(e.postMessage=()=>{});let t=e.self;typeof t.addEventListener!="function"&&(t.addEventListener=()=>{}),typeof t.postMessage!="function"&&(t.postMessage=()=>{}),typeof e.Worker!="function"&&(e.Worker=class{addEventListener(){}postMessage(){}terminate(){}}),e.write_file=(n,r)=>{let a=et(n);try{return we.mkdirSync(de.dirname(a),{recursive:!0}),we.writeFileSync(a,r),!0}catch(s){return console.error(`[FS Bridge] write_file failed for ${a}:`,s.message),!1}},e.read_file=n=>{let r=et(n);return we.readFileSync(r,"utf8")},e.file_exists=n=>{let r=et(n);return we.existsSync(r)},e.create_dir_all=n=>{let r=et(n);try{return we.mkdirSync(r,{recursive:!0}),!0}catch(a){return console.error(`[FS Bridge] create_dir_all failed for ${r}:`,a.message),!1}},e.list_dir=n=>{let r=et(n);try{return we.readdirSync(r)}catch{return[]}}}function et(e){let t=de.isAbsolute(e)?de.resolve(e):de.resolve(Yt,e);if(kn){let n=de.relative(Yt,t);if(n===".."||n.startsWith(`..${de.sep}`)||de.isAbsolute(n))throw new Error(`WASM file access escaped the active Vulcan workspace: ${e}`)}return t}function Cs(){if(Cn)return;let e=console.error.bind(console);console.log=(...t)=>{let n=t[0];typeof n=="string"&&n.startsWith("[WASM]")||e(...t)},Cn=!0}var En=!1;function Ss(){if(En)return;let e=globalThis.fetch?.bind(globalThis);globalThis.fetch=((t,n)=>{let r=typeof t=="string"?t:t instanceof URL?t.href:typeof t?.url=="string"?t.url:String(t);if(r.startsWith("file:")&&r.includes("wasm-bindgen-rayon"))return new Promise(()=>{});if(!e)throw new Error("global fetch is unavailable for WASM bridge requests");return e(t,n)}),En=!0}function Es(e){try{return JSON.parse(we.readFileSync(e,"utf8"))}catch{return}}function tt(e){return typeof e!="function"?void 0:e()||void 0}function ks(e){let t=tt(e);if(t)try{return JSON.parse(t)}catch{return t}}var Be=async e=>{let t=!!(e.targetManifestPath||e.targetManifestSha256);if(t&&(!e.targetManifestPath||!/^[a-f0-9]{64}$/.test(e.targetManifestSha256??"")))throw new Error("Supply both target_manifest and target_manifest_sha256 for an offline bundle, or neither to download the verified pinned target.");if(!t&&!e.targetBundleId)throw new Error("No HEM target identified. Save the source CSV with its TargetBundleId pin; installed legacy WASM cannot substitute it.");let n=await Pn(),r=t?{targetBundleId:e.targetBundleId,manifestPath:xs(e.workspace,e.targetManifestPath),manifestSha256:e.targetManifestSha256}:{targetBundleId:e.targetBundleId};if(e.operation==="snapshot")return n.adapter.snapshotTarget({workspace:e.workspace,config:e.config,...r});let a=e.wasmDir??n.wasmDir,s=e.wasmRemedy??"Reinstall the package.";if(e.operation==="batch"){let m={workspace:e.workspace,config:e.config,configName:e.configName,jobId:e.jobId,...r,wasmDir:a,wasmRemedy:s};return e.foreground?n.adapter.runTargetBrowser(m,{loadPackageWasm:_t}):As(n.adapterPath,m)}if(typeof e.csv!="string")throw new Error("CSV source required");let o=await n.adapter.workspaceReader(e.workspace),{manifest:i,text:u}=await n.adapter.readPreparationBundle(r),d=await _t(a,s);return n.preparation.prepareCsv({csv:e.csv,manifest:i,text:u,converter:{prepare_target_scenario:d.prepareTargetScenario},read:o})};async function rr(e){let{workspace:t,baseModel:n}=e,r=await Le(t,{scenario_1:{base_json:[n]}});if(!r)return{status:"unavailable",reason:`${n} is not pinned to a HEM version. Re-save it in the current Vulcan app, or convert its geometry CSV with vulcan_merge_csv_to_json.`};let a=await Pn(),s=a.preparation.heatingSizingUnavailable(r);if(s)return{status:"unavailable",reason:s};let o=await er(Qt(t,"input/base_models",`${n}.csv`),"utf8").catch(_=>{if(_.code!=="ENOENT")throw _}),i=o===void 0?{model:JSON.parse(await er(Qt(t,"input/batch_parameters/base_json",`${n}.json`),"utf8")),validation:JSON.parse(await er(Qt(t,"input/base_models",`${n}.target.json`),"utf8")).validation}:await Be({...e,operation:"prepare",csv:o,targetBundleId:r}),u=i.validation?.errors??[];if(u.length)return{status:"unavailable",reason:"Fix the model errors to size the heating.",errors:u.map(_=>_.message)};if(!Object.keys(i.model.SpaceHeatSystem??{}).length)return{status:"unavailable",reason:"The model has no space heating system to size."};let d=await a.adapter.resolveReleaseBundle(r),m=await a.adapter.loadDesignHeatLossTarget(d.manifestPath,d.manifestSha256);return m.reason?{status:"unavailable",reason:m.reason}:a.preparation.sizeTargetHeating(m.module,JSON.stringify(i.model))}async function Pn(){for(let e of["./hem-target-runtime/","../hem-target-runtime/"]){let t=new URL(e,import.meta.url),n=new URL("browser-adapter.mjs",t);try{await Rs(tr(n))}catch{continue}let[r,a]=await Promise.all([import(n.href),import(new URL("preparation.mjs",t).href)]);return{adapter:r,preparation:a,adapterPath:tr(n),wasmDir:tr(new URL("../../wasm/",t))}}throw new Error("Target assets are not installed. Build the local target CLI assets or install a helper release including them.")}function As(e,t){return new Promise((n,r)=>{let a=Ps(e,["--batch-child"],{detached:!0,stdio:["ignore","ignore","ignore","ipc"]}),s=setTimeout(()=>{a.kill(),r(new Error("Target batch did not acknowledge startup within 120 seconds"))},12e4);a.once("error",o=>{clearTimeout(s),r(o)}),a.once("exit",o=>{clearTimeout(s),r(new Error(`Target batch stopped before startup (${o})`))}),a.once("message",o=>{clearTimeout(s),o.started?(a.unref(),n({status:"started"})):(a.kill(),r(new Error(o.error??"Target batch failed to start")))}),a.send(t)})}import{randomUUID as js}from"crypto";import re from"fs/promises";import H from"path";async function nr(e,t,n={},r={}){let{config_name:a,base_model:s,weather_file:o,wrapper:i,parameters:u}=t;if(!a)throw new Error("config_name is required");if(De(a),!s)throw new Error("base_model is required");if(!u||typeof u!="object"||Array.isArray(u))throw new Error("parameters is required and must be an object mapping category to parameter IDs array");let d=Ts(u),m={base_json:[s],...i?{model_wrappers:[i]}:{},...d},_=await Le(e,{scenario_1:m}),g=!!(t.targetManifestPath||t.targetManifestSha256||_);if(!o&&!g)throw new Error("weather_file is required");o&&(m.weather_files=[g&&!o.endsWith(".epw")?`${o}.epw`:o]);let f={scenario_1:m};await r.gate?.(g?{...f,__hem:{}}:f);let v=qr(f,{requireWeather:!g});if(!v.valid)return{success:!1,valid:!1,errors:v.errors,warnings:v.warnings,message:`Config validation failed: ${v.errors.join("; ")}`};let A=Kr(f);if(A===null)return{success:!1,valid:!1,errors:["Failed to calculate permutations"],message:"Failed to calculate permutations for batch config"};let I=n.maxPermutations??500;if(!Number.isSafeInteger(I)||I<1)throw new Error("maxPermutations must be a positive integer");if(A>I)return{success:!1,valid:!1,errors:[`Total permutations (${A}) exceeds maximum of ${I}`],message:`Config would generate ${A} permutations, which exceeds the limit of ${I}`};let C=f;if(g){let k=await(r.runTarget??Be)({workspace:e,operation:"snapshot",config:f,targetBundleId:_,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256});C={...f,__hem:k}}else{let k=await Xr(e,f);if(!k.valid)return{success:!1,valid:!1,errors:k.errors,missingFiles:k.missingFiles,message:`Some parameter files are missing: ${k.errors.slice(0,3).join("; ")}${k.errors.length>3?"...":""}`};let W=H.join(e,"input","batch_parameters","base_json",`${s}.json`);try{await re.access(W)}catch{return{success:!1,valid:!1,errors:[`Base model '${s}' not found at ${W}`],message:`Base model file not found: ${s}`}}let Q=H.join(e,"input","batch_parameters","weather_files",o.endsWith(".epw")?o:`${o}.epw`);try{await re.access(Q)}catch{return{success:!1,valid:!1,errors:[`Weather file '${o}' not found at ${Q}`],message:`Weather file not found: ${o}`}}}await r.gate?.(C);let x=H.join(e,"input","batch_configs");if(g){let k=await re.realpath(e);for(let W of["input","batch_configs"])if(k=H.join(k,W),await re.mkdir(k).catch(Q=>{if(Q.code!=="EEXIST")throw Q}),await re.realpath(k)!==k)throw new Error("Target config directory is a symlink")}else await re.mkdir(x,{recursive:!0});let O=a.endsWith(".json")?a:`${a}.json`,V=H.join(x,O);try{return await re.access(V),{success:!1,valid:!1,errors:[`Config file '${O}' already exists`],message:"Config file already exists. Use a different name or delete the existing file first."}}catch{}return await re.writeFile(V,JSON.stringify(C,null,2),{encoding:"utf8",flag:"wx"}),{success:!0,valid:!0,message:`Batch config '${a}' created successfully`,config_path:V,permutations:A,structure:f}}async function ar(e,t,n){let{config_name:r,job_id:a}=t;if(!r)throw new Error("config_name is required");let s=a||n.generateJobId?.()||`mcp_${js()}`;De(r);let o=r.endsWith(".json")?r:`${r}.json`,i=H.join(e,"input","batch_configs",o),u;try{u=await re.readFile(i,"utf8")}catch(g){let f=g;throw f.code==="ENOENT"?new Error(`Batch config '${r}' not found at ${i}`):new Error(`Failed to read config file: ${f.message}`)}let d=JSON.parse(u);if(await n.gate?.(d),d&&typeof d=="object"&&("__hem"in d||"targetBundleId"in d)){let g=d.__hem;if(!g){let f="This batch names a HEM target but has no saved __hem source snapshot. Re-save the batch in the app (or create it with vulcan_create_batch_config).";return{job_id:s,status:"error",message:f,error:f}}try{return await(n.runTarget??Be)({workspace:e,operation:"batch",config:d,targetBundleId:g.targetBundleId,configName:r.replace(/\.json$/,""),jobId:s,targetManifestPath:t.targetManifestPath,targetManifestSha256:t.targetManifestSha256}),{job_id:s,status:"started",config_name:r,output_dir:H.join(e,"output"),message:"Exact target batch started. Read progress with batch status (MCP: vulcan_get_batch_status; Analyst: vulcan-analyst batch status); runtime provenance is stored with outputs."}}catch(f){let v=f.message;return{job_id:s,status:"error",message:v,error:v}}}let m=await Xt(e,d);if(m)return{job_id:s,status:"error",message:m,error:m};if(t.targetManifestPath||t.targetManifestSha256){let g="Save a batch with an exact __hem source/snippet snapshot before selecting its target bundle.";return{job_id:s,status:"error",message:g,error:g}}let _=H.join(e,"output");await re.mkdir(_,{recursive:!0});try{let g=await n.processBatchConfig(u,e,_,r.replace(/\.json$/,""),s),f=JSON.parse(g);return f.error?{job_id:s,status:"error",message:`Batch execution failed: ${f.error}`,error:f.error}:{job_id:s,status:"started",message:"Batch execution started successfully",config_name:r,output_dir:_}}catch(g){let f=g;return{job_id:s,status:"error",message:`Failed to start batch execution: ${f.message}`,error:f.message}}}async function sr(e,t={}){let{job_id:n}=t,r=t.config_name?.replace(/\.json$/,"");r&&De(r);let a=H.join(e,"output"),s;if(r&&!n){if(s=await ht(e,r),!s.jobId){let x=s.error!==void 0?"error":s.unknown?"unknown":"not_run",O=s.error??s.unknown??s.changed??`Batch config '${r}' has no recorded run. A legacy engine run records its config only in its result folders: pass the job_id from vulcan_run_batch instead.`;return{config_name:r,status:x,progress:0,passes:0,failures:0,output_dir:a,error:O,...An(s.warnings)}}n=s.jobId}if(!n)throw new Error("Either job_id or config_name is required");if(/[\\/]/.test(n)||n==="."||n==="..")throw new Error(`Invalid job_id '${n}': a job id is a plain name, as vulcan_run_batch returns it`);let o=s?.warnings??[],i=H.join(a,`progress_${n}.json`),u=H.join(a,`sim_progress_${n}.json`),d=await Ae(i,o),m=await Ae(u,o),_=await Mn(a,n,o);if(!s&&_.config){let x=await ht(e,_.config);o.push(...x.warnings),x.jobId===n&&(s=x),r??=_.config}let g=_.records>0||typeof d?.targetBundleId=="string",f="queued",v=0,A=0,I=0,C=null;if(d?(jn(d.status)?f=d.status:typeof d.percentage=="number"?(v=d.percentage,f=v>=100?"completed":"running"):typeof d.current_combination=="number"&&typeof d.total_combinations=="number"&&(v=Math.round(d.current_combination/d.total_combinations*100),f=v>=100?"completed":"running"),typeof d.percentage=="number"&&(v=d.percentage),typeof d.error=="string"&&(C=d.error,f="error")):_.records&&(_.stopped?(f="error",C=_.stopped):s?.expected!==void 0&&_.passes===s.expected?(f="completed",v=100):(f="unknown",C=`Job ${n} has finished ${_.passes} of ${s?.expected??"an unknown number of"} scenarios and recorded no failure. The app writes no progress file, so the helper cannot tell whether the run is still going or has stopped; check the app.`)),_.records&&({passes:A,failures:I}=_),s?.error!==void 0&&(C=s.error,f="error"),m&&!g&&(jn(m.status)&&(f=m.status),typeof m.passes=="number"&&(A=m.passes),typeof m.failures=="number"&&(I=m.failures),typeof m.error=="string"&&(C=m.error,f="error")),!d&&!m&&!_.records){let x=H.join(a,n);try{let O=await re.readdir(x);f=O.length>0?"completed":"queued",v=O.length>0?100:0}catch(O){throw O.code!=="ENOENT"?O:new Error(`Job ${n} does not exist in this workspace: ${a} holds no progress file, run record or folder for it.`)}}return{job_id:n,...r?{config_name:r}:{},status:f,progress:v,passes:A,failures:I,output_dir:a,error:C,batch_progress:d??null,sim_progress:g?null:m??null,...An(o)}}async function ht(e,t){let n=H.join(e,"output"),r=[],a=[],s=async T=>(await re.stat(T)).mtimeMs,o=T=>typeof T.startedAt=="string"?T.startedAt:void 0;for(let T of await re.readdir(n).catch(wt)??[]){if(!T.startsWith("progress_")||!T.endsWith(".json"))continue;let M=await Ae(H.join(n,T),r),c=T.slice(9,-5);M?.config_name===t&&a.push({run:c,jobId:c,startedAt:o(M),fileTime:await s(H.join(n,T))})}De(t);let i=H.join(e,"input","batch_configs",`${t}.json`),u=await Ae(i,r),d=u?dt(t,u):[],m,_=[];for(let T of d){let M=H.join(n,T),c=await re.readdir(M,{withFileTypes:!0}).catch(wt);if(!c)continue;if(!c.some(p=>p.name==="target-run.json")){let p=c.filter(h=>h.isFile()&&gn(h.name)).map(h=>H.join(M,h.name));if(!p.length)continue;m??=`Batch config '${t}' has results in output/${T} from the legacy engine, which does not record the job that wrote them. Pass the job_id from vulcan_run_batch.`,a.push({run:xn,fileTime:Math.max(...await Promise.all(p.map(s)))});continue}let l=T.slice(`result_${t}_`.length);for(let p of c.filter(h=>h.isDirectory()))for(let h of await re.readdir(H.join(M,p.name),{withFileTypes:!0})){if(!h.isDirectory())continue;let w=H.join(M,p.name,h.name,"target-run.json"),$=r.length,b=await Ae(w,r);if(!b){r.length>$&&_.push({warning:r.at(-1),fileTime:await s(w)});continue}b.name!==l||b.kind==="overheating"||a.push({run:h.name,jobId:h.name,startedAt:o(b),fileTime:await s(w)})}}let g=H.join(n,`batch_status_${t}.json`),f=await Ae(g,r),v=f?.status==="error"||f?.status==="running",A=v?o(f):void 0,I=A===void 0?void 0:a.find(T=>T.jobId&&T.startedAt===A)?.jobId;v&&!I&&a.push({run:Rn,startedAt:A,fileTime:await s(g)});let C=u?d.length:void 0,x=a.flatMap(T=>T.startedAt===void 0?[]:[Date.parse(T.startedAt)]),O=_.find(T=>!x.length||T.fileTime>=Math.max(...x));if(O)return{unknown:`The helper cannot read a run record of batch config '${t}', so it cannot tell which run is latest. ${O.warning}`,expected:C,warnings:r};if(!a.length)return{legacyCurrent:!0,expected:C,warnings:r};if(u&&qt(await s(i))>qt(Math.max(...a.map(T=>T.fileTime))))return{changed:`Batch config '${t}' was saved after its last run. Results from that run are earlier-run results. Run the config again.`,expected:C,warnings:r};let V=zt(a);if("unknown"in V)return{unknown:V.unknown,expected:C,warnings:r};if(V.run===xn)return{unknown:m,legacyCurrent:!0,expected:C,warnings:r};let k=f?.error_message,W=f?.status!=="error"?void 0:typeof k=="string"&&k?k:`The app recorded the run of batch config '${t}' as failed, with no reason.`;if(V.run!==Rn)return{jobId:V.run,...V.run===I?{error:W}:{},expected:C,warnings:r};if(f?.status==="running")return{unknown:`The app started a run of batch config '${t}' at ${A} and has written no scenario yet. It may still be preparing, or it stopped without recording why; check the app.`,expected:C,warnings:r};if(A!==void 0)return{error:W,expected:C,warnings:r};let Q=zt(a.filter(T=>T.jobId)),Se=Q&&"run"in Q?Q.run:void 0;return{...Se&&(await Mn(n,Se,r)).stopped?{jobId:Se}:{},error:W,expected:C,warnings:r}}var xn="legacy engine results";async function Tn(e,t){let n=[];for(let r of await re.readdir(e,{withFileTypes:!0}).catch(wt)??[])if(r.isDirectory())for(let a of await re.readdir(H.join(e,r.name),{withFileTypes:!0})){let s=H.join(e,r.name,a.name),o=a.isDirectory()?await Ae(H.join(s,"target-run.json"),[]):void 0;o?.kind==="overheating"&&!o.parentJob&&n.push({name:t,job_id:a.name,status:String(o.status),path:s})}return n}var Rn="the app's run status";async function Mn(e,t,n){let r={records:0,passes:0,failures:0,stopped:void 0,config:void 0};for(let a of await re.readdir(e,{withFileTypes:!0}).catch(wt)??[])if(!(!a.isDirectory()||!a.name.startsWith("result_")))for(let s of await re.readdir(H.join(e,a.name),{withFileTypes:!0})){if(!s.isDirectory())continue;let o=await Ae(H.join(e,a.name,s.name,t,"target-run.json"),n);if(!o||o.kind==="overheating")continue;r.records+=1;let i=`_${String(o.name)}`;a.name.endsWith(i)&&(r.config??=a.name.slice(7,-i.length)),o.status==="complete"?r.passes+=1:o.status==="failed"&&(r.failures+=1),(o.status==="failed"||o.status==="cancelled")&&(r.stopped??=`Scenario ${String(o.name)} ${o.status}${typeof o.error=="string"?`: ${o.error}`:""}`)}return r}async function Ae(e,t){let n;try{n=await re.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}try{return JSON.parse(n)}catch(r){t.push(`Skipped ${e}: ${r.message}`);return}}function wt(e){if(e.code!=="ENOENT")throw e}function An(e){return e.length?{warnings:e}:{}}function De(e){let t=e.endsWith(".json")?e.slice(0,-5):e;if(!t.trim()||H.basename(t)!==t||/[\\/\0]/.test(t)||t.startsWith("."))throw new Error(`Invalid batch config name: ${JSON.stringify(e)} (no path separators or leading '.')`)}function Ts(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?n.map(String):[String(n)]]))}function jn(e){return e==="queued"||e==="running"||e==="completed"||e==="error"}import Ao from"crypto";import je from"fs/promises";import ne from"path";import Ms from"fs/promises";import $n from"path";var Po=$n.join("input","base_models");async function ir(e){await On(e,"Workspace"),await On($n.join(e,"input","batch_parameters"),"Vulcan workspace input/batch_parameters").catch(t=>{throw new Error(`${t.message}. Point the tool at a folder opened as a workspace in the Vulcan app.`)})}async function On(e,t){try{if(!(await Ms.stat(e)).isDirectory())throw new Error(`${t} is not a directory: ${e}`)}catch(n){let r=n;throw r.code==="ENOENT"?new Error(`${t} directory not found: ${e}`):r}}var rt="The schema and defaults arguments were removed. The CSV's TargetBundleId row decides the schema; a CSV with no TargetBundleId row uses HEM:FHS 1.0.0a7. The defaults are the target's own. A DefaultsPath row in the CSV must hold the same defaults.";async function or(e){let{workspace:t,csvPath:n,outputPath:r}=e,a=ne.isAbsolute(n)?n:ne.join(t,n),s;try{s=await je.readFile(a,"utf8")}catch(i){let u=i;throw u.code==="ENOENT"?new Error(`CSV file not found at ${a}`):new Error(`Failed to read CSV file: ${u.message}`)}let o=await ft(s);try{let i=await(e.runTarget??Be)({workspace:t,operation:"prepare",csv:s,targetBundleId:o,targetManifestPath:e.targetManifestPath,targetManifestSha256:e.targetManifestSha256}),u=r?ne.resolve(t,r):Os(t,a);if(ne.extname(u)!==".json")throw new Error("Prepared target output must have a .json extension");return await Nn(t,u),await Fn(t,ne.join(t,"input/base_models",ne.basename(u,".json")+".target.json"),JSON.stringify({targetBundleId:o,validation:i.validation,schema_omissions:i.schema_omissions,readiness:"wrapper_input"})),await Fn(t,u,JSON.stringify(i.model,null,2)),{ok:!0,json_path:ne.relative(t,u),validation:i.validation,...i.schema_omissions?.length?{schema_omissions:i.schema_omissions}:{},schema_source:`target:${o}`,defaults_source:`target:${o}`,...i.notice?{notice:i.notice}:{}}}catch(i){return{ok:!1,error:i.message}}}function Os(e,t){let n=ne.basename(t,ne.extname(t));return ne.join(e,"input","batch_parameters","base_json",`${n}.json`)}async function Nn(e,t){let n=await je.realpath(e),r=ne.relative(ne.resolve(e),t);if(!r||r===".."||r.startsWith(`..${ne.sep}`)||ne.isAbsolute(r))throw new Error("Target preparation output must stay within the workspace");let a=ne.join(n,r),s=n;for(let o of ne.relative(n,ne.dirname(a)).split(ne.sep).filter(Boolean))if(s=ne.join(s,o),await je.mkdir(s).catch(i=>{if(i.code!=="EEXIST")throw i}),await je.realpath(s)!==s)throw new Error("Target preparation output directory is a symlink");try{if(await je.realpath(a)!==a)throw new Error("Target preparation output is a symlink")}catch(o){if(o.code!=="ENOENT")throw o}return a}async function Fn(e,t,n){let r=await Nn(e,t),a=await je.open(r,"wx").catch(async s=>{if(s.code!=="EEXIST")throw s;if(await je.realpath(r)!==r)throw new Error("Target preparation output is a symlink");return je.open(r,"w")});try{await a.writeFile(n)}finally{await a.close()}}import{fileURLToPath as $s}from"url";import fe from"fs/promises";import X from"path";function yt(e,t){if(!e||/[\/\\\0]/.test(e)||e.startsWith("."))throw new Error(`${t} must be a plain name, without path separators or a leading '.': ${JSON.stringify(e)}`)}async function cr(e,t={}){let{category:n}=t,r=X.join(e,"input","batch_parameters"),a=await fe.readdir(r,{withFileTypes:!0}),s={};for(let o of a){if(!o.isDirectory())continue;let i=o.name;if(n&&i!==n)continue;let u=X.join(r,i),d=await fe.readdir(u),m=[];for(let _ of d){if(!_.endsWith(".json"))continue;let g=_.replace(/\.json$/,""),f=X.join(u,_);try{let v=await fe.readFile(f,"utf8"),A=JSON.parse(v);m.push({id:g,name:typeof A.name=="string"?A.name:g,description:typeof A.description=="string"?A.description:"",category:i})}catch(v){console.error(`Failed to parse ${f}: ${v.message}`)}}m.length>0&&(s[i]={category:i,parameters:m.sort((_,g)=>_.name.localeCompare(g.name))})}return{catalog:s,total_categories:Object.keys(s).length,total_parameters:Object.values(s).reduce((o,i)=>o+i.parameters.length,0)}}async function lr(e,t){let{category:n,parameter_id:r}=t;if(!n)throw new Error("category is required");if(!r)throw new Error("parameter_id is required");yt(n,"category"),yt(r,"parameter_id");let a=X.join(e,"input","batch_parameters",n),s=X.join(a,`${r}.json`),o=X.join(a,`${r}.md`),i;try{let d=await fe.readFile(s,"utf8");i=JSON.parse(d)}catch(d){let m=d;throw m.code==="ENOENT"?new Error(`Parameter '${r}' not found in category '${n}'`):new Error(`Failed to read parameter JSON: ${m.message}`)}let u=null;try{u=await fe.readFile(o,"utf8")}catch(d){let m=d;m.code!=="ENOENT"&&console.warn(`Failed to read markdown file: ${m.message}`)}return{category:n,parameter_id:r,json:i,markdown:u,has_markdown:u!==null}}async function ur(e,t,n){let{category:r,parameter_id:a,content:s,markdown_content:o}=t;if(!r)throw new Error("category is required");if(!a)throw new Error("parameter_id is required");if(s==null||s==="")throw new Error("content is required");if(r!==r.toLowerCase())throw new Error(`category must be lowercase, as the workspace folders are: ${JSON.stringify(r)}`);yt(r,"category"),yt(a,"parameter_id");let i=Fs(s),[u,d]=await Promise.all([Bs(e),Ds(e,r)]),m=await Ls(e,Is(u)?"input_fhs":"input_core"),_=V=>{let k=JSON.parse(n.validateSnippetJs(r,JSON.stringify(V),JSON.stringify(m),JSON.stringify(u),d?JSON.stringify(d):null));return k.ok?[]:(k.errors??[]).map(W=>typeof W=="string"?{path:"",message:W}:{path:W.path??"",message:W.message||String(W)})},g=_(i),f=g.length>0&&!Ns.has(r),v=V=>`${V.path}\0${V.message}`,A=f?new Set(_({}).map(v)):new Set,I=g.filter(V=>V.message.startsWith("Merge failed")||!A.has(v(V))).map(V=>V.message);if(I.length>0)return{success:!1,valid:!1,errors:I,message:`Validation failed: ${I.join("; ")}`};let C=X.join(e,"input","batch_parameters",r);await fe.mkdir(C,{recursive:!0});let x=X.join(C,`${a}.json`);await fe.writeFile(x,JSON.stringify(i,null,2),"utf8");let O=null;return o&&(O=X.join(C,`${a}.md`),await fe.writeFile(O,o,"utf8")),{success:!0,valid:!0,errors:[],message:`Parameter '${a}' saved successfully in category '${r}'`,paths:{json:x,markdown:O}}}function Fs(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){throw new Error(`Invalid JSON syntax: ${t.message}`)}}var Ns=new Set(["model_wrappers","weather_files","external_conditions","tariff","simplified_fabric"]);function Is(e){return!!(e&&typeof e=="object"&&("General"in e||"PartGcompliance"in e))}function In(e){return["../schemas/","../../schemas/"].map(t=>$s(new URL(t+e,import.meta.url)))}async function Ls(e,t){let n=t==="input_fhs"?"input_fhs.schema.json":"core-input.schema.json",r=t==="input_fhs"?[X.join(e,"input_fhs.schema.json"),X.join(e,"schemas","input_fhs.schema.json"),X.join(Zt(e),"hem_fhs_upstream","schema","input_fhs.schema.json"),...In(n)]:[X.join(e,"input_core.schema.json"),X.join(e,"hem_engine_upstream","schemas","core-input.schema.json"),X.join(e,"core-input.schema.json"),X.join(e,"schemas","core-input.schema.json"),X.join(e,"input.schema.json"),X.join(Zt(e),"hem_engine_upstream","schemas","core-input.schema.json"),...In(n)];for(let a of r)try{return JSON.parse(await fe.readFile(a,"utf8"))}catch{}throw new Error(`Schema file not found (${t}). Tried: ${r.join(", ")}`)}async function Bs(e){let t=X.join(e,"input","batch_parameters","base_json"),n=(await fe.readdir(t).catch(()=>[])).filter(i=>i.endsWith(".json")).sort(),r=new Set(await fe.readdir(X.join(e,"input","base_models")).catch(()=>[])),a=n.filter(i=>!i.startsWith("defaults_template")),s=n.includes("demo_hp_annual.json")?"demo_hp_annual.json":a.find(i=>r.has(i.replace(/\.json$/,".csv")))??a[0];if(!s)throw new Error(`No base model to validate the snippet against: add one to ${t} (convert a geometry CSV with merge-csv-to-json).`);let o=X.join(t,s);try{return JSON.parse(await fe.readFile(o,"utf8"))}catch(i){throw new Error(`Could not read base model ${o}: ${i.message}`)}}async function Ds(e,t){if(t!=="simplified_fabric")return null;let n=[X.join(e,"input","batch_parameters","simplified_fabric","good_insulation_compliance.json"),X.join(e,"input","batch_parameters","simplified_fabric","compliance_example.json")];for(let r of n)try{return JSON.parse(await fe.readFile(r,"utf8"))}catch{}return null}import pr from"fs/promises";import bt from"path";import Te from"fs/promises";import _e from"path";async function Je(e,t){let n=_e.join(e,"output"),r=Dn(t.config_name);De(r);let a=[],s=new Set,o=[],i=[],u=[];try{let d=_e.join(n,r),m=await vt(d);m&&await Ln(e,d,a,s);let _;try{_=JSON.parse(await Te.readFile(_e.join(e,"input","batch_configs",`${r}.json`),"utf8"))}catch(C){if(C.code!=="ENOENT")throw C;if(!m)throw new Error(`Batch config '${r}' was not found in input/batch_configs.`)}for(let C of _===void 0?[]:dt(r,_)){let x=_e.join(n,C);if(!await vt(x))continue;let O=C.slice(`result_${r}_`.length);i.push(...await Tn(x,O));try{await Ln(e,x,a,s,O)}catch(V){let k=await Te.readFile(_e.join(x,"target-run.json"),"utf8").then(JSON.parse,()=>{});k?.status==="failed"||k?.status==="cancelled"?o.push({name:O,...typeof k.jobId=="string"?{job_id:k.jobId}:{},error:typeof k.error=="string"?k.error:`The scenario's run is recorded as ${k.status}, with no reason.`}):k?.status==="running"?u.push(`Scenario ${O} has no results yet: its run${typeof k.jobId=="string"?` (job ${k.jobId})`:""} is recorded as running.`):u.push(`Failed to read result directory ${C}: ${V.message}`)}}a.sort((C,x)=>C.name.localeCompare(x.name));let g=_===void 0?void 0:await ht(e,r),f=g?.jobId;u.push(...g?.warnings??[]),f&&g?.error!==void 0&&!o.some(C=>C.job_id===f)&&u.push(`The app recorded run ${f} of batch config '${r}' as failed after these scenarios finished: ${g.error}`);let v=g===void 0?[]:a.filter(C=>C.job_id===void 0?!g.legacyCurrent:C.job_id!==f),A=f||g?.legacyCurrent?void 0:g?.changed??g?.unknown??(g?.error!==void 0?`The latest run of batch config '${r}' failed before it wrote any scenario: ${g.error}`:void 0),I=a.filter(C=>!v.includes(C));return{config_name:r,models:I,total_models:I.length,output_dir:n,...f?{latest_job_id:f}:{},...v.length?{earlier_run_models:v}:{},...A?{latest_run_unknown:A}:{},...o.length?{failed_models:o}:{},...i.length?{overheating_runs:i}:{},...u.length?{warnings:u}:{}}}catch(d){return{config_name:r,models:[],total_models:0,output_dir:n,error:`Failed to list models: ${d.message}`}}}async function dr(e,t){let n=Dn(t.config_name),r=await Je(e,{config_name:n}),a=r.models.find(m=>m.name===t.model_name)?.csv_path;if(!a)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,error:mr(r,t.model_name)};let o=(await Te.readFile(a,"utf8")).split(`
|
|
13
13
|
`).filter(m=>m.trim());if(o.length<2)return{config_name:n,model_name:t.model_name,columns:[],total_columns:0,csv_path:a,error:"CSV must have at least headers and units rows"};let i=Bn(o[0]??"").map(m=>m.trim()),u=Bn(o[1]??"").map(m=>m.trim()),d=[];for(let m=1;m<i.length;m+=1){let _=i[m],g=m<u.length?u[m]:"";_&&d.push({name:_,unit:g||"",index:m-1})}return{config_name:n,model_name:t.model_name,columns:d,total_columns:d.length,csv_path:a}}function mr(e,t){let n=e.earlier_run_models?.find(r=>r.name===t);if(n){let r=e.latest_job_id?`The config's latest run is job ${e.latest_job_id}. `:e.latest_run_unknown?`${e.latest_run_unknown} `:"";return`Model ${t} has results only from ${n.job_id?`job ${n.job_id}`:"the legacy engine"}, an earlier run. ${r}They do not reflect the latest inputs: re-run the config.`}return e.error??`No completed actual-dwelling CSV found for model ${t}`}var fr={fileExists:vt,readFile:e=>Te.readFile(e,"utf8"),listFiles:e=>Te.readdir(e)};async function Ln(e,t,n,r,a){let s={fileExists:f=>vt(_e.join(e,f)),readFile:f=>Te.readFile(_e.join(e,f),"utf8")},o=_e.relative(e,t).split(_e.sep).join("/"),i=_e.join(e,await pn(s,o)),d=(await mn(fr,i)).map(f=>typeof f=="string"?f:f.name),m=await Te.readFile(_e.join(i,"target-run.json"),"utf8").then(JSON.parse,()=>{}),_=typeof m?.jobId=="string"?m.jobId:void 0,g=(f,v)=>{r.has(f)||(r.add(f),n.push({name:f,csv_path:_e.join(i,v),has_results:!0,..._?{job_id:_}:{}}))};if(a){let f=Gt(d,"results");f&&g(a,f);return}for(let f of d){if(!Gt([f],"results"))continue;let v=f.match(/^(.+?)__(?:core__|FHS__)?results\.csv$/);v?.[1]&&g(v[1],f)}}function Dn(e){return e.replace(/\.json$/,"")}async function vt(e){try{return await Te.access(e),!0}catch{return!1}}function Bn(e){let t=[],n="",r=!1;for(let a=0;a<e.length;a+=1){let s=e[a];r?s==='"'?e[a+1]==='"'?(n+='"',a+=1):r=!1:n+=s:s==='"'?r=!0:s===","?(t.push(n),n=""):n+=s}return t.push(n),t}var Vs=new Set(["sumif","averageif","countif"]),Vn=new Set([">=","<=",">","<","="]);async function _r(e,t,n){let{config_name:r,model_names:a,metric_definitions:s,time_range:o,tariff_file_path:i,tariff_column_index:u}=t;if(!r)throw new Error("config_name is required");if(!a||!Array.isArray(a)||a.length===0)throw new Error("model_names is required and must be a non-empty array");if(!s||!Array.isArray(s)||s.length===0)throw new Error("metric_definitions is required and must be a non-empty array");let d=r.replace(/\.json$/,""),{encodedMetrics:m,metadata:_}=Us(s);if(_.some(x=>x.function.toLowerCase()==="cost")&&(!i||u===void 0))throw new Error("Cost metrics require both tariff_file_path and tariff_column_index parameters");let f;if(i&&u!==void 0){let x=await Hs(i,u,e);f=JSON.stringify(x)}let v=[],A=await Je(e,{config_name:d}),I=[],C=[];for(let x of a){let O=A.models.find(k=>k.name===x)?.csv_path;if(!O){let k=A.earlier_run_models?.find(Q=>Q.name===x),W=A.failed_models?.find(Q=>Q.name===x);if(W)C.push({model_name:x,...W.job_id?{job_id:W.job_id}:{},error:W.error});else if(k)I.push({model_name:x,...k.job_id?{job_id:k.job_id}:{}});else throw new Error(mr(A,x));continue}let V=await pr.readFile(O,"utf8");try{let k=Ws(V,x,r);if(_.some(ae=>ae.isCompliance)){let ae=bt.join(bt.dirname(O),"fhs_compliance_report.json");if(!await fn(fr,ae))throw new Error("Completed FHS compliance report is unavailable");let T=JSON.parse(await pr.readFile(ae,"utf8")),M=["dwelling_emission_rate","dwelling_primary_energy_rate","dwelling_fabric_energy_efficiency"];for(let c of M){let l=T[c];k[c]=typeof l=="number"&&Number.isFinite(l)?l:null}for(let c of _.filter(l=>l.isCompliance)){let l=M.find(p=>p===c.column);if(!l||k[l]===null)throw new Error(`Completed FHS compliance rate '${c.column}' is unavailable`)}}if(k.timestamps.length===0)throw new Error(`No timestamps found in CSV for model ${x}`);if(Object.keys(k.columns).length===0)throw new Error(`No columns found in CSV for model ${x}`);let W=zs(k,m,_);if(W.length>0){let ae=Object.keys(k.columns).slice(0,10);throw new Error(`Columns not found in CSV: ${W.join(", ")}. Available columns: ${ae.join(", ")}...`)}let Q=n.calculateMetricsFromParsedData(JSON.stringify(k),JSON.stringify(m),o?JSON.stringify(o):void 0,f);if(!Q||typeof Q!="string")throw new Error(`WASM returned invalid result: ${typeof Q}`);let Se=JSON.parse(Q);if(!Array.isArray(Se))throw new Error(`WASM returned non-array result: ${typeof Se}`);Se.forEach((ae,T)=>{let M=_[T],[c=ae.name,l="sum"]=ae.name.split("|");v.push({id:M?.id||ae.name,name:M?.name||ae.name,column:M?.column||c,function:M?.function||l,comparator:M?.comparator,threshold:M?.threshold,value:ae.value,model_name:x})})}catch(k){let W=k;if(W.code==="ENOENT"){console.warn(`CSV file not found for model ${x}: ${O}`);continue}throw new Error(`Failed to process model ${x}: ${W.message}`)}}return{metrics:v,total_models:a.length-I.length-C.length,total_metrics:v.length,...I.length?{earlier_run_models:I}:{},...C.length?{failed_models:C}:{},...A.latest_run_unknown?{latest_run_unknown:A.latest_run_unknown}:{},...A.warnings?{warnings:A.warnings}:{}}}function Ws(e,t,n){let r=e.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vulcan-energy/mcp-helper",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"description": "Vulcan Home Energy Model tools for AI assistants over MCP (Claude Code, Codex, Claude Desktop, Cursor). Runs locally; Free tools need no account.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
package/wasm/wasm_version.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"build_id": "20261117-
|
|
2
|
+
"build_id": "20261117-131029",
|
|
3
3
|
"variant": "free",
|
|
4
|
-
"sha256": "
|
|
5
|
-
"js_sha256": "
|
|
6
|
-
"source_git_commit": "
|
|
7
|
-
"source_tree_sha256": "
|
|
4
|
+
"sha256": "5beb38bb31fe43b169a1e1e97dd13928e051d3b60551667bff058835ce9de2ed",
|
|
5
|
+
"js_sha256": "43a7f0946ae8751760a4c017e24f94c972fc15e83eb3043d9535b19f4bb9bba1",
|
|
6
|
+
"source_git_commit": "fba186af3f8da4f44486b61c5ab6c9e4fe049c18",
|
|
7
|
+
"source_tree_sha256": "f8879c2f02a1a8e783f9aad3174bdf61268a68fcfbe45b25914dc0fd0512b900",
|
|
8
8
|
"source_tree_dirty": false,
|
|
9
|
-
"timestamp": "2026-11-
|
|
9
|
+
"timestamp": "2026-11-17T13:19:39.570Z",
|
|
10
10
|
"runtime_origin": "Vulcan browser HEM runtime; source origin: Home Energy Foundry Limited; marker: HEF-VULCAN-RUNTIME-2026",
|
|
11
|
-
"size_bytes":
|
|
12
|
-
"js_size_bytes":
|
|
11
|
+
"size_bytes": 18506630,
|
|
12
|
+
"js_size_bytes": 52755,
|
|
13
13
|
"wasm_filename": "wasm_wrapper_bg.wasm",
|
|
14
14
|
"js_filename": "wasm_wrapper.js",
|
|
15
|
-
"hashed_wasm_filename": "wasm_wrapper_bg.
|
|
16
|
-
"hashed_js_filename": "wasm_wrapper.
|
|
15
|
+
"hashed_wasm_filename": "wasm_wrapper_bg.5beb38bb.wasm",
|
|
16
|
+
"hashed_js_filename": "wasm_wrapper.43a7f094.js"
|
|
17
17
|
}
|
package/wasm/wasm_wrapper.js
CHANGED
|
@@ -169,6 +169,27 @@ export function get_build_info() {
|
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* A ground floor's U-value (W/m²K) from its HEM element fields, by BS EN ISO 13370 as BR 443
|
|
174
|
+
* directs: the converter's own floor calculation (`vulcan_model_transform::ground_floor_u_value`),
|
|
175
|
+
* for the editor's derived-value placeholder and the thermal-bridge flanking U. `undefined` when an
|
|
176
|
+
* input it needs is missing; an error when `element_json` is not a JSON object. `whole_basement`:
|
|
177
|
+
* the target takes a heated basement's U-value as the floor and its walls below ground (HEM:EPC).
|
|
178
|
+
* @param {string} element_json
|
|
179
|
+
* @param {number | null | undefined} wind_speed_mps
|
|
180
|
+
* @param {boolean} whole_basement
|
|
181
|
+
* @returns {number | undefined}
|
|
182
|
+
*/
|
|
183
|
+
export function ground_floor_u_value(element_json, wind_speed_mps, whole_basement) {
|
|
184
|
+
const ptr0 = passStringToWasm0(element_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
185
|
+
const len0 = WASM_VECTOR_LEN;
|
|
186
|
+
const ret = wasm.ground_floor_u_value(ptr0, len0, !isLikeNone(wind_speed_mps), isLikeNone(wind_speed_mps) ? 0 : wind_speed_mps, whole_basement);
|
|
187
|
+
if (ret[3]) {
|
|
188
|
+
throw takeFromExternrefTable0(ret[2]);
|
|
189
|
+
}
|
|
190
|
+
return ret[0] === 0 ? undefined : ret[1];
|
|
191
|
+
}
|
|
192
|
+
|
|
172
193
|
/**
|
|
173
194
|
* Sum `hem_pv_micro` timestep PV AC output (kWh) over aligned irradiance/shading series (same contract as `annual_pv_kwh_sum`).
|
|
174
195
|
* Returns `[energy_produced_kwh, energy_lost_kwh]` for the full series.
|
|
@@ -1389,22 +1410,22 @@ async function __wbg_init(module_or_path, memory) {
|
|
|
1389
1410
|
export { initSync, __wbg_init as default };
|
|
1390
1411
|
|
|
1391
1412
|
// Build hash injected at build time
|
|
1392
|
-
export const BUILD_HASH = "
|
|
1393
|
-
export const BUILD_ID = "20261117-
|
|
1394
|
-
export const SOURCE_GIT_COMMIT = "
|
|
1395
|
-
export const SOURCE_TREE_SHA256 = "
|
|
1413
|
+
export const BUILD_HASH = "5beb38bb31fe43b169a1e1e97dd13928e051d3b60551667bff058835ce9de2ed";
|
|
1414
|
+
export const BUILD_ID = "20261117-131029";
|
|
1415
|
+
export const SOURCE_GIT_COMMIT = "fba186af3f8da4f44486b61c5ab6c9e4fe049c18";
|
|
1416
|
+
export const SOURCE_TREE_SHA256 = "f8879c2f02a1a8e783f9aad3174bdf61268a68fcfbe45b25914dc0fd0512b900";
|
|
1396
1417
|
export const SOURCE_TREE_DIRTY = false;
|
|
1397
1418
|
export const WASM_FILENAME = "wasm_wrapper_bg.wasm";
|
|
1398
1419
|
export const JS_FILENAME = "wasm_wrapper.js";
|
|
1399
1420
|
|
|
1400
1421
|
// Function to get the current build hash
|
|
1401
1422
|
export function getBuildHash() {
|
|
1402
|
-
return "
|
|
1423
|
+
return "5beb38bb31fe43b169a1e1e97dd13928e051d3b60551667bff058835ce9de2ed";
|
|
1403
1424
|
}
|
|
1404
1425
|
|
|
1405
1426
|
// Function to get the current build ID
|
|
1406
1427
|
export function getBuildId() {
|
|
1407
|
-
return "20261117-
|
|
1428
|
+
return "20261117-131029";
|
|
1408
1429
|
}
|
|
1409
1430
|
|
|
1410
1431
|
// Function to get the WASM filename
|
|
Binary file
|