@vulcan-energy/mcp-helper 0.1.8 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ // ../hem-target-runtime/src/hem/targets.ts
2
+ var HEM_TARGETS = [
3
+ {
4
+ id: "rust-fhs-a7-62d3df70-c5ba2673-v1",
5
+ label: "Rust HEM:FHS 1.0.0a7",
6
+ runtime: "rust",
7
+ version: "1.0.0a7",
8
+ engineVersion: "1.0.0a7",
9
+ wrapperVersion: "1.0.0a7",
10
+ wrapper: "fhs",
11
+ engineCommit: "62d3df705690f33b3fc3e905c9971d4f3743bf2e",
12
+ wrapperCommit: "c5ba2673fbd886cfe4fb528f61b376bdf406ebbd",
13
+ conversionProfile: "current_rust_fhs"
14
+ },
15
+ {
16
+ id: "python-fhs-a9-918addad-b9b90138-v1",
17
+ label: "Python HEM:FHS 1.0.0a9",
18
+ runtime: "python",
19
+ version: "1.0.0a9",
20
+ engineVersion: "1.0.0a9",
21
+ wrapperVersion: "1.0.0a9",
22
+ wrapper: "fhs",
23
+ engineCommit: "918addad2f9ffbcd9c7a4ed73497d047210be2d2",
24
+ wrapperCommit: "b9b901382feb0e5d27f969532842250147fb4068",
25
+ conversionProfile: "python_fhs_a9"
26
+ },
27
+ {
28
+ id: "python-fhs-a8-f2ab6cf7-8ca182b0-v1",
29
+ label: "Python HEM:FHS 1.0.0a8",
30
+ runtime: "python",
31
+ version: "1.0.0a8",
32
+ engineVersion: "1.0.0a8",
33
+ wrapperVersion: "1.0.0a8",
34
+ wrapper: "fhs",
35
+ engineCommit: "f2ab6cf78860c36d260cb21396b747cc372f2c9d",
36
+ wrapperCommit: "8ca182b0171a3a928059a9c0ec0145ecefe3f4e9",
37
+ conversionProfile: "python_fhs_a8"
38
+ }
39
+ ];
40
+ var RECOMMENDED_HEM_TARGET = HEM_TARGETS[0].id;
41
+
42
+ // ../hem-target-runtime/src/hem/targetAssets.ts
43
+ var RELEASE_MANIFEST_HASHES = {
44
+ "rust-fhs-a7-62d3df70-c5ba2673-v1": "66bda0b9b88323ec8759c8ccc4dc9dff8916639771a175cf01e0c4c2c881d485",
45
+ "python-fhs-a8-f2ab6cf7-8ca182b0-v1": "963f49337f1823e50e7a558f982ddb00a924d71f9ece53111c456bc82504a1b5",
46
+ "python-fhs-a9-918addad-b9b90138-v1": "f643197c37e7f8986a67c0c6eab32523cb54f5b7e8b4b7b09685b9a66c1faee1"
47
+ };
48
+ export {
49
+ RELEASE_MANIFEST_HASHES
50
+ };
@@ -0,0 +1,460 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // ../hem-target-runtime/src/hem/targets.ts
6
+ var WRAPPERS = {
7
+ fhs: {
8
+ profile: "fhs",
9
+ modes: ["actual", "actual-fee", "notional", "notional-fee"],
10
+ scenarioModes: {
11
+ fhs_assumptions: ["actual"],
12
+ fhs_compliance: ["actual", "actual-fee", "notional", "notional-fee"]
13
+ },
14
+ pythonModule: "bin.fhs",
15
+ coreDistribution: "hem-core",
16
+ wrapperDistribution: "hem-fhs-wrapper"
17
+ }
18
+ };
19
+ function targetWrapper(target) {
20
+ const wrapper = WRAPPERS[target.wrapper];
21
+ if (!wrapper) throw new Error(`Unsupported HEM wrapper: ${target.wrapper}`);
22
+ return wrapper;
23
+ }
24
+ function assertRustTargetVersions(target, engineVersion, wrapperVersion) {
25
+ if (engineVersion !== target.engineVersion || wrapperVersion !== target.wrapperVersion) throw new Error("Rust runtime version mismatch");
26
+ }
27
+ var HEM_TARGETS = [
28
+ {
29
+ id: "rust-fhs-a7-62d3df70-c5ba2673-v1",
30
+ label: "Rust HEM:FHS 1.0.0a7",
31
+ runtime: "rust",
32
+ version: "1.0.0a7",
33
+ engineVersion: "1.0.0a7",
34
+ wrapperVersion: "1.0.0a7",
35
+ wrapper: "fhs",
36
+ engineCommit: "62d3df705690f33b3fc3e905c9971d4f3743bf2e",
37
+ wrapperCommit: "c5ba2673fbd886cfe4fb528f61b376bdf406ebbd",
38
+ conversionProfile: "current_rust_fhs"
39
+ },
40
+ {
41
+ id: "python-fhs-a9-918addad-b9b90138-v1",
42
+ label: "Python HEM:FHS 1.0.0a9",
43
+ runtime: "python",
44
+ version: "1.0.0a9",
45
+ engineVersion: "1.0.0a9",
46
+ wrapperVersion: "1.0.0a9",
47
+ wrapper: "fhs",
48
+ engineCommit: "918addad2f9ffbcd9c7a4ed73497d047210be2d2",
49
+ wrapperCommit: "b9b901382feb0e5d27f969532842250147fb4068",
50
+ conversionProfile: "python_fhs_a9"
51
+ },
52
+ {
53
+ id: "python-fhs-a8-f2ab6cf7-8ca182b0-v1",
54
+ label: "Python HEM:FHS 1.0.0a8",
55
+ runtime: "python",
56
+ version: "1.0.0a8",
57
+ engineVersion: "1.0.0a8",
58
+ wrapperVersion: "1.0.0a8",
59
+ wrapper: "fhs",
60
+ engineCommit: "f2ab6cf78860c36d260cb21396b747cc372f2c9d",
61
+ wrapperCommit: "8ca182b0171a3a928059a9c0ec0145ecefe3f4e9",
62
+ conversionProfile: "python_fhs_a8"
63
+ }
64
+ ];
65
+ var RECOMMENDED_HEM_TARGET = HEM_TARGETS[0].id;
66
+ function resolveHemTarget(id) {
67
+ const target = HEM_TARGETS.find((target2) => target2.id === id);
68
+ if (!target) throw new Error(`HEM target '${id}' is unavailable. Select a supported target explicitly; saved runs are never upgraded automatically.`);
69
+ return target;
70
+ }
71
+ function modelArtifacts(manifest2) {
72
+ return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/"));
73
+ }
74
+ function validateTargetManifest(manifest2, target) {
75
+ if (manifest2.bundleId !== target.id || manifest2.protocol !== 1 || manifest2.engineCommit !== target.engineCommit || manifest2.wrapperCommit !== target.wrapperCommit || manifest2.conversionProfile !== target.conversionProfile) {
76
+ throw new Error(`Target manifest identity mismatch for ${target.id}`);
77
+ }
78
+ const paths = /* @__PURE__ */ new Set();
79
+ const sizesByHash = /* @__PURE__ */ new Map();
80
+ const isRelativePath = (path) => typeof path === "string" && /^[a-zA-Z0-9_./+-]+$/.test(path) && path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
81
+ for (const artifact of manifest2.artifacts) {
82
+ if (!isRelativePath(artifact.path) || !/^[a-f0-9]{64}$/.test(artifact.sha256) || !Number.isSafeInteger(artifact.bytes) || artifact.bytes <= 0 || paths.has(artifact.path)) {
83
+ throw new Error(`Invalid artifact in ${target.id}: ${artifact.path}`);
84
+ }
85
+ const priorSize = sizesByHash.get(artifact.sha256);
86
+ if (priorSize !== void 0 && priorSize !== artifact.bytes) throw new Error(`Conflicting sizes for pinned artifact hash ${artifact.sha256}`);
87
+ sizesByHash.set(artifact.sha256, artifact.bytes);
88
+ paths.add(artifact.path);
89
+ }
90
+ for (const path of [...Object.values(manifest2.preparation), manifest2.runtime.javascript, ...manifest2.runtime.wasm ? [manifest2.runtime.wasm] : [], ...manifest2.runtime.wheels ?? []]) {
91
+ if (path.startsWith("source/") || path.startsWith("notices/")) throw new Error(`Runtime/preparation cannot reference reserved source/notice material: ${path}`);
92
+ if (!paths.has(path)) throw new Error(`Target manifest is missing required artifact ${path}`);
93
+ }
94
+ if (!manifest2.modes.length || new Set(manifest2.modes).size !== manifest2.modes.length || manifest2.modes.some((mode) => !targetWrapper(target).modes.includes(mode))) throw new Error("Unsupported or duplicate FHS calculation modes");
95
+ if (target.runtime === "rust") {
96
+ if (!manifest2.runtime.wasm) throw new Error("Rust target manifest is missing its runtime WASM artifact");
97
+ if (manifest2.modes.some((mode) => mode !== "actual") && manifest2.modes.length !== targetWrapper(target).modes.length) throw new Error("Rust target modes require actual alone or the complete compliance set");
98
+ } else {
99
+ const { index, wheels, requiredVersions } = manifest2.runtime;
100
+ if (index?.startsWith("source/") || index?.startsWith("notices/")) throw new Error("Python runtime cannot use the reserved source/notice directory");
101
+ if (!index?.endsWith("/") || !isRelativePath(index.slice(0, -1))) throw new Error("Python runtime index must be a relative directory ending in /");
102
+ if (!wheels?.length || new Set(wheels).size !== wheels.length) throw new Error("Python runtime requires its exact wheel artifacts");
103
+ for (const file of ["pyodide.asm.js", "pyodide.asm.wasm", "pyodide-lock.json", "python_stdlib.zip"]) {
104
+ if (!paths.has(`${index}${file}`)) throw new Error(`Python runtime is missing pinned artifact ${index}${file}`);
105
+ }
106
+ if (requiredVersions?.[targetWrapper(target).coreDistribution] !== target.engineVersion || requiredVersions?.[targetWrapper(target).wrapperDistribution] !== target.wrapperVersion) {
107
+ throw new Error(`Python runtime must pin matching engine ${target.engineVersion} and wrapper ${target.wrapperVersion} distributions`);
108
+ }
109
+ }
110
+ }
111
+
112
+ // ../hem-target-runtime/src/hem/targetAssets.ts
113
+ var CACHE = "vulcan-hem-artifacts-v1";
114
+ async function sha256(bytes) {
115
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0")).join("");
116
+ }
117
+ var keyFor = (artifact) => new URL(`/__hem_content/${artifact.sha256}`, globalThis.location.origin).href;
118
+ async function verified(response, artifact, preserveBody = true) {
119
+ const bytes = new Uint8Array(await (preserveBody ? response.clone() : response).arrayBuffer());
120
+ return bytes.byteLength === artifact.bytes && await sha256(bytes) === artifact.sha256;
121
+ }
122
+ var TargetAssets = class _TargetAssets {
123
+ constructor(cache, fetcher = (...args) => globalThis.fetch(...args)) {
124
+ this.cache = cache;
125
+ this.fetcher = fetcher;
126
+ }
127
+ static async open() {
128
+ return new _TargetAssets(await caches.open(CACHE));
129
+ }
130
+ async inspect(manifest2, signal) {
131
+ signal?.throwIfAborted();
132
+ const unique = [...new Map(modelArtifacts(manifest2).map((artifact) => [artifact.sha256, artifact])).values()];
133
+ const missing = [];
134
+ for (let offset = 0; offset < unique.length; offset += 4) {
135
+ signal?.throwIfAborted();
136
+ const results = await Promise.all(unique.slice(offset, offset + 4).map(async (artifact) => {
137
+ signal?.throwIfAborted();
138
+ const key = keyFor(artifact);
139
+ const response = await this.cache.match(key);
140
+ signal?.throwIfAborted();
141
+ const valid = response && await verified(response, artifact, false);
142
+ signal?.throwIfAborted();
143
+ if (valid) return void 0;
144
+ if (response) await this.cache.delete(key);
145
+ return artifact;
146
+ }));
147
+ missing.push(...results.filter((artifact) => artifact !== void 0));
148
+ }
149
+ signal?.throwIfAborted();
150
+ return { missing, missingBytes: missing.reduce((bytes, artifact) => bytes + artifact.bytes, 0) };
151
+ }
152
+ async download(manifest2, progress, signal) {
153
+ const { missing, missingBytes } = await this.inspect(manifest2, signal);
154
+ signal?.throwIfAborted();
155
+ let downloaded = 0;
156
+ let next = 0;
157
+ let failure;
158
+ const controller = new AbortController();
159
+ const abort = () => controller.abort(signal?.reason);
160
+ signal?.addEventListener("abort", abort, { once: true });
161
+ const activeSignal = controller.signal;
162
+ const acquire = async (artifact) => {
163
+ activeSignal.throwIfAborted();
164
+ const response = await this.fetcher(`/hem-targets/${manifest2.bundleId}/${artifact.path}`, { signal: activeSignal, cache: "no-store" });
165
+ activeSignal.throwIfAborted();
166
+ if (!response.ok) throw new Error(`Missing or corrupt HEM artifact: ${artifact.path}. Retry the download.`);
167
+ const bytes = new Uint8Array(artifact.bytes);
168
+ let received = 0;
169
+ const append = (chunk) => {
170
+ activeSignal.throwIfAborted();
171
+ if (received + chunk.byteLength > artifact.bytes) throw new Error(`Missing or corrupt HEM artifact size: ${artifact.path}. Retry the download.`);
172
+ bytes.set(chunk, received);
173
+ received += chunk.byteLength;
174
+ downloaded += chunk.byteLength;
175
+ progress(downloaded, missingBytes);
176
+ };
177
+ if (response.body) {
178
+ const reader = response.body.getReader();
179
+ const cancelReader = () => {
180
+ void reader.cancel(activeSignal.reason).catch(() => {
181
+ });
182
+ };
183
+ activeSignal.addEventListener("abort", cancelReader, { once: true });
184
+ try {
185
+ while (true) {
186
+ activeSignal.throwIfAborted();
187
+ const { done, value } = await reader.read();
188
+ activeSignal.throwIfAborted();
189
+ if (done) break;
190
+ append(value);
191
+ }
192
+ } catch (error) {
193
+ await reader.cancel(error).catch(() => {
194
+ });
195
+ throw error;
196
+ } finally {
197
+ activeSignal.removeEventListener("abort", cancelReader);
198
+ reader.releaseLock();
199
+ }
200
+ } else {
201
+ append(new Uint8Array(await response.arrayBuffer()));
202
+ }
203
+ if (received !== artifact.bytes || await sha256(bytes) !== artifact.sha256) throw new Error(`Missing or corrupt HEM artifact: ${artifact.path}. Retry the download.`);
204
+ activeSignal.throwIfAborted();
205
+ await this.cache.put(keyFor(artifact), new Response(bytes, { headers: response.headers }));
206
+ activeSignal.throwIfAborted();
207
+ };
208
+ const worker = async () => {
209
+ try {
210
+ while (next < missing.length) {
211
+ activeSignal.throwIfAborted();
212
+ const artifact = missing[next++];
213
+ await acquire(artifact);
214
+ }
215
+ } catch (error) {
216
+ failure ?? (failure = error);
217
+ controller.abort(error);
218
+ }
219
+ };
220
+ try {
221
+ signal?.throwIfAborted();
222
+ progress(0, missingBytes);
223
+ await Promise.all(Array.from({ length: Math.min(4, missing.length) }, worker));
224
+ if (failure !== void 0) throw failure;
225
+ activeSignal.throwIfAborted();
226
+ } finally {
227
+ signal?.removeEventListener("abort", abort);
228
+ }
229
+ }
230
+ /** Load only the editor schema; selecting a version must not fetch its runtime. */
231
+ async ensureBytes(bundleId, artifact) {
232
+ let response = await this.cache.match(keyFor(artifact));
233
+ if (!response || !await verified(response, artifact)) {
234
+ response = await this.fetcher(`/hem-targets/${bundleId}/${artifact.path}`, { cache: "no-store" });
235
+ if (!response.ok || !await verified(response, artifact)) {
236
+ throw new Error(`Missing or corrupt HEM artifact: ${artifact.path}. Retry the download.`);
237
+ }
238
+ await this.cache.put(keyFor(artifact), response.clone());
239
+ }
240
+ return new Uint8Array(await response.arrayBuffer());
241
+ }
242
+ async bytes(artifact) {
243
+ const response = await this.cache.match(keyFor(artifact));
244
+ if (!response || !await verified(response, artifact)) throw new Error(`Exact HEM artifact unavailable: ${artifact.path}. Download this target again.`);
245
+ return new Uint8Array(await response.arrayBuffer());
246
+ }
247
+ };
248
+
249
+ // ../hem-target-runtime/src/hem/preparedRun.ts
250
+ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, write2, progress) {
251
+ if (manifest2.bundleId !== bundleId) throw new Error("Worker target identity mismatch");
252
+ if (!jobs.length) throw new Error("Batch has no prepared jobs");
253
+ const allowedModes = new Set(manifest2.modes);
254
+ const reservedNames = /* @__PURE__ */ new Set(["model.json", "source.csv", "weather.epw", "target-run.json"]);
255
+ for (const [index, job] of jobs.entries()) {
256
+ 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
+ if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
258
+ if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory.split("/").some((segment) => segment === ".."))) throw new Error("Invalid archive path");
259
+ const archive = job.archiveDirectory ?? job.outputDirectory;
260
+ const inputSha256 = await sha256(new TextEncoder().encode(job.input));
261
+ 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 };
263
+ try {
264
+ await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
265
+ if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
266
+ await write2(`${archive}/model.json`, job.input);
267
+ if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
268
+ if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
269
+ progress(index, jobs.length);
270
+ const files = await execute(job.input, job.modes, job.weather);
271
+ const names = Object.keys(files);
272
+ if (!names.length) throw new Error("Calculation produced no result files");
273
+ for (const [name, content] of Object.entries(files)) {
274
+ if (reservedNames.has(name) || !name || name === "." || name === ".." || /[\\/]/.test(name)) throw new Error("Unexpected result path");
275
+ await write2(`${archive}/${name}`, content);
276
+ }
277
+ if (archive !== job.outputDirectory) {
278
+ for (const [name, content] of Object.entries(files)) await write2(`${job.outputDirectory}/${name}`, content);
279
+ await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names, archive }));
280
+ }
281
+ await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
282
+ } 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;
286
+ }
287
+ }
288
+ }
289
+
290
+ // ../hem-target-runtime/src/workers/workerProtocol.ts
291
+ var FS_REQUEST_TYPE = "file_system";
292
+ var FS_RESPONSE_TYPE = "file_system_response";
293
+
294
+ // ../hem-target-runtime/src/workers/batchWorkerFileSystemBridge.ts
295
+ var DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS = 3e4;
296
+ var BatchWorkerFileSystemAcknowledgements = class {
297
+ constructor(timeoutMs = DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS) {
298
+ this.timeoutMs = timeoutMs;
299
+ __publicField(this, "pending", /* @__PURE__ */ new Map());
300
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
301
+ throw new Error("Batch worker filesystem acknowledgement timeout must be positive");
302
+ }
303
+ }
304
+ get pendingCount() {
305
+ return this.pending.size;
306
+ }
307
+ register(request) {
308
+ if (request.operation !== "write_file" && request.operation !== "delete_file") {
309
+ throw new Error(`Cannot acknowledge unsupported filesystem operation '${request.operation}'`);
310
+ }
311
+ if (this.pending.has(request.messageId)) {
312
+ throw new Error(`Duplicate filesystem acknowledgement id '${request.messageId}'`);
313
+ }
314
+ let resolve;
315
+ let reject;
316
+ const promise = new Promise((promiseResolve, promiseReject) => {
317
+ resolve = promiseResolve;
318
+ reject = promiseReject;
319
+ });
320
+ void promise.catch(() => void 0);
321
+ const entry = {
322
+ operation: request.operation,
323
+ path: request.path,
324
+ promise,
325
+ resolve,
326
+ reject,
327
+ settled: false
328
+ };
329
+ entry.timer = setTimeout(() => {
330
+ this.settleFailure(
331
+ request.messageId,
332
+ `Timed out after ${this.timeoutMs}ms waiting for ${request.operation} acknowledgement for '${request.path}'`
333
+ );
334
+ }, this.timeoutMs);
335
+ this.pending.set(request.messageId, entry);
336
+ }
337
+ acknowledge(messageId, error) {
338
+ const entry = this.pending.get(messageId);
339
+ if (!entry) return false;
340
+ if (error) {
341
+ this.settleFailure(
342
+ messageId,
343
+ `Physical ${entry.operation} failed for '${entry.path}': ${error}`
344
+ );
345
+ } else {
346
+ this.settleSuccess(entry);
347
+ }
348
+ return true;
349
+ }
350
+ async waitForPending() {
351
+ const failures = [];
352
+ while (this.pending.size > 0) {
353
+ const snapshot = Array.from(this.pending.entries());
354
+ const results = await Promise.allSettled(snapshot.map(([, entry]) => entry.promise));
355
+ results.forEach((result) => {
356
+ if (result.status === "rejected") {
357
+ failures.push(
358
+ result.reason instanceof Error ? result.reason : new Error(String(result.reason))
359
+ );
360
+ }
361
+ });
362
+ snapshot.forEach(([messageId, entry]) => {
363
+ if (this.pending.get(messageId) === entry) {
364
+ if (entry.timer) clearTimeout(entry.timer);
365
+ this.pending.delete(messageId);
366
+ }
367
+ });
368
+ }
369
+ if (failures.length === 1) throw failures[0];
370
+ if (failures.length > 1) {
371
+ throw new Error(
372
+ `Multiple batch worker filesystem operations failed: ${failures.map((failure) => failure.message).join("; ")}`
373
+ );
374
+ }
375
+ }
376
+ settleSuccess(entry) {
377
+ if (entry.settled) return;
378
+ entry.settled = true;
379
+ if (entry.timer) clearTimeout(entry.timer);
380
+ entry.resolve();
381
+ }
382
+ settleFailure(messageId, message) {
383
+ const entry = this.pending.get(messageId);
384
+ if (!entry || entry.settled) return;
385
+ entry.settled = true;
386
+ if (entry.timer) clearTimeout(entry.timer);
387
+ entry.reject(new Error(message));
388
+ }
389
+ };
390
+
391
+ // ../hem-target-runtime/src/hem/rustFhsWorker.ts
392
+ var manifest;
393
+ var runInput;
394
+ var supportsWeather = false;
395
+ var busy = false;
396
+ var acknowledgements = new BatchWorkerFileSystemAcknowledgements();
397
+ var send = (message) => self.postMessage(message);
398
+ async function write(path, content) {
399
+ const request = { type: FS_REQUEST_TYPE, operation: "write_file", path, content, messageId: crypto.randomUUID() };
400
+ acknowledgements.register(request);
401
+ send(request);
402
+ await acknowledgements.waitForPending();
403
+ }
404
+ async function initialize(bundle) {
405
+ const target = resolveHemTarget(bundle.bundleId);
406
+ validateTargetManifest(bundle, target);
407
+ if (target.runtime !== "rust" || target.wrapper !== "fhs" || !bundle.runtime.wasm) throw new Error("Rust worker requires a pinned Rust runtime");
408
+ const assets = await TargetAssets.open();
409
+ const bytes = async (path) => {
410
+ const artifact = bundle.artifacts.find((artifact2) => artifact2.path === path);
411
+ if (!artifact) throw new Error(`Missing Rust artifact ${path}`);
412
+ return assets.bytes(artifact);
413
+ };
414
+ const url = URL.createObjectURL(new Blob([await bytes(bundle.runtime.javascript)], { type: "text/javascript" }));
415
+ try {
416
+ const module = await import(
417
+ /* @vite-ignore */
418
+ url
419
+ );
420
+ await module.default({ module_or_path: await bytes(bundle.runtime.wasm) });
421
+ assertRustTargetVersions(target, module.metadata_hem_core_version?.(), module.metadata_fhs_wrapper_version?.());
422
+ if (typeof module.initialize_rayon_thread_pool !== "function") throw new Error("Pinned Rust runtime lacks worker pool initialization");
423
+ await module.initialize_rayon_thread_pool(1);
424
+ supportsWeather = module.target_weather_protocol_version?.() === 1;
425
+ if (typeof module.run_target_input !== "function") throw new Error("Pinned runtime does not support prepared target jobs");
426
+ runInput = module.run_target_input;
427
+ } finally {
428
+ URL.revokeObjectURL(url);
429
+ }
430
+ manifest = bundle;
431
+ send({ type: "worker_ready", targetBundleId: bundle.bundleId });
432
+ }
433
+ self.onmessage = async ({ data }) => {
434
+ if (data.type === FS_RESPONSE_TYPE) {
435
+ acknowledgements.acknowledge(data.messageId, data.error ?? null);
436
+ return;
437
+ }
438
+ if (busy) {
439
+ send({ type: "error", jobId: data.jobId, error: "A calculation is already active" });
440
+ return;
441
+ }
442
+ busy = true;
443
+ try {
444
+ if (data.type === "initialize") await initialize(data.manifest);
445
+ else if (data.type === "run_prepared_batch") {
446
+ 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) => {
448
+ if (weather && !supportsWeather) throw new Error("Pinned Rust runtime does not implement custom EPW protocol 1; rebuild and qualify its bundle");
449
+ const result = JSON.parse(weather ? runInput(input, "model", JSON.stringify(modes), weather.epw) : runInput(input, "model", JSON.stringify(modes)));
450
+ if (result.status !== "calculated") throw new Error(result.error ?? "Rust calculation failed");
451
+ return result.files;
452
+ }, write, (completed, total) => send({ type: "progress", jobId: data.jobId, progress: { completed, total } }));
453
+ send({ type: "complete", jobId: data.jobId, targetBundleId: manifest.bundleId, result: { status: "success", targetBundleId: manifest.bundleId } });
454
+ } else throw new Error("Unknown Rust target message");
455
+ } catch (error) {
456
+ send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: String(error) });
457
+ } finally {
458
+ busy = false;
459
+ }
460
+ };