@vulcan-energy/mcp-helper 0.2.2 → 0.2.4
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/THIRD_PARTY_NOTICES.md +185 -0
- package/dist/bin/vulcan-mcp-helper.js +30 -23
- package/dist/hem-target-runtime/browser-adapter.mjs +26 -12
- package/dist/hem-target-runtime/host.mjs +11034 -1145
- package/dist/hem-target-runtime/python-worker.mjs +183 -7
- package/dist/hem-target-runtime/release-manifests.mjs +3 -3
- package/dist/hem-target-runtime/rust-worker.mjs +199 -8
- package/dist/server.js +29 -22
- package/package.json +1 -1
- package/wasm/wasm_version.json +10 -10
- package/wasm/wasm_wrapper.js +41 -7
- package/wasm/wasm_wrapper_bg.wasm +0 -0
|
@@ -455,6 +455,116 @@ function pythonFhsArguments(inputPath, modes, weatherPath) {
|
|
|
455
455
|
return ["--mode", cliModes[mode]];
|
|
456
456
|
})];
|
|
457
457
|
}
|
|
458
|
+
var MAX_DETAIL_LINE = 200;
|
|
459
|
+
function pythonFailureMessage(text) {
|
|
460
|
+
const lastFrame = text.lastIndexOf('\n File "');
|
|
461
|
+
if (lastFrame < 0 || !text.includes("Traceback (most recent call last)")) return text;
|
|
462
|
+
const lines = text.slice(lastFrame + 1).split("\n").slice(1);
|
|
463
|
+
const header = lines.findIndex((line) => line.trim() && !/^\s/.test(line));
|
|
464
|
+
if (header < 0) return text;
|
|
465
|
+
const exception = lines.slice(header).map((line) => line.trim().replace(/, input_value=.*$/, "]")).filter((line) => line && !line.startsWith("For further information visit")).map((line) => line.length > MAX_DETAIL_LINE ? `${line.slice(0, MAX_DETAIL_LINE - 1)}\u2026` : line);
|
|
466
|
+
return `HEM could not calculate this model. ${exception.join(" ")}`;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ../hem-target-runtime/src/hem/heatingProfile.ts
|
|
470
|
+
function parseHeatingProfile(value) {
|
|
471
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Heating profile must be an object");
|
|
472
|
+
const profile = value;
|
|
473
|
+
const keys = profile.type === "reference" ? ["type"] : ["type", "weekday", "weekend", "setback"];
|
|
474
|
+
if (Object.keys(profile).some((key) => !keys.includes(key))) throw new Error("Unknown heating profile field");
|
|
475
|
+
if (profile.type === "reference") return { type: "reference" };
|
|
476
|
+
if (profile.type !== "weekly") throw new Error("Heating profile type must be reference or weekly");
|
|
477
|
+
if (typeof profile.setback !== "number" || !Number.isFinite(profile.setback) || profile.setback < 0 || profile.setback > 30) throw new Error("Heating setback must be between 0 and 30 C");
|
|
478
|
+
for (const day of ["weekday", "weekend"]) {
|
|
479
|
+
const periods = profile[day];
|
|
480
|
+
if (!Array.isArray(periods) || !periods.length) throw new Error(`Heating ${day} needs at least one period`);
|
|
481
|
+
let end = 0;
|
|
482
|
+
for (const period of periods) {
|
|
483
|
+
if (!Array.isArray(period) || period.length !== 2 || period.some((time) => typeof time !== "number" || !Number.isFinite(time)) || period[0] < 0 || period[1] > 24 || period[0] >= period[1]) throw new Error("Heating periods must be [start, end] within 0\u201324 hours");
|
|
484
|
+
if (period[0] < end) throw new Error("Heating periods must be ordered without overlap");
|
|
485
|
+
end = period[1];
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return structuredClone(profile);
|
|
489
|
+
}
|
|
490
|
+
function applyHeatingProfile(input, supplied) {
|
|
491
|
+
const profile = parseHeatingProfile(supplied);
|
|
492
|
+
if (profile.type === "reference") return input;
|
|
493
|
+
const model = JSON.parse(input);
|
|
494
|
+
const names = /* @__PURE__ */ new Set();
|
|
495
|
+
for (const system of Object.values(model.SpaceHeatSystem ?? {})) {
|
|
496
|
+
if (typeof system.Control !== "string") throw new Error("Space heating system has no generated setpoint control");
|
|
497
|
+
names.add(system.Control);
|
|
498
|
+
}
|
|
499
|
+
if (!names.size) throw new Error("No space heating controls to adjust");
|
|
500
|
+
for (const name of names) {
|
|
501
|
+
const control = model.Control?.[name];
|
|
502
|
+
if (control?.type !== "SetpointTimeControl" || control.start_day !== 0) throw new Error(`Unsupported generated heating control ${name}`);
|
|
503
|
+
const step = control.time_series_step;
|
|
504
|
+
if (!(step > 0) || !Number.isInteger(24 / step)) throw new Error("Heating control timestep must divide a day");
|
|
505
|
+
const targets = /* @__PURE__ */ new Set();
|
|
506
|
+
const visit = (entries, active = /* @__PURE__ */ new Set()) => {
|
|
507
|
+
if (!Array.isArray(entries)) throw new Error("Unsupported generated heating schedule");
|
|
508
|
+
for (const entry of entries) {
|
|
509
|
+
const value = entry && typeof entry === "object" ? entry.value : entry;
|
|
510
|
+
if (typeof value === "number" && Number.isFinite(value)) targets.add(value);
|
|
511
|
+
else if (typeof value === "string") {
|
|
512
|
+
if (active.has(value)) throw new Error("Cyclic heating schedule");
|
|
513
|
+
visit(control.schedule[value], /* @__PURE__ */ new Set([...active, value]));
|
|
514
|
+
} else if (value !== null) throw new Error("Unsupported generated heating schedule value");
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
visit(control.schedule?.main);
|
|
518
|
+
if (targets.size !== 1) throw new Error(`Heating control ${name} must have a single generated occupied target`);
|
|
519
|
+
const target = [...targets][0];
|
|
520
|
+
if (profile.setback > target) throw new Error("Heating setback exceeds the generated occupied target");
|
|
521
|
+
const day = (periods) => {
|
|
522
|
+
if (periods.flat().some((hour) => !Number.isInteger(hour / step))) throw new Error("Heating periods must align with the generated control timestep");
|
|
523
|
+
return Array.from({ length: 24 / step }, (_, index) => periods.some(([start, end]) => index * step >= start && index * step < end) ? target : null);
|
|
524
|
+
};
|
|
525
|
+
control.schedule = {
|
|
526
|
+
main: [{ value: "week", repeat: Math.ceil(model.SimulationTime.end / 168) + 1 }],
|
|
527
|
+
week: [{ value: "weekday", repeat: 5 }, { value: "weekend", repeat: 2 }],
|
|
528
|
+
weekday: day(profile.weekday),
|
|
529
|
+
weekend: day(profile.weekend)
|
|
530
|
+
};
|
|
531
|
+
control.advanced_start = 0;
|
|
532
|
+
control.setpoint_min = profile.setback;
|
|
533
|
+
}
|
|
534
|
+
return JSON.stringify(model);
|
|
535
|
+
}
|
|
536
|
+
async function runHeatingProfile(input, profile, run2) {
|
|
537
|
+
const exported = await run2(input, "preprocess");
|
|
538
|
+
const names = Object.keys(exported).filter((name) => name.endsWith("__preproc.json"));
|
|
539
|
+
if (names.length !== 1) throw new Error("Heating sensitivity requires exactly one actual FHS export");
|
|
540
|
+
const original = exported[names[0]];
|
|
541
|
+
const adjusted = applyHeatingProfile(original, profile);
|
|
542
|
+
const results = await run2(adjusted, "core");
|
|
543
|
+
if (!Object.keys(results).some((name) => name.endsWith("__results.csv"))) throw new Error("Core replay produced no timestep results");
|
|
544
|
+
if ("fhs_compliance_report.json" in results) throw new Error("Operating sensitivity cannot return an FHS compliance report");
|
|
545
|
+
return { ...results, "fhs-preprocessed.json": original, "heating-input.json": adjusted, "heating-profile.json": JSON.stringify(profile) };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ../hem-target-runtime/src/hem/pythonHeatingProfile.ts
|
|
549
|
+
async function executePythonHeatingProfile(py, folder, input, profile, weatherPath) {
|
|
550
|
+
return runHeatingProfile(input, profile, async (data, stage) => {
|
|
551
|
+
const stem = stage === "preprocess" ? "model" : "heating";
|
|
552
|
+
const path = `${folder}/${stem}.json`;
|
|
553
|
+
py.FS.writeFile(path, data);
|
|
554
|
+
if (stage === "preprocess") {
|
|
555
|
+
const args = [...pythonFhsArguments(path, ["actual"], weatherPath), "--preprocess-only"];
|
|
556
|
+
await py.runPythonAsync(`main(${JSON.stringify(args)}, standalone_mode=False)`);
|
|
557
|
+
} else {
|
|
558
|
+
const args = [path, "--heat-balance", "--detailed-output-heating-cooling", "--fail-fast"];
|
|
559
|
+
await py.runPythonAsync(`from hem_core.hem import main as run_core
|
|
560
|
+
core_status = run_core(${JSON.stringify(args)})
|
|
561
|
+
if core_status != 0:
|
|
562
|
+
raise RuntimeError(f"Core replay failed with status {core_status}")`);
|
|
563
|
+
}
|
|
564
|
+
const output = `${folder}/${stem}__results`;
|
|
565
|
+
return Object.fromEntries(py.FS.readdir(output).filter((name) => name !== "." && name !== "..").map((name) => [name, py.FS.readFile(`${output}/${name}`, { encoding: "utf8" })]));
|
|
566
|
+
});
|
|
567
|
+
}
|
|
458
568
|
|
|
459
569
|
// ../hem-target-runtime/src/hem/pythonFhsCompliance.ts
|
|
460
570
|
var import_papaparse = __toESM(require_papaparse_min(), 1);
|
|
@@ -740,6 +850,58 @@ var TargetAssets = class _TargetAssets {
|
|
|
740
850
|
}
|
|
741
851
|
};
|
|
742
852
|
|
|
853
|
+
// ../hem-target-runtime/src/hem/targetSchemaCorrections.ts
|
|
854
|
+
var PYTHON_TARGETS = /* @__PURE__ */ new Set(["python-fhs-a8-f2ab6cf7-8ca182b0-v1", "python-fhs-a9-918addad-b9b90138-v1"]);
|
|
855
|
+
var RUST_A7 = "rust-fhs-a7-62d3df70-c5ba2673-v1";
|
|
856
|
+
var FIELD = "is_adjacent_space_within_dwelling";
|
|
857
|
+
var WARM_AIR_FIELD = "temp_diff_emit_dsgn";
|
|
858
|
+
var STORAGE_FAN_FIELD = "fan_pwr";
|
|
859
|
+
var hasTargetSchemaCorrection = (targetId) => PYTHON_TARGETS.has(targetId) || targetId === RUST_A7;
|
|
860
|
+
var ruleTypes = (rule) => [rule.if?.properties?.type?.const, ...(rule.if?.anyOf ?? []).map((branch) => branch?.properties?.type?.const)].filter((type) => !!type);
|
|
861
|
+
function thenFor(targetId, rules, ...types) {
|
|
862
|
+
const matches = rules.filter((rule) => {
|
|
863
|
+
const own = ruleTypes(rule);
|
|
864
|
+
return own.length === types.length && types.every((type) => own.includes(type));
|
|
865
|
+
});
|
|
866
|
+
if (matches.length !== 1) throw new Error(`Schema correction for ${targetId} no longer applies: ${matches.length} rules for ${types.join(" or ")}`);
|
|
867
|
+
return matches[0].then;
|
|
868
|
+
}
|
|
869
|
+
function correctTargetSchema(targetId, schemaText) {
|
|
870
|
+
if (!hasTargetSchemaCorrection(targetId)) return schemaText;
|
|
871
|
+
const schema = JSON.parse(schemaText);
|
|
872
|
+
const elementRules = schema.properties.Zone.additionalProperties.properties.BuildingElement.additionalProperties.allOf;
|
|
873
|
+
if (targetId === RUST_A7) {
|
|
874
|
+
const window2 = thenFor(targetId, elementRules, "BuildingElementTransparent");
|
|
875
|
+
const shared = schema.$defs.WindowShading;
|
|
876
|
+
const types = shared.items.properties.type.enum;
|
|
877
|
+
if (window2.properties.shading?.$ref !== "#/$defs/WindowShading" || !types.includes("reveal")) {
|
|
878
|
+
throw new Error(`Schema correction for ${targetId} no longer applies`);
|
|
879
|
+
}
|
|
880
|
+
const shading = structuredClone(shared);
|
|
881
|
+
shading.items.properties.type.enum = types.filter((type) => type !== "reveal");
|
|
882
|
+
window2.properties.shading = shading;
|
|
883
|
+
return JSON.stringify(schema);
|
|
884
|
+
}
|
|
885
|
+
const branch = thenFor(
|
|
886
|
+
targetId,
|
|
887
|
+
elementRules,
|
|
888
|
+
"BuildingElementAdjacentConditionedSpace",
|
|
889
|
+
"BuildingElementAdjacentUnconditionedSpace_Simple"
|
|
890
|
+
);
|
|
891
|
+
const spaceHeatRules = schema.properties.SpaceHeatSystem.additionalProperties.allOf;
|
|
892
|
+
const storage = thenFor(targetId, spaceHeatRules, "ElecStorageHeater");
|
|
893
|
+
const warmAir = thenFor(targetId, spaceHeatRules, "WarmAir");
|
|
894
|
+
if (!branch.required.includes(FIELD) || !warmAir.required.includes(WARM_AIR_FIELD) || storage.properties[STORAGE_FAN_FIELD]) {
|
|
895
|
+
throw new Error(`Schema correction for ${targetId} no longer applies`);
|
|
896
|
+
}
|
|
897
|
+
branch.required = branch.required.filter((key) => key !== FIELD);
|
|
898
|
+
warmAir.required = warmAir.required.filter((key) => key !== WARM_AIR_FIELD);
|
|
899
|
+
warmAir.properties[WARM_AIR_FIELD] = false;
|
|
900
|
+
storage.properties[STORAGE_FAN_FIELD] = { type: "number", minimum: 0 };
|
|
901
|
+
storage.required = [...storage.required, STORAGE_FAN_FIELD];
|
|
902
|
+
return JSON.stringify(schema);
|
|
903
|
+
}
|
|
904
|
+
|
|
743
905
|
// ../hem-target-runtime/src/workers/workerProtocol.ts
|
|
744
906
|
var FS_REQUEST_TYPE = "file_system";
|
|
745
907
|
var FS_RESPONSE_TYPE = "file_system_response";
|
|
@@ -851,10 +1013,14 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
851
1013
|
if (!/^[a-zA-Z0-9_./ -]+$/.test(job.outputDirectory) || job.outputDirectory.split("/").some((segment) => segment === "..") || !job.outputDirectory.startsWith("output/")) throw new Error("Invalid run output path");
|
|
852
1014
|
if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
|
|
853
1015
|
if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
|
|
1016
|
+
if (job.heatingProfile) {
|
|
1017
|
+
parseHeatingProfile(job.heatingProfile);
|
|
1018
|
+
if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
|
|
1019
|
+
}
|
|
854
1020
|
const archive = job.archiveDirectory ?? job.outputDirectory;
|
|
855
1021
|
const inputSha256 = await sha256(new TextEncoder().encode(job.input));
|
|
856
1022
|
if (job.weather && (!job.weather.epw.trim() || await sha256(new TextEncoder().encode(job.weather.epw)) !== job.weather.sha256)) throw new Error("Prepared weather hash mismatch or empty EPW");
|
|
857
|
-
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, target: manifest2, inputSha256, modes: job.modes, jobId, name: job.name };
|
|
1023
|
+
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, inputSha256, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
|
|
858
1024
|
try {
|
|
859
1025
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
|
|
860
1026
|
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
|
|
@@ -862,7 +1028,7 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
862
1028
|
if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
|
|
863
1029
|
if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
|
|
864
1030
|
progress(index, jobs.length);
|
|
865
|
-
const files = await execute(job.input, job.modes, job.weather);
|
|
1031
|
+
const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
|
|
866
1032
|
const names = Object.keys(files);
|
|
867
1033
|
if (!names.length) throw new Error("Calculation produced no result files");
|
|
868
1034
|
for (const [name, content] of Object.entries(files)) {
|
|
@@ -875,9 +1041,11 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
875
1041
|
}
|
|
876
1042
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
|
|
877
1043
|
} catch (error) {
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
1044
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1045
|
+
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message }));
|
|
1046
|
+
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
|
|
1047
|
+
const files = job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : "";
|
|
1048
|
+
throw new Error(`Scenario ${job.name}${files}: ${message}`);
|
|
881
1049
|
}
|
|
882
1050
|
}
|
|
883
1051
|
}
|
|
@@ -947,18 +1115,24 @@ from ${targetWrapper(target).pythonModule} import main`);
|
|
|
947
1115
|
for (const [name, version] of Object.entries(bundle.runtime.requiredVersions)) {
|
|
948
1116
|
if (versions[name.toLowerCase().replace(/_/g, "-")] !== version) throw new Error(`Python runtime identity mismatch for ${name}`);
|
|
949
1117
|
}
|
|
1118
|
+
if (hasTargetSchemaCorrection(bundle.bundleId)) {
|
|
1119
|
+
const schemaPath = py.runPython(`import os, future_homes_standard.schema_validation as v
|
|
1120
|
+
os.path.join(os.path.dirname(v.__file__), 'schema.json')`);
|
|
1121
|
+
py.FS.writeFile(schemaPath, correctTargetSchema(bundle.bundleId, py.FS.readFile(schemaPath, { encoding: "utf8" })));
|
|
1122
|
+
}
|
|
950
1123
|
manifest = bundle;
|
|
951
1124
|
send({ type: "worker_ready", targetBundleId: bundle.bundleId });
|
|
952
1125
|
}
|
|
953
1126
|
async function run(jobId, bundleId, jobs) {
|
|
954
1127
|
if (!runtime || !manifest) throw new Error("Python worker is not initialized");
|
|
955
|
-
await executePreparedJobs(manifest, bundleId, jobId, jobs, async (input, modes, weather) => {
|
|
1128
|
+
await executePreparedJobs(manifest, bundleId, jobId, jobs, async (input, modes, weather, heatingProfile) => {
|
|
956
1129
|
const py = runtime;
|
|
957
1130
|
const folder = `/runs/${crypto.randomUUID()}`;
|
|
958
1131
|
py.FS.mkdirTree(folder);
|
|
959
1132
|
py.FS.writeFile(`${folder}/model.json`, input);
|
|
960
1133
|
try {
|
|
961
1134
|
if (weather) py.FS.writeFile(`${folder}/weather.epw`, weather.epw);
|
|
1135
|
+
if (heatingProfile) return await executePythonHeatingProfile(py, folder, input, heatingProfile, weather ? `${folder}/weather.epw` : void 0);
|
|
962
1136
|
const args = pythonFhsArguments(`${folder}/model.json`, modes, weather ? `${folder}/weather.epw` : void 0);
|
|
963
1137
|
await py.runPythonAsync(`main(${JSON.stringify(args)}, standalone_mode=False)`);
|
|
964
1138
|
const output = `${folder}/model__results`;
|
|
@@ -988,7 +1162,9 @@ self.onmessage = async ({ data }) => {
|
|
|
988
1162
|
else if (data.type === "run_prepared_batch") await run(data.jobId, data.targetBundleId, data.jobs);
|
|
989
1163
|
else throw new Error(`Unsupported Python worker message ${data.type}`);
|
|
990
1164
|
} catch (error) {
|
|
991
|
-
|
|
1165
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
1166
|
+
console.error(text);
|
|
1167
|
+
send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: pythonFailureMessage(text) });
|
|
992
1168
|
} finally {
|
|
993
1169
|
busy = false;
|
|
994
1170
|
}
|
|
@@ -41,9 +41,9 @@ var RECOMMENDED_HEM_TARGET = HEM_TARGETS[0].id;
|
|
|
41
41
|
|
|
42
42
|
// ../hem-target-runtime/src/hem/targetAssets.ts
|
|
43
43
|
var RELEASE_MANIFEST_HASHES = {
|
|
44
|
-
"rust-fhs-a7-62d3df70-c5ba2673-v1": "
|
|
45
|
-
"python-fhs-a8-f2ab6cf7-8ca182b0-v1": "
|
|
46
|
-
"python-fhs-a9-918addad-b9b90138-v1": "
|
|
44
|
+
"rust-fhs-a7-62d3df70-c5ba2673-v1": "e1c0bc53d7bdfcf3bddff8eab8f8623d7620caeca447da51178c219ac15c4917",
|
|
45
|
+
"python-fhs-a8-f2ab6cf7-8ca182b0-v1": "7fee2a81a84036198e467d61f41c6c8fe8f25fadba209689d3794c44fbe635a9",
|
|
46
|
+
"python-fhs-a9-918addad-b9b90138-v1": "b7a52e5b1f2f9477f4c20e9ddc6b572a55eaae21dc6242b4aee0fefafbb11011"
|
|
47
47
|
};
|
|
48
48
|
export {
|
|
49
49
|
RELEASE_MANIFEST_HASHES
|
|
@@ -2,6 +2,179 @@ var __defProp = Object.defineProperty;
|
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
3
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
4
|
|
|
5
|
+
// ../hem-target-runtime/src/hem/isolatedRustWorker.ts
|
|
6
|
+
function installIsolatedRustWorker(scope) {
|
|
7
|
+
let child;
|
|
8
|
+
let manifest2;
|
|
9
|
+
let batch;
|
|
10
|
+
let completed = 0;
|
|
11
|
+
let initialized = false;
|
|
12
|
+
let starting = false;
|
|
13
|
+
let startup;
|
|
14
|
+
const fail = (error, jobId = batch?.jobId) => {
|
|
15
|
+
clearTimeout(startup);
|
|
16
|
+
child?.terminate();
|
|
17
|
+
child = void 0;
|
|
18
|
+
starting = false;
|
|
19
|
+
scope.postMessage({ type: initialized ? "error" : "init_error", jobId, error });
|
|
20
|
+
batch = void 0;
|
|
21
|
+
};
|
|
22
|
+
const runJob = () => child.postMessage({ type: "run_prepared_batch", targetBundleId: batch.targetBundleId, jobId: batch.jobId, jobs: [batch.jobs[completed]] });
|
|
23
|
+
const start = () => {
|
|
24
|
+
starting = true;
|
|
25
|
+
const worker = new Worker(scope.location.href, { type: "module", name: "vulcan-rust-execution" });
|
|
26
|
+
child = worker;
|
|
27
|
+
startup = setTimeout(() => {
|
|
28
|
+
if (child === worker) fail("Rust execution worker startup exceeded 120 seconds");
|
|
29
|
+
}, 12e4);
|
|
30
|
+
worker.onerror = (event) => {
|
|
31
|
+
if (child === worker) fail(event.message || "Rust execution worker failed");
|
|
32
|
+
};
|
|
33
|
+
worker.onmessageerror = () => {
|
|
34
|
+
if (child === worker) fail("Rust execution worker returned an unreadable message");
|
|
35
|
+
};
|
|
36
|
+
worker.onmessage = ({ data }) => {
|
|
37
|
+
if (child !== worker) return;
|
|
38
|
+
if (data.type === "worker_ready") {
|
|
39
|
+
if (data.targetBundleId !== manifest2.bundleId) {
|
|
40
|
+
fail("Worker target identity mismatch");
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
clearTimeout(startup);
|
|
44
|
+
starting = false;
|
|
45
|
+
if (!initialized) {
|
|
46
|
+
initialized = true;
|
|
47
|
+
scope.postMessage(data);
|
|
48
|
+
} else if (batch) runJob();
|
|
49
|
+
} else if (data.type === "complete") {
|
|
50
|
+
if (!batch || data.targetBundleId !== manifest2.bundleId || data.jobId !== batch.jobId) {
|
|
51
|
+
fail("Completed worker identity mismatch");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
clearTimeout(startup);
|
|
55
|
+
worker.terminate();
|
|
56
|
+
child = void 0;
|
|
57
|
+
completed++;
|
|
58
|
+
scope.postMessage({ type: "progress", jobId: batch.jobId, progress: { completed, total: batch.jobs.length } });
|
|
59
|
+
if (completed < batch.jobs.length) start();
|
|
60
|
+
else {
|
|
61
|
+
scope.postMessage(data);
|
|
62
|
+
batch = void 0;
|
|
63
|
+
}
|
|
64
|
+
} else if (data.type === "progress") {
|
|
65
|
+
if (batch) scope.postMessage({ ...data, progress: { completed, total: batch.jobs.length } });
|
|
66
|
+
} else if (data.type === "error" || data.type === "init_error") fail(data.error || "Rust execution worker reported an error");
|
|
67
|
+
else scope.postMessage(data);
|
|
68
|
+
};
|
|
69
|
+
worker.postMessage({ type: "initialize", manifest: manifest2 });
|
|
70
|
+
};
|
|
71
|
+
scope.onmessage = ({ data }) => {
|
|
72
|
+
if (data.type === "file_system_response") {
|
|
73
|
+
child?.postMessage(data);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (batch || starting) {
|
|
77
|
+
scope.postMessage({ type: "error", jobId: data.jobId, error: "A calculation or initialization is already active" });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (data.type === "initialize") {
|
|
81
|
+
clearTimeout(startup);
|
|
82
|
+
child?.terminate();
|
|
83
|
+
manifest2 = data.manifest;
|
|
84
|
+
initialized = false;
|
|
85
|
+
start();
|
|
86
|
+
} else if (data.type === "run_prepared_batch") {
|
|
87
|
+
if (!manifest2 || !initialized || data.targetBundleId !== manifest2.bundleId || !data.jobs?.length) {
|
|
88
|
+
fail("Rust target identity or prepared jobs are invalid", data.jobId);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
batch = data;
|
|
92
|
+
completed = 0;
|
|
93
|
+
if (child) runJob();
|
|
94
|
+
else start();
|
|
95
|
+
} else fail("Unknown Rust target message");
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ../hem-target-runtime/src/hem/heatingProfile.ts
|
|
100
|
+
function parseHeatingProfile(value) {
|
|
101
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Heating profile must be an object");
|
|
102
|
+
const profile = value;
|
|
103
|
+
const keys = profile.type === "reference" ? ["type"] : ["type", "weekday", "weekend", "setback"];
|
|
104
|
+
if (Object.keys(profile).some((key) => !keys.includes(key))) throw new Error("Unknown heating profile field");
|
|
105
|
+
if (profile.type === "reference") return { type: "reference" };
|
|
106
|
+
if (profile.type !== "weekly") throw new Error("Heating profile type must be reference or weekly");
|
|
107
|
+
if (typeof profile.setback !== "number" || !Number.isFinite(profile.setback) || profile.setback < 0 || profile.setback > 30) throw new Error("Heating setback must be between 0 and 30 C");
|
|
108
|
+
for (const day of ["weekday", "weekend"]) {
|
|
109
|
+
const periods = profile[day];
|
|
110
|
+
if (!Array.isArray(periods) || !periods.length) throw new Error(`Heating ${day} needs at least one period`);
|
|
111
|
+
let end = 0;
|
|
112
|
+
for (const period of periods) {
|
|
113
|
+
if (!Array.isArray(period) || period.length !== 2 || period.some((time) => typeof time !== "number" || !Number.isFinite(time)) || period[0] < 0 || period[1] > 24 || period[0] >= period[1]) throw new Error("Heating periods must be [start, end] within 0\u201324 hours");
|
|
114
|
+
if (period[0] < end) throw new Error("Heating periods must be ordered without overlap");
|
|
115
|
+
end = period[1];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return structuredClone(profile);
|
|
119
|
+
}
|
|
120
|
+
function applyHeatingProfile(input, supplied) {
|
|
121
|
+
const profile = parseHeatingProfile(supplied);
|
|
122
|
+
if (profile.type === "reference") return input;
|
|
123
|
+
const model = JSON.parse(input);
|
|
124
|
+
const names = /* @__PURE__ */ new Set();
|
|
125
|
+
for (const system of Object.values(model.SpaceHeatSystem ?? {})) {
|
|
126
|
+
if (typeof system.Control !== "string") throw new Error("Space heating system has no generated setpoint control");
|
|
127
|
+
names.add(system.Control);
|
|
128
|
+
}
|
|
129
|
+
if (!names.size) throw new Error("No space heating controls to adjust");
|
|
130
|
+
for (const name of names) {
|
|
131
|
+
const control = model.Control?.[name];
|
|
132
|
+
if (control?.type !== "SetpointTimeControl" || control.start_day !== 0) throw new Error(`Unsupported generated heating control ${name}`);
|
|
133
|
+
const step = control.time_series_step;
|
|
134
|
+
if (!(step > 0) || !Number.isInteger(24 / step)) throw new Error("Heating control timestep must divide a day");
|
|
135
|
+
const targets = /* @__PURE__ */ new Set();
|
|
136
|
+
const visit = (entries, active = /* @__PURE__ */ new Set()) => {
|
|
137
|
+
if (!Array.isArray(entries)) throw new Error("Unsupported generated heating schedule");
|
|
138
|
+
for (const entry of entries) {
|
|
139
|
+
const value = entry && typeof entry === "object" ? entry.value : entry;
|
|
140
|
+
if (typeof value === "number" && Number.isFinite(value)) targets.add(value);
|
|
141
|
+
else if (typeof value === "string") {
|
|
142
|
+
if (active.has(value)) throw new Error("Cyclic heating schedule");
|
|
143
|
+
visit(control.schedule[value], /* @__PURE__ */ new Set([...active, value]));
|
|
144
|
+
} else if (value !== null) throw new Error("Unsupported generated heating schedule value");
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
visit(control.schedule?.main);
|
|
148
|
+
if (targets.size !== 1) throw new Error(`Heating control ${name} must have a single generated occupied target`);
|
|
149
|
+
const target = [...targets][0];
|
|
150
|
+
if (profile.setback > target) throw new Error("Heating setback exceeds the generated occupied target");
|
|
151
|
+
const day = (periods) => {
|
|
152
|
+
if (periods.flat().some((hour) => !Number.isInteger(hour / step))) throw new Error("Heating periods must align with the generated control timestep");
|
|
153
|
+
return Array.from({ length: 24 / step }, (_, index) => periods.some(([start, end]) => index * step >= start && index * step < end) ? target : null);
|
|
154
|
+
};
|
|
155
|
+
control.schedule = {
|
|
156
|
+
main: [{ value: "week", repeat: Math.ceil(model.SimulationTime.end / 168) + 1 }],
|
|
157
|
+
week: [{ value: "weekday", repeat: 5 }, { value: "weekend", repeat: 2 }],
|
|
158
|
+
weekday: day(profile.weekday),
|
|
159
|
+
weekend: day(profile.weekend)
|
|
160
|
+
};
|
|
161
|
+
control.advanced_start = 0;
|
|
162
|
+
control.setpoint_min = profile.setback;
|
|
163
|
+
}
|
|
164
|
+
return JSON.stringify(model);
|
|
165
|
+
}
|
|
166
|
+
async function runHeatingProfile(input, profile, run) {
|
|
167
|
+
const exported = await run(input, "preprocess");
|
|
168
|
+
const names = Object.keys(exported).filter((name) => name.endsWith("__preproc.json"));
|
|
169
|
+
if (names.length !== 1) throw new Error("Heating sensitivity requires exactly one actual FHS export");
|
|
170
|
+
const original = exported[names[0]];
|
|
171
|
+
const adjusted = applyHeatingProfile(original, profile);
|
|
172
|
+
const results = await run(adjusted, "core");
|
|
173
|
+
if (!Object.keys(results).some((name) => name.endsWith("__results.csv"))) throw new Error("Core replay produced no timestep results");
|
|
174
|
+
if ("fhs_compliance_report.json" in results) throw new Error("Operating sensitivity cannot return an FHS compliance report");
|
|
175
|
+
return { ...results, "fhs-preprocessed.json": original, "heating-input.json": adjusted, "heating-profile.json": JSON.stringify(profile) };
|
|
176
|
+
}
|
|
177
|
+
|
|
5
178
|
// ../hem-target-runtime/src/hem/targets.ts
|
|
6
179
|
var WRAPPERS = {
|
|
7
180
|
fhs: {
|
|
@@ -256,10 +429,14 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
256
429
|
if (!/^[a-zA-Z0-9_./ -]+$/.test(job.outputDirectory) || job.outputDirectory.split("/").some((segment) => segment === "..") || !job.outputDirectory.startsWith("output/")) throw new Error("Invalid run output path");
|
|
257
430
|
if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
|
|
258
431
|
if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
|
|
432
|
+
if (job.heatingProfile) {
|
|
433
|
+
parseHeatingProfile(job.heatingProfile);
|
|
434
|
+
if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
|
|
435
|
+
}
|
|
259
436
|
const archive = job.archiveDirectory ?? job.outputDirectory;
|
|
260
437
|
const inputSha256 = await sha256(new TextEncoder().encode(job.input));
|
|
261
438
|
if (job.weather && (!job.weather.epw.trim() || await sha256(new TextEncoder().encode(job.weather.epw)) !== job.weather.sha256)) throw new Error("Prepared weather hash mismatch or empty EPW");
|
|
262
|
-
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, target: manifest2, inputSha256, modes: job.modes, jobId, name: job.name };
|
|
439
|
+
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, inputSha256, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
|
|
263
440
|
try {
|
|
264
441
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
|
|
265
442
|
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
|
|
@@ -267,7 +444,7 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
267
444
|
if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
|
|
268
445
|
if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
|
|
269
446
|
progress(index, jobs.length);
|
|
270
|
-
const files = await execute(job.input, job.modes, job.weather);
|
|
447
|
+
const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
|
|
271
448
|
const names = Object.keys(files);
|
|
272
449
|
if (!names.length) throw new Error("Calculation produced no result files");
|
|
273
450
|
for (const [name, content] of Object.entries(files)) {
|
|
@@ -280,9 +457,11 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
280
457
|
}
|
|
281
458
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
|
|
282
459
|
} catch (error) {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
460
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
461
|
+
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message }));
|
|
462
|
+
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
|
|
463
|
+
const files = job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : "";
|
|
464
|
+
throw new Error(`Scenario ${job.name}${files}: ${message}`);
|
|
286
465
|
}
|
|
287
466
|
}
|
|
288
467
|
}
|
|
@@ -392,6 +571,7 @@ var BatchWorkerFileSystemAcknowledgements = class {
|
|
|
392
571
|
var manifest;
|
|
393
572
|
var runInput;
|
|
394
573
|
var supportsWeather = false;
|
|
574
|
+
var runStage;
|
|
395
575
|
var busy = false;
|
|
396
576
|
var acknowledgements = new BatchWorkerFileSystemAcknowledgements();
|
|
397
577
|
var send = (message) => self.postMessage(message);
|
|
@@ -424,13 +604,15 @@ async function initialize(bundle) {
|
|
|
424
604
|
supportsWeather = module.target_weather_protocol_version?.() === 1;
|
|
425
605
|
if (typeof module.run_target_input !== "function") throw new Error("Pinned runtime does not support prepared target jobs");
|
|
426
606
|
runInput = module.run_target_input;
|
|
607
|
+
runStage = module.target_heating_profile_protocol_version?.() === 1 && typeof module.run_target_stage === "function" ? module.run_target_stage : void 0;
|
|
427
608
|
} finally {
|
|
428
609
|
URL.revokeObjectURL(url);
|
|
429
610
|
}
|
|
430
611
|
manifest = bundle;
|
|
431
612
|
send({ type: "worker_ready", targetBundleId: bundle.bundleId });
|
|
432
613
|
}
|
|
433
|
-
self.
|
|
614
|
+
if (self.name !== "vulcan-rust-execution") installIsolatedRustWorker(self);
|
|
615
|
+
else self.onmessage = async ({ data }) => {
|
|
434
616
|
if (data.type === FS_RESPONSE_TYPE) {
|
|
435
617
|
acknowledgements.acknowledge(data.messageId, data.error ?? null);
|
|
436
618
|
return;
|
|
@@ -444,7 +626,16 @@ self.onmessage = async ({ data }) => {
|
|
|
444
626
|
if (data.type === "initialize") await initialize(data.manifest);
|
|
445
627
|
else if (data.type === "run_prepared_batch") {
|
|
446
628
|
if (!manifest || !runInput) throw new Error("Rust target is not initialized");
|
|
447
|
-
await executePreparedJobs(manifest, data.targetBundleId, data.jobId, data.jobs, async (input, modes, weather) => {
|
|
629
|
+
await executePreparedJobs(manifest, data.targetBundleId, data.jobId, data.jobs, async (input, modes, weather, heatingProfile) => {
|
|
630
|
+
if (heatingProfile) {
|
|
631
|
+
if (!runStage) throw new Error("Pinned Rust bundle lacks heating profile protocol 1; rebuild and qualify its adapter");
|
|
632
|
+
const stage = async (data2, step) => {
|
|
633
|
+
const result2 = JSON.parse(runStage(data2, step, step === "preprocess" ? weather?.epw : void 0));
|
|
634
|
+
if (result2.status !== "calculated") throw new Error(result2.error ?? "Heating profile stage failed");
|
|
635
|
+
return result2.files;
|
|
636
|
+
};
|
|
637
|
+
return runHeatingProfile(input, heatingProfile, stage);
|
|
638
|
+
}
|
|
448
639
|
if (weather && !supportsWeather) throw new Error("Pinned Rust runtime does not implement custom EPW protocol 1; rebuild and qualify its bundle");
|
|
449
640
|
const result = JSON.parse(weather ? runInput(input, "model", JSON.stringify(modes), weather.epw) : runInput(input, "model", JSON.stringify(modes)));
|
|
450
641
|
if (result.status !== "calculated") throw new Error(result.error ?? "Rust calculation failed");
|
|
@@ -453,7 +644,7 @@ self.onmessage = async ({ data }) => {
|
|
|
453
644
|
send({ type: "complete", jobId: data.jobId, targetBundleId: manifest.bundleId, result: { status: "success", targetBundleId: manifest.bundleId } });
|
|
454
645
|
} else throw new Error("Unknown Rust target message");
|
|
455
646
|
} catch (error) {
|
|
456
|
-
send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: String(error) });
|
|
647
|
+
send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: error instanceof Error ? error.message : String(error) });
|
|
457
648
|
} finally {
|
|
458
649
|
busy = false;
|
|
459
650
|
}
|