dsh-molbio-tools 0.28.0 → 0.28.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.
package/index.mjs CHANGED
@@ -155,7 +155,7 @@ import {
155
155
  batchColumns,
156
156
  batchTable,
157
157
  detectBatchFormat,
158
- globToRegExp,
158
+ globMatches,
159
159
  } from './batch.mjs';
160
160
  import { designSilentSite } from './silent-site.mjs';
161
161
  import { relative, sep } from 'node:path';
@@ -170,7 +170,7 @@ export const inject = ['tools', 'systemPrompt'];
170
170
  * validation itself: required presence, per-property types, enums, and nested
171
171
  * object/array shapes.
172
172
  */
173
- function validateArgsAgainstSchema(schema, args, label = '') {
173
+ function validateArgsAgainstSchema(schema, args) {
174
174
  if (typeof args !== 'object' || args === null || Array.isArray(args)) {
175
175
  throw new MolbioInputError('tool arguments must be an object');
176
176
  }
@@ -183,7 +183,12 @@ function validateArgsAgainstSchema(schema, args, label = '') {
183
183
  }
184
184
  if (schema.additionalProperties === false) {
185
185
  for (const key of Object.keys(args)) {
186
- if (!Object.hasOwn(properties, key)) violations.push(`unknown argument "${key}"`);
186
+ if (!Object.hasOwn(properties, key)) {
187
+ // Name the valid keys: a model that guesses `vector` for `sequence` should
188
+ // get the answer in the error, not a bare rejection (this is the exact
189
+ // confusion the region-extract benchmark recorded).
190
+ violations.push(`unknown argument "${key}" (valid: ${Object.keys(properties).join(', ')})`);
191
+ }
187
192
  }
188
193
  }
189
194
  if (violations.length > 0) throw new MolbioInputError(`invalid arguments: ${violations.join('; ')}`);
@@ -196,7 +201,10 @@ function validateArgsAgainstSchema(schema, args, label = '') {
196
201
  if (type === 'boolean' && typeof value !== 'boolean') throw new MolbioInputError(`invalid argument "${key}": expected a boolean`);
197
202
  if (type === 'array' && !Array.isArray(value)) throw new MolbioInputError(`invalid argument "${key}": expected an array`);
198
203
  if (type === 'object' && (typeof value !== 'object' || value === null || Array.isArray(value))) throw new MolbioInputError(`invalid argument "${key}": expected an object`);
199
- if (type === 'string' && node.enum !== undefined && !node.enum.includes(value)) throw new MolbioInputError(`invalid argument "${key}": must be one of ${node.enum.join(', ')}`);
204
+ // Enums apply to EVERY type, not just strings: `strand: {type:'integer',
205
+ // enum:[1,-1]}` used to accept 7 and -3, which the consumers then read as
206
+ // "forward" and "reverse" respectively.
207
+ if (node.enum !== undefined && !node.enum.includes(value)) throw new MolbioInputError(`invalid argument "${key}": must be one of ${node.enum.join(', ')}`);
200
208
  if (type === 'object' && node.properties !== undefined) {
201
209
  for (const childKey of node.required ?? []) {
202
210
  if (value[childKey] === undefined || value[childKey] === null) throw new MolbioInputError(`invalid argument "${key}.${childKey}": missing`);
@@ -204,6 +212,11 @@ function validateArgsAgainstSchema(schema, args, label = '') {
204
212
  for (const [childKey, child] of Object.entries(node.properties)) {
205
213
  if (value[childKey] !== undefined) check(child, value[childKey], `${key}.${childKey}`);
206
214
  }
215
+ if (node.additionalProperties === false) {
216
+ for (const childKey of Object.keys(value)) {
217
+ if (!Object.hasOwn(node.properties, childKey)) throw new MolbioInputError(`invalid argument "${key}.${childKey}": unknown`);
218
+ }
219
+ }
207
220
  }
208
221
  if (type === 'array' && node.items !== undefined) {
209
222
  for (let i = 0; i < value.length; i++) check(node.items, value[i], `${key}[${i}]`);
@@ -231,10 +244,17 @@ function validateArgsAgainstSchema(schema, args, label = '') {
231
244
  * the model — the same mechanism the harness's own `read_image` tool uses.
232
245
  */
233
246
  function define({ name: toolName, description, parameters, outputSchema, render, presentationMeta, execute, safe = true }) {
247
+ // Every tool rejects arguments it never declared. Leaving `additionalProperties`
248
+ // out made the validator's unknown-argument branch unreachable, so a misspelled
249
+ // call (`attach_imag`, `auto_vew`) ran with the default and still SUCCEEDED —
250
+ // the one failure mode that looks like a correct answer.
251
+ const declaredParameters = parameters.additionalProperties === undefined
252
+ ? { ...parameters, additionalProperties: false }
253
+ : parameters;
234
254
  return {
235
255
  name: toolName,
236
256
  description,
237
- parameters,
257
+ parameters: declaredParameters,
238
258
  output: {
239
259
  schema: outputSchema,
240
260
  render(_args, value) {
@@ -246,7 +266,7 @@ function define({ name: toolName, description, parameters, outputSchema, render,
246
266
  ...presentationMeta === undefined ? {} : { presentationMeta },
247
267
  },
248
268
  async execute(args, exec) {
249
- validateArgsAgainstSchema(parameters, args);
269
+ validateArgsAgainstSchema(declaredParameters, args);
250
270
  return execute(args, exec);
251
271
  },
252
272
  isConcurrencySafe: typeof safe === 'function' ? safe : () => safe,
@@ -278,6 +298,11 @@ function imageBlockFor(value) {
278
298
  };
279
299
  }
280
300
 
301
+ /** Note for a call that asked for a picture but passed no path to draw one. */
302
+ function attachImageWithoutPicture(args, hint) {
303
+ return args.attach_image === true ? { image_note: hint } : {};
304
+ }
305
+
281
306
  /** Human/model-facing note for a picture attached to (or missing from) a result. */
282
307
  function imageNote(value) {
283
308
  if (value?.image !== undefined) return ' The rendered PNG is attached to this result, so you can look at the picture directly.';
@@ -661,7 +686,7 @@ const translateTool = define({
661
686
 
662
687
  const restrictionTool = define({
663
688
  name: 'molbio_restriction_sites',
664
- description: 'Find restriction enzyme recognition sites in a sequence and compute the expected digestion fragments (linear or circular). Pass the enzyme names you care about, or ["common"] to scan every enzyme in the built-in table. Cut positions use the standard cut notation of each site (e.g. EcoRI G^AATTC).',
689
+ description: 'Find restriction enzyme recognition sites in a sequence and compute the expected digestion fragments (linear or circular). Pass the enzyme names you care about, or ["common"] to scan every enzyme in the built-in table. Cut positions use the standard cut notation of each site (e.g. EcoRI G^AATTC). With ["common"] only the enzymes that actually cut are listed — pass only_cutting: false for the full table, or name the enzymes you care about.',
665
690
  parameters: {
666
691
  type: 'object',
667
692
  required: ['sequence', 'enzymes'],
@@ -669,6 +694,7 @@ const restrictionTool = define({
669
694
  sequence: requiredString('DNA sequence to digest (IUPAC; ambiguous bases in the sequence are treated as no-match).'),
670
695
  enzymes: { type: 'array', items: { type: 'string' }, description: 'Enzyme names, or ["common"] for all built-in enzymes.' },
671
696
  circular: { type: 'boolean', description: 'True for circular DNA (plasmids): fragments wrap around the origin. Default false (linear).' },
697
+ only_cutting: { type: 'boolean', description: 'Report only enzymes that cut at least once. Defaults to true when `enzymes` is ["common"] (the whole table), which otherwise prints 100+ lines of "no sites"; pass false to see the full table.' },
672
698
  },
673
699
  },
674
700
  outputSchema: {
@@ -677,6 +703,8 @@ const restrictionTool = define({
677
703
  required: ['circular', 'enzymes'],
678
704
  properties: {
679
705
  circular: { type: 'boolean' },
706
+ only_cutting: { type: 'boolean' },
707
+ checked: { type: 'integer' },
680
708
  enzymes: {
681
709
  type: 'array',
682
710
  items: {
@@ -717,16 +745,22 @@ const restrictionTool = define({
717
745
  lines.push(` ${enzyme.fragments.length} fragment(s): ${enzyme.fragments.join(', ')} bp`);
718
746
  }
719
747
  }
748
+ if (value.only_cutting === true && value.checked !== undefined && value.checked > value.enzymes.length) {
749
+ lines.push(`note: showing only the ${value.enzymes.length} of ${value.checked} enzyme(s) that cut; pass only_cutting: false for the full table`);
750
+ }
720
751
  return lines.join('\n');
721
752
  },
722
753
  execute(args) {
723
754
  const seq = normalizeSequence(args.sequence);
724
755
  let enzymes = args.enzymes;
725
756
  if (!Array.isArray(enzymes) || enzymes.length === 0) throw new MolbioInputError('enzymes must be a non-empty array of enzyme names');
726
- if (enzymes.length === 1 && enzymes[0] === 'common') enzymes = ENZYME_NAMES;
757
+ const expandAll = enzymes.length === 1 && enzymes[0] === 'common';
758
+ if (expandAll) enzymes = ENZYME_NAMES;
727
759
  const circular = args.circular === true;
728
760
  const results = digest(seq, enzymes, circular);
729
- return { circular, enzymes: results };
761
+ const onlyCutting = args.only_cutting ?? expandAll;
762
+ const kept = onlyCutting ? results.filter((entry) => entry.cut_positions.length > 0) : results;
763
+ return { circular, enzymes: kept, only_cutting: onlyCutting, checked: results.length };
730
764
  },
731
765
  });
732
766
 
@@ -771,6 +805,7 @@ const enzymeLookupTool = define({
771
805
  enzymes: { type: 'array', items: { type: 'string' }, description: 'Enzyme names to look up; omit (or pass ["common"]) for the whole table, sorted.' },
772
806
  sequence: { type: 'string', description: 'Optional sequence (IUPAC) to count cuts and compute fragment sizes on.' },
773
807
  circular: { type: 'boolean', description: 'Treat the sequence as circular for the fragment math (default false).' },
808
+ only_cutting: { type: 'boolean', description: 'Report only enzymes that cut the given sequence at least once (default false). Use it when looking for alternatives — the full table prints 100+ enzymes.' },
774
809
  },
775
810
  },
776
811
  outputSchema: {
@@ -803,10 +838,12 @@ const enzymeLookupTool = define({
803
838
  : ENZYME_NAMES;
804
839
  const sequence = args.sequence !== undefined && args.sequence !== '' ? normalizeSequence(args.sequence) : undefined;
805
840
  const circular = args.circular === true;
841
+ let entries = names.map((name) => enzymeCatalog(name, sequence, circular));
842
+ if (args.only_cutting === true && sequence !== undefined) entries = entries.filter((entry) => (entry.cuts ?? 0) > 0);
806
843
  return {
807
- total: names.length,
844
+ total: entries.length,
808
845
  ...(sequence !== undefined ? { sequence_length: sequence.length, circular } : {}),
809
- enzymes: names.map((name) => enzymeCatalog(name, sequence, circular)),
846
+ enzymes: entries,
810
847
  };
811
848
  },
812
849
  });
@@ -1189,14 +1226,14 @@ const PRIMER_SCHEMA = {
1189
1226
  length: { type: 'integer' },
1190
1227
  tm: { type: 'number' },
1191
1228
  gc_percent: { type: 'number' },
1192
- self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score (v12).' },
1193
- self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score (v12).' },
1194
- hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none; v12).' },
1195
- end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol (v12).' },
1196
- end_gc_count: { type: 'integer', description: 'G/C bases among the last five 3\' bases (v12).' },
1197
- mismatch_count: { type: 'integer', description: 'Number of primer-template mismatches this primer carries (0 = exact match; v12).' },
1229
+ self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score.' },
1230
+ self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score.' },
1231
+ hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none).' },
1232
+ end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol.' },
1233
+ end_gc_count: { type: 'integer', description: 'G/C bases among the last five 3\' bases.' },
1234
+ mismatch_count: { type: 'integer', description: 'Number of primer-template mismatches this primer carries (0 = exact match).' },
1198
1235
  mismatches: { type: 'array', items: MISMATCH_SCHEMA },
1199
- mispriming_count: { type: 'integer', description: 'Extra template sites where the 3\' tail can anneal (v12 mispriming check).' },
1236
+ mispriming_count: { type: 'integer', description: 'Extra template sites where the 3\' tail can anneal (mispriming check).' },
1200
1237
  mispriming_sites: { type: 'array', items: MISPRIMING_SITE_SCHEMA },
1201
1238
  target_distance: { type: 'integer', description: 'v13: bp between the primer 3\' end and target_position (present only when target_position is given).' },
1202
1239
  },
@@ -1204,7 +1241,7 @@ const PRIMER_SCHEMA = {
1204
1241
 
1205
1242
  const designPrimersTool = define({
1206
1243
  name: 'molbio_design_primers',
1207
- description: 'Design PCR primer pairs on a template sequence. Scans for forward and reverse primers that satisfy Tm (SantaLucia 1998 NN; defaults 50 mM Na+, 1.5 mM Mg2+, 200 nM primer — adjustable via na_mm/mg_mm/dntp_mm/primer_nm), GC content, length, GC clamp (0-3 consecutive G/C at the 3\' end), mononucleotide-run, end-stability and Primer3-style structural constraints — self-complementarity (local alignment score, match +1/mismatch -1/gap -0.25), hairpin folding Tm and primer-dimer Tm (default 47 °C each, from the same NN parameters) — then ranks pairs inside the amplicon window (lower penalty is better). v12: pass max_mismatches > 0 to also allow primers with a few positional mismatches (never on the 3\'-terminal base, avoided in the 3\'-terminal critical zone by default; each is reported and penalized); pass check_mispriming: true to reject/penalize primers whose 3\' tail anneals at extra template sites. v13: pass target_position to prefer pairs whose nearer 3\' end lands close to that template position (SNP / site-directed design).',
1244
+ description: 'Design PCR primer pairs on a template. Scans forward and reverse primers that satisfy Tm (SantaLucia 1998 NN; defaults 50 mM Na+, 1.5 mM Mg2+, 200 nM primer — adjustable via na_mm/mg_mm/dntp_mm/primer_nm), GC content, length, GC clamp, mononucleotide runs, end stability and Primer3-style structural constraints (self-complementarity local alignment, hairpin and primer-dimer Tm at 47 °C), then ranks the pairs inside the amplicon window; lower penalty is better. One call returns the ranked pairs with their Tm, GC and penalties, so a follow-up primer_tm or primer_check pass is not needed. max_mismatches > 0 also allows a few positional mismatches (never at the 3\'-terminal base); check_mispriming penalises primers whose 3\' tail anneals at extra template sites; target_position prefers pairs whose nearer 3\' end lands close to that position. When nothing is returned, the parameters you set are the filters — relax the tightest one and call again.',
1208
1245
  parameters: {
1209
1246
  type: 'object',
1210
1247
  required: ['template'],
@@ -1422,7 +1459,7 @@ const CONDITIONS_SCHEMA = {
1422
1459
  const taqmanTool = (ctx) => define({
1423
1460
  safe: (args) => args.save_path === undefined || args.save_path === '',
1424
1461
  name: 'molbio_design_taqman',
1425
- description: 'Design a TaqMan (5\'-nuclease, hydrolysis probe) assay: it runs the standard primer-pair designer first (qPCR-sized amplicons, 70-200 bp by default), then places a probe inside the amplicon between the primers and applies the probe rules — no 5\' terminal G (it quenches the reporter), probe Tm at least min_tm_delta °C above the hotter primer, no mononucleotide run or repeat, bounded self-complementarity, and a check that the probe does not dimerize with either primer. Each assay reports the primer pair, the probe (sequence to order, position, orientation, Tm margin) and a transparent ranking penalty. Probe and primer Tm are the same SantaLucia-1998 nearest-neighbour estimates the other molbio tools use; they are design heuristics, not an efficiency prediction.',
1462
+ description: 'Design a TaqMan (5\'-nuclease, hydrolysis probe) assay: it runs the standard primer-pair designer first (qPCR-sized amplicons, 70-200 bp by default), then places a probe inside the amplicon between the primers and applies the probe rules — no 5\' terminal G (it quenches the reporter), probe Tm at least min_tm_delta °C above the hotter primer, no mononucleotide run or repeat, bounded self-complementarity, and a check that the probe does not dimerize with either primer. Each assay reports the primer pair, the probe (sequence to order, position, orientation, Tm margin) and a transparent ranking penalty. Probe and primer Tm are the same SantaLucia-1998 nearest-neighbour estimates the other molbio tools use; they are design heuristics, not an efficiency prediction. The probe-Tm margin RANKS candidate amplicons and is reported with each one: when the top assay\'s margin falls short of min_tm_delta the result says so — pass that note on instead of re-ranking or tightening the Tm window, unless the user explicitly asks for a stricter margin.',
1426
1463
  parameters: {
1427
1464
  type: 'object',
1428
1465
  required: ['sequence'],
@@ -1608,8 +1645,7 @@ const taqmanTool = (ctx) => define({
1608
1645
  let savedTo = '';
1609
1646
  if (args.save_path !== undefined && args.save_path !== '') {
1610
1647
  const fs = fsService(ctx);
1611
- const sandboxPolicyService = ctx.get('sandboxPolicy');
1612
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
1648
+ const policy = resolveSandboxPolicy(ctx, exec);
1613
1649
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
1614
1650
  await writeWorkspaceFile(fs, file, taqmanOrderCsv(order), policy);
1615
1651
  savedTo = file;
@@ -1636,7 +1672,7 @@ const MULTIPLEX_PRIMER_IN_SCHEMA = {
1636
1672
 
1637
1673
  const multiplexTool = define({
1638
1674
  name: 'molbio_multiplex_check',
1639
- description: 'Check whether several PCR primer pairs can be run together in one multiplex tube. It reports (1) every primer-primer interaction across the panel with the most stable (any) and 3\'-anchored duplex Tm, flagging the ones above the dimer threshold, (2) unintended annealing of each primer\'s 3\' tail — off-target sites in its own template and perfect matches in another target\'s template (the multiplex cross-reaction), and (3) amplicon sizes that are too close to resolve on a gel, plus concrete redesign advice. All Tms come from the same NN model as the primer designer and are risk estimates, not a prediction of the multiplex result.',
1675
+ description: 'Check whether several primer pairs can share one multiplex tube — one call answers the whole panel: every primer-primer interaction with the most stable (any) and 3\'-anchored duplex Tm (flagged above dimer_tm_threshold), unintended 3\'-tail annealing in the primer\'s own template and in the other targets\' templates, amplicon sizes too close to resolve on a gel, plus concrete redesign advice. Design the pairs first (molbio_design_primers) and pass them all in `targets`; do not pre-screen the panel pair-by-pair with align, primer_tm, primer_check or pcr_simulate — that recomputes what this call reports. Every Tm comes from the primer designer\'s NN model and is a risk estimate, not a prediction of the multiplex result.',
1640
1676
  parameters: {
1641
1677
  type: 'object',
1642
1678
  required: ['targets'],
@@ -2109,14 +2145,15 @@ function multiPartNote(features) {
2109
2145
  : `note: ${count} feature(s) have a multi-part location (join/order, or several segments); start-end is their OUTER bound and includes the gaps — read "location" for the parts.`;
2110
2146
  }
2111
2147
 
2112
- const parseGenbankTool = define({
2148
+ const parseGenbankTool = (ctx) => define({
2113
2149
  name: 'molbio_parse_genbank',
2114
2150
  description: 'Parse a GenBank flatfile record into structured data: locus name, accession, definition, topology (circular/linear), features (type, 1-based span, strand, label from /product or /gene), and the origin sequence. A feature whose location has several parts (join/order) comes back with `multi_part: true` and its original location string: `start`/`end` are then only the OUTER bounds and include the gaps, so read `location` before calling it a length. Feed the returned features to molbio_plasmid_map to draw the map.',
2115
2151
  parameters: {
2116
2152
  type: 'object',
2117
- required: ['genbank'],
2153
+ required: [],
2118
2154
  properties: {
2119
- genbank: requiredString('Complete GenBank record text (LOCUS ... //).'),
2155
+ genbank: { type: 'string', description: 'Complete GenBank record text (LOCUS ... //).' },
2156
+ path: { type: 'string', description: 'Workspace path to a .gb/.gbk file; alternative to `genbank`. Prefer this for a file: retyping a record can corrupt the sequence (a dropped base changes the ORIGIN length, and a lost complement() flips a strand).' },
2120
2157
  },
2121
2158
  },
2122
2159
  outputSchema: {
@@ -2168,8 +2205,12 @@ const parseGenbankTool = define({
2168
2205
  if (value.length_declared !== undefined) lines.push(`note: the LOCUS line declares ${value.length_declared} bp but ORIGIN holds ${value.length} bp; the sequence is what the tools use.`);
2169
2206
  return lines.join('\n');
2170
2207
  },
2171
- execute(args) {
2172
- return parseGenBank(args.genbank);
2208
+ async execute(args, exec) {
2209
+ const hasText = args.genbank !== undefined && args.genbank !== '';
2210
+ const hasPath = args.path !== undefined && args.path !== '';
2211
+ if (hasText === hasPath) throw new MolbioInputError('provide exactly one of genbank (the record text) or path (a .gb/.gbk file in the workspace)');
2212
+ const text = hasPath ? new TextDecoder().decode(await readFileBytes(ctx, exec, args.path)) : args.genbank;
2213
+ return parseGenBank(text);
2173
2214
  },
2174
2215
  });
2175
2216
 
@@ -2188,8 +2229,7 @@ function svgFileName(name) {
2188
2229
  */
2189
2230
  async function writeSvgFile(ctx, exec, args, svg, defaultName) {
2190
2231
  const fs = fsService(ctx);
2191
- const sandboxPolicyService = ctx.get('sandboxPolicy');
2192
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
2232
+ const policy = resolveSandboxPolicy(ctx, exec);
2193
2233
  const file = workspaceFilePath(args.output_path ?? svgFileName(defaultName), exec, policy?.workspaceRoot);
2194
2234
  await writeWorkspaceFile(fs, file, svg, policy);
2195
2235
  let viewed = false;
@@ -2217,7 +2257,7 @@ async function autoViewWritten(args, file) {
2217
2257
  const plasmidMapTool = (ctx) => define({
2218
2258
  safe: false,
2219
2259
  name: 'molbio_plasmid_map',
2220
- description: 'Render a plasmid map (circular by default, or linear) from a sequence plus features (from molbio_parse_genbank / molbio_parse_snapgene or hand-written) and WRITE it as a standalone SVG file in the session workspace. The tool writes the file itself — the SVG text never reaches the conversation, so do not try to re-render or copy it. After writing, the tool also opens the SVG automatically with the OS default application (auto_view, default true) so the user sees the picture without hunting for the file; pass auto_view: false to skip.',
2260
+ description: 'Render a plasmid map (circular by default, or linear) from a sequence plus features (from molbio_parse_genbank / molbio_parse_snapgene or hand-written) and WRITE it as a standalone SVG file in the session workspace. The tool writes the file itself and returns its path. When the user asks about the plasmid itself, relay the topology, feature count and cut-mark count the result states.',
2221
2261
  parameters: {
2222
2262
  type: 'object',
2223
2263
  required: ['sequence'],
@@ -2318,6 +2358,18 @@ const plasmidMapTool = (ctx) => define({
2318
2358
 
2319
2359
  const MAX_DNA_BYTES = 50 * 1024 * 1024;
2320
2360
 
2361
+ /**
2362
+ * Resolve the session's sandbox policy for one tool call.
2363
+ *
2364
+ * Every write path needs this exact expression. It used to be copy-pasted at 17
2365
+ * call sites, which is 17 places to forget when `resolve()` gains an argument —
2366
+ * and a write with no policy is a write outside the session sandbox.
2367
+ */
2368
+ function resolveSandboxPolicy(ctx, exec) {
2369
+ const service = ctx.get('sandboxPolicy');
2370
+ return service?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
2371
+ }
2372
+
2321
2373
  function fsService(ctx) {
2322
2374
  const fs = ctx.get('fs');
2323
2375
  if (fs === undefined) throw new MolbioInputError('the filesystem service is not available in this composition; reading .dna/.gb files needs ctx.fs');
@@ -2331,8 +2383,7 @@ async function readFileBytes(ctx, exec, path) {
2331
2383
  // default (process.cwd()), which is why tool-fs asks `workingDirectory` for
2332
2384
  // the agent's cwd; the sandbox policy carries the same root here. Absolute
2333
2385
  // paths are still accepted unchanged (workspaceFilePath leaves them alone).
2334
- const sandboxPolicyService = ctx.get('sandboxPolicy');
2335
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
2386
+ const policy = resolveSandboxPolicy(ctx, exec);
2336
2387
  const target = await fs.resolve(workspaceFilePath(path, exec, policy?.workspaceRoot), { signal: exec?.signal });
2337
2388
  return await fs.readBytes(target, exec?.signal, MAX_DNA_BYTES);
2338
2389
  }
@@ -2422,7 +2473,7 @@ const parseSnapgeneTool = (ctx) => define({
2422
2473
  const plasmidMapFileTool = (ctx) => define({
2423
2474
  safe: false,
2424
2475
  name: 'molbio_plasmid_map_file',
2425
- description: 'Read a plasmid file (.dna SnapGene, or .gb/.gbk GenBank) from disk and render its map, WRITING it as a standalone SVG file in the session workspace in one call. Features come from the file\'s annotations; optionally mark restriction enzyme cut sites. The tool writes the file itself — the SVG text never reaches the conversation, so do not try to re-render or copy it. After writing, the tool also opens the SVG automatically with the OS default application (auto_view, default true) so the user sees the picture without hunting for the file; pass auto_view: false to skip.',
2476
+ description: 'Read a plasmid file (.dna SnapGene, or .gb/.gbk GenBank) from disk and render its map, WRITING it as a standalone SVG file in the session workspace in one call. Features come from the file\'s annotations; optionally mark restriction enzyme cut sites. The tool writes the file itself and returns its path. When the user asks about the plasmid itself, relay the topology, feature count and cut-mark count the result states.',
2426
2477
  parameters: {
2427
2478
  type: 'object',
2428
2479
  required: ['path'],
@@ -2622,11 +2673,11 @@ const INTRON_PRIMER_SCHEMA = {
2622
2673
  length: { type: 'integer' },
2623
2674
  tm: { type: 'number' },
2624
2675
  gc_percent: { type: 'number' },
2625
- self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score (v12).' },
2626
- self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score (v12).' },
2627
- hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none; v12).' },
2628
- end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol (v12).' },
2629
- end_gc_count: { type: 'integer', description: 'G/C bases among the last five 3\' bases (v12).' },
2676
+ self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score.' },
2677
+ self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score.' },
2678
+ hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none).' },
2679
+ end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol.' },
2680
+ end_gc_count: { type: 'integer', description: 'G/C bases among the last five 3\' bases.' },
2630
2681
  spliced_start: { type: 'integer' },
2631
2682
  spliced_end: { type: 'integer' },
2632
2683
  genomic_start: { type: 'integer' },
@@ -2635,9 +2686,9 @@ const INTRON_PRIMER_SCHEMA = {
2635
2686
  exon: { type: 'integer' },
2636
2687
  junction_left: { type: 'integer' },
2637
2688
  junction_right: { type: 'integer' },
2638
- mismatch_count: { type: 'integer', description: 'Number of primer-template mismatches this primer carries (0 = exact match; v12).' },
2689
+ mismatch_count: { type: 'integer', description: 'Number of primer-template mismatches this primer carries (0 = exact match).' },
2639
2690
  mismatches: { type: 'array', items: INTRON_MISMATCH_SCHEMA },
2640
- mispriming_count: { type: 'integer', description: 'Extra transcript sites where the 3\' tail can anneal (v12 mispriming check).' },
2691
+ mispriming_count: { type: 'integer', description: 'Extra transcript sites where the 3\' tail can anneal (mispriming check).' },
2641
2692
  mispriming_sites: { type: 'array', items: INTRON_MISPRIMING_SITE_SCHEMA },
2642
2693
  target_distance: { type: 'integer', description: 'v13: spliced bp between the primer 3\' end and target_position (present only when target_position is given).' },
2643
2694
  },
@@ -2645,7 +2696,7 @@ const INTRON_PRIMER_SCHEMA = {
2645
2696
 
2646
2697
  const intronPrimersTool = (ctx) => define({
2647
2698
  name: 'molbio_design_intron_primers',
2648
- description: 'Design qPCR primer pairs where ONE primer spans an exon-exon junction (>= min_junction_bases on each side) so genomic DNA cannot be amplified. In the returned pair the junction is carried by the REVERSE primer (the assay sits 5\' of the junction): the forward primer is upstream inside a single exon, and the reverse sequence is the molecule to order (the reverse complement of its spliced site), so F is upstream of R and the pair amplifies as printed. Provide the genomic sequence and the exon spans (1-based, inclusive). min_genomic_span enforces a minimal genomic distance between the primers (making gDNA amplification impossible or easily detectable). Coordinates come back both on the spliced transcript and on the genomic sequence. v12: Primer3-style structural filters (self-complementarity alignment scores, hairpin/dimer folding Tm at 47 °C defaults, end stability/end GC, GC clamp levels); pass max_mismatches > 0 to allow mismatched primers (never on the 3\'-terminal base) with spliced+genomic mismatch reports; pass check_mispriming: true to reject/penalize non-specific 3\'-tail annealing on the transcript.',
2699
+ description: 'Design qPCR primer pairs where ONE primer spans an exon-exon junction (>= min_junction_bases on each side) so genomic DNA cannot be amplified. In the returned pair the junction is carried by the REVERSE primer (the assay sits 5\' of the junction): the forward primer is upstream inside a single exon, and the reverse sequence is the molecule to order (the reverse complement of its spliced site), so F is upstream of R and the pair amplifies as printed. Provide the genomic sequence and the exon spans (1-based, inclusive). min_genomic_span enforces a minimal genomic distance between the primers (making gDNA amplification impossible or easily detectable). Coordinates come back both on the spliced transcript and on the genomic sequence. v12: Primer3-style structural filters (self-complementarity alignment scores, hairpin/dimer folding Tm at 47 °C defaults, end stability/end GC, GC clamp levels); pass max_mismatches > 0 to allow mismatched primers (never on the 3\'-terminal base) with spliced+genomic mismatch reports; pass check_mispriming: true to reject/penalize non-specific 3\'-tail annealing on the transcript. The design, the structural filters and the optional mismatch/mispriming screens all run inside this one call; primer_check and pcr_simulate afterwards only recompute the same pair.',
2649
2700
  parameters: {
2650
2701
  type: 'object',
2651
2702
  required: ['exons'],
@@ -3001,7 +3052,7 @@ const uniqueCuttersTool = (ctx) => define({
3001
3052
  const cloneSimulateTool = (ctx) => define({
3002
3053
  safe: (args) => args.save_path === undefined && args.map_path === undefined,
3003
3054
  name: 'molbio_clone_simulate',
3004
- description: 'Simulate a cloning reaction in silico and return the final plasmid sequence with its remapped features. method=restriction: the tool itself checks that each enzyme cuts the vector exactly once (do not pre-verify by thinking), digests the insert with the same enzymes, ligates, remaps feature coordinates, and predicts verification digests; add_flanks: true lets the tool add the enzyme sites to a bare insert; orientation=auto (default) reverse-complements an inverted insert automatically. method=gibson: replace the vector region (region_start..region_end) with the insert and report the insert-to-order with homology arms. Save the final plasmid with save_path (FASTA) and/or draw the new plasmid map directly with map_path (SVG), which then opens automatically with the OS default application (auto_view default true; set auto_view: false to skip).',
3055
+ description: 'Simulate a cloning reaction in silico and return the final plasmid sequence with its remapped features. method=restriction: the tool itself checks that each enzyme cuts the vector exactly once (do not pre-verify by thinking), digests the insert with the same enzymes, ligates, remaps feature coordinates, and predicts verification digests; add_flanks: true lets the tool add the enzyme sites to a bare insert; orientation=auto (default) reverse-complements an inverted insert automatically. method=gibson: replace the vector region (region_start..region_end) with the insert and report the insert-to-order with homology arms. Save the final plasmid with save_path (FASTA) and/or draw the new plasmid map directly with map_path (SVG), .',
3005
3056
  parameters: {
3006
3057
  type: 'object',
3007
3058
  required: ['insert'],
@@ -3134,8 +3185,7 @@ const cloneSimulateTool = (ctx) => define({
3134
3185
  ...result.insert_reverse_complemented !== undefined ? { insert_reverse_complemented: result.insert_reverse_complemented } : {},
3135
3186
  };
3136
3187
  const fs = fsService(ctx);
3137
- const sandboxPolicyService = ctx.get('sandboxPolicy');
3138
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
3188
+ const policy = resolveSandboxPolicy(ctx, exec);
3139
3189
  if (args.save_path !== undefined && args.save_path !== '') {
3140
3190
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
3141
3191
  await writeWorkspaceFile(fs, file, `>${vector.name}_clone ${method}\n${result.final_sequence}\n`, policy);
@@ -3158,7 +3208,7 @@ const cloneSimulateTool = (ctx) => define({
3158
3208
  out.map_path = file;
3159
3209
  out.auto_viewed = await autoViewWritten(args, file);
3160
3210
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, `${vector.name}_clone`) ?? {});
3161
- }
3211
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when map_path names the file to write'));
3162
3212
  return out;
3163
3213
  },
3164
3214
  });
@@ -3192,7 +3242,7 @@ const GG_FRAGMENT_SCHEMA = {
3192
3242
  const goldenGateTool = (ctx) => define({
3193
3243
  safe: false,
3194
3244
  name: 'molbio_golden_gate',
3195
- description: 'Simulate a Golden Gate assembly (type IIS enzyme, e.g. BsaI) in silico. Pass the vector (with its own inward BsaI-style cassette, or BARE with replace_region so the tool adds the cassette and designs both vector junctions) and the BARE fragment sequences in assembly order: the tool designs unique, non-palindromic, non-complementary 4 bp junctions, checks that the enzyme never cuts inside a fragment or the bare vector, builds the fragments-to-order with recognition sites and filler bases, assembles the final plasmid (no recognition site appears at any junction; the vector cassette sites stay in the backbone, as in standard destination vectors), remaps feature coordinates, and predicts verification digests. Save the final plasmid with save_path (FASTA) and/or draw the map with map_path (SVG), which then opens automatically with the OS default application (auto_view default true; set auto_view: false to skip).',
3245
+ description: 'Simulate a Golden Gate assembly (type IIS enzyme, e.g. BsaI) in silico. Pass the vector (with its own inward BsaI-style cassette, or BARE with replace_region so the tool adds the cassette and designs both vector junctions) and the BARE fragment sequences in assembly order: the tool designs unique, non-palindromic, non-complementary 4 bp junctions, checks that the enzyme never cuts inside a fragment or the bare vector, builds the fragments-to-order with recognition sites and filler bases, assembles the final plasmid (no recognition site appears at any junction; the vector cassette sites stay in the backbone, as in standard destination vectors), remaps feature coordinates, and predicts verification digests. Save the final plasmid with save_path (FASTA) and/or draw the map with map_path (SVG), .',
3196
3246
  parameters: {
3197
3247
  type: 'object',
3198
3248
  required: ['inserts'],
@@ -3309,8 +3359,7 @@ const goldenGateTool = (ctx) => define({
3309
3359
  notes: result.notes,
3310
3360
  };
3311
3361
  const fs = fsService(ctx);
3312
- const sandboxPolicyService = ctx.get('sandboxPolicy');
3313
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
3362
+ const policy = resolveSandboxPolicy(ctx, exec);
3314
3363
  if (args.save_path !== undefined && args.save_path !== '') {
3315
3364
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
3316
3365
  await writeWorkspaceFile(fs, file, `>${vector.name}_golden_gate ${result.enzyme}\n${result.final_sequence}\n`, policy);
@@ -3333,14 +3382,14 @@ const goldenGateTool = (ctx) => define({
3333
3382
  out.map_path = file;
3334
3383
  out.auto_viewed = await autoViewWritten(args, file);
3335
3384
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, `${vector.name}_golden_gate`) ?? {});
3336
- }
3385
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when map_path names the file to write'));
3337
3386
  return out;
3338
3387
  },
3339
3388
  });
3340
3389
 
3341
3390
  const clonePrimersTool = (ctx) => define({
3342
3391
  name: 'molbio_clone_primers',
3343
- description: 'Design primers that amplify a template with cloning tails. mode=restriction: adds 5\' protection bases and restriction site(s) (1 or 2 enzymes) to the primer ends and re-checks Tm/GC/dimers; warns when an enzyme also cuts inside the template. mode=gibson: adds the vector homology arms flanking the replaced region to the primer ends.',
3392
+ description: 'Design primers that amplify a template with cloning tails. mode=restriction: adds 5\' protection bases and restriction site(s) (1 or 2 enzymes) to the primer ends and re-checks Tm/GC/dimers; warns when an enzyme also cuts inside the template. mode=gibson: adds the vector homology arms flanking the replaced region to the primer ends. The render gives the reverse primer\'s 3\' binding part AS ORDERED — pass that string, not its reverse complement, when you verify the pair with molbio_pcr_simulate.',
3344
3393
  parameters: {
3345
3394
  type: 'object',
3346
3395
  required: ['template'],
@@ -3392,7 +3441,7 @@ const clonePrimersTool = (ctx) => define({
3392
3441
  const lines = [
3393
3442
  `cloning primers (${value.mode}):`,
3394
3443
  ` forward: ${value.forward} (binding ${value.forward_binding})`,
3395
- ` reverse: ${value.reverse} (binding ${value.reverse_binding})`,
3444
+ ` reverse: ${value.reverse} (3' binding part as ordered ${reverseComplement(value.reverse_binding)}; template site ${value.reverse_binding})`,
3396
3445
  `Tm: forward ${c.forward_tm} °C / reverse ${c.reverse_tm} °C (binding parts: ${c.binding_tm_forward} / ${c.binding_tm_reverse} °C)`,
3397
3446
  `GC: ${c.gc_forward}% / ${c.gc_reverse}% · dimer score ${c.dimer_score} · self scores ${c.forward_self_score}/${c.reverse_self_score}`,
3398
3447
  ];
@@ -3423,7 +3472,7 @@ const clonePrimersTool = (ctx) => define({
3423
3472
 
3424
3473
  const mutagenesisTool = define({
3425
3474
  name: 'molbio_mutagenesis_primers',
3426
- description: 'Design QuickChange-style site-directed mutagenesis primer pairs. Mutations are given as strings on the original template coordinates: substitutions "A123G" or "123A>G", deletions "123_125del", insertions "after123insGCT". The mutation is centered in the primers, which are checked for Tm (NN estimate), GC, G/C ends, runs and self-complementarity. The amino-acid change is reported assuming the template reads in frame 1.',
3475
+ description: 'Design QuickChange-style site-directed mutagenesis primer pairs. Mutations use the original template coordinates: substitutions "A123G" or "123A>G", deletions "123_125del", insertions "after123insGCT". Pass ALL mutations of the experiment in one `mutations` call: it returns one pair per mutation with Tm (NN estimate), GC, G/C ends, runs and self-complementarity, plus the amino-acid change from the template read in frame 1, so neither a per-mutation re-run nor a separate translate call is needed. The mutation position and the amino-acid change come back in the same result, so do not rebuild or translate the mutant to confirm them; if the result says no pair satisfied the constraints, widen primer_len_min/max or tm_min/max once and retry.',
3427
3476
  parameters: {
3428
3477
  type: 'object',
3429
3478
  required: ['template', 'mutations'],
@@ -3511,7 +3560,7 @@ const mutagenesisTool = define({
3511
3560
 
3512
3561
  const verifySangerTool = (ctx) => define({
3513
3562
  name: 'molbio_verify_sanger',
3514
- description: 'Verify a clone by Sanger sequencing: read a trace file (.ab1 with quality values, or .seq/.txt/.fasta plain text), align it against a reference (sequence or .dna/.gb plasmid file, circular-aware), and report mismatches, deletions, insertions, coverage, identity, and amino-acid consequences inside a CDS window. Low-quality (<20) positions are flagged and excluded from a "differences found" verdict.',
3563
+ description: 'Verify a clone by Sanger sequencing: read a trace file (.ab1 with quality values, or .seq/.txt/.fasta plain text), align it against a reference (sequence or .dna/.gb plasmid file, circular-aware), and report mismatches, deletions, insertions, coverage, identity, and amino-acid consequences inside a CDS window. Low-quality (<20) positions are flagged and excluded from a "differences found" verdict. The trace must be a sequencing read: an input as long as the reference is refused, because a partial alignment window is not a whole-molecule comparison (use molbio_align for that).',
3515
3564
  parameters: {
3516
3565
  type: 'object',
3517
3566
  required: ['trace_path'],
@@ -3584,6 +3633,12 @@ const verifySangerTool = (ctx) => define({
3584
3633
  const lines = [
3585
3634
  `verdict: ${value.verdict}`,
3586
3635
  `aligned ${value.aligned_span.start}-${value.aligned_span.end} of ${value.reference_length} bp reference; identity ${value.identity_percent}%`,
3636
+ ...value.aligned_span.end - value.aligned_span.start + 1 < value.reference_length
3637
+ ? [`note: the aligned window is ${value.aligned_span.end - value.aligned_span.start + 1} of ${value.reference_length} bp — a PARTIAL window, not a whole-molecule comparison`]
3638
+ : [],
3639
+ ...value.trace_length === value.reference_length
3640
+ ? ['note: the trace is as long as the reference — if this is a whole molecule rather than a read, use molbio_align']
3641
+ : [],
3587
3642
  ];
3588
3643
  if (value.quality_mean !== undefined) lines.push(`mean trace quality: ${value.quality_mean}`);
3589
3644
  const confident = value.differences.filter((d) => !(d.quality !== undefined && d.quality < 20));
@@ -3617,6 +3672,9 @@ const verifySangerTool = (ctx) => define({
3617
3672
  } else {
3618
3673
  throw new MolbioInputError('provide either `reference` (a sequence) or `reference_path` (a .dna/.gb/.fa file)');
3619
3674
  }
3675
+ if (trace.bases.length > reference.length) {
3676
+ throw new MolbioInputError(`the trace is ${trace.bases.length} bp, longer than the ${reference.length} bp reference — a read cannot exceed its reference; use molbio_align for a two-sequence comparison`);
3677
+ }
3620
3678
  return verifySanger({
3621
3679
  traceBases: trace.bases,
3622
3680
  traceQualities: trace.qualities,
@@ -3869,7 +3927,7 @@ const peptideDigestTool = define({
3869
3927
 
3870
3928
  const codonOptimizeTool = define({
3871
3929
  name: 'molbio_codon_optimize',
3872
- description: 'Codon-optimize a protein sequence for a host (E. coli, yeast, or human) using published high-frequency codon tables (heuristic). Optionally avoid introducing restriction sites (avoid_enzymes): synonymous swaps remove them where possible, deterministically.',
3930
+ description: 'Codon-optimize a protein sequence for a host (E. coli, yeast, or human) using published high-frequency codon tables (heuristic). Optionally avoid introducing restriction sites (avoid_enzymes): synonymous swaps remove them where possible, deterministically. The result already carries the optimised CDS with its GC, restriction-site screen and translation check, so re-verifying it with translate, gc_content or restriction_sites adds nothing.',
3873
3931
  parameters: {
3874
3932
  type: 'object',
3875
3933
  required: ['sequence'],
@@ -3933,7 +3991,7 @@ const helicalWheelTool = (ctx) => define({
3933
3991
  // never concurrency-safe; the old predicate marked the common case safe.
3934
3992
  safe: false,
3935
3993
  name: 'molbio_helical_wheel',
3936
- description: 'Draw the helical wheel (Schiffer-Edmundson projection) of a peptide or protein stretch and analyse it: residues are placed 100° apart on the circle (3.6 residues per turn of an ideal alpha-helix), coloured by residue class (hydrophobic/polar/acidic/basic), with the Eisenberg hydrophobic moment μH of the stretch and the maximum μH over every window of moment_window residues (11 by default). An amphipathic helix shows one hydrophobic face and one polar face. The tool WRITES an SVG file and opens it with the OS default viewer (auto_view, default true); all values are sequence-propensity estimates from published scales, not a structure prediction.',
3994
+ description: 'Draw the helical wheel (Schiffer-Edmundson projection) of a peptide or protein stretch and analyse it: residues are placed 100° apart on the circle (3.6 residues per turn of an ideal alpha-helix), coloured by residue class (hydrophobic/polar/acidic/basic), with the Eisenberg hydrophobic moment μH of the stretch and the maximum μH over every window of moment_window residues (11 by default). An amphipathic helix shows one hydrophobic face and one polar face. The tool writes the SVG file itself (auto_view, default true); all values are sequence-propensity estimates from published scales, not a structure prediction.',
3937
3995
  parameters: {
3938
3996
  type: 'object',
3939
3997
  required: ['sequence'],
@@ -4053,7 +4111,7 @@ const hydropathyTool = (ctx) => define({
4053
4111
  // Always writes the SVG; see the helical-wheel note.
4054
4112
  safe: false,
4055
4113
  name: 'molbio_hydropathy_plot',
4056
- description: 'Plot the Kyte-Doolittle hydropathy profile of a protein: a sliding-window average (window, default 9; use 19-21 for transmembrane spans), the GRAVY value, and every peak whose window average reaches the threshold (default 1.6, the classic membrane-spanning cutoff). The tool WRITES an SVG file and opens it with the OS default viewer (auto_view, default true); the per-residue profile is also returned so it can feed further analysis. Values are the Kyte-Doolittle propensity scale, not a topology prediction.',
4114
+ description: 'Plot the Kyte-Doolittle hydropathy profile of a protein: a sliding-window average (window, default 9; use 19-21 for transmembrane spans), the GRAVY value, and every peak whose window average reaches the threshold (default 1.6, the classic membrane-spanning cutoff). The tool writes the SVG file itself (auto_view, default true); the per-residue profile is also returned so it can feed further analysis. Values are the Kyte-Doolittle propensity scale, not a topology prediction.',
4057
4115
  parameters: {
4058
4116
  type: 'object',
4059
4117
  required: ['sequence'],
@@ -4114,7 +4172,7 @@ const hydropathyTool = (ctx) => define({
4114
4172
  const qpcrEfficiencyTool = (ctx) => define({
4115
4173
  safe: (args) => args.plot_path === undefined || args.plot_path === '',
4116
4174
  name: 'molbio_qpcr_efficiency',
4117
- description: 'Fit a qPCR standard curve from a dilution series: dilution_factors (e.g. [1, 10, 100, 1000]) with the matching ct_values. Fits Ct vs log10(relative quantity), reports slope, intercept, R², and amplification efficiency E = 10^(−1/slope) − 1. Pass plot_path to write the scatter + fit line as an SVG file in the workspace and open it automatically with the OS default application (auto_view default true).',
4175
+ description: 'Fit a qPCR standard curve from a dilution series: dilution_factors (e.g. [1, 10, 100, 1000]) with the matching ct_values. Fits Ct vs log10(relative quantity), reports slope, intercept, R², and amplification efficiency E = 10^(−1/slope) − 1. Pass plot_path to write the scatter + fit line as an SVG file in the workspace.',
4118
4176
  parameters: {
4119
4177
  type: 'object',
4120
4178
  required: ['dilution_factors', 'ct_values'],
@@ -4190,8 +4248,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4190
4248
  };
4191
4249
  if (args.plot_path !== undefined && args.plot_path !== '') {
4192
4250
  const fs = fsService(ctx);
4193
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4194
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4251
+ const policy = resolveSandboxPolicy(ctx, exec);
4195
4252
  const file = workspaceFilePath(args.plot_path, exec, policy?.workspaceRoot);
4196
4253
  const svg = renderScatterChart({
4197
4254
  title: 'qPCR standard curve',
@@ -4205,7 +4262,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4205
4262
  out.plot_path = file;
4206
4263
  out.auto_viewed = await autoViewWritten(args, file);
4207
4264
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, 'qpcr-standard-curve') ?? {});
4208
- }
4265
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when plot_path names the file to write'));
4209
4266
  return out;
4210
4267
  },
4211
4268
  });
@@ -4224,8 +4281,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4224
4281
  */
4225
4282
  async function resolveChartTable(ctx, exec, args) {
4226
4283
  const fs = fsService(ctx);
4227
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4228
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4284
+ const policy = resolveSandboxPolicy(ctx, exec);
4229
4285
  const table = await resolveTable(args, async (path) => {
4230
4286
  const target = workspaceFilePath(path, exec, policy?.workspaceRoot);
4231
4287
  // Check existence first: a missing file otherwise reaches the parser as an
@@ -4609,7 +4665,7 @@ const plotTool = (ctx) => define({
4609
4665
  const virtualGelTool = (ctx) => define({
4610
4666
  safe: false,
4611
4667
  name: 'molbio_virtual_gel',
4612
- description: 'Render a virtual agarose gel as an SVG file in the workspace. Each lane lists the EXPECTED DNA fragment sizes in bp (e.g. a restriction digest, a PCR, or a ligation check) and the tool draws the band pattern with a size ladder so the expected picture can be compared against a real gel. The tool writes the file itself — the SVG never reaches the conversation — and then opens it automatically with the OS default application (auto_view default true; set auto_view: false to skip).',
4668
+ description: 'Render a virtual agarose gel as an SVG file in the workspace. Each lane lists the EXPECTED DNA fragment sizes in bp (e.g. a restriction digest, a PCR, or a ligation check) and the tool draws the band pattern with a size ladder so the expected picture can be compared against a real gel. The tool writes the SVG file itself.',
4613
4669
  parameters: {
4614
4670
  type: 'object',
4615
4671
  required: ['lanes'],
@@ -4679,15 +4735,17 @@ const virtualGelTool = (ctx) => define({
4679
4735
  },
4680
4736
  });
4681
4737
 
4682
- const alignTool = define({
4738
+ const alignTool = (ctx) => define({
4683
4739
  name: 'molbio_align',
4684
- description: 'Locally align two sequences (Smith-Waterman). Returns the aligned strings, the aligned span, identity %, and a list of mismatches/gaps. NOTE the span fields: a_start/b_start are 0-BASED offsets and a_end/b_end are 0-based EXCLUSIVE ends — the 1-based inclusive span is a_start+1..a_end, which is what the rendered text prints. The pairwise matrix is capped at 50,000,000 cells (sequence1 x sequence2, roughly 7,000 x 7,000 bases); a larger pair is refused with an error rather than exhausting host memory, so align a window or use molbio_verify_sanger, which anchors a read to a reference. Use it to compare two sequences, check a primer against a template, or verify an edited region.',
4740
+ description: 'Locally align two sequences (Smith-Waterman). Returns the aligned strings, the aligned span, identity %, and a list of mismatches/gaps. NOTE the span fields: a_start/b_start are 0-BASED offsets and a_end/b_end are 0-based EXCLUSIVE ends — the 1-based inclusive span is a_start+1..a_end, which is what the rendered text prints. The pairwise matrix is capped at 50,000,000 cells (sequence1 x sequence2, roughly 7,000 x 7,000 bases); a larger pair is refused with an error rather than exhausting host memory, so align a window or use molbio_verify_sanger, which anchors a read to a reference. Use it to compare two sequences, check a primer against a template, or verify an edited region. Either side may instead be a workspace file (path1/path2), which makes this the pairwise comparison for two long sequences where the MSA has a 3000 bp cap.',
4685
4741
  parameters: {
4686
4742
  type: 'object',
4687
- required: ['sequence1', 'sequence2'],
4743
+ required: [],
4688
4744
  properties: {
4689
- sequence1: requiredString('First sequence (typically the query/read).'),
4690
- sequence2: requiredString('Second sequence (typically the reference).'),
4745
+ sequence1: { type: 'string', description: 'First sequence (typically the query/read).' },
4746
+ path1: { type: 'string', description: 'Workspace file holding sequence1 (FASTA or plain text); alternative to `sequence1`.' },
4747
+ sequence2: { type: 'string', description: 'Second sequence (typically the reference).' },
4748
+ path2: { type: 'string', description: 'Workspace file holding sequence2; alternative to `sequence2`.' },
4691
4749
  },
4692
4750
  },
4693
4751
  outputSchema: {
@@ -4740,9 +4798,20 @@ const alignTool = define({
4740
4798
  }
4741
4799
  return lines.join('\n');
4742
4800
  },
4743
- execute(args) {
4744
- const a = normalizeSequence(args.sequence1, 'sequence1');
4745
- const b = normalizeSequence(args.sequence2, 'sequence2');
4801
+ async execute(args, exec) {
4802
+ const readSide = async (sequence, path, label, pathLabel) => {
4803
+ const hasSequence = sequence !== undefined && sequence !== '';
4804
+ const hasPath = path !== undefined && path !== '';
4805
+ if (hasSequence === hasPath) throw new MolbioInputError(`provide exactly one of ${label} (a sequence) or ${pathLabel} (a workspace file)`);
4806
+ if (hasSequence) return sequence;
4807
+ const bytes = await readFileBytes(ctx, exec, path);
4808
+ if (String(path).toLowerCase().endsWith('.dna')) return parseSnapGeneBytes(bytes).sequence;
4809
+ const text = new TextDecoder().decode(bytes).replace(/^\uFEFF/, '');
4810
+ if (/^LOCUS\s/.test(text.trimStart())) return parseGenBank(text).sequence;
4811
+ return text.trimStart().startsWith('>') ? parseFasta(text)[0].sequence : text;
4812
+ };
4813
+ const a = normalizeSequence(await readSide(args.sequence1, args.path1, 'sequence1', 'path1'), 'sequence1');
4814
+ const b = normalizeSequence(await readSide(args.sequence2, args.path2, 'sequence2', 'path2'), 'sequence2');
4746
4815
  const result = smithWaterman(a, b);
4747
4816
  const differences = result.differences.map((d) => ({
4748
4817
  kind: d.kind,
@@ -4870,8 +4939,7 @@ const msaAlignTool = (ctx) => define({
4870
4939
  let savedTo = '';
4871
4940
  if (args.save_path !== undefined && args.save_path !== '') {
4872
4941
  const fs = fsService(ctx);
4873
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4874
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4942
+ const policy = resolveSandboxPolicy(ctx, exec);
4875
4943
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
4876
4944
  await writeWorkspaceFile(fs, file, toFasta(result.alignment.map((row) => ({ id: row.id, description: '', sequence: row.sequence }))), policy);
4877
4945
  savedTo = file;
@@ -4892,7 +4960,7 @@ const msaAlignTool = (ctx) => define({
4892
4960
  const conservationTool = (ctx) => define({
4893
4961
  safe: true,
4894
4962
  name: 'molbio_conservation',
4895
- description: 'Conservation analysis of a set of IUPAC DNA sequences: consensus sequence, per-column identity (fraction of residues matching the top residue), entropy-based conservation score, conserved/variable columns, and pairwise identity statistics. Provide exactly one of `alignment` (pre-aligned equal-length sequences, "-" for gaps — e.g. the output of molbio_msa_align), `sequences` (unaligned; aligned first with the molbio_msa_align method), or `fasta_path`. `threshold` (default 0.8) is the column identity at or above which a column counts as conserved; columns below it are listed in variable_positions (capped at 200, see variable_positions_truncated). All-gap columns count as conserved; per_column details are returned for alignments up to 300 columns. Deterministic; all scores are heuristic estimates.',
4963
+ description: 'Conservation analysis of a set of IUPAC DNA sequences: consensus sequence, per-column identity (fraction of residues matching the top residue), entropy-based conservation score, conserved/variable columns, and pairwise identity statistics. Provide exactly one of `alignment` (pre-aligned equal-length rows), `sequences` (unaligned) or `fasta_path`. `threshold` (default 0.8) is the column identity at or above which a column counts as conserved; columns below it are listed in variable_positions (capped at 200, see variable_positions_truncated). All-gap columns count as conserved; per_column details are returned for alignments up to 300 columns. Deterministic; all scores are heuristic estimates. Each sequence is capped at 3000 bases; for a two-sequence comparison above that, use molbio_align instead.',
4896
4964
  parameters: {
4897
4965
  type: 'object',
4898
4966
  properties: {
@@ -4982,7 +5050,14 @@ const conservationTool = (ctx) => define({
4982
5050
  source = 'alignment';
4983
5051
  } else {
4984
5052
  const entries = await msaEntries(ctx, exec, args, 'molbio_conservation');
4985
- rows = progressiveAlign(entries).alignment.map((row) => row.sequence);
5053
+ try {
5054
+ rows = progressiveAlign(entries).alignment.map((row) => row.sequence);
5055
+ } catch (error) {
5056
+ if (error instanceof MolbioInputError && /3000/.test(error.message)) {
5057
+ throw new MolbioInputError(`${error.message} — for a TWO-sequence comparison above that limit use molbio_align (pairwise, up to 50M matrix cells).`);
5058
+ }
5059
+ throw error;
5060
+ }
4986
5061
  source = 'msa';
4987
5062
  }
4988
5063
  return { source, ...conservationAnalysis(rows, threshold) };
@@ -4991,12 +5066,12 @@ const conservationTool = (ctx) => define({
4991
5066
 
4992
5067
  const alignmentPostprocessTool = (ctx) => define({
4993
5068
  name: 'molbio_alignment_postprocess',
4994
- description: 'Post-process an alignment: IUPAC consensus, gap-ratio column trimming, a pairwise identity matrix, and per-column coverage. Provide exactly one of `alignment` (pre-aligned equal-length sequences, "-" for gaps — e.g. the output of molbio_msa_align), `sequences` (unaligned; aligned first with the same method as molbio_msa_align), or `fasta_path`. '
5069
+ description: 'Post-process an alignment: IUPAC consensus, gap-ratio column trimming, a pairwise identity matrix, and per-column coverage. One of `alignment` (pre-aligned rows), `sequences` (unaligned) or `fasta_path` (same inputs as molbio_conservation). '
4995
5070
  + '`consensus_mode` picks which consensus is reported, and they are genuinely different answers: "plurality" (default) gives the top residue when it reaches `consensus_threshold` (default 0.5) and otherwise the IUPAC code for everything observed; "union" always gives that IUPAC code; "strict" gives the top residue above the threshold and N otherwise, so a mixed position never masquerades as a base. '
4996
5071
  + '`max_gap_fraction` (default 0.5) marks columns to trim and reports the column numbers BEFORE trimming (original 1-based coordinates, so they stay comparable with the input); the trimmed alignment itself is not returned — only which columns would go and how many remain. '
4997
5072
  + '`coverage_threshold` (default 0.8, a non-gap fraction) lists poorly covered columns; `mean_coverage` and `fully_covered_columns` summarise the same numbers. '
4998
5073
  + 'NOTE ON THE IDENTITY MATRIX: its denominator is the columns where at least one of the two rows has a residue (double-gap columns excluded), which is NOT the convention molbio_conservation uses for its pairwise_identity_percent (that one divides by all columns). Both are documented and internally consistent; do not compare the two numbers directly. '
4999
- + 'Heuristic reporting for working comparisons; deterministic.',
5074
+ + 'Heuristic reporting for working comparisons; deterministic. The four outputs come back together; a second call is only for a different alignment.',
5000
5075
  parameters: {
5001
5076
  type: 'object',
5002
5077
  properties: {
@@ -5143,7 +5218,7 @@ const sequenceLogoTool = (ctx) => define({
5143
5218
  // safe let two parallel calls overwrite one file.
5144
5219
  safe: false,
5145
5220
  name: 'molbio_sequence_logo',
5146
- description: 'Render a sequence logo (per-position base composition, letter height = information content in bits) as an SVG file in the session workspace, then open it with the OS default application. Provide exactly one of `alignment` (pre-aligned equal-length sequences, "-" for gaps — e.g. the output of molbio_msa_align), `sequences` (unaligned; aligned first), or `fasta_path`. Frequencies are computed over residues only (gaps excluded and reported per column); IUPAC ambiguity codes are expanded into their base sets. `small_sample` (default true) subtracts the conventional (K-1)/(2·ln2·n) entropy correction, which matters most for few sequences; `score_type: "frequency"` switches to a plain frequency plot (letters sum to 1, y axis 0-1) instead of bits (0-2). Heuristic visualisation of an alignment — it shows the data you give it, and says nothing about function on its own.',
5221
+ description: 'Render a sequence logo (per-position base composition, letter height = information content in bits) as an SVG file in the session workspace, then open it with the OS default application. Accepts the same `alignment`, `sequences` or `fasta_path` inputs as molbio_conservation. Frequencies are computed over residues only (gaps excluded and reported per column); IUPAC ambiguity codes are expanded into their base sets. `small_sample` (default true) subtracts the conventional (K-1)/(2·ln2·n) entropy correction, which matters most for few sequences; `score_type: "frequency"` switches to a plain frequency plot (letters sum to 1, y axis 0-1) instead of bits (0-2). Heuristic visualisation of an alignment — it shows the data you give it, and says nothing about function on its own.',
5147
5222
  parameters: {
5148
5223
  type: 'object',
5149
5224
  properties: {
@@ -5469,8 +5544,7 @@ const grnaDesignTool = (ctx) => define({
5469
5544
  let savedTo = '';
5470
5545
  if (args.save_path !== undefined && args.save_path !== '') {
5471
5546
  const fs = fsService(ctx);
5472
- const sandboxPolicyService = ctx.get('sandboxPolicy');
5473
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
5547
+ const policy = resolveSandboxPolicy(ctx, exec);
5474
5548
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
5475
5549
  await writeWorkspaceFile(fs, file, guideCsv(guides, result.cas_family), policy);
5476
5550
  savedTo = file;
@@ -5618,7 +5692,7 @@ const fastaFastqTool = (ctx) => define({
5618
5692
  safe: (args) => !(args.action === 'convert'
5619
5693
  || (args.action === 'extract' && args.output_path !== undefined && args.output_path !== '')),
5620
5694
  name: 'molbio_fasta_fastq',
5621
- description: 'Work with FASTA/FASTQ files in the workspace. action=stats: per-entry and overall statistics (length/GC). action=extract: pull entries by id (exact or substring) and optionally write them to a FASTA file. action=convert: FASTQ → FASTA (output_path required). action=qc: FASTQ quality statistics (mean/min/max Phred, low-quality fraction, per-position means).',
5695
+ description: 'Work with FASTA/FASTQ files in the workspace. action=stats: per-entry and overall statistics (length/GC). action=extract: pull entries by id (exact or substring) and optionally write them to a FASTA file. action=convert: FASTQ → FASTA (output_path required). action=qc: FASTQ quality statistics (mean/min/max Phred, low-quality fraction, per-position means). The result carries the per-file counts and quality numbers: quote them in the answer instead of only pointing at the files. When the request is a QC question, the read count and mean quality ARE the answer: a reply that only lists the written files is incomplete.',
5622
5696
  parameters: {
5623
5697
  type: 'object',
5624
5698
  required: ['path'],
@@ -5696,8 +5770,7 @@ const fastaFastqTool = (ctx) => define({
5696
5770
  if (action === 'qc' && format !== 'fastq') throw new MolbioInputError('action=qc needs a FASTQ file');
5697
5771
  let savedTo = '';
5698
5772
  const fs = fsService(ctx);
5699
- const sandboxPolicyService = ctx.get('sandboxPolicy');
5700
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
5773
+ const policy = resolveSandboxPolicy(ctx, exec);
5701
5774
  if (action === 'extract') {
5702
5775
  if (args.id === undefined || args.id === '') throw new MolbioInputError('action=extract needs an id');
5703
5776
  const exact = parsed.filter((entry) => entry.id === args.id);
@@ -5810,7 +5883,7 @@ async function batchFileList(ctx, exec, args, policy, root) {
5810
5883
  if (info === undefined || info.type !== 'directory') {
5811
5884
  throw new MolbioInputError('batch directory ' + JSON.stringify(args.directory ?? '.') + ' is not a directory');
5812
5885
  }
5813
- const pattern = globToRegExp(args.pattern ?? '*');
5886
+ const pattern = args.pattern ?? '*';
5814
5887
  const recursive = args.recursive === true;
5815
5888
  const maxFiles = Math.min(args.max_files ?? 50, BATCH_LIMITS.maxFiles);
5816
5889
  let totalBytes = 0;
@@ -5833,7 +5906,7 @@ async function batchFileList(ctx, exec, args, policy, root) {
5833
5906
  }
5834
5907
  if (entry.type !== 'file') continue;
5835
5908
  const haystack = String(args.pattern ?? '').includes('/') ? label : entry.name;
5836
- if (!pattern.test(haystack)) continue;
5909
+ if (!globMatches(pattern, haystack)) continue;
5837
5910
  files.push({ target: entry.target, label, size: entry.size });
5838
5911
  totalBytes += entry.size ?? 0;
5839
5912
  if (totalBytes > BATCH_LIMITS.maxTotalBytes) {
@@ -5936,7 +6009,7 @@ const batchAnalyzeTool = (ctx) => define({
5936
6009
  return lines.join('\n');
5937
6010
  },
5938
6011
  async execute(args, exec) {
5939
- const policy = ctx.get('sandboxPolicy')?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
6012
+ const policy = resolveSandboxPolicy(ctx, exec);
5940
6013
  const root = policy?.workspaceRoot ?? exec?.agent?.session?.header?.cwd ?? process.cwd();
5941
6014
  const analysis = args.analysis ?? 'summary';
5942
6015
  const wantsOrf = analysis === 'orf' || analysis === 'all';
@@ -6175,8 +6248,7 @@ const extractRegionTool = (ctx) => define({
6175
6248
  let savedTo = '';
6176
6249
  if (args.output_path !== undefined && args.output_path !== '') {
6177
6250
  const fs = fsService(ctx);
6178
- const sandboxPolicyService = ctx.get('sandboxPolicy');
6179
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
6251
+ const policy = resolveSandboxPolicy(ctx, exec);
6180
6252
  const file = workspaceFilePath(args.output_path, exec, policy?.workspaceRoot);
6181
6253
  await writeWorkspaceFile(fs, file, `>${vector.name}_${start}-${end}\n${fragment}\n`, policy);
6182
6254
  savedTo = file;
@@ -6312,7 +6384,7 @@ const PCR_PAIR_IN_SCHEMA = {
6312
6384
  const pcrSimulateTool = (ctx) => define({
6313
6385
  safe: false,
6314
6386
  name: 'molbio_pcr_simulate',
6315
- description: 'In-silico PCR: find every amplicon a primer pair produces on a template, searching both strands, with product sizes, coordinates and mismatch detail. Answers "where else will this pair amplify, and what band should I see". Mismatch tolerance (`max_mismatches`) and the exact-match requirement at the primer 3\' end (`three_prime_exact`, default 3 bases) are separate knobs, because a middle mismatch still extends while a 3\' mismatch usually does not. Handles circular templates (products across the origin) and can screen extra templates such as a vector. Draws the expected gel with the same renderer as molbio_virtual_gel.',
6387
+ description: 'In-silico PCR: every amplicon a primer pair produces on a template, both strands, with product sizes, coordinates and mismatch detail. Answers where else a pair amplifies and what band to expect. Pass ALL pairs in one `primer_pairs` call, one template per call — re-calling per pair only repeats the same scan. Mismatch tolerance (`max_mismatches`) and the exact-match requirement at the primer 3\' end (`three_prime_exact`, default 3 bases) are separate knobs: a middle mismatch still extends, a 3\' mismatch usually does not. Handles circular templates (products across the origin) and extra templates, and draws the expected gel. For a whole multiplex panel use molbio_multiplex_check instead of running this pair by pair. Matches the WHOLE primer, so a 5\' cloning or restriction tail cannot anneal — for tailed primers verify the binding part, or pass the bare binding sequence.',
6316
6388
  parameters: {
6317
6389
  type: 'object',
6318
6390
  properties: {
@@ -6367,6 +6439,9 @@ const pcrSimulateTool = (ctx) => define({
6367
6439
  }
6368
6440
  if (pair.truncated) lines.push(` more products exist than the listing cap (${pair.amplicon_count} shown)`);
6369
6441
  if (pair.out_of_range > 0) lines.push(` ${pair.out_of_range} product(s) fell outside the size window`);
6442
+ if (pair.amplicon_count === 0 && pair.forward_sites.length === 0 && pair.reverse_sites.length === 0) {
6443
+ lines.push(" no full-length primer site: this tool matches the WHOLE primer, so a 5' cloning tail (protection bases + restriction site) never anneals — verify the binding part alone, or rely on molbio_clone_primers' own warning.");
6444
+ }
6370
6445
  }
6371
6446
  for (const screen of value.screens) {
6372
6447
  const hits = screen.products.filter((entry) => entry.amplicon_count > 0);
@@ -7060,8 +7135,7 @@ const fastqTrimTool = (ctx) => define({
7060
7135
  });
7061
7136
  const outputFormat = args.output_format ?? 'fastq';
7062
7137
  const fs = fsService(ctx);
7063
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7064
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7138
+ const policy = resolveSandboxPolicy(ctx, exec);
7065
7139
  const file = workspaceFilePath(args.output_path, exec, policy?.workspaceRoot);
7066
7140
  await writeWorkspaceFile(fs, file, outputFormat === 'fasta' ? toFasta(trimmed.entries) : toFastq(trimmed.entries), policy);
7067
7141
  return { ...trimmed.stats, saved_to: file, output_format: outputFormat };
@@ -7348,8 +7422,7 @@ const phylogeneticTreeTool = (ctx) => define({
7348
7422
  },
7349
7423
  async execute(args, exec) {
7350
7424
  const fs = fsService(ctx);
7351
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7352
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7425
+ const policy = resolveSandboxPolicy(ctx, exec);
7353
7426
  // 1. Collect the input rows.
7354
7427
  let entries;
7355
7428
  if (args.sequences !== undefined && args.sequences.length > 0) {
@@ -7488,7 +7561,7 @@ async function eutilsRequest(web, url, signal, label) {
7488
7561
  try {
7489
7562
  result = await web.fetch({ url }, signal);
7490
7563
  } catch (error) {
7491
- throw new MolbioInputError(`${label} could not be reached: ${error instanceof Error ? error.message : String(error)}`);
7564
+ throw new MolbioInputError(`${label} could not be reached (a network/service failure, not an argument problem): ${error instanceof Error ? error.message : String(error)}`);
7492
7565
  }
7493
7566
  const body = result?.body?.content;
7494
7567
  if (typeof body !== 'string' || body === '') {
@@ -7582,7 +7655,7 @@ const pubmedAbstractTool = (ctx) => define({
7582
7655
  if (pmids.length === 0) throw new MolbioInputError('pmids must contain numeric PubMed IDs');
7583
7656
  const web = ctx.get('web');
7584
7657
  if (web === undefined || typeof web.fetch !== 'function') {
7585
- throw new MolbioInputError('this deployment provides no web fetch capability, so PubMed abstracts cannot be retrieved; molbio_pubmed_search still works for titles and snippets');
7658
+ throw new MolbioInputError('this deployment provides no web fetch capability (a composition limit, not an argument problem), so PubMed abstracts cannot be retrieved; molbio_pubmed_search still works for titles and snippets');
7586
7659
  }
7587
7660
  const apiKey = await pubmedKey(args, ctx);
7588
7661
  const url = pubmedFetchUrl(pmids, apiKey);
@@ -7592,7 +7665,7 @@ const pubmedAbstractTool = (ctx) => define({
7592
7665
  } catch (error) {
7593
7666
  // Same contract as eutilsRequest: a transport failure is a tool-input
7594
7667
  // error the caller can report, not a raw exception escaping the tool.
7595
- throw new MolbioInputError(`PubMed efetch could not be reached: ${error instanceof Error ? error.message : String(error)}`);
7668
+ throw new MolbioInputError(`PubMed efetch could not be reached (a network failure, not an argument problem): ${error instanceof Error ? error.message : String(error)}`);
7596
7669
  }
7597
7670
  const body = result?.body?.content;
7598
7671
  if (typeof body !== 'string' || body === '') {
@@ -7894,8 +7967,7 @@ const experimentListTool = (ctx) => define({
7894
7967
 
7895
7968
  function recordDeps(ctx, exec, args, defaultFile) {
7896
7969
  const fs = fsService(ctx);
7897
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7898
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7970
+ const policy = resolveSandboxPolicy(ctx, exec);
7899
7971
  const path = recordPath(args, exec, policy?.workspaceRoot, defaultFile);
7900
7972
  return { fs, path, policy };
7901
7973
  }
@@ -7939,15 +8011,14 @@ const PAPER_IN_SCHEMA = {
7939
8011
  function paperServiceDeps(ctx, exec, args) {
7940
8012
  const fs = ctx.get('fs');
7941
8013
  if (fs === undefined) throw new MolbioInputError('the filesystem service is not available in this composition; the paper library needs ctx.fs');
7942
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7943
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
8014
+ const policy = resolveSandboxPolicy(ctx, exec);
7944
8015
  const path = libraryPath(args, exec, policy?.workspaceRoot);
7945
8016
  return { fs, path, policy };
7946
8017
  }
7947
8018
 
7948
8019
  const pubmedSearchTool = (ctx) => define({
7949
8020
  name: 'molbio_pubmed_search',
7950
- description: 'Search PubMed for literature. With an NCBI API key (the api_key argument, the harness credential store under NCBI_API_KEY / MOLBIO_NCBI_API_KEY, or the environment) it queries the official E-utilities API and returns PubMed records with PMIDs, titles, journal/year, authors and DOI; without a key it falls back to the harness web-search service. Add the papers you keep to the reading library with molbio_paper_add.',
8021
+ description: 'Search PubMed for literature. With an NCBI API key (the api_key argument, the harness credential store under NCBI_API_KEY / MOLBIO_NCBI_API_KEY, or the environment) it queries the official E-utilities API and returns PubMed records with PMIDs, titles, journal/year, authors and DOI; without a key it falls back to the harness web-search service. Add the papers you keep to the reading library with molbio_paper_add. One query returns the PMIDs: search once with the combined terms, then fetch abstracts only for the PMIDs you will cite.',
7951
8022
  parameters: {
7952
8023
  type: 'object',
7953
8024
  required: ['query'],
@@ -8016,7 +8087,7 @@ const pubmedSearchTool = (ctx) => define({
8016
8087
  const apiKey = await pubmedKey(args, ctx);
8017
8088
  if (apiKey !== undefined) {
8018
8089
  if (web === undefined || typeof web.fetch !== 'function') {
8019
- throw new MolbioInputError('an NCBI API key was provided, but this deployment provides no web fetch capability; the official PubMed API needs ctx.web.fetch');
8090
+ throw new MolbioInputError('an NCBI API key was provided, but this deployment provides no web fetch capability (a composition limit, not an argument problem); the official PubMed API needs ctx.web.fetch');
8020
8091
  }
8021
8092
  const search = await eutilsRequest(web, pubmedSearchUrl(args.query, maxResults, apiKey), exec?.signal, 'PubMed esearch');
8022
8093
  const { ids, count } = parseEsearch(search);
@@ -8368,7 +8439,7 @@ const signalPeptideTool = (ctx) => define({
8368
8439
  else lines.push(`candidate transmembrane segments: ${value.transmembrane_segments.map((s) => `${s.start}-${s.end} (${s.length} aa)`).join(', ')}`);
8369
8440
  lines.push('Heuristics: von Heijne 1986 weights and Kyte-Doolittle runs — candidates, not SignalP/TMHMM predictions; topology is not predicted.');
8370
8441
  lines.push(`score profile: ${value.svg_path}${value.auto_viewed ? ' (opened in the default viewer)' : ''}`);
8371
- return lines.join('\n');
8442
+ return lines.join('\n') + imageNote(value);
8372
8443
  },
8373
8444
  async execute(args, exec) {
8374
8445
  const analysis = signalPeptideAnalysis(args.sequence, {
@@ -8468,8 +8539,7 @@ const EXPORT_FEATURE_IN_SCHEMA = {
8468
8539
 
8469
8540
  async function writeTextOutput(ctx, exec, path, content) {
8470
8541
  const fs = fsService(ctx);
8471
- const sandboxPolicyService = ctx.get('sandboxPolicy');
8472
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
8542
+ const policy = resolveSandboxPolicy(ctx, exec);
8473
8543
  const file = workspaceFilePath(path, exec, policy?.workspaceRoot);
8474
8544
  await writeWorkspaceFile(fs, file, content, policy);
8475
8545
  return file;
@@ -8615,6 +8685,17 @@ async function readSequencingInputs(ctx, exec, args) {
8615
8685
  const reads = [];
8616
8686
  for (const path of args.paths ?? []) {
8617
8687
  const bytes = await readFileBytes(ctx, exec, path);
8688
+ const lower = String(path).toLowerCase();
8689
+ // A multi-record FASTA is a read SET, not a malformed trace: expand it into
8690
+ // one named read per record so a file can be handed over as-is.
8691
+ if (lower.endsWith('.fasta') || lower.endsWith('.fa') || lower.endsWith('.fna')) {
8692
+ const text = new TextDecoder().decode(bytes).replace(/^\uFEFF/, '');
8693
+ const entries = text.trimStart().startsWith('>') ? parseFasta(text) : [];
8694
+ if (entries.length > 1) {
8695
+ for (const entry of entries) reads.push({ name: entry.id, sequence: normalizeSequence(entry.sequence, `read ${entry.id}`) });
8696
+ continue;
8697
+ }
8698
+ }
8618
8699
  const trace = readTraceFromBytes(bytes, path);
8619
8700
  const name = String(path).split(/[\\/]/).pop().replace(/\.[^.]*$/, '') || 'read';
8620
8701
  reads.push({ name, sequence: trace.bases, qualities: trace.qualities });
@@ -8754,7 +8835,7 @@ const ALLELE_SCHEMA = {
8754
8835
 
8755
8836
  const editingOutcomeTool = (ctx) => define({
8756
8837
  name: 'molbio_editing_outcome',
8757
- description: 'Cluster ALL reads against the reference in ONE call and report each allele\'s frequency and (inside an optional CDS) its protein effect — do not call this once per read and do not re-derive the effect with molbio_translate, a script, or a shell command; the result already carries frameshift/missense/nonsense/silent/in_frame_indel. Pass every read in `reads` as [{name, sequence}] with sequences copied exactly (or pass `paths` for .ab1/.seq/.fasta files instead of retyping them), and pass the COMPLETE reference molecule in `reference` — not the CDS and not one of the reads; `cds_start`/`cds_end` are 1-based inclusive coordinates ON that reference. Reads align in both orientations; reads below the identity/span thresholds are reported as unaligned rather than forced into an allele. Frequencies are fractions of the ALIGNED reads (read-fraction clustering, NOT TIDE peak decomposition). A `wild_type` allele means a read identical to the reference; if you expected wild-type reads and none appear, check that `reference` is the full molecule.',
8838
+ description: 'Cluster ALL reads against the reference in ONE call and report each allele\'s frequency and (inside an optional CDS) its protein effect — do not call this once per read and do not re-derive the effect with molbio_translate, a script, or a shell command; the result already carries frameshift/missense/nonsense/silent/in_frame_indel. Pass every read in `reads` as [{name, sequence}] with sequences copied exactly (or pass `paths` for .ab1/.seq/.fasta files instead of retyping them), and pass the COMPLETE reference molecule in `reference` — not the CDS and not one of the reads; `cds_start`/`cds_end` are 1-based inclusive coordinates ON that reference. Reads align in both orientations; reads below the identity/span thresholds are reported as unaligned rather than forced into an allele. Frequencies are fractions of the ALIGNED reads (read-fraction clustering, NOT TIDE peak decomposition). A `wild_type` allele means a read identical to the reference; if you expected wild-type reads and none appear, check that `reference` is the full molecule. One call answers the whole read set: the CDS effect is already classified, so a translate pass, a shell script or a per-allele re-call adds nothing. Read fidelity decides the answer: prefer `paths`, and if you retype a sequence check its length against the reference first — one missing base turns a 3 bp in-frame deletion into a frameshift.',
8758
8839
  parameters: {
8759
8840
  type: 'object',
8760
8841
  properties: {
@@ -8810,38 +8891,56 @@ const editingOutcomeTool = (ctx) => define({
8810
8891
  },
8811
8892
  });
8812
8893
 
8813
- // ── prompt guidance for the v0.28.0 tools ──────────────────────────────────
8814
-
8815
- const NEW_PROMPT_LINES = [
8816
- '- Protein annotation (v0.28): molbio_protein_features (PTM motifs, SEG-style low-complexity regions, aromaticity, instability index), molbio_signal_peptide (von Heijne 1986 cleavage score + candidate transmembrane segments + a score SVG) and molbio_antigenicity (Kolaskar-Tongaonkar 7-mer propensity with Parker/Emini/Vihinen region means). All three are heuristics from published tables: never call them SignalP/TMHMM/NetNGlyc/BepiPred predictions.',
8817
- '- Formats and sequence surgery (v0.28): molbio_feature_export writes features as GFF3 (1-based inclusive), BED (0-based half-open) or CSV and states which convention it used; molbio_sequence_edit rotates/inserts/deletes/replaces/splits/joins and does NOT remap features — re-export annotations when an edit moves them.',
8818
- '- Sequencing read sets (v0.28): molbio_sanger_assemble builds a quality-weighted consensus contig from a few reads (both orientations, opt-in circular closure); molbio_editing_outcome clusters reads into alleles and classifies the CDS effect. Its frequencies are fractions of aligned reads, not TIDE peak decomposition.',
8894
+ // ── prompt guidance ─────────────────────────────────────────────────────────
8895
+ //
8896
+ // Routing and cross-tool rules ONLY. What a tool does, what its arguments mean
8897
+ // and which model or table it uses live in that tool's own description, so each
8898
+ // rule belongs in exactly one place. test/prompt.mjs enforces the split: it
8899
+ // fails on a registered tool this list never names, on a release marker such as
8900
+ // "(v19)", on a span copied from a tool description, on an over-long line, and
8901
+ // on a section over its character budget.
8902
+
8903
+ const PROMPT_SECTION = [
8904
+ 'Molecular-biology tools (dsh-molbio-tools) are available with the molbio_* prefix. Route by the question being asked: each tool description carries its arguments, its model and its limits, so read it before filling parameters.',
8905
+ '',
8906
+ '## Route by question',
8907
+ '- sequence basics — reverse complement, GC, translation and ORFs, where enzymes cut: molbio_reverse_complement, molbio_gc_content, molbio_translate, molbio_restriction_sites.',
8908
+ '- enzymes — catalog entry and cut geometry, Dam/Dcm blocking, two-enzyme plans: molbio_enzyme_lookup, molbio_methylation_check, molbio_double_digest.',
8909
+ '- primers — automatic pair design, a qPCR pair across an exon junction, Tm, red-flag screen: molbio_design_primers, molbio_design_intron_primers, molbio_primer_tm, molbio_primer_check.',
8910
+ '- probe assays and multiplexing — hydrolysis probe with an ordering CSV, several pairs in one tube: molbio_design_taqman, molbio_multiplex_check.',
8911
+ '- thermodynamics of one exact duplex: molbio_duplex_thermo.',
8912
+ '- qPCR numbers and bench math — Ct to fold change, standard curve, dilutions and molarity: molbio_qpcr_analysis, molbio_qpcr_efficiency, molbio_lab_math.',
8913
+ '- plasmids — open a GenBank text or a SnapGene .dna file, draw and annotate the map: molbio_parse_genbank, molbio_parse_snapgene, molbio_plasmid_map_file, molbio_plasmid_map.',
8914
+ '- cloning — unique cutters, restriction or Gibson simulation, Golden Gate, tails on primers: molbio_unique_cutters, molbio_clone_simulate, molbio_golden_gate, molbio_clone_primers.',
8915
+ '- mutagenesis — QuickChange-style primers, add or drop a site without changing the protein: molbio_mutagenesis_primers, molbio_silent_site_mutagenesis.',
8916
+ '- sequencing — verify a trace against the reference, assemble reads into a contig, classify editing outcomes: molbio_verify_sanger, molbio_sanger_assemble, molbio_editing_outcome.',
8917
+ '- proteins — properties and charge curve, peptide digest, codon optimisation, wheel, hydropathy: molbio_protein_props, molbio_protein_charge, molbio_peptide_digest, molbio_codon_optimize, molbio_helical_wheel, molbio_hydropathy_plot.',
8918
+ '- protein annotation — PTM motifs and low-complexity regions, signal peptide, antigenicity: molbio_protein_features, molbio_signal_peptide, molbio_antigenicity.',
8919
+ '- figures — experiment-data charts, expected gel: molbio_plot, molbio_virtual_gel.',
8920
+ '- alignments — pairwise, multiple, conservation, consensus and column trimming, logo, dotplot: molbio_align, molbio_msa_align, molbio_conservation, molbio_alignment_postprocess, molbio_sequence_logo, molbio_dotplot.',
8921
+ '- CRISPR guide candidates with off-target search: molbio_grna_design.',
8922
+ '- files — FASTA/FASTQ stats and conversion, read QC, trimming, vector/adapter screen: molbio_fasta_fastq, molbio_fastq_qc, molbio_fastq_trim, molbio_contamination_screen.',
8923
+ '- batch and formats — one table for a whole directory, region extraction, feature export (GFF3/BED/CSV), sequence surgery: molbio_batch_analyze, molbio_extract_region, molbio_feature_export, molbio_sequence_edit.',
8924
+ '- predictions over a sequence — in-silico PCR and expected bands, composition and CpG islands, phylogeny, codon usage: molbio_pcr_simulate, molbio_gc_composition, molbio_phylogenetic_tree, molbio_codon_usage.',
8925
+ '- literature and records — search, abstracts, BibTeX, reading library, protocols, experiment log: molbio_pubmed_search, molbio_pubmed_abstract, molbio_paper_export_bibtex, molbio_paper_add, molbio_paper_list, molbio_paper_update, molbio_paper_remove, molbio_protocol_add, molbio_protocol_list, molbio_protocol_update, molbio_experiment_log, molbio_experiment_list.',
8926
+ '',
8927
+ '## Hard rules',
8928
+ '1. Coordinates, feature positions and insert orientation come from tool output. Never re-derive them by reasoning, and never rebuild a feature list by hand.',
8929
+ '2. Call a tool once with all the input it takes — every read, every allele, every row. Do not re-call it per record, and do not recompute what it already returned with another tool, a script or a shell command.',
8930
+ '3. Files a tool writes (SVG, CSV, FASTA, GenBank) are reported by path — but a path is not the answer: state the numbers the tool computed (sizes, counts, quality, verdict) in the reply too. Do not reproduce file content; when one run writes several, pass auto_view: false and list the paths.',
8931
+ '4. Image tools open the SVG themselves (auto_view defaults to true; auto_viewed reports whether it worked). Tell the user it opened, and do not claim to have looked at the picture unless attach_image delivered it to you.',
8932
+ '5. Estimates stay labelled as estimates: Tm (SantaLucia-1998 nearest-neighbour), pI, A280, GRAVY, and every heuristic ranking (guide score, antigenicity, signal peptide, hydropathy peaks). Never present them as SignalP/TMHMM/BepiPred/BLAST/TIDE output.',
8933
+ '6. Positions are 1-based inclusive unless the tool or format says otherwise: GFF3 is 1-based inclusive, BED is 0-based half-open, and molbio_feature_export reports which one it wrote.',
8934
+ '7. A MolbioInputError that names an argument: fix that argument and retry. One that says a service or network failed is not an argument problem — retry the same call later, never recompute the biology by hand.',
8935
+ '8. Skip a tool call for a conceptual or literature-only question: these tools compute on real input, they are not needed to explain a method.',
8936
+ '',
8937
+ '## Conventions',
8938
+ '- Prefer a *_path argument over retyping a sequence; workspace files are the normal input.',
8939
+ '- When the numbers are already in a file, pass data_path with columns naming the roles. Do not retype a column into a call.',
8940
+ '- The reading library, protocols and experiments persist in papers.json, protocols.json and experiments.json in the workspace; every other tool is a pure computation.',
8941
+ '- Literature tools need the network: molbio_pubmed_search uses E-utilities when it has an NCBI key (api_key, credential store or environment) and otherwise falls back to the harness search.',
8942
+ '- Report numbers at the precision the tool returns, with units, and say which model produced them when it matters.',
8819
8943
  ].join('\n');
8820
- const PROMPT_SECTION = `Molecular-biology tools (dsh-molbio-tools) are available with the molbio_* prefix:
8821
- - Sequence math: molbio_reverse_complement, molbio_gc_content, molbio_translate, molbio_restriction_sites, molbio_methylation_check (which enzymes a Dam/Dcm-methylated template blocks, plus the enzymes that survive), molbio_double_digest (two enzymes: per-enzyme and combined fragments + whether they share a buffer).
8822
- - Primer work: molbio_design_primers (automatic pair design), molbio_design_intron_primers (qPCR primers spanning an exon-exon junction against a genomic sequence + exon list, so gDNA does not amplify), molbio_primer_tm, molbio_primer_check, molbio_duplex_thermo (ΔH/ΔS/ΔG°37/Tm for one exact duplex plus hairpin and dimer checks; a mismatched partner is refused, not estimated), molbio_design_taqman (hydrolysis-probe assay: primer pair + probe with the no-5'-G / probe-Tm-margin rules; probe_chemistry='mgb' for shorter MGB probes with an explicitly unmodified NN Tm, and save_path for an ordering CSV of F/R/P with modifications/scale/purification), molbio_multiplex_check (whether several primer pairs can share one tube: cross-dimers, cross-template annealing, gel-resolvable amplicon sizes, plus an annealing-temperature recommendation and a size-balanced starting primer-concentration plan).
8823
- - qPCR and bench math: molbio_qpcr_analysis, molbio_lab_math.
8824
- - Plasmids: molbio_parse_genbank (GenBank text), molbio_parse_snapgene (SnapGene .dna files — researchers usually have .dna files, so when the user names a .dna path use this), molbio_plasmid_map_file (reads a .dna/.gb file and writes the map SVG directly into the workspace in one call), molbio_plasmid_map (same, from a sequence + features). Both map tools WRITE the .svg file themselves and return svg_path — never try to reproduce SVG text in the conversation. Every image-writing tool (maps, plots, virtual gels, qPCR standard curves, clone/Golden Gate maps) opens the generated SVG automatically with the OS default application (auto_view defaults to true; the result's auto_viewed field says whether the hand-off worked), so there is normally nothing for the user to open manually; pass auto_view: false only when the caller explicitly wants no viewer window.
8825
- - Cloning: molbio_unique_cutters (pick enzymes that cut the vector once and never the insert), molbio_clone_simulate (restriction-ligation or Gibson assembly → final plasmid sequence + verification digests; pass save_path to write a FASTA), molbio_golden_gate (type IIS multi-fragment assembly: the tool designs the 4 bp junctions and the fragments-to-order, and simulates the final plasmid — use it for BsaI-style Golden Gate instead of reasoning about overhangs by hand), molbio_enzyme_lookup (enzyme catalog: recognition/cut geometry/overhang, plus every cut of a sequence in both strand orientations), molbio_clone_primers (enzyme tails or Gibson arms on amplification primers, with re-checks), molbio_mutagenesis_primers (QuickChange-style mutation primers), molbio_silent_site_mutagenesis (add or remove a restriction site with synonymous codons only, keeping the protein unchanged; the returned mutation_texts feed molbio_mutagenesis_primers).
8826
- - Verification: molbio_verify_sanger (read .ab1/.seq traces, align to the reference plasmid — circular-aware — and report mismatches/indels/amino-acid changes).
8827
- - Proteins: molbio_protein_props (MW/pI/A280/GRAVY — estimates), molbio_peptide_digest (trypsin etc. for MS), molbio_codon_optimize (E. coli/yeast/human, can avoid restriction sites), molbio_helical_wheel (Schiffer-Edmundson wheel + Eisenberg hydrophobic moment, written as an SVG), molbio_hydropathy_plot (Kyte-Doolittle sliding-window profile with the 1.6 threshold peaks, written as an SVG).
8828
- - Quantitation: molbio_qpcr_efficiency (standard curve + plot), molbio_plot (experiment-data charts written to files), molbio_virtual_gel (expected band pattern as an SVG gel image with a size ladder).
8829
- - molbio_plot kinds: bar (labelled values + optional SD error bars) and scatter (x/y + optional least-squares line) take their arrays directly in the call; the table kinds read a workspace CSV/TSV — pass data_path plus columns naming which column plays which role, or pass data with the table text inline. Use a table kind whenever the numbers are already in a file: do NOT retype a column into the call. line = one series per group_column; histogram = distribution of one column (bins default to Freedman-Diaconis unless you pass bins); box = Q1-Q3 box, median, 1.5xIQR whiskers, outliers as dots; violin = the same samples as a kernel-density silhouette with the box summary inside (use it when the SHAPE matters, not just the five numbers); volcano = effect size against significance from a log2-fold-change column and a p column, with dashed thresholds — it computes no statistics of its own, so the p-values must already be in the table; heatmap = a row x column matrix, one cell per value plus a colour bar, accepting either a wide table (first column = row labels, the rest = samples) or the long form (columns.row/column/value), with scale row_zscore|log2 as an explicitly-reported DISPLAY transform. The result carries the computed statistics (medians, quartiles, outliers, bin counts, axis ranges, significance counts, matrix extent), so quote THOSE instead of estimating values off the picture.
8830
- - Sequences & files: molbio_align (local alignment with a readable match line), molbio_msa_align (progressive multiple sequence alignment — pass an array of sequences or a workspace FASTA), molbio_conservation (consensus + per-column identity/conservation + variable positions; accepts aligned rows or raw sequences it aligns first), molbio_sequence_logo (draws the same alignment as a sequence logo SVG — pass the molbio_msa_align output rows as the alignment argument; letters are sized by per-position information content), molbio_fasta_fastq (FASTA/FASTQ stats/extract/convert/QC on workspace files), molbio_contamination_screen (embedded short vector/adapter signatures, both strands, exact or 0-2 mismatches — a short-signature screen, not BLAST), molbio_batch_analyze (run one summary/ORF/enzyme analysis over every matching FASTA/FASTQ/GenBank/.dna file in a directory and write one CSV/TSV table), molbio_extract_region (pull a CDS/promoter/region from a plasmid file by feature label or coordinates).
8831
- - CRISPR: molbio_grna_design (family-aware guide RNAs over a sequence or plasmid file: cas_family spcas9/sacas9/cas12a/cas13a/cas13b/cas13d selects the PAM side, crRNA length, seed and target type — Cas12a uses a 5' TTTV PAM and 23 nt crRNA; Cas13 targets RNA and reports a PFS preference rather than a PAM. Both strands are scanned for DNA families, the sense strand by default for Cas13; guides are filtered on GC/poly-T/self-complementarity and ranked, with a mismatch-tolerant off-target search over the same sequence — reaching a whole genome simply means passing it as the target). Pass the top candidates on for ordering with save_path (CSV) or map_path (SVG map); the ranking is a heuristic and says so, so present it as candidate ranking, never as a validated efficiency prediction.
8832
- - Map extras: pass gc_skew: true for the GC skew ring, show_unique_cutters: true to mark single-cutting enzymes on the map.
8833
- - Literature & records: molbio_pubmed_abstract (fetch abstracts by PMID — needs web fetch; an NCBI key comes from the api_key argument, the credential store's NCBI_API_KEY, or the environment), molbio_paper_export_bibtex (papers.json → .bib), molbio_protocol_add / molbio_protocol_list / molbio_protocol_update (protocols.json), molbio_experiment_log / molbio_experiment_list (experiments.json).
8834
- - Bench analysis (v19): molbio_fastq_qc (read-level QC for a FASTQ file: per-base quality with quartiles, per-read quality, base content, GC distribution, length, exact duplication, over-represented sequences, adapter screen, plus a report SVG — use it for "is this run good"), molbio_codon_usage (CAI/RSCU/Nc/GC3, rare-codon list and CDS CpG against E. coli/yeast/human — use it for "will this gene express"; it explains, molbio_codon_optimize rewrites), molbio_phylogenetic_tree (distance method: p-distance/JC/K2P/Tamura-Nei, UPGMA or neighbour-joining, bootstrap support, consensus, Newick file and an SVG tree — it is NOT a maximum-likelihood or Bayesian analysis, and bootstrap percentages are not p-values), molbio_pcr_simulate (where a primer pair amplifies: product sizes and coordinates on both strands, mismatch detail, the 3'-end exact-match requirement, circular templates, screening other templates, and an expected gel — use it for "what band will I see"), molbio_gc_composition (sliding-window GC, CpG islands under the Gardiner-Garden or Takai criteria, GC/AT skew with the cumulative-skew origin/terminus indication, dinucleotide obs/exp, entropy, complexity, N50/L50, plus a figure — use it for "is this a promoter or an origin"), molbio_fastq_trim (trim low-quality 3' tails, exact adapters/primers, poly-G/poly-A, then filter by length/N and write FASTQ/FASTA — not a paired-end merger).
8835
- - Literature: molbio_pubmed_search — with an NCBI API key (api_key argument, the credential store under NCBI_API_KEY / MOLBIO_NCBI_API_KEY, or the environment) it uses the official PubMed E-utilities API and returns PMIDs, titles, journal/year, authors and DOI; without a key it falls back to the harness web search. The reading library is molbio_paper_add / molbio_paper_list / molbio_paper_update / molbio_paper_remove (papers.json in the workspace).
8836
-
8837
- ${NEW_PROMPT_LINES}
8838
-
8839
- Cloning workflow rules (follow them to avoid slow re-derivation):
8840
- - To clone a sequence into a plasmid, call molbio_clone_simulate FIRST — pass the BARE insert with add_flanks: true and the tool adds the enzyme recognition sites itself. The tool also validates single cutting, insert orientation, and internal sites itself: never pre-verify enzymes, cutting counts, or flank construction by thinking. Its output already contains final_sequence AND the remapped feature coordinates (features field). NEVER recompute feature coordinates or insert positions by reasoning — always take them from the tool output.
8841
- - To draw the new plasmid, either pass map_path to molbio_clone_simulate (one call writes the SVG with remapped features and verification enzymes marked) or feed its features + final_sequence to molbio_plasmid_map. Never rebuild the feature list by hand.
8842
- - Insert orientation is the tool's job: orientation=auto (the default) reverse-complements an inverted insert automatically. If the tool still reports an inverted insert, pass orientation=reverse instead of re-deriving coordinates.
8843
- - Never parse tool outputs with regex, shell commands, or throwaway scripts — every tool returns structured data that feeds the next tool directly. Mutation descriptions (A123G etc.) are parsed by molbio_mutagenesis_primers, not by you.
8844
- - All tools are pure computations except the paper library, pubmed search, and file-backed outputs, which use the harness filesystem and web services under the usual sandbox policy. The Tm model is a SantaLucia-1998 nearest-neighbour estimate — always say it is an estimate.`;
8845
8944
 
8846
8945
  export function apply(ctx) {
8847
8946
  ctx.systemPrompt.section({
@@ -8866,7 +8965,7 @@ export function apply(ctx) {
8866
8965
  multiplexTool,
8867
8966
  methylationTool,
8868
8967
  doubleDigestTool,
8869
- parseGenbankTool,
8968
+ parseGenbankTool(ctx),
8870
8969
  plasmidMapTool(ctx),
8871
8970
  parseSnapgeneTool(ctx),
8872
8971
  plasmidMapFileTool(ctx),
@@ -8886,7 +8985,7 @@ export function apply(ctx) {
8886
8985
  qpcrEfficiencyTool(ctx),
8887
8986
  plotTool(ctx),
8888
8987
  virtualGelTool(ctx),
8889
- alignTool,
8988
+ alignTool(ctx),
8890
8989
  msaAlignTool(ctx),
8891
8990
  conservationTool(ctx),
8892
8991
  alignmentPostprocessTool(ctx),