@vulcan-energy/mcp-helper 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
- // Local MCP/CLI transport for the app's exact target preparation and workers.
1
+ // Local MCP/CLI transport: verified target bundles, and the app's target workers in Chrome.
2
+ // Preparation runs in Node (preparation.mjs); Chrome is needed only to run an engine.
2
3
  import { readFile, writeFile, mkdir, realpath, open, unlink, rename } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
4
5
  import { createHash, randomUUID } from 'node:crypto';
@@ -12,10 +13,13 @@ const RELEASE_ORIGIN = 'https://usevulcan.app';
12
13
  // that is not also the runtime. The host converts with the package's own WASM.
13
14
  const isModelArtifact = (manifest, path) => !path.startsWith('source/') && !path.startsWith('notices/')
14
15
  && !([manifest.preparation?.javascript, manifest.preparation?.wasm].includes(path) && ![manifest.runtime?.javascript, manifest.runtime?.wasm].includes(path));
16
+ // Preparation reads only the pinned schema and defaults.
17
+ const isSelected = (manifest, path, preparationOnly) => preparationOnly
18
+ ? [manifest.preparation?.schema, manifest.preparation?.defaults].includes(path) : isModelArtifact(manifest, path);
15
19
  function assertArtifactPath(path) {
16
20
  if (!path || path.includes('\\') || path.startsWith('/') || path.split('/').some(part => !part || part === '..' || part === '.')) throw new Error('Invalid target artifact path');
17
21
  }
18
- export async function readVerifiedBundle(manifestPath, expectedHash) {
22
+ export async function readVerifiedBundle(manifestPath, expectedHash, { preparationOnly = false } = {}) {
19
23
  if (!/^[a-f0-9]{64}$/.test(expectedHash ?? '')) throw new Error('Supply the exact target manifest SHA-256; local bundles are never inferred or upgraded.');
20
24
  const bytes = await readFile(manifestPath);
21
25
  if (hash(bytes) !== expectedHash) throw new Error('Target manifest hash mismatch');
@@ -25,7 +29,7 @@ export async function readVerifiedBundle(manifestPath, expectedHash) {
25
29
  const routes = new Map();
26
30
  for (const artifact of manifest.artifacts) {
27
31
  assertArtifactPath(artifact.path);
28
- if (!isModelArtifact(manifest, artifact.path)) continue;
32
+ if (!isSelected(manifest, artifact.path, preparationOnly)) continue;
29
33
  const file = await realpath(resolve(root, artifact.path));
30
34
  if (!file.startsWith(root + sep)) throw new Error('Target artifact escapes bundle directory');
31
35
  const contents = await readFile(file);
@@ -35,27 +39,6 @@ export async function readVerifiedBundle(manifestPath, expectedHash) {
35
39
  return { manifest, routes };
36
40
  }
37
41
 
38
- /** The package's own WASM, served at /app/: the glue, the binary, the version file, and the glue's relative imports. */
39
- export async function readPackageWasm(wasmDir) {
40
- if (!wasmDir) throw new Error('No WASM directory given: target preparation converts with the package\'s own WASM.');
41
- const read = name => readFile(join(wasmDir, name)).catch(() => {
42
- throw new Error(`The package WASM is incomplete: ${join(wasmDir, name)} is missing. Reinstall the package, or pass a complete WASM directory.`);
43
- });
44
- const [version, glue, binary] = await Promise.all(['wasm_version.json', 'wasm_wrapper.js', 'wasm_wrapper_bg.wasm'].map(read));
45
- const info = JSON.parse(version);
46
- // The glue and binary are checked against wasm_version.json. The wasm-bindgen-rayon snippets/ file the Free glue
47
- // imports is served unhashed: the version file has no hash for it. This catches a mismatched build; it is not a security boundary.
48
- for (const key of ['js_sha256', 'sha256']) if (!info[key]) throw new Error(`${join(wasmDir, 'wasm_version.json')} has no ${key}`);
49
- if (hash(glue) !== info.js_sha256 || hash(binary) !== info.sha256) throw new Error(`The WASM in ${wasmDir} does not match its wasm_version.json`);
50
- const routes = new Map([['/app/wasm_version.json', version], ['/app/wasm_wrapper.js', glue], ['/app/wasm_wrapper_bg.wasm', binary]]);
51
- // The same import scan deploy-mcp.sh uses to copy these files into the package.
52
- for (const [, path] of glue.toString().matchAll(/(?:from |import\()['"]\.\/([^'"]+)/g)) {
53
- assertArtifactPath(path);
54
- routes.set(`/app/${path}`, await read(path));
55
- }
56
- return routes;
57
- }
58
-
59
42
  async function releasePin(bundleId, pins) {
60
43
  if (!pins) {
61
44
  try { pins = (await import('./release-manifests.mjs')).RELEASE_MANIFEST_HASHES; }
@@ -73,7 +56,7 @@ async function writeAtomic(file, bytes) {
73
56
  }
74
57
  // The largest released artifact is ~14 MB, so five minutes per request needs only ~50 kB/s.
75
58
  const DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
76
- async function fetchBytes(fetcher, bundleId, url, timeoutMs) {
59
+ async function fetchBytes(fetcher, bundleId, url, timeoutMs, root) {
77
60
  let response, bytes;
78
61
  // The signal also bounds reading the body, so a stalled transfer cannot hold the workspace lock.
79
62
  const controller = new AbortController();
@@ -82,27 +65,28 @@ async function fetchBytes(fetcher, bundleId, url, timeoutMs) {
82
65
  response = await fetcher(url, { cache: 'no-store', signal: controller.signal });
83
66
  if (response.ok) bytes = Buffer.from(await response.arrayBuffer());
84
67
  } catch (error) {
85
- if (controller.signal.aborted) throw new Error(`HEM target ${bundleId} download timed out after ${timeoutMs / 1000} s: ${url}. Check your connection and retry, or supply target_manifest + target_manifest_sha256 for an offline bundle.`);
86
- throw new Error(`Could not download HEM target ${bundleId} from ${url} (${error.cause?.message ?? error.message}). Check your connection, or supply target_manifest + target_manifest_sha256 for an offline bundle.`);
68
+ if (controller.signal.aborted) throw new Error(`HEM target ${bundleId} download timed out after ${timeoutMs / 1000} s: ${url} (cache: ${root}). Check your connection and retry, or supply target_manifest + target_manifest_sha256 for an offline bundle.`);
69
+ throw new Error(`Could not download HEM target ${bundleId} from ${url} into ${root} (${error.cause?.message ?? error.message}). This target is not in the cache yet. Check your connection, or supply target_manifest + target_manifest_sha256 for an offline bundle.`);
87
70
  } finally { clearTimeout(timer); }
88
- if (!response.ok) throw new Error(`HEM target download failed (${response.status}): ${url}`);
71
+ if (!response.ok) throw new Error(`HEM target download failed (${response.status}): ${url} (cache: ${root})`);
89
72
  return bytes;
90
73
  }
91
74
 
92
75
  /** Resolve a released bundle into a local cache, verified against the pins compiled into this helper. */
93
- export async function resolveReleaseBundle(bundleId, { cacheDir = join(homedir(), '.cache/vulcan/hem-targets'), fetch: fetcher = globalThis.fetch, pins, onProgress, timeoutMs = DOWNLOAD_TIMEOUT_MS } = {}) {
76
+ // The user cache (XDG_CACHE_HOME, as other tools read it); a host whose home is read-only sets it.
77
+ export async function resolveReleaseBundle(bundleId, { cacheDir = join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'vulcan/hem-targets'), fetch: fetcher = globalThis.fetch, pins, onProgress, timeoutMs = DOWNLOAD_TIMEOUT_MS, preparationOnly = false } = {}) {
94
78
  const expected = await releasePin(bundleId, pins);
95
79
  const root = join(cacheDir, bundleId);
96
80
  const manifestPath = join(root, 'manifest.json');
97
81
  const base = `${RELEASE_ORIGIN}/hem-targets/${bundleId}/`;
98
82
  let bytes = await readFile(manifestPath).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
99
83
  if (!bytes || hash(bytes) !== expected) {
100
- bytes = await fetchBytes(fetcher, bundleId, base + 'manifest.json', timeoutMs);
84
+ bytes = await fetchBytes(fetcher, bundleId, base + 'manifest.json', timeoutMs, root);
101
85
  if (hash(bytes) !== expected) throw new Error(`HEM target manifest hash mismatch: ${bundleId}`);
102
86
  await writeAtomic(manifestPath, bytes);
103
87
  }
104
88
  const manifest = JSON.parse(bytes);
105
- const artifacts = manifest.artifacts.filter(artifact => { assertArtifactPath(artifact.path); return isModelArtifact(manifest, artifact.path); });
89
+ const artifacts = manifest.artifacts.filter(artifact => { assertArtifactPath(artifact.path); return isSelected(manifest, artifact.path, preparationOnly); });
106
90
  const missing = [];
107
91
  const realRoot = await realpath(root);
108
92
  for (const artifact of artifacts) {
@@ -122,7 +106,7 @@ export async function resolveReleaseBundle(bundleId, { cacheDir = join(homedir()
122
106
  try {
123
107
  while (next < missing.length && !failed) {
124
108
  const artifact = missing[next++];
125
- const contents = await fetchBytes(fetcher, bundleId, base + artifact.path, timeoutMs);
109
+ const contents = await fetchBytes(fetcher, bundleId, base + artifact.path, timeoutMs, root);
126
110
  if (contents.length !== artifact.bytes || hash(contents) !== artifact.sha256) throw new Error(`Corrupt HEM target artifact ${artifact.path}; retry the download`);
127
111
  await writeAtomic(join(root, artifact.path), contents);
128
112
  completed += artifact.bytes;
@@ -141,13 +125,63 @@ export function forwardPanicLines(page, write = line => process.stderr.write(`${
141
125
  page.on('console', message => { if (message.text().startsWith('[WASM] PANIC')) write(message.text()); });
142
126
  }
143
127
 
128
+ /** The verified pinned schema and defaults of a supplied or released bundle, for preparation in Node. */
129
+ export async function readPreparationBundle(options, dependencies = {}) {
130
+ const located = options.manifestPath ? { manifestPath: options.manifestPath, manifestSha256: options.manifestSha256 }
131
+ : await resolveReleaseBundle(options.targetBundleId, { cacheDir: dependencies.cacheDir, fetch: dependencies.fetch, pins: dependencies.pins, preparationOnly: true });
132
+ const { manifest, routes } = await readVerifiedBundle(located.manifestPath, located.manifestSha256, { preparationOnly: true });
133
+ return { manifest, text: artifactText(manifest, routes) };
134
+ }
135
+
136
+ /** Reads workspace files for preparation; a path that leaves the workspace is refused. */
137
+ export async function workspaceReader(workspacePath) {
138
+ const workspace = await realpath(workspacePath);
139
+ return async path => {
140
+ if (typeof path !== 'string' || path.includes('\\')) throw new Error('Invalid workspace path');
141
+ const file = await realpath(resolve(workspace, path));
142
+ if (!file.startsWith(workspace + sep)) throw new Error('Target read escapes workspace');
143
+ return readFile(file, 'utf8');
144
+ };
145
+ }
146
+
147
+ /** The verified pinned artifact text of a bundle, as the browser's TargetAssets text. */
148
+ const artifactText = (manifest, routes) => async path => {
149
+ const bytes = routes.get(`/hem-targets/${manifest.bundleId}/${path}`);
150
+ if (!bytes) throw new Error(`Missing preparation content ${path}`);
151
+ return new TextDecoder().decode(bytes);
152
+ };
153
+
154
+ /** Prepares every scenario of a saved target batch in Node with the package's own WASM; no browser. */
155
+ async function prepareJobs(options, manifest, routes, onJob, dependencies) {
156
+ const [{ prepareBatch }, loader] = await Promise.all([import('./preparation.mjs'), dependencies.loadPackageWasm ? undefined : import('./wasm-loader.mjs')]);
157
+ const wasmRemedy = options.wasmRemedy ?? 'Reinstall the package.';
158
+ const wasm = await (dependencies.loadPackageWasm ?? loader.loadPackageWasm)(options.wasmDir, wasmRemedy);
159
+ return prepareBatch({ config: options.config, manifest, text: artifactText(manifest, routes), converter: { prepare_target_scenario: wasm.prepareTargetScenario },
160
+ versionInfo: wasm.versionInfo, wasmRemedy, configName: options.configName, jobId: options.jobId, startedAt: options.startedAt, onJob });
161
+ }
162
+
163
+ /** A batch's exact source, defaults, snippet and weather bytes, read in Node; its target must be the supplied or pinned one. */
164
+ export async function snapshotTarget(options, dependencies = {}) {
165
+ const { snapshotBatchTarget } = await import('./preparation.mjs');
166
+ const snapshot = await snapshotBatchTarget(options.config, await workspaceReader(options.workspace));
167
+ const expected = options.manifestPath
168
+ ? (await readVerifiedBundle(options.manifestPath, options.manifestSha256, { preparationOnly: true })).manifest.bundleId
169
+ : (await releasePin(options.targetBundleId, dependencies.pins), options.targetBundleId);
170
+ if (snapshot.targetBundleId !== expected) throw new Error('Batch source and supplied manifest target differ');
171
+ return snapshot;
172
+ }
173
+
174
+ /** `operation: 'snapshot'` captures a batch; otherwise runs one saved target batch: under the workspace lock, prepares it in Node, then runs the jobs in Chrome. */
144
175
  export async function runTargetBrowser(options, dependencies = {}) {
176
+ if (options.operation === 'snapshot') return snapshotTarget(options, dependencies);
177
+ if (options.operation !== undefined && options.operation !== 'batch') throw new Error(`Unknown target operation '${options.operation}'`);
145
178
  // A bundle id resolves only after the workspace lock, so a long first download is reported as batch progress.
146
179
  const bundleId = options.manifestPath ? undefined : options.targetBundleId;
147
180
  let manifest, routes;
148
181
  if (options.manifestPath) ({ manifest, routes } = await readVerifiedBundle(options.manifestPath, options.manifestSha256));
149
182
  else await releasePin(bundleId, dependencies.pins);
150
- const assets = await readPackageWasm(options.wasmDir);
183
+ if (!options.config) throw new Error('Batch configuration required');
184
+ const assets = new Map();
151
185
  const runtimeRoot = options.runtimeRoot ?? dirname(fileURLToPath(import.meta.url));
152
186
  for (const name of ['host.mjs', 'python-worker.mjs', 'rust-worker.mjs']) {
153
187
  try { assets.set('/' + name, await readFile(join(runtimeRoot, name))); }
@@ -167,11 +201,6 @@ export async function runTargetBrowser(options, dependencies = {}) {
167
201
  if (!file.startsWith(workspace + sep)) throw new Error('Target file escapes workspace');
168
202
  return file;
169
203
  };
170
- const read = async path => {
171
- const file = await realpath(contained(path));
172
- if (!file.startsWith(workspace + sep)) throw new Error('Target read escapes workspace');
173
- return readFile(file, 'utf8');
174
- };
175
204
  const markers = new Map();
176
205
  const write = async (path, content) => {
177
206
  if (!path.startsWith('output/')) throw new Error('Target workers may only write workspace outputs');
@@ -196,7 +225,6 @@ export async function runTargetBrowser(options, dependencies = {}) {
196
225
  };
197
226
  let progressWrites = Promise.resolve();
198
227
  const progress = value => {
199
- if (options.operation !== 'batch') return Promise.resolve();
200
228
  // Download callbacks can overlap. Preserve ordering through the final status.
201
229
  // Status readers poll this file: write a new file and rename it over the old, so none sees it truncated.
202
230
  const file = `output/progress_${jobId}.json`;
@@ -232,6 +260,11 @@ export async function runTargetBrowser(options, dependencies = {}) {
232
260
  onProgress: (completed, total) => { void progress({ status: 'running', stage: 'download', completed, total }); } });
233
261
  ({ manifest, routes } = await readVerifiedBundle(resolved.manifestPath, resolved.manifestSha256));
234
262
  }
263
+ // ponytail: every prepared job is held in memory and served to the page at once; stream them if batches outgrow that.
264
+ const jobs = await (dependencies.prepareJobs ?? prepareJobs)({ ...options, jobId, startedAt }, manifest, routes,
265
+ // A signal during preparation stops it at the next scenario, as a signal during the run closes Chrome.
266
+ prepared => { if (interrupted) throw interrupted; return progress({ status: 'running', stage: 'prepare', completed: prepared }); }, dependencies);
267
+ assets.set('/prepared-jobs.json', Buffer.from(JSON.stringify(jobs)));
235
268
  for (const [route, bytes] of assets) routes.set(route, bytes);
236
269
  server = createServer((req, res) => {
237
270
  res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
@@ -251,7 +284,6 @@ export async function runTargetBrowser(options, dependencies = {}) {
251
284
  const page = await browser.newPage();
252
285
  forwardPanicLines(page);
253
286
  await page.route('**/*', route => route.request().url().startsWith(origin + '/') ? route.continue() : route.abort());
254
- await page.exposeFunction('targetCliRead', read);
255
287
  await page.exposeFunction('targetCliWrite', write);
256
288
  await page.exposeFunction('targetCliProgress', progress);
257
289
  await progress({ status: 'running', progress: 0 });
@@ -262,7 +294,7 @@ export async function runTargetBrowser(options, dependencies = {}) {
262
294
  const { run } = await import('/host.mjs');
263
295
  return { result: await run(request) };
264
296
  } catch (error) { return { error: error instanceof Error ? error.message : String(error) }; }
265
- }, { manifest, operation: options.operation, csv: options.csv, config: options.config, configName: options.configName, jobId, startedAt, wasmRemedy: options.wasmRemedy });
297
+ }, { manifest, jobsUrl: '/prepared-jobs.json', jobId });
266
298
  if (interrupted) throw interrupted;
267
299
  if ('error' in outcome) throw new Error(outcome.error);
268
300
  const { result } = outcome;