dsh-molbio-tools 0.28.1 → 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/genbank.mjs CHANGED
@@ -41,15 +41,35 @@ function parseLocation(raw) {
41
41
  const parts = [...cleaned.matchAll(/\d+(?:\.\.\d+)?/g)];
42
42
  const numbers = [...cleaned.matchAll(/\d+/g)].map((match) => Number(match[0]));
43
43
  if (numbers.length === 0) return undefined;
44
+ // Reduce with a loop, never `Math.min(...numbers)`: a 20 Mb join() with a few
45
+ // hundred thousand parts is a real NCBI record shape, and spreading it into
46
+ // the argument list throws `RangeError: Maximum call stack size exceeded`
47
+ // instead of returning a span.
48
+ let start = numbers[0];
49
+ let end = numbers[0];
50
+ for (const number of numbers) {
51
+ if (number < start) start = number;
52
+ if (number > end) end = number;
53
+ }
44
54
  return {
45
- start: Math.min(...numbers),
46
- end: Math.max(...numbers),
55
+ start,
56
+ end,
47
57
  strand: /complement/i.test(raw) ? -1 : 1,
48
58
  raw: raw.trim(),
49
59
  multiPart: parts.length > 1,
50
60
  };
51
61
  }
52
62
 
63
+ /** Does this location still have an unclosed `(` (i.e. it wraps onto the next line)? */
64
+ function isLocationOpen(text) {
65
+ let depth = 0;
66
+ for (const character of text) {
67
+ if (character === '(') depth += 1;
68
+ else if (character === ')') depth = Math.max(0, depth - 1);
69
+ }
70
+ return depth > 0;
71
+ }
72
+
53
73
  /** Parse one qualifier line: /key="value" (or unquoted value). */
54
74
  function parseQualifier(line) {
55
75
  const match = /^\s*\/?([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(?:"([^"]*)"|(\S+))/.exec(line);
@@ -82,6 +102,31 @@ export function parseGenBank(text) {
82
102
  let inOrigin = false;
83
103
  let currentFeature = undefined;
84
104
  let currentQualifier = undefined;
105
+ let currentLocation = '';
106
+ let locationOpen = false;
107
+ let placed = false;
108
+
109
+ /** Publish the current feature once its location can be placed. */
110
+ const placeCurrentFeature = () => {
111
+ if (currentFeature === undefined) return;
112
+ const parsedLocation = parseLocation(currentLocation);
113
+ if (parsedLocation === undefined) return;
114
+ currentFeature.location = parsedLocation;
115
+ if (!placed) {
116
+ features.push(currentFeature);
117
+ placed = true;
118
+ }
119
+ };
120
+
121
+ /** Count a feature that never got a placeable location, then reset per-feature state. */
122
+ const finishFeature = () => {
123
+ if (currentFeature !== undefined && !placed) skippedFeatures += 1;
124
+ currentFeature = undefined;
125
+ currentQualifier = undefined;
126
+ currentLocation = '';
127
+ locationOpen = false;
128
+ placed = false;
129
+ };
85
130
 
86
131
  for (let i = locusIndex; i < lines.length; i++) {
87
132
  const line = lines[i];
@@ -92,29 +137,35 @@ export function parseGenBank(text) {
92
137
  }
93
138
  if (inFeatures) {
94
139
  if (/^ORIGIN/.test(line)) {
140
+ finishFeature();
95
141
  inFeatures = false;
96
142
  inOrigin = true;
97
143
  continue;
98
144
  }
99
145
  if (/^\s{5}\S/.test(line)) {
100
146
  // New feature: 5 spaces, then type and location.
147
+ finishFeature();
101
148
  const match = /^\s{5}(\S+)\s*(.*)$/.exec(line);
102
149
  if (match === null) {
103
150
  skippedFeatures += 1;
104
151
  continue;
105
152
  }
106
- currentFeature = {
107
- type: match[1],
108
- location: parseLocation(match[2] ?? ''),
109
- qualifiers: {},
110
- };
111
- if (currentFeature.location === undefined) {
112
- // No digits in the location: the feature cannot be placed. It is
113
- // dropped, and the caller reports the count.
114
- skippedFeatures += 1;
115
- continue;
116
- }
117
- features.push(currentFeature);
153
+ currentFeature = { type: match[1], location: undefined, qualifiers: {} };
154
+ currentLocation = match[2] ?? '';
155
+ locationOpen = isLocationOpen(currentLocation);
156
+ placeCurrentFeature();
157
+ continue;
158
+ }
159
+ // A location wider than the column wraps onto 21-space continuation lines
160
+ // (`join(1..10,30..40,` + `50..60,70..80)`), which is how NCBI writes any
161
+ // long join(). Such a line belongs to the LOCATION. It used to be read as
162
+ // a qualifier continuation only, so the span silently stopped at the first
163
+ // line and every downstream coordinate (map, batch table, feature counts)
164
+ // sat on the wrong bases.
165
+ if (locationOpen && /^\s{21}[0-9()][0-9,().^<>?\s]*$/.test(line)) {
166
+ currentLocation += line.trim();
167
+ locationOpen = isLocationOpen(currentLocation);
168
+ placeCurrentFeature();
118
169
  continue;
119
170
  }
120
171
  if (/^\s{21}\//.test(line) && currentFeature !== undefined) {
package/host.mjs CHANGED
@@ -27,7 +27,7 @@
27
27
  *
28
28
  * ── WHY NOT JUST ANCHOR ON index.mjs ───────────────────────────────────────
29
29
  *
30
- * `index.mjs` is the TOOL plugin: importing it must register all 65 tools and
30
+ * `index.mjs` is the TOOL plugin: importing it must register all 72 tools and
31
31
  * a prompt section. A host row naming it would put every tool back into every
32
32
  * session, which is the thing the preset split exists to avoid. This anchor is
33
33
  * deliberately inert.
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.';
@@ -1201,14 +1226,14 @@ const PRIMER_SCHEMA = {
1201
1226
  length: { type: 'integer' },
1202
1227
  tm: { type: 'number' },
1203
1228
  gc_percent: { type: 'number' },
1204
- self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score (v12).' },
1205
- self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score (v12).' },
1206
- hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none; v12).' },
1207
- end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol (v12).' },
1208
- end_gc_count: { type: 'integer', description: 'G/C bases among the last five 3\' bases (v12).' },
1209
- 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).' },
1210
1235
  mismatches: { type: 'array', items: MISMATCH_SCHEMA },
1211
- 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).' },
1212
1237
  mispriming_sites: { type: 'array', items: MISPRIMING_SITE_SCHEMA },
1213
1238
  target_distance: { type: 'integer', description: 'v13: bp between the primer 3\' end and target_position (present only when target_position is given).' },
1214
1239
  },
@@ -1620,8 +1645,7 @@ const taqmanTool = (ctx) => define({
1620
1645
  let savedTo = '';
1621
1646
  if (args.save_path !== undefined && args.save_path !== '') {
1622
1647
  const fs = fsService(ctx);
1623
- const sandboxPolicyService = ctx.get('sandboxPolicy');
1624
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
1648
+ const policy = resolveSandboxPolicy(ctx, exec);
1625
1649
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
1626
1650
  await writeWorkspaceFile(fs, file, taqmanOrderCsv(order), policy);
1627
1651
  savedTo = file;
@@ -2205,8 +2229,7 @@ function svgFileName(name) {
2205
2229
  */
2206
2230
  async function writeSvgFile(ctx, exec, args, svg, defaultName) {
2207
2231
  const fs = fsService(ctx);
2208
- const sandboxPolicyService = ctx.get('sandboxPolicy');
2209
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
2232
+ const policy = resolveSandboxPolicy(ctx, exec);
2210
2233
  const file = workspaceFilePath(args.output_path ?? svgFileName(defaultName), exec, policy?.workspaceRoot);
2211
2234
  await writeWorkspaceFile(fs, file, svg, policy);
2212
2235
  let viewed = false;
@@ -2234,7 +2257,7 @@ async function autoViewWritten(args, file) {
2234
2257
  const plasmidMapTool = (ctx) => define({
2235
2258
  safe: false,
2236
2259
  name: 'molbio_plasmid_map',
2237
- 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.',
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.',
2238
2261
  parameters: {
2239
2262
  type: 'object',
2240
2263
  required: ['sequence'],
@@ -2335,6 +2358,18 @@ const plasmidMapTool = (ctx) => define({
2335
2358
 
2336
2359
  const MAX_DNA_BYTES = 50 * 1024 * 1024;
2337
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
+
2338
2373
  function fsService(ctx) {
2339
2374
  const fs = ctx.get('fs');
2340
2375
  if (fs === undefined) throw new MolbioInputError('the filesystem service is not available in this composition; reading .dna/.gb files needs ctx.fs');
@@ -2348,8 +2383,7 @@ async function readFileBytes(ctx, exec, path) {
2348
2383
  // default (process.cwd()), which is why tool-fs asks `workingDirectory` for
2349
2384
  // the agent's cwd; the sandbox policy carries the same root here. Absolute
2350
2385
  // paths are still accepted unchanged (workspaceFilePath leaves them alone).
2351
- const sandboxPolicyService = ctx.get('sandboxPolicy');
2352
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
2386
+ const policy = resolveSandboxPolicy(ctx, exec);
2353
2387
  const target = await fs.resolve(workspaceFilePath(path, exec, policy?.workspaceRoot), { signal: exec?.signal });
2354
2388
  return await fs.readBytes(target, exec?.signal, MAX_DNA_BYTES);
2355
2389
  }
@@ -2439,7 +2473,7 @@ const parseSnapgeneTool = (ctx) => define({
2439
2473
  const plasmidMapFileTool = (ctx) => define({
2440
2474
  safe: false,
2441
2475
  name: 'molbio_plasmid_map_file',
2442
- 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.',
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.',
2443
2477
  parameters: {
2444
2478
  type: 'object',
2445
2479
  required: ['path'],
@@ -2639,11 +2673,11 @@ const INTRON_PRIMER_SCHEMA = {
2639
2673
  length: { type: 'integer' },
2640
2674
  tm: { type: 'number' },
2641
2675
  gc_percent: { type: 'number' },
2642
- self_any: { type: 'number', description: 'Primer3-style self-complementarity alignment score (v12).' },
2643
- self_end: { type: 'number', description: 'Primer3-style 3\'-anchored self-complementarity score (v12).' },
2644
- hairpin_tm: { type: 'number', description: 'Melting temperature of the most stable hairpin (°C, 0 = none; v12).' },
2645
- end_stability_kcal: { type: 'number', description: 'ΔG(37 °C) of the last five 3\' bases in kcal/mol (v12).' },
2646
- 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.' },
2647
2681
  spliced_start: { type: 'integer' },
2648
2682
  spliced_end: { type: 'integer' },
2649
2683
  genomic_start: { type: 'integer' },
@@ -2652,9 +2686,9 @@ const INTRON_PRIMER_SCHEMA = {
2652
2686
  exon: { type: 'integer' },
2653
2687
  junction_left: { type: 'integer' },
2654
2688
  junction_right: { type: 'integer' },
2655
- 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).' },
2656
2690
  mismatches: { type: 'array', items: INTRON_MISMATCH_SCHEMA },
2657
- 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).' },
2658
2692
  mispriming_sites: { type: 'array', items: INTRON_MISPRIMING_SITE_SCHEMA },
2659
2693
  target_distance: { type: 'integer', description: 'v13: spliced bp between the primer 3\' end and target_position (present only when target_position is given).' },
2660
2694
  },
@@ -3151,8 +3185,7 @@ const cloneSimulateTool = (ctx) => define({
3151
3185
  ...result.insert_reverse_complemented !== undefined ? { insert_reverse_complemented: result.insert_reverse_complemented } : {},
3152
3186
  };
3153
3187
  const fs = fsService(ctx);
3154
- const sandboxPolicyService = ctx.get('sandboxPolicy');
3155
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
3188
+ const policy = resolveSandboxPolicy(ctx, exec);
3156
3189
  if (args.save_path !== undefined && args.save_path !== '') {
3157
3190
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
3158
3191
  await writeWorkspaceFile(fs, file, `>${vector.name}_clone ${method}\n${result.final_sequence}\n`, policy);
@@ -3175,7 +3208,7 @@ const cloneSimulateTool = (ctx) => define({
3175
3208
  out.map_path = file;
3176
3209
  out.auto_viewed = await autoViewWritten(args, file);
3177
3210
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, `${vector.name}_clone`) ?? {});
3178
- }
3211
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when map_path names the file to write'));
3179
3212
  return out;
3180
3213
  },
3181
3214
  });
@@ -3326,8 +3359,7 @@ const goldenGateTool = (ctx) => define({
3326
3359
  notes: result.notes,
3327
3360
  };
3328
3361
  const fs = fsService(ctx);
3329
- const sandboxPolicyService = ctx.get('sandboxPolicy');
3330
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
3362
+ const policy = resolveSandboxPolicy(ctx, exec);
3331
3363
  if (args.save_path !== undefined && args.save_path !== '') {
3332
3364
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
3333
3365
  await writeWorkspaceFile(fs, file, `>${vector.name}_golden_gate ${result.enzyme}\n${result.final_sequence}\n`, policy);
@@ -3350,7 +3382,7 @@ const goldenGateTool = (ctx) => define({
3350
3382
  out.map_path = file;
3351
3383
  out.auto_viewed = await autoViewWritten(args, file);
3352
3384
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, `${vector.name}_golden_gate`) ?? {});
3353
- }
3385
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when map_path names the file to write'));
3354
3386
  return out;
3355
3387
  },
3356
3388
  });
@@ -4216,8 +4248,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4216
4248
  };
4217
4249
  if (args.plot_path !== undefined && args.plot_path !== '') {
4218
4250
  const fs = fsService(ctx);
4219
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4220
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4251
+ const policy = resolveSandboxPolicy(ctx, exec);
4221
4252
  const file = workspaceFilePath(args.plot_path, exec, policy?.workspaceRoot);
4222
4253
  const svg = renderScatterChart({
4223
4254
  title: 'qPCR standard curve',
@@ -4231,7 +4262,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4231
4262
  out.plot_path = file;
4232
4263
  out.auto_viewed = await autoViewWritten(args, file);
4233
4264
  Object.assign(out, await withAttachedImage(ctx, exec, args, svg, 'qpcr-standard-curve') ?? {});
4234
- }
4265
+ } else Object.assign(out, attachImageWithoutPicture(args, 'this tool only draws when plot_path names the file to write'));
4235
4266
  return out;
4236
4267
  },
4237
4268
  });
@@ -4250,8 +4281,7 @@ const qpcrEfficiencyTool = (ctx) => define({
4250
4281
  */
4251
4282
  async function resolveChartTable(ctx, exec, args) {
4252
4283
  const fs = fsService(ctx);
4253
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4254
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4284
+ const policy = resolveSandboxPolicy(ctx, exec);
4255
4285
  const table = await resolveTable(args, async (path) => {
4256
4286
  const target = workspaceFilePath(path, exec, policy?.workspaceRoot);
4257
4287
  // Check existence first: a missing file otherwise reaches the parser as an
@@ -4909,8 +4939,7 @@ const msaAlignTool = (ctx) => define({
4909
4939
  let savedTo = '';
4910
4940
  if (args.save_path !== undefined && args.save_path !== '') {
4911
4941
  const fs = fsService(ctx);
4912
- const sandboxPolicyService = ctx.get('sandboxPolicy');
4913
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
4942
+ const policy = resolveSandboxPolicy(ctx, exec);
4914
4943
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
4915
4944
  await writeWorkspaceFile(fs, file, toFasta(result.alignment.map((row) => ({ id: row.id, description: '', sequence: row.sequence }))), policy);
4916
4945
  savedTo = file;
@@ -5515,8 +5544,7 @@ const grnaDesignTool = (ctx) => define({
5515
5544
  let savedTo = '';
5516
5545
  if (args.save_path !== undefined && args.save_path !== '') {
5517
5546
  const fs = fsService(ctx);
5518
- const sandboxPolicyService = ctx.get('sandboxPolicy');
5519
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
5547
+ const policy = resolveSandboxPolicy(ctx, exec);
5520
5548
  const file = workspaceFilePath(args.save_path, exec, policy?.workspaceRoot);
5521
5549
  await writeWorkspaceFile(fs, file, guideCsv(guides, result.cas_family), policy);
5522
5550
  savedTo = file;
@@ -5742,8 +5770,7 @@ const fastaFastqTool = (ctx) => define({
5742
5770
  if (action === 'qc' && format !== 'fastq') throw new MolbioInputError('action=qc needs a FASTQ file');
5743
5771
  let savedTo = '';
5744
5772
  const fs = fsService(ctx);
5745
- const sandboxPolicyService = ctx.get('sandboxPolicy');
5746
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
5773
+ const policy = resolveSandboxPolicy(ctx, exec);
5747
5774
  if (action === 'extract') {
5748
5775
  if (args.id === undefined || args.id === '') throw new MolbioInputError('action=extract needs an id');
5749
5776
  const exact = parsed.filter((entry) => entry.id === args.id);
@@ -5856,7 +5883,7 @@ async function batchFileList(ctx, exec, args, policy, root) {
5856
5883
  if (info === undefined || info.type !== 'directory') {
5857
5884
  throw new MolbioInputError('batch directory ' + JSON.stringify(args.directory ?? '.') + ' is not a directory');
5858
5885
  }
5859
- const pattern = globToRegExp(args.pattern ?? '*');
5886
+ const pattern = args.pattern ?? '*';
5860
5887
  const recursive = args.recursive === true;
5861
5888
  const maxFiles = Math.min(args.max_files ?? 50, BATCH_LIMITS.maxFiles);
5862
5889
  let totalBytes = 0;
@@ -5879,7 +5906,7 @@ async function batchFileList(ctx, exec, args, policy, root) {
5879
5906
  }
5880
5907
  if (entry.type !== 'file') continue;
5881
5908
  const haystack = String(args.pattern ?? '').includes('/') ? label : entry.name;
5882
- if (!pattern.test(haystack)) continue;
5909
+ if (!globMatches(pattern, haystack)) continue;
5883
5910
  files.push({ target: entry.target, label, size: entry.size });
5884
5911
  totalBytes += entry.size ?? 0;
5885
5912
  if (totalBytes > BATCH_LIMITS.maxTotalBytes) {
@@ -5982,7 +6009,7 @@ const batchAnalyzeTool = (ctx) => define({
5982
6009
  return lines.join('\n');
5983
6010
  },
5984
6011
  async execute(args, exec) {
5985
- const policy = ctx.get('sandboxPolicy')?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
6012
+ const policy = resolveSandboxPolicy(ctx, exec);
5986
6013
  const root = policy?.workspaceRoot ?? exec?.agent?.session?.header?.cwd ?? process.cwd();
5987
6014
  const analysis = args.analysis ?? 'summary';
5988
6015
  const wantsOrf = analysis === 'orf' || analysis === 'all';
@@ -6221,8 +6248,7 @@ const extractRegionTool = (ctx) => define({
6221
6248
  let savedTo = '';
6222
6249
  if (args.output_path !== undefined && args.output_path !== '') {
6223
6250
  const fs = fsService(ctx);
6224
- const sandboxPolicyService = ctx.get('sandboxPolicy');
6225
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
6251
+ const policy = resolveSandboxPolicy(ctx, exec);
6226
6252
  const file = workspaceFilePath(args.output_path, exec, policy?.workspaceRoot);
6227
6253
  await writeWorkspaceFile(fs, file, `>${vector.name}_${start}-${end}\n${fragment}\n`, policy);
6228
6254
  savedTo = file;
@@ -7109,8 +7135,7 @@ const fastqTrimTool = (ctx) => define({
7109
7135
  });
7110
7136
  const outputFormat = args.output_format ?? 'fastq';
7111
7137
  const fs = fsService(ctx);
7112
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7113
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7138
+ const policy = resolveSandboxPolicy(ctx, exec);
7114
7139
  const file = workspaceFilePath(args.output_path, exec, policy?.workspaceRoot);
7115
7140
  await writeWorkspaceFile(fs, file, outputFormat === 'fasta' ? toFasta(trimmed.entries) : toFastq(trimmed.entries), policy);
7116
7141
  return { ...trimmed.stats, saved_to: file, output_format: outputFormat };
@@ -7397,8 +7422,7 @@ const phylogeneticTreeTool = (ctx) => define({
7397
7422
  },
7398
7423
  async execute(args, exec) {
7399
7424
  const fs = fsService(ctx);
7400
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7401
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7425
+ const policy = resolveSandboxPolicy(ctx, exec);
7402
7426
  // 1. Collect the input rows.
7403
7427
  let entries;
7404
7428
  if (args.sequences !== undefined && args.sequences.length > 0) {
@@ -7537,7 +7561,7 @@ async function eutilsRequest(web, url, signal, label) {
7537
7561
  try {
7538
7562
  result = await web.fetch({ url }, signal);
7539
7563
  } catch (error) {
7540
- 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)}`);
7541
7565
  }
7542
7566
  const body = result?.body?.content;
7543
7567
  if (typeof body !== 'string' || body === '') {
@@ -7631,7 +7655,7 @@ const pubmedAbstractTool = (ctx) => define({
7631
7655
  if (pmids.length === 0) throw new MolbioInputError('pmids must contain numeric PubMed IDs');
7632
7656
  const web = ctx.get('web');
7633
7657
  if (web === undefined || typeof web.fetch !== 'function') {
7634
- 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');
7635
7659
  }
7636
7660
  const apiKey = await pubmedKey(args, ctx);
7637
7661
  const url = pubmedFetchUrl(pmids, apiKey);
@@ -7641,7 +7665,7 @@ const pubmedAbstractTool = (ctx) => define({
7641
7665
  } catch (error) {
7642
7666
  // Same contract as eutilsRequest: a transport failure is a tool-input
7643
7667
  // error the caller can report, not a raw exception escaping the tool.
7644
- 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)}`);
7645
7669
  }
7646
7670
  const body = result?.body?.content;
7647
7671
  if (typeof body !== 'string' || body === '') {
@@ -7943,8 +7967,7 @@ const experimentListTool = (ctx) => define({
7943
7967
 
7944
7968
  function recordDeps(ctx, exec, args, defaultFile) {
7945
7969
  const fs = fsService(ctx);
7946
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7947
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
7970
+ const policy = resolveSandboxPolicy(ctx, exec);
7948
7971
  const path = recordPath(args, exec, policy?.workspaceRoot, defaultFile);
7949
7972
  return { fs, path, policy };
7950
7973
  }
@@ -7988,8 +8011,7 @@ const PAPER_IN_SCHEMA = {
7988
8011
  function paperServiceDeps(ctx, exec, args) {
7989
8012
  const fs = ctx.get('fs');
7990
8013
  if (fs === undefined) throw new MolbioInputError('the filesystem service is not available in this composition; the paper library needs ctx.fs');
7991
- const sandboxPolicyService = ctx.get('sandboxPolicy');
7992
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
8014
+ const policy = resolveSandboxPolicy(ctx, exec);
7993
8015
  const path = libraryPath(args, exec, policy?.workspaceRoot);
7994
8016
  return { fs, path, policy };
7995
8017
  }
@@ -8065,7 +8087,7 @@ const pubmedSearchTool = (ctx) => define({
8065
8087
  const apiKey = await pubmedKey(args, ctx);
8066
8088
  if (apiKey !== undefined) {
8067
8089
  if (web === undefined || typeof web.fetch !== 'function') {
8068
- 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');
8069
8091
  }
8070
8092
  const search = await eutilsRequest(web, pubmedSearchUrl(args.query, maxResults, apiKey), exec?.signal, 'PubMed esearch');
8071
8093
  const { ids, count } = parseEsearch(search);
@@ -8417,7 +8439,7 @@ const signalPeptideTool = (ctx) => define({
8417
8439
  else lines.push(`candidate transmembrane segments: ${value.transmembrane_segments.map((s) => `${s.start}-${s.end} (${s.length} aa)`).join(', ')}`);
8418
8440
  lines.push('Heuristics: von Heijne 1986 weights and Kyte-Doolittle runs — candidates, not SignalP/TMHMM predictions; topology is not predicted.');
8419
8441
  lines.push(`score profile: ${value.svg_path}${value.auto_viewed ? ' (opened in the default viewer)' : ''}`);
8420
- return lines.join('\n');
8442
+ return lines.join('\n') + imageNote(value);
8421
8443
  },
8422
8444
  async execute(args, exec) {
8423
8445
  const analysis = signalPeptideAnalysis(args.sequence, {
@@ -8517,8 +8539,7 @@ const EXPORT_FEATURE_IN_SCHEMA = {
8517
8539
 
8518
8540
  async function writeTextOutput(ctx, exec, path, content) {
8519
8541
  const fs = fsService(ctx);
8520
- const sandboxPolicyService = ctx.get('sandboxPolicy');
8521
- const policy = sandboxPolicyService?.resolve({ ...exec?.agent !== undefined ? { session: exec.agent.session } : {} });
8542
+ const policy = resolveSandboxPolicy(ctx, exec);
8522
8543
  const file = workspaceFilePath(path, exec, policy?.workspaceRoot);
8523
8544
  await writeWorkspaceFile(fs, file, content, policy);
8524
8545
  return file;
@@ -8910,7 +8931,7 @@ const PROMPT_SECTION = [
8910
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.',
8911
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.',
8912
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.',
8913
- '7. On a MolbioInputError, fix the arguments and retry. Do not fall back to computing the biology by hand.',
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.',
8914
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.',
8915
8936
  '',
8916
8937
  '## Conventions',