@moldesk/adapters 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bindcraft2/index.d.ts +2 -0
  3. package/dist/bindcraft2/index.js +348 -0
  4. package/dist/bindcraft2/index.test.d.ts +1 -0
  5. package/dist/bindcraft2/index.test.js +232 -0
  6. package/dist/boltz/index.d.ts +2 -0
  7. package/dist/boltz/index.js +285 -0
  8. package/dist/boltz/index.test.d.ts +1 -0
  9. package/dist/boltz/index.test.js +368 -0
  10. package/dist/catalog.d.ts +6 -0
  11. package/dist/catalog.js +37 -0
  12. package/dist/catalog.test.d.ts +1 -0
  13. package/dist/catalog.test.js +33 -0
  14. package/dist/diffdock/index.d.ts +2 -0
  15. package/dist/diffdock/index.js +470 -0
  16. package/dist/diffdock/index.test.d.ts +1 -0
  17. package/dist/diffdock/index.test.js +595 -0
  18. package/dist/index.d.ts +121 -0
  19. package/dist/index.js +2 -0
  20. package/dist/ligandmpnn/index.d.ts +2 -0
  21. package/dist/ligandmpnn/index.js +80 -0
  22. package/dist/ligandmpnn/index.test.d.ts +1 -0
  23. package/dist/ligandmpnn/index.test.js +85 -0
  24. package/dist/opendde/index.d.ts +2 -0
  25. package/dist/opendde/index.js +551 -0
  26. package/dist/opendde/index.test.d.ts +1 -0
  27. package/dist/opendde/index.test.js +577 -0
  28. package/dist/outputs.d.ts +8 -0
  29. package/dist/outputs.js +79 -0
  30. package/dist/outputs.test.d.ts +1 -0
  31. package/dist/outputs.test.js +69 -0
  32. package/dist/params.d.ts +13 -0
  33. package/dist/params.js +69 -0
  34. package/dist/params.test.d.ts +1 -0
  35. package/dist/params.test.js +41 -0
  36. package/dist/planned.d.ts +1 -0
  37. package/dist/planned.js +9 -0
  38. package/dist/proteinmpnn/index.d.ts +2 -0
  39. package/dist/proteinmpnn/index.js +84 -0
  40. package/dist/proteinmpnn/index.test.d.ts +1 -0
  41. package/dist/proteinmpnn/index.test.js +101 -0
  42. package/package.json +32 -3
  43. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pourya Kalantari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ import type { ModelAdapterDefinition } from "../index.js";
2
+ export declare const bindcraft2Adapter: ModelAdapterDefinition;
@@ -0,0 +1,348 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { MoldeskError } from "@moldesk/registry";
4
+ import { runCommand } from "@moldesk/runtime";
5
+ import { collectGlobOutputs } from "../outputs.js";
6
+ const MODALITIES = ["binder", "peptide", "cyclic_peptide", "VHH", "ARP"];
7
+ const RESOLVED = "moldesk-campaign.json";
8
+ const SUMMARY = "moldesk-summary.json";
9
+ const AF_MODELS = ["model_1_multimer_v3", "model_2_multimer_v3", "model_3_multimer_v3", "model_4_multimer_v3", "model_5_multimer_v3", "model_1_ptm", "model_2_ptm"];
10
+ const AF_HASHES = {
11
+ "model_1_multimer_v3": {
12
+ "size": 373043148,
13
+ "sha256": "611da8fc7478928f68de12e8b226260ef1f4ce62bcc29b008572e52f4f212959"
14
+ },
15
+ "model_2_multimer_v3": {
16
+ "size": 373043148,
17
+ "sha256": "51362b0844382ae0f5720c59b81dd13a43eea40fbf9995dd2573bdab88865378"
18
+ },
19
+ "model_3_multimer_v3": {
20
+ "size": 373043148,
21
+ "sha256": "46d9bcad288edc7ad5a6362ee8e5f84307a69712e00e6c36b1ef9daf96ebc9ce"
22
+ },
23
+ "model_4_multimer_v3": {
24
+ "size": 373043148,
25
+ "sha256": "59bdabd2d69c07fe26b37882d544acbd1b9f89f196828f4220da49e0610b572c"
26
+ },
27
+ "model_5_multimer_v3": {
28
+ "size": 373043148,
29
+ "sha256": "917742be5a105d6b80f13f1f13f20459f27ec3fdcd34ea088b359f4502d6177f"
30
+ },
31
+ "model_1_ptm": {
32
+ "size": 373103340,
33
+ "sha256": "5e564f79af5bcd54ccef6e2a6bb0ff01015d01650ebc41d4575e35f0de9ecc84"
34
+ },
35
+ "model_2_ptm": {
36
+ "size": 373103340,
37
+ "sha256": "23645d9a82c4af2ed54cd48a7b3c1c2575dc6aa9fe931adb4d7203ca5f0dc398"
38
+ }
39
+ };
40
+ const MPNN_HASHES = {
41
+ neutral: "58db738bbf867ca9b9290ce3a6581b94649f108683ac0e6a10de6b4aeeed30b4",
42
+ negative: "b166276f80a45cb3de24bceb3b47b2f47a60ff654660f09837cd775846411ad1",
43
+ positive: "9b8b55fcb8a428ba85f583be828d1a8d14ab2fe0e02474979c3dcbae146795f5",
44
+ };
45
+ const OUTPUTS = [
46
+ { id: "campaign", glob: RESOLVED, required: true },
47
+ { id: "metadata", glob: "campaign_metadata.json", required: true },
48
+ { id: "trajectories", glob: "1_Trajectories/!_Trajectories.csv", required: true },
49
+ { id: "trajectory_structures", glob: "1_Trajectories/*/*.cif", required: false },
50
+ { id: "refolded", glob: "2_Refolded/!_Refolded.csv", required: false },
51
+ { id: "refolded_structures", glob: "2_Refolded/*.cif", required: false },
52
+ { id: "ranked", glob: "3_Ranked/!_Ranked.csv", required: false },
53
+ { id: "accepted_structures", glob: "3_Ranked/*.cif", required: false },
54
+ { id: "upstream_summary", glob: "summary.csv", required: true },
55
+ { id: "summary", glob: SUMMARY, required: false },
56
+ ];
57
+ const EXTENSIONS = [".pdb", ".cif", ".mmcif", ".fa", ".fasta"];
58
+ const KEYS = new Set(["targets", "modality", "binder_lengths", "binder_scaffold", "number_of_final_designs", "max_trajectories", "project_folder", "resume", "auto_multi_gpu", "design_workers", "campaign_seed"]);
59
+ const TARGET_KEYS = new Set(["name", "target_path", "chains", "hotspots", "coldspots", "objective", "weight"]);
60
+ function fail(message, code = "INVALID_RUN_INPUT") {
61
+ throw new MoldeskError({ code, message, remediation: "Use examples/bindcraft2/campaign.json; provide explicit targets and positive finite design/trajectory bounds." });
62
+ }
63
+ function object(value) { return !!value && typeof value === "object" && !Array.isArray(value); }
64
+ function positive(value) { return typeof value === "number" && Number.isSafeInteger(value) && value > 0; }
65
+ function parse(input) {
66
+ if (path.extname(input).toLowerCase() !== ".json")
67
+ fail("BindCraft2 requires a .json campaign.");
68
+ let raw;
69
+ try {
70
+ raw = JSON.parse(fs.readFileSync(input, "utf8"));
71
+ }
72
+ catch {
73
+ fail("BindCraft2 campaign is missing or invalid JSON.");
74
+ }
75
+ if (!object(raw) || !Array.isArray(raw.targets) || raw.targets.length === 0)
76
+ fail("BindCraft2 requires a non-empty explicit targets list.");
77
+ for (const key of Object.keys(raw))
78
+ if (!KEYS.has(key))
79
+ fail(`Unsupported BindCraft2 campaign field: ${key}.`);
80
+ const names = new Set();
81
+ for (const target of raw.targets) {
82
+ if (!object(target))
83
+ fail("Each target must be an object.");
84
+ for (const key of Object.keys(target))
85
+ if (!TARGET_KEYS.has(key))
86
+ fail(`Unsupported target field: ${key}.`);
87
+ if (typeof target.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(target.name) || names.has(target.name))
88
+ fail("Target names must be unique safe identifiers.");
89
+ names.add(target.name);
90
+ if (typeof target.target_path !== "string" || !EXTENSIONS.includes(path.extname(target.target_path).toLowerCase()))
91
+ fail("Each target needs a PDB/mmCIF/FASTA target_path.");
92
+ for (const key of ["chains", "hotspots", "coldspots"])
93
+ if (target[key] !== undefined && (typeof target[key] !== "string" || !target[key]))
94
+ fail(`Target ${key} must be a non-empty string.`);
95
+ if (target.objective !== undefined && !["target", "detarget"].includes(String(target.objective)))
96
+ fail("Unsupported target objective.");
97
+ if (target.weight !== undefined && (typeof target.weight !== "number" || !Number.isFinite(target.weight) || target.weight <= 0))
98
+ fail("Target weight must be finite and positive.");
99
+ }
100
+ if (raw.binder_scaffold !== undefined && (typeof raw.binder_scaffold !== "string" || ![".pdb", ".cif", ".mmcif"].includes(path.extname(raw.binder_scaffold).toLowerCase())))
101
+ fail("binder_scaffold must reference a PDB/mmCIF file.");
102
+ if (raw.project_folder !== undefined && typeof raw.project_folder !== "string")
103
+ fail("project_folder must be a string; MoleculeDesk replaces it with run output.");
104
+ if (raw.campaign_seed !== undefined && (typeof raw.campaign_seed !== "number" || !Number.isSafeInteger(raw.campaign_seed) || raw.campaign_seed < 0 || raw.campaign_seed > 0xffffffff))
105
+ fail("campaign_seed must be an integer in [0, 2^32-1].");
106
+ if (raw.resume !== undefined && raw.resume !== false)
107
+ fail("Resume is not supported; every MoleculeDesk campaign starts a fresh run.");
108
+ if (raw.auto_multi_gpu !== undefined && raw.auto_multi_gpu !== false)
109
+ fail("Automatic worker spawning is not supported.");
110
+ if (raw.design_workers !== undefined && raw.design_workers !== 1)
111
+ fail("Only one design worker is supported.");
112
+ if (!raw.targets.some((t) => t.objective !== "detarget"))
113
+ fail("Campaign needs at least one positive target.");
114
+ return raw;
115
+ }
116
+ function refs(job) {
117
+ const result = job.targets.map((t, i) => ({ id: `target-${i}`, sourcePath: t.target_path }));
118
+ if (job.binder_scaffold)
119
+ result.push({ id: "scaffold", sourcePath: job.binder_scaffold });
120
+ return result;
121
+ }
122
+ function checkReference(input, ref) {
123
+ const root = fs.realpathSync(path.dirname(input));
124
+ const requested = path.resolve(path.dirname(input), ref.sourcePath);
125
+ if (ref.sourcePath.split(/[\\/]/).includes(".."))
126
+ fail(`Traversal in companion: ${ref.id}.`);
127
+ let file;
128
+ try {
129
+ file = fs.realpathSync(requested);
130
+ }
131
+ catch {
132
+ fail(`Missing companion: ${ref.id}.`);
133
+ }
134
+ if (!file.startsWith(root + path.sep))
135
+ fail(`Companion escapes campaign directory: ${ref.id}.`);
136
+ const stat = fs.statSync(file);
137
+ if (!stat.isFile() || stat.size === 0)
138
+ fail(`Companion must be a non-empty regular file: ${ref.id}.`);
139
+ }
140
+ function bounded(job, params) {
141
+ const resolved = structuredClone(job);
142
+ for (const key of ["modality", "number_of_final_designs", "max_trajectories", "resume"])
143
+ if (params[key] !== undefined)
144
+ resolved[key] = params[key];
145
+ if (params.min_length !== undefined || params.max_length !== undefined) {
146
+ if (params.min_length === undefined || params.max_length === undefined)
147
+ fail("Pass both min_length and max_length.", "INVALID_RUN_PARAMS");
148
+ resolved.binder_lengths = [params.min_length, params.max_length];
149
+ }
150
+ if (!positive(resolved.number_of_final_designs) || !positive(resolved.max_trajectories))
151
+ fail("number_of_final_designs and max_trajectories must be positive integers.", "INVALID_RUN_PARAMS");
152
+ resolved.modality ??= "binder";
153
+ if (typeof resolved.modality !== "string" || !MODALITIES.includes(resolved.modality))
154
+ fail("Unsupported modality or modality combination.", "INVALID_RUN_PARAMS");
155
+ const scaffolded = ["VHH", "ARP"].includes(resolved.modality);
156
+ if (scaffolded && (resolved.binder_lengths !== undefined || resolved.binder_scaffold !== undefined))
157
+ fail("VHH/ARP use their pinned shipped scaffold; omit custom scaffold and lengths.", "INVALID_RUN_PARAMS");
158
+ if (!scaffolded && resolved.binder_scaffold && resolved.binder_lengths !== undefined)
159
+ fail("Custom scaffold determines binder length; omit binder_lengths.", "INVALID_RUN_PARAMS");
160
+ if (!scaffolded && !resolved.binder_scaffold) {
161
+ const lengths = resolved.binder_lengths;
162
+ if (!Array.isArray(lengths) || lengths.length !== 2 || !lengths.every(positive) || lengths[0] > lengths[1])
163
+ fail("binder_lengths must be an ordered positive integer pair.", "INVALID_RUN_PARAMS");
164
+ if (["peptide", "cyclic_peptide"].includes(resolved.modality) && lengths[1] >= 25)
165
+ fail("Peptide lengths must be below 25 residues.", "INVALID_RUN_PARAMS");
166
+ }
167
+ if (resolved.resume !== undefined && resolved.resume !== false)
168
+ fail("Resume is not supported.", "INVALID_RUN_PARAMS");
169
+ resolved.resume = false;
170
+ resolved.auto_multi_gpu = false;
171
+ resolved.design_workers = 1;
172
+ return resolved;
173
+ }
174
+ function environment(modelDir, assetsDir, cache) {
175
+ return {
176
+ PYTHONPATH: path.join(modelDir, "source"), PYTHONNOUSERSITE: "1",
177
+ BINDCRAFT_AF2_PARAMS: path.join(assetsDir, "alphafold"),
178
+ BINDCRAFT_MPNN_WEIGHTS: path.join(modelDir, "source/bindcraft/weights/proteinmpnn/weights_neutral"),
179
+ BINDCRAFT_WEIGHTS: assetsDir, XDG_CACHE_HOME: cache,
180
+ JAX_COMPILATION_CACHE_DIR: path.join(cache, "jax"), JAX_PLATFORMS: "cuda",
181
+ MPLCONFIGDIR: path.join(cache, "matplotlib"), LD_LIBRARY_PATH: "",
182
+ };
183
+ }
184
+ // Reset inherited upstream knobs before importing its CLI; neither worker identity
185
+ // nor an operator environment may bypass the bounded single-process campaign.
186
+ const CLEAN_ENV = `
187
+ import os
188
+ os.environ.pop('JAX_SKIP_CUDA_CONSTRAINTS_CHECK', None)
189
+ for key in tuple(os.environ):
190
+ if key.startswith('BINDCRAFT_') and key not in ('BINDCRAFT_AF2_PARAMS', 'BINDCRAFT_MPNN_WEIGHTS', 'BINDCRAFT_WEIGHTS'):
191
+ del os.environ[key]
192
+ `;
193
+ const CHECK_WEIGHTS = `
194
+ import hashlib, json, pathlib, zipfile
195
+ from bindcraft.model_weights import model_weights, missing_model_weights, alphafold_parameter_file
196
+ parameters, mpnn = model_weights(download=False)
197
+ assert not missing_model_weights(parameters, mpnn), missing_model_weights(parameters, mpnn)
198
+ for variant, expected in ${JSON.stringify(MPNN_HASHES)}.items():
199
+ file = pathlib.Path(mpnn).parent / ('weights_' + variant) / 'v_48_020.npz'
200
+ assert hashlib.sha256(file.read_bytes()).hexdigest() == expected, f'corrupt MPNN weights: {variant}'
201
+ for model, expected in ${JSON.stringify(AF_HASHES)}.items():
202
+ file = pathlib.Path(alphafold_parameter_file(parameters, model))
203
+ assert file.stat().st_size == expected['size'], f'wrong AlphaFold checkpoint size: {model}'
204
+ digest = hashlib.sha256()
205
+ with file.open('rb') as stream:
206
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''): digest.update(chunk)
207
+ assert digest.hexdigest() == expected['sha256'], f'corrupt AlphaFold checkpoint: {model}'
208
+ with zipfile.ZipFile(file) as checkpoint:
209
+ assert checkpoint.namelist(), f'empty AlphaFold checkpoint: {model}'
210
+ `;
211
+ const GPU_PROBE = `
212
+ import jax
213
+ assert jax.default_backend() == 'gpu', 'BindCraft2 requires JAX CUDA; CPU fallback refused'
214
+ assert jax.devices() and all(d.platform == 'gpu' for d in jax.devices()), 'no CUDA devices'
215
+ assert float(jax.numpy.arange(4, dtype=jax.numpy.float32).sum().block_until_ready()) == 6.0
216
+ print('BindCraft2 JAX CUDA:', jax.devices(), flush=True)
217
+ `;
218
+ const LAUNCH = `${CLEAN_ENV}\n${CHECK_WEIGHTS}\n${GPU_PROBE}\nfrom bindcraft.cli import main\nmain()`;
219
+ // csv.DictReader handles upstream's quoted sequences/metadata without duplicating
220
+ // a CSV parser in TypeScript. Paths arrive via argv, never script interpolation.
221
+ const RESULT_PROBE = `
222
+ import csv, json, pathlib, re, sys
223
+ root = pathlib.Path(sys.argv[1]).resolve()
224
+ campaign = json.loads((root / '${RESOLVED}').read_text())
225
+ assert isinstance(json.loads((root / 'campaign_metadata.json').read_text()), dict)
226
+ def table(file):
227
+ assert file.resolve().is_relative_to(root.resolve()) and not any(p.is_symlink() for p in (file, *file.parents)), f'unsafe output: {file}'
228
+ with file.open(newline='') as stream:
229
+ reader = csv.DictReader(stream)
230
+ assert reader.fieldnames and len(set(reader.fieldnames)) == len(reader.fieldnames), f'invalid CSV: {file}'
231
+ rows = list(reader)
232
+ assert all(None not in row and all(v is not None for v in row.values()) for row in rows), f'malformed CSV: {file}'
233
+ return reader.fieldnames, rows
234
+ fields, trajectories = table(root / '1_Trajectories/!_Trajectories.csv')
235
+ assert 'design' in fields and 'trajectory' in fields and trajectories, 'no completed trajectories'
236
+ _, rows = table(root / 'summary.csv')
237
+ counts = {r['metric']: float(r['mean']) for r in rows if r.get('scope') == 'campaign' and r.get('metric') in ('trajectories', 'accepted_designs')}
238
+ attempted, accepted = counts['trajectories'], counts['accepted_designs']
239
+ assert attempted.is_integer() and accepted.is_integer() and attempted > 0 and accepted >= 0, 'invalid campaign counts'
240
+ assert attempted <= campaign['max_trajectories'], 'trajectory budget exceeded'
241
+ assert attempted >= len(trajectories), 'inconsistent trajectory summary'
242
+ ranked = root / '3_Ranked/!_Ranked.csv'
243
+ if ranked.is_file():
244
+ fields, ranks = table(ranked)
245
+ assert 'design' in fields and 'rank' in fields, 'invalid ranked table'
246
+ assert len(ranks) == accepted, 'inconsistent accepted count'
247
+ assert [int(row['rank']) for row in ranks] == list(range(1, len(ranks) + 1)), 'invalid ranks'
248
+ assert len({row['design'] for row in ranks}) == len(ranks), 'duplicate accepted designs'
249
+ for row in ranks:
250
+ design = row['design']
251
+ assert re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*', design), 'unsafe design name'
252
+ files = list(ranked.parent.glob(design + '.cif')) + list(ranked.parent.glob(design + '_*.cif'))
253
+ assert any(f.name not in (design + '_monomer.cif',) and not f.is_symlink() and f.is_file() for f in files), f'missing accepted structure: {design}'
254
+ else:
255
+ assert accepted == 0, 'accepted designs missing ranked table'
256
+ assert accepted >= campaign['number_of_final_designs'] or attempted == campaign['max_trajectories'], 'campaign stopped before its budget or goal'
257
+ refolded = root / '2_Refolded/!_Refolded.csv'
258
+ if refolded.is_file(): table(refolded)
259
+ for filename in sys.argv[2:]:
260
+ from biotite.structure.io import pdbx
261
+ import numpy as np
262
+ structure = pdbx.get_structure(pdbx.CIFFile.read(filename), model=1)
263
+ assert len(structure) > 0 and np.isfinite(structure.coord).all(), f'invalid structure: {filename}'
264
+ print(json.dumps({'attempted': int(attempted), 'accepted': int(accepted), 'requested': campaign['number_of_final_designs'], 'budget': campaign['max_trajectories'], 'budgetExhausted': attempted == campaign['max_trajectories'], 'goalReached': accepted >= campaign['number_of_final_designs']}))
265
+ `;
266
+ export const bindcraft2Adapter = {
267
+ modelName: "bindcraft2",
268
+ params: [
269
+ { name: "modality", type: "string", enum: MODALITIES, description: "Binder format" },
270
+ { name: "number_of_final_designs", type: "number", min: 1, description: "Requested accepted designs" },
271
+ { name: "max_trajectories", type: "number", min: 1, description: "Required finite attempt budget" },
272
+ { name: "min_length", type: "number", min: 1 }, { name: "max_length", type: "number", min: 1 },
273
+ { name: "resume", type: "boolean", description: "Only false supported; each run is fresh" },
274
+ ],
275
+ async validateInput(inputPath) {
276
+ const job = parse(inputPath);
277
+ for (const ref of refs(job))
278
+ checkReference(inputPath, ref);
279
+ },
280
+ async resolveCompanionInputs(inputPath) { return refs(parse(inputPath)); },
281
+ async installPlan() { return { steps: [{ id: "dependencies", description: "Install pinned BindCraft2 and CUDA/JAX dependencies" }, { id: "assets", description: "Verify managed AlphaFold and shipped MPNN weights" }, { id: "verify", description: "Check presets, CLI, weights and real JAX CUDA operation" }] }; },
282
+ async command(context) {
283
+ if (context.platform !== "linux-x64")
284
+ fail("BindCraft2 requires the Linux x64 CUDA installation.", "INVALID_RUN_PARAMS");
285
+ const job = bounded(parse(context.inputPath), context.params);
286
+ const staged = new Map(context.companionInputs?.map((r) => [r.id, r.path]));
287
+ for (const ref of refs(job)) {
288
+ const file = staged.get(ref.id);
289
+ const inputRoot = fs.realpathSync(path.dirname(context.inputPath));
290
+ if (!file || !fs.existsSync(file) || fs.lstatSync(file).isSymbolicLink() || !fs.statSync(file).isFile() || !fs.realpathSync(file).startsWith(inputRoot + path.sep))
291
+ fail(`Missing or unsafe staged companion: ${ref.id}.`);
292
+ if (ref.id === "scaffold")
293
+ job.binder_scaffold = file;
294
+ else
295
+ job.targets[Number(ref.id.slice(7))].target_path = file;
296
+ }
297
+ job.project_folder = context.outputDir;
298
+ const campaignPath = path.join(context.outputDir, RESOLVED);
299
+ fs.writeFileSync(campaignPath, `${JSON.stringify(job, null, 2)}\n`, { flag: "wx" });
300
+ // Keep working caches beside output, not in collected scientific results.
301
+ const cache = path.join(path.dirname(context.outputDir), "cache");
302
+ return { executable: context.runtimeExecutable, args: ["-c", LAUNCH, "design", campaignPath], env: environment(context.modelDir, context.assetsDir, cache) };
303
+ },
304
+ async collectOutputs(context) {
305
+ const collected = collectGlobOutputs(context.outputDir, OUTPUTS);
306
+ const structures = collected.filter((o) => o.id.endsWith("structures"));
307
+ for (const output of structures) {
308
+ const text = fs.readFileSync(output.path, "utf8");
309
+ if (!/^data_\S+/m.test(text) || !text.includes("_atom_site."))
310
+ fail(`Invalid mmCIF output: ${output.path}.`, "INVALID_RUN_OUTPUT");
311
+ }
312
+ const result = await (context.runner ?? runCommand)(context.runtimeExecutable, ["-c", RESULT_PROBE, context.outputDir, ...structures.map((s) => s.path)], {
313
+ cwd: context.outputDir, timeoutMs: 60_000,
314
+ env: { ...process.env, ...environment(context.modelDir, context.assetsDir, path.join(path.dirname(context.outputDir), "cache")) },
315
+ });
316
+ if (result.code !== 0)
317
+ fail(`Invalid BindCraft2 campaign results: ${result.stderr.slice(-1000)}.`, "INVALID_RUN_OUTPUT");
318
+ let summary;
319
+ try {
320
+ summary = JSON.parse(result.stdout);
321
+ }
322
+ catch {
323
+ fail("BindCraft2 result parser returned invalid JSON.", "INVALID_RUN_OUTPUT");
324
+ }
325
+ if (!object(summary) || !Number.isSafeInteger(summary.accepted) || summary.accepted < 0)
326
+ fail("Invalid accepted design count.", "INVALID_RUN_OUTPUT");
327
+ if (summary.accepted > 0 && !collected.some((o) => o.id === "accepted_structures"))
328
+ fail("Accepted designs have no structures.", "INVALID_RUN_OUTPUT");
329
+ fs.writeFileSync(path.join(context.outputDir, SUMMARY), `${JSON.stringify(summary, null, 2)}\n`, { flag: "wx" });
330
+ return collectGlobOutputs(context.outputDir, OUTPUTS);
331
+ },
332
+ async verifyInstallation(context) {
333
+ if (context.platform !== "linux-x64")
334
+ return { passed: false, output: "BindCraft2 supports Linux x64/NVIDIA only." };
335
+ const source = path.join(context.modelDir, "source");
336
+ const python = path.join(context.modelDir, ".venv/bin/python");
337
+ const required = [python, path.join(context.modelDir, ".venv/bin/bindcraft"), path.join(source, "settings/core/default.json"),
338
+ ...AF_MODELS.map((model) => path.join(context.assetsDir, "alphafold", `params_${model}.npz`)),
339
+ ...Object.keys(MPNN_HASHES).map((variant) => path.join(source, "bindcraft/weights/proteinmpnn", `weights_${variant}`, "v_48_020.npz"))];
340
+ // Managed venv interpreters can be symlinks to uv's managed Python.
341
+ for (const file of required)
342
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile())
343
+ return { passed: false, output: `Missing installation file: ${file}` };
344
+ const script = `${CLEAN_ENV}\nimport importlib.metadata, shutil, subprocess, sys\nassert importlib.metadata.version('bindcraft') == '1.0.3'\nassert importlib.metadata.version('jax') == '0.11.2'\nassert shutil.disk_usage(${JSON.stringify(context.modelDir)}).free >= 2 * 1024**3, 'at least 2 GiB free required for campaign results'\n${CHECK_WEIGHTS}\n${GPU_PROBE}\nsubprocess.run([sys.executable, '-m', 'bindcraft.selfcheck', 'cuda12'], check=True)\nsubprocess.run([sys.executable, '-m', 'bindcraft.cli', 'design', '--help'], check=True)`;
345
+ const result = await (context.runner ?? runCommand)(python, ["-c", script], { cwd: source, env: { ...process.env, ...environment(context.modelDir, context.assetsDir, path.join(context.modelDir, "cache")) }, timeoutMs: 300_000 });
346
+ return { passed: result.code === 0, output: `${result.stdout}\n${result.stderr}`.trim() };
347
+ },
348
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,232 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+ import { parse as parseYaml } from "yaml";
8
+ import { modelManifestV1Schema } from "@moldesk/registry";
9
+ import { stageCompanionInputs } from "@moldesk/runtime";
10
+ import { bindcraft2Adapter as adapter } from "./index.js";
11
+ let root;
12
+ let input;
13
+ let context;
14
+ const job = () => ({ targets: [{ name: "target", target_path: "target.pdb", chains: "A" }], modality: "binder", binder_lengths: [50, 60], number_of_final_designs: 1, max_trajectories: 2 });
15
+ function writeJob(value) { fs.writeFileSync(input, JSON.stringify(value)); }
16
+ beforeEach(() => {
17
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "bindcraft2-test-"));
18
+ input = path.join(root, "campaign.json");
19
+ fs.writeFileSync(path.join(root, "target.pdb"), "ATOM target\n");
20
+ writeJob(job());
21
+ context = { manifestName: "bindcraft2", inputPath: input, outputDir: path.join(root, "run/output"), modelDir: path.join(root, "model"), assetsDir: path.join(root, "model/assets"), runtimeExecutable: "python3", platform: "linux-x64", params: {} };
22
+ fs.mkdirSync(context.outputDir, { recursive: true });
23
+ });
24
+ afterEach(() => fs.rmSync(root, { recursive: true, force: true }));
25
+ async function stage() {
26
+ const inputDir = path.join(root, "run/input");
27
+ fs.mkdirSync(inputDir, { recursive: true });
28
+ const paths = stageCompanionInputs({ jobFilePath: input, refs: await adapter.resolveCompanionInputs(input), inputDir });
29
+ const copied = path.join(inputDir, "campaign.json");
30
+ fs.copyFileSync(input, copied);
31
+ context.inputPath = copied;
32
+ context.companionInputs = paths.map((p) => ({ id: p.id, path: p.storedPath }));
33
+ }
34
+ function output(relative, text) {
35
+ const file = path.join(context.outputDir, relative);
36
+ fs.mkdirSync(path.dirname(file), { recursive: true });
37
+ fs.writeFileSync(file, text);
38
+ }
39
+ function results(accepted = 0, attempted = 2) {
40
+ output("moldesk-campaign.json", JSON.stringify({ ...job(), project_folder: context.outputDir }));
41
+ output("campaign_metadata.json", "{}");
42
+ output("1_Trajectories/!_Trajectories.csv", 'design,trajectory,Timing\nfirst,1,"compile,design"\nsecond,2,"compile,design"\n');
43
+ output("summary.csv", `campaign,scope,metric,samples,mean,std,min,max\nx,campaign,trajectories,1,${attempted},0,${attempted},${attempted}\nx,campaign,accepted_designs,1,${accepted},0,${accepted},${accepted}\n`);
44
+ }
45
+ describe("BindCraft2 inputs and staging", () => {
46
+ it("accepts the checked-in bounded campaign", async () => {
47
+ await adapter.validateInput(fileURLToPath(new URL("../../../../examples/bindcraft2/campaign.json", import.meta.url)));
48
+ });
49
+ it.each([null, [], {}, { targets: [] }, { ...job(), arbitrary_file: "outside" }, { ...job(), target: "hPDL1" }, { ...job(), resume: true }, { ...job(), auto_multi_gpu: true }, { ...job(), design_workers: 2 }, { ...job(), campaign_seed: -1 }, { ...job(), binder_scaffold: "scaffold.exe" }, { ...job(), targets: [{ name: "../bad", target_path: "target.pdb" }] }, { ...job(), targets: [{ name: "target", target_path: "target.pdb", arbitrary_file: "outside" }] }, { ...job(), targets: [job().targets[0], job().targets[0]] }])("rejects malformed/unsupported campaign %#", async (value) => {
50
+ writeJob(value);
51
+ await expect(adapter.validateInput(input)).rejects.toBeDefined();
52
+ });
53
+ it.each(["missing.pdb", "../escape.pdb", "/etc/passwd", "target.exe"])('rejects unsafe/missing target "%s"', async (target_path) => {
54
+ writeJob({ ...job(), targets: [{ name: "target", target_path }] });
55
+ await expect(adapter.validateInput(input)).rejects.toBeDefined();
56
+ });
57
+ it("rejects empty files and ancestor symlinks escaping the job tree", async () => {
58
+ fs.writeFileSync(path.join(root, "target.pdb"), "");
59
+ await expect(adapter.validateInput(input)).rejects.toBeDefined();
60
+ fs.symlinkSync(os.tmpdir(), path.join(root, "outside"));
61
+ writeJob({ ...job(), targets: [{ name: "target", target_path: `outside/${path.basename(root)}/target.pdb` }] });
62
+ // A symlink to the same input tree is allowed; this target remains empty.
63
+ await expect(adapter.validateInput(input)).rejects.toBeDefined();
64
+ const escaped = path.join(os.tmpdir(), `escape-${path.basename(root)}.pdb`);
65
+ fs.writeFileSync(escaped, "ATOM outside\n");
66
+ try {
67
+ writeJob({ ...job(), targets: [{ name: "target", target_path: `outside/${path.basename(escaped)}` }] });
68
+ await expect(adapter.validateInput(input)).rejects.toBeDefined();
69
+ }
70
+ finally {
71
+ fs.unlinkSync(escaped);
72
+ }
73
+ });
74
+ it("stages every target and custom scaffold; command survives deleting originals", async () => {
75
+ fs.writeFileSync(path.join(root, "scaffold.cif"), "data_scaffold\n");
76
+ writeJob({ ...job(), binder_lengths: undefined, binder_scaffold: "scaffold.cif" });
77
+ await stage();
78
+ fs.unlinkSync(input);
79
+ fs.unlinkSync(path.join(root, "target.pdb"));
80
+ fs.unlinkSync(path.join(root, "scaffold.cif"));
81
+ await adapter.command(context);
82
+ const resolved = JSON.parse(fs.readFileSync(path.join(context.outputDir, "moldesk-campaign.json"), "utf8"));
83
+ expect(resolved.targets[0].target_path).toBe(context.companionInputs[0].path);
84
+ expect(resolved.binder_scaffold).toBe(context.companionInputs[1].path);
85
+ expect(resolved.project_folder).toBe(context.outputDir);
86
+ });
87
+ });
88
+ describe("BindCraft2 command", () => {
89
+ it("runs installed CLI module against managed source/assets with bounded single-worker settings", async () => {
90
+ await stage();
91
+ context.params = { max_trajectories: 1, number_of_final_designs: 2, min_length: 60, max_length: 70 };
92
+ const command = await adapter.command(context);
93
+ expect(command.executable).toBe(context.runtimeExecutable);
94
+ expect(command.args.slice(0, 1)).toEqual(["-c"]);
95
+ expect(command.args.slice(-2)).toEqual(["design", path.join(context.outputDir, "moldesk-campaign.json")]);
96
+ expect(command.args[1]).toContain("from bindcraft.cli import main");
97
+ expect(command.args[1]).toContain("del os.environ[key]");
98
+ expect(command.args[1]).toContain("model_weights(download=False)");
99
+ expect(command.args[1]).toContain("CPU fallback refused");
100
+ expect(command.env?.PYTHONPATH).toBe(path.join(context.modelDir, "source"));
101
+ expect(command.env?.JAX_PLATFORMS).toBe("cuda");
102
+ expect(command.env?.BINDCRAFT_AF2_PARAMS).toBe(path.join(context.assetsDir, "alphafold"));
103
+ const resolved = JSON.parse(fs.readFileSync(command.args.at(-1), "utf8"));
104
+ expect(resolved).toMatchObject({ max_trajectories: 1, number_of_final_designs: 2, binder_lengths: [60, 70], resume: false, auto_multi_gpu: false, design_workers: 1 });
105
+ });
106
+ it.each([{}, { max_trajectories: 0 }, { max_trajectories: 1.5 }, { max_trajectories: Number.MAX_SAFE_INTEGER + 1 }, { max_trajectories: 1, number_of_final_designs: -1 }, { max_trajectories: 1, modality: "binder,VHH" }, { max_trajectories: 1, min_length: 10 }, { max_trajectories: 1, min_length: 70, max_length: 60 }, { max_trajectories: 1, resume: true }])("rejects invalid effective params %#", async (params) => {
107
+ writeJob({ ...job(), max_trajectories: undefined });
108
+ await stage();
109
+ context.params = params;
110
+ await expect(adapter.command(context)).rejects.toBeDefined();
111
+ expect(fs.existsSync(path.join(context.outputDir, "moldesk-campaign.json"))).toBe(false);
112
+ });
113
+ it("rejects non-Linux installs and missing staged files", async () => {
114
+ await expect(adapter.command(context)).rejects.toBeDefined();
115
+ await stage();
116
+ context.platform = "darwin-arm64";
117
+ await expect(adapter.command(context)).rejects.toBeDefined();
118
+ });
119
+ it("rejects a staged reference whose ancestor symlink escapes immutable input", async () => {
120
+ await stage();
121
+ const link = path.join(path.dirname(context.inputPath), "escape");
122
+ fs.symlinkSync(root, link);
123
+ context.companionInputs[0].path = path.join(link, "target.pdb");
124
+ await expect(adapter.command(context)).rejects.toBeDefined();
125
+ });
126
+ it("accepts a shipped VHH scaffold and rejects conflicting lengths", async () => {
127
+ writeJob({ ...job(), modality: "VHH", binder_lengths: undefined });
128
+ await stage();
129
+ await expect(adapter.command(context)).resolves.toBeDefined();
130
+ fs.unlinkSync(path.join(context.outputDir, "moldesk-campaign.json"));
131
+ context.params = { min_length: 50, max_length: 60 };
132
+ await expect(adapter.command(context)).rejects.toBeDefined();
133
+ });
134
+ it("uses final installation paths after atomic relocation", async () => {
135
+ await stage();
136
+ context.modelDir = path.join(root, "promoted-install");
137
+ context.assetsDir = path.join(context.modelDir, "assets");
138
+ const command = await adapter.command(context);
139
+ expect(command.env?.PYTHONPATH).toBe(path.join(root, "promoted-install/source"));
140
+ expect(Object.values(command.env)).not.toContain(".partial");
141
+ });
142
+ });
143
+ describe("BindCraft2 manifest", () => {
144
+ const manifest = modelManifestV1Schema.parse(parseYaml(fs.readFileSync(fileURLToPath(new URL("../../../../models/bindcraft2/manifest.yaml", import.meta.url)), "utf8")));
145
+ it("stays planned, restricts Linux/NVIDIA and preserves exact hosting-restricted license", () => {
146
+ expect(manifest.status).toBe("planned");
147
+ expect(manifest.hardware.platforms).toEqual(["linux-x64"]);
148
+ expect(manifest.hardware.nvidiaGpu).toBe("required");
149
+ expect(manifest.license).toBe("BindCraft2 Source-Available License (Hosting-Restricted)");
150
+ expect(manifest.adapterVerification).toBeUndefined();
151
+ });
152
+ it("pins source, full dependency closure, binary accelerator artifacts and official archive", () => {
153
+ expect(manifest.source?.revision).toMatch(/^[0-9a-f]{40}$/);
154
+ const runtime = manifest.runtimes[0];
155
+ expect(runtime.kind).toBe("python");
156
+ if (runtime.kind !== "python")
157
+ throw new Error("expected Python runtime");
158
+ expect(runtime.python).toBe("3.12");
159
+ for (const requirement of runtime.requirements)
160
+ expect(requirement.version ?? requirement.revision).toBeTruthy();
161
+ for (const name of runtime.binaryOnly)
162
+ expect(runtime.requirements.find((r) => r.name === name)?.hashes).toHaveLength(1);
163
+ expect(runtime.requirements.find((r) => r.name === "bindcraft")).toMatchObject({ revision: manifest.source.revision, extras: ["cuda12"] });
164
+ expect(manifest.assets).toEqual([expect.objectContaining({ archive: "tar", target: "alphafold", sizeBytes: 5587968000, sha256: "36d4b0220f3c735f3296d301152b738c9776d16981d054845a68a1370b26cfe3" })]);
165
+ });
166
+ });
167
+ const hasPython = spawnSync("python3", ["--version"]).status === 0;
168
+ describe.skipIf(!hasPython)("BindCraft2 real result parser (stdlib Python)", () => {
169
+ it("accepts finite zero-design results and parses quoted CSV fields", async () => {
170
+ results();
171
+ const collected = await adapter.collectOutputs(context);
172
+ expect(collected.some((o) => o.id === "accepted_structures")).toBe(false);
173
+ expect(JSON.parse(fs.readFileSync(path.join(context.outputDir, "moldesk-summary.json"), "utf8"))).toMatchObject({ attempted: 2, accepted: 0, budgetExhausted: true, goalReached: false });
174
+ });
175
+ it.each(["missing metadata", "invalid metadata", "malformed csv", "over budget", "early stop", "missing accepted structure", "symlink ranked output"])("rejects %s", async (kind) => {
176
+ results();
177
+ if (kind === "missing metadata")
178
+ fs.unlinkSync(path.join(context.outputDir, "campaign_metadata.json"));
179
+ if (kind === "invalid metadata")
180
+ output("campaign_metadata.json", "[]");
181
+ if (kind === "malformed csv")
182
+ output("1_Trajectories/!_Trajectories.csv", "design,trajectory\nx,1,extra\n");
183
+ if (kind === "over budget")
184
+ results(0, 3);
185
+ if (kind === "early stop") {
186
+ results(0, 1);
187
+ output("1_Trajectories/!_Trajectories.csv", "design,trajectory\nx,1\n");
188
+ }
189
+ if (kind === "missing accepted structure") {
190
+ results(1);
191
+ output("3_Ranked/!_Ranked.csv", "design,rank\nx,1\n");
192
+ }
193
+ if (kind === "symlink ranked output") {
194
+ fs.mkdirSync(path.join(context.outputDir, "3_Ranked"));
195
+ fs.symlinkSync(input, path.join(context.outputDir, "3_Ranked/!_Ranked.csv"));
196
+ }
197
+ await expect(adapter.collectOutputs(context)).rejects.toBeDefined();
198
+ expect(fs.existsSync(path.join(context.outputDir, "moldesk-summary.json"))).toBe(false);
199
+ });
200
+ });
201
+ describe("BindCraft2 installation verification", () => {
202
+ it("rejects unsupported platform or missing installation files before running a probe", async () => {
203
+ const runner = vi.fn();
204
+ expect((await adapter.verifyInstallation({ ...context, manifestName: "bindcraft2", platform: "darwin-arm64", runner })).passed).toBe(false);
205
+ expect((await adapter.verifyInstallation({ ...context, manifestName: "bindcraft2", runner })).passed).toBe(false);
206
+ expect(runner).not.toHaveBeenCalled();
207
+ });
208
+ it("checks pinned package, MPNN digests, AlphaFold integrity, real CUDA operation, CLI and upstream self-check", async () => {
209
+ for (const relative of [".venv/bin/python", ".venv/bin/bindcraft", "source/settings/core/default.json",
210
+ ...[1, 2, 3, 4, 5].map((i) => `assets/alphafold/params_model_${i}_multimer_v3.npz`),
211
+ ...[1, 2].map((i) => `assets/alphafold/params_model_${i}_ptm.npz`),
212
+ ...["neutral", "negative", "positive"].map((v) => `source/bindcraft/weights/proteinmpnn/weights_${v}/v_48_020.npz`)]) {
213
+ const file = path.join(context.modelDir, relative);
214
+ fs.mkdirSync(path.dirname(file), { recursive: true });
215
+ fs.writeFileSync(file, "stub");
216
+ }
217
+ const runner = vi.fn(async () => ({ code: 0, stdout: "cuda ok", stderr: "" }));
218
+ expect((await adapter.verifyInstallation({ ...context, manifestName: "bindcraft2", runner })).passed).toBe(true);
219
+ const call = runner.mock.calls[0];
220
+ expect(call[1][1]).toContain("version('bindcraft') == '1.0.3'");
221
+ expect(call[1][1]).toContain("digest.hexdigest() == expected['sha256']");
222
+ expect(call[1][1]).toContain("default_backend() == 'gpu'");
223
+ expect(call[1][1]).toContain("bindcraft.selfcheck");
224
+ expect(call[2].env.JAX_PLATFORMS).toBe("cuda");
225
+ runner.mockResolvedValue({ code: 1, stdout: "", stderr: "no GPU" });
226
+ expect((await adapter.verifyInstallation({ ...context, manifestName: "bindcraft2", runner })).passed).toBe(false);
227
+ runner.mockClear();
228
+ fs.unlinkSync(path.join(context.assetsDir, "alphafold/params_model_1_ptm.npz"));
229
+ expect((await adapter.verifyInstallation({ ...context, manifestName: "bindcraft2", runner })).passed).toBe(false);
230
+ expect(runner).not.toHaveBeenCalled();
231
+ });
232
+ });
@@ -0,0 +1,2 @@
1
+ import type { ModelAdapterDefinition } from "../index.js";
2
+ export declare const boltzAdapter: ModelAdapterDefinition;