@vulcan-energy/mcp-helper 0.2.3 → 0.2.5

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.
@@ -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);
@@ -563,7 +673,9 @@ function resolveHemTarget(id) {
563
673
  return target;
564
674
  }
565
675
  function modelArtifacts(manifest2) {
566
- return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/"));
676
+ const runtime2 = [manifest2.runtime.javascript, manifest2.runtime.wasm];
677
+ const converter = [manifest2.preparation.javascript, manifest2.preparation.wasm].filter((path) => !runtime2.includes(path));
678
+ return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/") && !converter.includes(artifact.path));
567
679
  }
568
680
  function validateTargetManifest(manifest2, target) {
569
681
  if (manifest2.bundleId !== target.id || manifest2.protocol !== 1 || manifest2.engineCommit !== target.engineCommit || manifest2.wrapperCommit !== target.wrapperCommit || manifest2.conversionProfile !== target.conversionProfile) {
@@ -581,7 +693,7 @@ function validateTargetManifest(manifest2, target) {
581
693
  sizesByHash.set(artifact.sha256, artifact.bytes);
582
694
  paths.add(artifact.path);
583
695
  }
584
- for (const path of [...Object.values(manifest2.preparation), manifest2.runtime.javascript, ...manifest2.runtime.wasm ? [manifest2.runtime.wasm] : [], ...manifest2.runtime.wheels ?? []]) {
696
+ for (const path of [manifest2.preparation.schema, manifest2.preparation.defaults, manifest2.runtime.javascript, ...manifest2.runtime.wasm ? [manifest2.runtime.wasm] : [], ...manifest2.runtime.wheels ?? []]) {
585
697
  if (path.startsWith("source/") || path.startsWith("notices/")) throw new Error(`Runtime/preparation cannot reference reserved source/notice material: ${path}`);
586
698
  if (!paths.has(path)) throw new Error(`Target manifest is missing required artifact ${path}`);
587
699
  }
@@ -740,6 +852,58 @@ var TargetAssets = class _TargetAssets {
740
852
  }
741
853
  };
742
854
 
855
+ // ../hem-target-runtime/src/hem/targetSchemaCorrections.ts
856
+ var PYTHON_TARGETS = /* @__PURE__ */ new Set(["python-fhs-a8-f2ab6cf7-8ca182b0-v1", "python-fhs-a9-918addad-b9b90138-v1"]);
857
+ var RUST_A7 = "rust-fhs-a7-62d3df70-c5ba2673-v1";
858
+ var FIELD = "is_adjacent_space_within_dwelling";
859
+ var WARM_AIR_FIELD = "temp_diff_emit_dsgn";
860
+ var STORAGE_FAN_FIELD = "fan_pwr";
861
+ var hasTargetSchemaCorrection = (targetId) => PYTHON_TARGETS.has(targetId) || targetId === RUST_A7;
862
+ var ruleTypes = (rule) => [rule.if?.properties?.type?.const, ...(rule.if?.anyOf ?? []).map((branch) => branch?.properties?.type?.const)].filter((type) => !!type);
863
+ function thenFor(targetId, rules, ...types) {
864
+ const matches = rules.filter((rule) => {
865
+ const own = ruleTypes(rule);
866
+ return own.length === types.length && types.every((type) => own.includes(type));
867
+ });
868
+ if (matches.length !== 1) throw new Error(`Schema correction for ${targetId} no longer applies: ${matches.length} rules for ${types.join(" or ")}`);
869
+ return matches[0].then;
870
+ }
871
+ function correctTargetSchema(targetId, schemaText) {
872
+ if (!hasTargetSchemaCorrection(targetId)) return schemaText;
873
+ const schema = JSON.parse(schemaText);
874
+ const elementRules = schema.properties.Zone.additionalProperties.properties.BuildingElement.additionalProperties.allOf;
875
+ if (targetId === RUST_A7) {
876
+ const window2 = thenFor(targetId, elementRules, "BuildingElementTransparent");
877
+ const shared = schema.$defs.WindowShading;
878
+ const types = shared.items.properties.type.enum;
879
+ if (window2.properties.shading?.$ref !== "#/$defs/WindowShading" || !types.includes("reveal")) {
880
+ throw new Error(`Schema correction for ${targetId} no longer applies`);
881
+ }
882
+ const shading = structuredClone(shared);
883
+ shading.items.properties.type.enum = types.filter((type) => type !== "reveal");
884
+ window2.properties.shading = shading;
885
+ return JSON.stringify(schema);
886
+ }
887
+ const branch = thenFor(
888
+ targetId,
889
+ elementRules,
890
+ "BuildingElementAdjacentConditionedSpace",
891
+ "BuildingElementAdjacentUnconditionedSpace_Simple"
892
+ );
893
+ const spaceHeatRules = schema.properties.SpaceHeatSystem.additionalProperties.allOf;
894
+ const storage = thenFor(targetId, spaceHeatRules, "ElecStorageHeater");
895
+ const warmAir = thenFor(targetId, spaceHeatRules, "WarmAir");
896
+ if (!branch.required.includes(FIELD) || !warmAir.required.includes(WARM_AIR_FIELD) || storage.properties[STORAGE_FAN_FIELD]) {
897
+ throw new Error(`Schema correction for ${targetId} no longer applies`);
898
+ }
899
+ branch.required = branch.required.filter((key) => key !== FIELD);
900
+ warmAir.required = warmAir.required.filter((key) => key !== WARM_AIR_FIELD);
901
+ warmAir.properties[WARM_AIR_FIELD] = false;
902
+ storage.properties[STORAGE_FAN_FIELD] = { type: "number", minimum: 0 };
903
+ storage.required = [...storage.required, STORAGE_FAN_FIELD];
904
+ return JSON.stringify(schema);
905
+ }
906
+
743
907
  // ../hem-target-runtime/src/workers/workerProtocol.ts
744
908
  var FS_REQUEST_TYPE = "file_system";
745
909
  var FS_RESPONSE_TYPE = "file_system_response";
@@ -851,10 +1015,14 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
851
1015
  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
1016
  if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
853
1017
  if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
1018
+ if (job.heatingProfile) {
1019
+ parseHeatingProfile(job.heatingProfile);
1020
+ if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
1021
+ }
854
1022
  const archive = job.archiveDirectory ?? job.outputDirectory;
855
1023
  const inputSha256 = await sha256(new TextEncoder().encode(job.input));
856
1024
  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, ...job.warnings?.length ? { warnings: job.warnings } : {} };
1025
+ const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, inputSha256, ...job.preparedBy ? { preparedBy: job.preparedBy } : {}, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
858
1026
  try {
859
1027
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
860
1028
  if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
@@ -862,7 +1030,7 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
862
1030
  if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
863
1031
  if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
864
1032
  progress(index, jobs.length);
865
- const files = await execute(job.input, job.modes, job.weather);
1033
+ const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
866
1034
  const names = Object.keys(files);
867
1035
  if (!names.length) throw new Error("Calculation produced no result files");
868
1036
  for (const [name, content] of Object.entries(files)) {
@@ -875,9 +1043,11 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
875
1043
  }
876
1044
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
877
1045
  } catch (error) {
878
- await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: String(error) }));
879
- if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: String(error), archive }));
880
- throw error;
1046
+ const message = error instanceof Error ? error.message : String(error);
1047
+ await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message }));
1048
+ if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
1049
+ const files = job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : "";
1050
+ throw new Error(`Scenario ${job.name}${files}: ${message}`);
881
1051
  }
882
1052
  }
883
1053
  }
@@ -947,18 +1117,24 @@ from ${targetWrapper(target).pythonModule} import main`);
947
1117
  for (const [name, version] of Object.entries(bundle.runtime.requiredVersions)) {
948
1118
  if (versions[name.toLowerCase().replace(/_/g, "-")] !== version) throw new Error(`Python runtime identity mismatch for ${name}`);
949
1119
  }
1120
+ if (hasTargetSchemaCorrection(bundle.bundleId)) {
1121
+ const schemaPath = py.runPython(`import os, future_homes_standard.schema_validation as v
1122
+ os.path.join(os.path.dirname(v.__file__), 'schema.json')`);
1123
+ py.FS.writeFile(schemaPath, correctTargetSchema(bundle.bundleId, py.FS.readFile(schemaPath, { encoding: "utf8" })));
1124
+ }
950
1125
  manifest = bundle;
951
1126
  send({ type: "worker_ready", targetBundleId: bundle.bundleId });
952
1127
  }
953
1128
  async function run(jobId, bundleId, jobs) {
954
1129
  if (!runtime || !manifest) throw new Error("Python worker is not initialized");
955
- await executePreparedJobs(manifest, bundleId, jobId, jobs, async (input, modes, weather) => {
1130
+ await executePreparedJobs(manifest, bundleId, jobId, jobs, async (input, modes, weather, heatingProfile) => {
956
1131
  const py = runtime;
957
1132
  const folder = `/runs/${crypto.randomUUID()}`;
958
1133
  py.FS.mkdirTree(folder);
959
1134
  py.FS.writeFile(`${folder}/model.json`, input);
960
1135
  try {
961
1136
  if (weather) py.FS.writeFile(`${folder}/weather.epw`, weather.epw);
1137
+ if (heatingProfile) return await executePythonHeatingProfile(py, folder, input, heatingProfile, weather ? `${folder}/weather.epw` : void 0);
962
1138
  const args = pythonFhsArguments(`${folder}/model.json`, modes, weather ? `${folder}/weather.epw` : void 0);
963
1139
  await py.runPythonAsync(`main(${JSON.stringify(args)}, standalone_mode=False)`);
964
1140
  const output = `${folder}/model__results`;
@@ -988,7 +1164,9 @@ self.onmessage = async ({ data }) => {
988
1164
  else if (data.type === "run_prepared_batch") await run(data.jobId, data.targetBundleId, data.jobs);
989
1165
  else throw new Error(`Unsupported Python worker message ${data.type}`);
990
1166
  } catch (error) {
991
- send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: String(error) });
1167
+ const text = error instanceof Error ? error.message : String(error);
1168
+ console.error(text);
1169
+ send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: pythonFailureMessage(text) });
992
1170
  } finally {
993
1171
  busy = false;
994
1172
  }
@@ -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": "117bc2684a5dc0744497e865e8df27bf61e87f1907a9a86e6b71ab238b94ce96",
45
- "python-fhs-a8-f2ab6cf7-8ca182b0-v1": "671617990795f3d0651fc9ec839ced0efe480ac4133e087a3c64b446a24127e0",
46
- "python-fhs-a9-918addad-b9b90138-v1": "3558a43a589195c09045a59c21ab180e81f77ea5fd0f45f81aabe51670573fcc"
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: {
@@ -69,7 +242,9 @@ function resolveHemTarget(id) {
69
242
  return target;
70
243
  }
71
244
  function modelArtifacts(manifest2) {
72
- return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/"));
245
+ const runtime = [manifest2.runtime.javascript, manifest2.runtime.wasm];
246
+ const converter = [manifest2.preparation.javascript, manifest2.preparation.wasm].filter((path) => !runtime.includes(path));
247
+ return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/") && !converter.includes(artifact.path));
73
248
  }
74
249
  function validateTargetManifest(manifest2, target) {
75
250
  if (manifest2.bundleId !== target.id || manifest2.protocol !== 1 || manifest2.engineCommit !== target.engineCommit || manifest2.wrapperCommit !== target.wrapperCommit || manifest2.conversionProfile !== target.conversionProfile) {
@@ -87,7 +262,7 @@ function validateTargetManifest(manifest2, target) {
87
262
  sizesByHash.set(artifact.sha256, artifact.bytes);
88
263
  paths.add(artifact.path);
89
264
  }
90
- for (const path of [...Object.values(manifest2.preparation), manifest2.runtime.javascript, ...manifest2.runtime.wasm ? [manifest2.runtime.wasm] : [], ...manifest2.runtime.wheels ?? []]) {
265
+ for (const path of [manifest2.preparation.schema, manifest2.preparation.defaults, manifest2.runtime.javascript, ...manifest2.runtime.wasm ? [manifest2.runtime.wasm] : [], ...manifest2.runtime.wheels ?? []]) {
91
266
  if (path.startsWith("source/") || path.startsWith("notices/")) throw new Error(`Runtime/preparation cannot reference reserved source/notice material: ${path}`);
92
267
  if (!paths.has(path)) throw new Error(`Target manifest is missing required artifact ${path}`);
93
268
  }
@@ -256,10 +431,14 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
256
431
  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
432
  if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
258
433
  if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
434
+ if (job.heatingProfile) {
435
+ parseHeatingProfile(job.heatingProfile);
436
+ if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
437
+ }
259
438
  const archive = job.archiveDirectory ?? job.outputDirectory;
260
439
  const inputSha256 = await sha256(new TextEncoder().encode(job.input));
261
440
  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, ...job.warnings?.length ? { warnings: job.warnings } : {} };
441
+ const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, inputSha256, ...job.preparedBy ? { preparedBy: job.preparedBy } : {}, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
263
442
  try {
264
443
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
265
444
  if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
@@ -267,7 +446,7 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
267
446
  if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
268
447
  if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
269
448
  progress(index, jobs.length);
270
- const files = await execute(job.input, job.modes, job.weather);
449
+ const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
271
450
  const names = Object.keys(files);
272
451
  if (!names.length) throw new Error("Calculation produced no result files");
273
452
  for (const [name, content] of Object.entries(files)) {
@@ -280,9 +459,11 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
280
459
  }
281
460
  await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
282
461
  } catch (error) {
283
- await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: String(error) }));
284
- if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: String(error), archive }));
285
- throw error;
462
+ const message = error instanceof Error ? error.message : String(error);
463
+ await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message }));
464
+ if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
465
+ const files = job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : "";
466
+ throw new Error(`Scenario ${job.name}${files}: ${message}`);
286
467
  }
287
468
  }
288
469
  }
@@ -392,6 +573,7 @@ var BatchWorkerFileSystemAcknowledgements = class {
392
573
  var manifest;
393
574
  var runInput;
394
575
  var supportsWeather = false;
576
+ var runStage;
395
577
  var busy = false;
396
578
  var acknowledgements = new BatchWorkerFileSystemAcknowledgements();
397
579
  var send = (message) => self.postMessage(message);
@@ -424,13 +606,15 @@ async function initialize(bundle) {
424
606
  supportsWeather = module.target_weather_protocol_version?.() === 1;
425
607
  if (typeof module.run_target_input !== "function") throw new Error("Pinned runtime does not support prepared target jobs");
426
608
  runInput = module.run_target_input;
609
+ runStage = module.target_heating_profile_protocol_version?.() === 1 && typeof module.run_target_stage === "function" ? module.run_target_stage : void 0;
427
610
  } finally {
428
611
  URL.revokeObjectURL(url);
429
612
  }
430
613
  manifest = bundle;
431
614
  send({ type: "worker_ready", targetBundleId: bundle.bundleId });
432
615
  }
433
- self.onmessage = async ({ data }) => {
616
+ if (self.name !== "vulcan-rust-execution") installIsolatedRustWorker(self);
617
+ else self.onmessage = async ({ data }) => {
434
618
  if (data.type === FS_RESPONSE_TYPE) {
435
619
  acknowledgements.acknowledge(data.messageId, data.error ?? null);
436
620
  return;
@@ -444,7 +628,16 @@ self.onmessage = async ({ data }) => {
444
628
  if (data.type === "initialize") await initialize(data.manifest);
445
629
  else if (data.type === "run_prepared_batch") {
446
630
  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) => {
631
+ await executePreparedJobs(manifest, data.targetBundleId, data.jobId, data.jobs, async (input, modes, weather, heatingProfile) => {
632
+ if (heatingProfile) {
633
+ if (!runStage) throw new Error("Pinned Rust bundle lacks heating profile protocol 1; rebuild and qualify its adapter");
634
+ const stage = async (data2, step) => {
635
+ const result2 = JSON.parse(runStage(data2, step, step === "preprocess" ? weather?.epw : void 0));
636
+ if (result2.status !== "calculated") throw new Error(result2.error ?? "Heating profile stage failed");
637
+ return result2.files;
638
+ };
639
+ return runHeatingProfile(input, heatingProfile, stage);
640
+ }
448
641
  if (weather && !supportsWeather) throw new Error("Pinned Rust runtime does not implement custom EPW protocol 1; rebuild and qualify its bundle");
449
642
  const result = JSON.parse(weather ? runInput(input, "model", JSON.stringify(modes), weather.epw) : runInput(input, "model", JSON.stringify(modes)));
450
643
  if (result.status !== "calculated") throw new Error(result.error ?? "Rust calculation failed");
@@ -453,7 +646,7 @@ self.onmessage = async ({ data }) => {
453
646
  send({ type: "complete", jobId: data.jobId, targetBundleId: manifest.bundleId, result: { status: "success", targetBundleId: manifest.bundleId } });
454
647
  } else throw new Error("Unknown Rust target message");
455
648
  } catch (error) {
456
- send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: String(error) });
649
+ send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: error instanceof Error ? error.message : String(error) });
457
650
  } finally {
458
651
  busy = false;
459
652
  }