@gcszhn/mol4agent-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,9 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
28
28
  - Commands are JSON-serializable; **loading is a method, not a command**, because
29
29
  adapter-owned bytes may not be serializable.
30
30
  - `@gcszhn/mol4agent-core/parse` is pure and works in Node and the browser.
31
+ - `@gcszhn/mol4agent-core/sources` is pure too: it turns an entry id into a
32
+ download plan (`url`, optional JSON `indexField`, format, file name). Network
33
+ access and file writes stay in the adapter.
31
34
 
32
35
  ## Install
33
36
 
@@ -37,10 +40,10 @@ pnpm add @gcszhn/mol4agent-core molstar
37
40
  pnpm add react
38
41
  ```
39
42
 
40
- The package is not published to npm yet; from this monorepo use the workspace
41
- link. The command above applies once `0.1.0` is published. `molstar` and `react`
42
- are peer dependencies. The DSH adapter bundles Mol* into a single client script;
43
- a plain web app can use the package directly.
43
+ The package is published on npm as `@gcszhn/mol4agent-core@0.3.0`; inside this
44
+ monorepo, pnpm links the workspace copy instead. `molstar` and `react` are peer
45
+ dependencies. The DSH adapter bundles Mol* into a single client script; a plain
46
+ web app can use the package directly.
44
47
 
45
48
  Build and pack:
46
49
 
@@ -57,9 +60,10 @@ Package `exports` point at `lib`, and the npm `files` allowlist includes only
57
60
 
58
61
  | Import | Exports |
59
62
  |---|---|
60
- | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, `summarizeStructure`, `compileSelector`, `selectorSchema` |
61
- | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `Mol4AgentError`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
63
+ | `@gcszhn/mol4agent-core` | `createMolViewer`, protocol types, format helpers, source helpers, `summarizeStructure`, `compileSelector`, `selectorSchema` |
64
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `Mol4AgentError`, `parseColor` / `formatColor` / `COLOR_SYNTAX`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
62
65
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`, `summarizePdbLike`, `summarizeCif`, `summarizeSdf`, `summarizeMol2`, `summarizeXyz`, `summarizeGro` |
66
+ | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`, `SOURCE_DATABASE_INFO`, `resolveSource`, `normalizeSourceDb`, `readSourceIndexField`, and the `isSourceDatabase` guard |
63
67
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
64
68
 
65
69
  ## `createMolViewer`
@@ -92,7 +96,7 @@ stylesheet once per viewer and removes it on `dispose()`.
92
96
  |---|---|---|
93
97
  | `container` | `HTMLElement` | Host element; the viewer fills it with `position:relative;width:100%;height:100%` |
94
98
  | `theme` | `'light' \| 'dark'` | Initial Mol* skin and canvas background |
95
- | `background` | `string` | Optional explicit canvas background |
99
+ | `background` | `string \| number` | Optional explicit canvas background (same colour syntax as `colorParams.value`) |
96
100
 
97
101
  ### `MolViewer`
98
102
 
@@ -161,7 +165,7 @@ can be stored in a session log, then replayed after `load()`.
161
165
  | `clear-selection` | `mode?` | Clear select/highlight interactivity |
162
166
  | `focus` | optional `target` | Focus camera on the selection or the whole structure |
163
167
  | `camera` | `action: 'reset'` | Reset the camera |
164
- | `background` | `color: string \| 'theme'` | Set the canvas background |
168
+ | `background` | `color: string \| number \| 'theme'` | Set the canvas background |
165
169
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`, `targets` 2/3/4 | Add a measurement |
166
170
  | `label` | `target`, optional `text` | Add a 3D label |
167
171
 
@@ -195,6 +199,32 @@ Examples:
195
199
  }
196
200
  ```
197
201
 
202
+ ### Colours
203
+
204
+ `color` selects a Mol* colour **theme** (`chain-id`, `element-symbol`, ...).
205
+ `colorParams.value` only affects the `uniform` theme; `color: "uniform"` alone
206
+ is a theme name, not a colour.
207
+
208
+ `colorParams.value` accepts one of:
209
+
210
+ | Form | Examples |
211
+ |---|---|
212
+ | CSS colour name (case-insensitive) | `red`, `lightgrey`, `rebeccapurple` |
213
+ | Hex, optionally with alpha | `#f00`, `#ff0000`, `#ff000080`, `#f008` |
214
+ | `0x` or bare hex | `0xB0B0B0`, `B0B0B0` |
215
+ | `rgb()` / `rgba()` | `rgb(255, 0, 0)`, `rgb(100%, 0%, 0%)`, `rgba(255, 0, 0, 0.5)` |
216
+ | 24-bit integer | `16711680`, `0xff0000` |
217
+
218
+ Alpha is accepted but ignored because Mol* colours and the canvas are opaque.
219
+ The `background` command and `capture({ background })` accept the same forms
220
+ (the command additionally accepts `'theme'`). Values that cannot be parsed
221
+ return `INVALID_COMMAND` instead of silently rendering black; a successful
222
+ `represent` echoes the resolved hex, for example
223
+ `Applied cartoon / uniform #ff0000 to polymer.`
224
+
225
+ Common values: red `0xff0000`, blue `0x0000ff`, white `0xffffff`, grey
226
+ `0x808080`, light grey `0xd3d3d3`.
227
+
198
228
  ### `CommandResult`
199
229
 
200
230
  ```ts
@@ -205,7 +235,7 @@ type CommandResult =
205
235
 
206
236
  Error codes: `INVALID_COMMAND`, `UNSUPPORTED_FORMAT`, `UNSUPPORTED_REPRESENTATION`,
207
237
  `REPRESENT_FAILED`, `NO_STRUCTURE`, `LOAD_FAILED`, `CAPTURE_FAILED`,
208
- `SUMMARY_UNSUPPORTED`, `DISPOSED`.
238
+ `SUMMARY_UNSUPPORTED`, `UNSUPPORTED_SOURCE`, `INVALID_ENTRY_ID`, `DISPOSED`.
209
239
 
210
240
  ## Selectors
211
241
 
@@ -272,6 +302,44 @@ BCIF can be rendered but not summarized from raw bytes yet; `summarizeStructure`
272
302
  throws `SUMMARY_UNSUPPORTED`. A post-load viewer fallback may still expose
273
303
  `complete: false`.
274
304
 
305
+ ## Database sources
306
+
307
+ `mol_fetch` starts from an entry id instead of a local file. Core validates the
308
+ id and returns a download plan; it never performs the request or writes a file.
309
+ Adapters execute the plan with their own HTTPS and filesystem APIs.
310
+
311
+ ```ts
312
+ import { resolveSource } from '@gcszhn/mol4agent-core/sources'
313
+
314
+ resolveSource({ entryId: '1crn' })
315
+ // { sourceDb: 'rcsb-pdb', entryId: '1CRN', format: 'pdb',
316
+ // fileName: '1CRN.pdb',
317
+ // plan: { url: 'https://files.rcsb.org/download/1CRN.pdb' },
318
+ // description: 'RCSB PDB entry 1CRN (PDB format)' }
319
+
320
+ resolveSource({ entryId: 'P00533', sourceDb: 'alphafold' })
321
+ // plan: { url: 'https://alphafold.ebi.ac.uk/api/prediction/P00533',
322
+ // indexField: '0.pdbUrl' }
323
+ ```
324
+
325
+ | `source_db` | `entry_id` | Format |
326
+ |---|---|---|
327
+ | `rcsb-pdb` (default) | 4-character PDB id (`1crn`) | `pdb` |
328
+ | `rcsb-cif` | 4-character PDB id (`1crn`) | `mmcif` |
329
+ | `rcsb-bcif` | 4-character PDB id (`1crn`) | `bcif` |
330
+ | `alphafold` | UniProt accession (`P00533`) | `pdb` |
331
+ | `pubchem` | CID (`2244`) or compound name (`aspirin`) | `sdf` |
332
+ | `chembl` | `CHEMBL25`, or a bare number (`25`) | `sdf` |
333
+
334
+ `plan.indexField` marks a JSON index document: the adapter reads that dot path
335
+ and downloads the URL it names. AlphaFold file names are versioned, so
336
+ `0.pdbUrl` skips the API's array wrapper and selects the current PDB URL. Use
337
+ `readSourceIndexField(payload, field)` for that lookup.
338
+
339
+ `SOURCE_DATABASE_INFO` supplies the label, description, entry hint, and format
340
+ for tool descriptions. `normalizeSourceDb` enforces the closed list, and invalid
341
+ ids raise `Mol4AgentError` with `UNSUPPORTED_SOURCE` or `INVALID_ENTRY_ID`.
342
+
275
343
  ## Capture
276
344
 
277
345
  ```ts
@@ -279,7 +347,7 @@ const png = await viewer.capture({
279
347
  width: 1024, // optional; default 1024
280
348
  height: 768, // optional; default 768
281
349
  transparent: true, // optional
282
- background: '#101418', // optional
350
+ background: '#101418', // optional; colour names and integers also work
283
351
  })
284
352
  ```
285
353
 
@@ -347,8 +415,8 @@ sequenceDiagram
347
415
 
348
416
  ## Status
349
417
 
350
- - `protocol`, `formats`, `parse/*`, `viewer`, `select`, `react` are implemented
351
- and typechecked.
418
+ - `protocol`, `formats`, `parse/*`, `sources`, `viewer`, `select`, `react` are
419
+ implemented and typechecked.
352
420
  - Verified in headless Chrome + SwiftShader with real 1CRN PDB/CIF, 1ATP, and a
353
421
  PubChem aspirin SDF: official UI, load, cartoon/polymer-and-ligand, ligand
354
422
  highlight, focus, and PNG capture.
package/README_zh.md CHANGED
@@ -28,6 +28,9 @@ core: createPluginUI -> Mol* state tree -> commands -> capture
28
28
  - 命令是 JSON 可序列化的;**加载是方法,不是命令**,因为适配包持有的字节
29
29
  不一定可序列化。
30
30
  - `@gcszhn/mol4agent-core/parse` 是纯函数,Node 和浏览器都能用。
31
+ - `@gcszhn/mol4agent-core/sources` 同样是纯函数:把条目 id 变成下载计划
32
+ (`url`、可选的 JSON `indexField`、格式、文件名)。网络和写文件仍由适配包
33
+ 负责。
31
34
 
32
35
  ## 安装
33
36
 
@@ -37,8 +40,8 @@ pnpm add @gcszhn/mol4agent-core molstar
37
40
  pnpm add react
38
41
  ```
39
42
 
40
- 本包尚未发布到 npm;在 monorepo 内先用 workspace link,上面的命令适用于
41
- `0.1.0` 发布之后。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
43
+ 本包已发布到 npm(`@gcszhn/mol4agent-core@0.3.0`);在 monorepo 内 pnpm 会链接
44
+ workspace 版本。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
42
45
  打进单个 client bundle;普通 web 应用可以直接使用本包。
43
46
 
44
47
  构建与打包:
@@ -55,9 +58,10 @@ Package `exports` 指向 `lib`,npm `files` 只包含 `lib` 和 README;`src/`
55
58
 
56
59
  | Import | 导出 |
57
60
  |---|---|
58
- | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
59
- | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
61
+ | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、source 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
62
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`、`parseColor` / `formatColor` / `COLOR_SYNTAX`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
60
63
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`、`summarizePdbLike`、`summarizeCif`、`summarizeSdf`、`summarizeMol2`、`summarizeXyz`、`summarizeGro` |
64
+ | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`、`SOURCE_DATABASE_INFO`、`resolveSource`、`normalizeSourceDb`、`readSourceIndexField`,以及 `isSourceDatabase` 守卫 |
61
65
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`、`Mol4AgentViewerHandle`、`Mol4AgentScene` |
62
66
 
63
67
  ## `createMolViewer`
@@ -90,7 +94,7 @@ viewer.dispose()
90
94
  |---|---|---|
91
95
  | `container` | `HTMLElement` | 宿主元素;viewer 用 `position:relative;width:100%;height:100%` 填满 |
92
96
  | `theme` | `'light' \| 'dark'` | 初始 Mol* 皮肤和画布背景 |
93
- | `background` | `string` | 可选,显式指定画布背景 |
97
+ | `background` | `string \| number` | 可选,显式指定画布背景(颜色语法同 `colorParams.value`) |
94
98
 
95
99
  ### `MolViewer`
96
100
 
@@ -158,7 +162,7 @@ interface StructureData {
158
162
  | `clear-selection` | `mode?` | 清除 select/highlight 交互 |
159
163
  | `focus` | 可选 `target` | 聚焦选择或整个结构 |
160
164
  | `camera` | `action: 'reset'` | 重置镜头 |
161
- | `background` | `color: string \| 'theme'` | 设置画布背景 |
165
+ | `background` | `color: string \| number \| 'theme'` | 设置画布背景 |
162
166
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`,`targets` 2/3/4 个 | 添加测量 |
163
167
  | `label` | `target`,可选 `text` | 添加 3D 标签 |
164
168
 
@@ -192,6 +196,30 @@ interface StructureData {
192
196
  }
193
197
  ```
194
198
 
199
+ ### 颜色
200
+
201
+ `color` 选择 Mol* 的颜色**主题**(`chain-id`、`element-symbol` 等);
202
+ `colorParams.value` 只对 `uniform` 主题生效。单独写 `color: "uniform"` 只是主题
203
+ 名,不是具体颜色。
204
+
205
+ `colorParams.value` 接受以下形式:
206
+
207
+ | 形式 | 示例 |
208
+ |---|---|
209
+ | CSS 颜色名(大小写不敏感) | `red`、`lightgrey`、`rebeccapurple` |
210
+ | 十六进制,可带 alpha | `#f00`、`#ff0000`、`#ff000080`、`#f008` |
211
+ | `0x` 或裸十六进制 | `0xB0B0B0`、`B0B0B0` |
212
+ | `rgb()` / `rgba()` | `rgb(255, 0, 0)`、`rgb(100%, 0%, 0%)`、`rgba(255, 0, 0, 0.5)` |
213
+ | 24 位整数 | `16711680`、`0xff0000` |
214
+
215
+ alpha 会被接受但忽略,因为 Mol* 颜色与画布都是不透明的。`background` 命令与
216
+ `capture({ background })` 接受相同形式(命令还额外接受 `'theme'`)。无法解析的
217
+ 值返回 `INVALID_COMMAND`,不会再静默渲染成黑色;成功的 `represent` 会回显解析后
218
+ 的十六进制颜色,例如 `Applied cartoon / uniform #ff0000 to polymer.`。
219
+
220
+ 常用值:红 `0xff0000`、蓝 `0x0000ff`、白 `0xffffff`、灰 `0x808080`、
221
+ 浅灰 `0xd3d3d3`。
222
+
195
223
  ### `CommandResult`
196
224
 
197
225
  ```ts
@@ -202,7 +230,7 @@ type CommandResult =
202
230
 
203
231
  错误码:`INVALID_COMMAND`、`UNSUPPORTED_FORMAT`、`UNSUPPORTED_REPRESENTATION`、
204
232
  `REPRESENT_FAILED`、`NO_STRUCTURE`、`LOAD_FAILED`、`CAPTURE_FAILED`、
205
- `SUMMARY_UNSUPPORTED`、`DISPOSED`。
233
+ `SUMMARY_UNSUPPORTED`、`UNSUPPORTED_SOURCE`、`INVALID_ENTRY_ID`、`DISPOSED`。
206
234
 
207
235
  ## 选择器
208
236
 
@@ -267,6 +295,43 @@ const summary = summarizeStructure({ data: pdbText, format: 'pdb', label: '1atp.
267
295
  BCIF 可以渲染,但目前不能从 raw bytes 摘要;`summarizeStructure` 会抛
268
296
  `SUMMARY_UNSUPPORTED`。viewer 的兜底摘要仍可能返回 `complete: false`。
269
297
 
298
+ ## 数据库来源
299
+
300
+ `mol_fetch` 从条目 id 而不是本地文件开始。core 只校验 id 并返回下载计划,
301
+ 不发起请求、不写文件;实际请求和落盘由适配包用各自的 HTTPS/文件系统 API
302
+ 完成。
303
+
304
+ ```ts
305
+ import { resolveSource } from '@gcszhn/mol4agent-core/sources'
306
+
307
+ resolveSource({ entryId: '1crn' })
308
+ // { sourceDb: 'rcsb-pdb', entryId: '1CRN', format: 'pdb',
309
+ // fileName: '1CRN.pdb',
310
+ // plan: { url: 'https://files.rcsb.org/download/1CRN.pdb' },
311
+ // description: 'RCSB PDB entry 1CRN (PDB format)' }
312
+
313
+ resolveSource({ entryId: 'P00533', sourceDb: 'alphafold' })
314
+ // plan: { url: 'https://alphafold.ebi.ac.uk/api/prediction/P00533',
315
+ // indexField: '0.pdbUrl' }
316
+ ```
317
+
318
+ | `source_db` | `entry_id` | 格式 |
319
+ |---|---|---|
320
+ | `rcsb-pdb`(默认) | 4 字符 PDB id(`1crn`) | `pdb` |
321
+ | `rcsb-cif` | 4 字符 PDB id(`1crn`) | `mmcif` |
322
+ | `rcsb-bcif` | 4 字符 PDB id(`1crn`) | `bcif` |
323
+ | `alphafold` | UniProt accession(`P00533`) | `pdb` |
324
+ | `pubchem` | CID(`2244`)或化合物名(`aspirin`) | `sdf` |
325
+ | `chembl` | `CHEMBL25`,或纯数字(`25`) | `sdf` |
326
+
327
+ `plan.indexField` 表示这是一个 JSON 索引文档:适配包按点路径取值,再下载其中
328
+ 的 URL。AlphaFold 的文件名带版本号,所以 `0.pdbUrl` 跳过 API 的数组包装并取
329
+ 当前 PDB URL。取该字段可用 `readSourceIndexField(payload, field)`。
330
+
331
+ `SOURCE_DATABASE_INFO` 提供每个来源的 label、描述、entry 提示和格式,供工具
332
+ 描述使用。`normalizeSourceDb` 校验闭集;非法 id 会抛出 `Mol4AgentError`,
333
+ 错误码为 `UNSUPPORTED_SOURCE` 或 `INVALID_ENTRY_ID`。
334
+
270
335
  ## 截图
271
336
 
272
337
  ```ts
@@ -341,8 +406,8 @@ sequenceDiagram
341
406
 
342
407
  ## 状态
343
408
 
344
- - `protocol`、`formats`、`parse/*`、`viewer`、`select`、`react` 均已实现并通过
345
- typecheck。
409
+ - `protocol`、`formats`、`parse/*`、`sources`、`viewer`、`select`、`react` 均已
410
+ 实现并通过 typecheck。
346
411
  - 在 headless Chrome + SwiftShader 下用真实 1CRN PDB/CIF、1ATP 和 PubChem
347
412
  aspirin SDF 验证过:官方 UI、加载、cartoon/polymer-and-ligand、配体高亮、
348
413
  聚焦和 PNG 截图。
package/lib/color.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Colour parsing for the harness-neutral protocol.
3
+ *
4
+ * Mol*'s uniform theme and canvas renderer take a 24-bit `0xRRGGBB` integer.
5
+ * Agents naturally write CSS colours instead (`"red"`, `"#ff0000"`,
6
+ * `"rgb(255, 0, 0)"`), so normalize every accepted form here. The parser is
7
+ * pure and Node-safe: core tests and adapter tool handlers share it without
8
+ * pulling in Mol* or a DOM.
9
+ *
10
+ * @module @gcszhn/mol4agent-core/color
11
+ */
12
+ /** Syntax accepted by {@link parseColor}; also used in model-facing errors. */
13
+ export declare const COLOR_SYNTAX: string;
14
+ /**
15
+ * Parse one agent-supplied colour into a 24-bit `0xRRGGBB` integer.
16
+ *
17
+ * Alpha is accepted syntactically (`#rrggbbaa`, 4-digit hex, `rgba()`) but
18
+ * dropped because Mol* colours and the canvas background are opaque.
19
+ *
20
+ * @throws Error naming the offending value and {@link COLOR_SYNTAX} when the
21
+ * value is not a recognizable colour.
22
+ */
23
+ export declare function parseColor(value: unknown): number;
24
+ /** Render a normalized colour as `#rrggbb` for tool results and logs. */
25
+ export declare function formatColor(value: number): string;
package/lib/color.js ADDED
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Colour parsing for the harness-neutral protocol.
3
+ *
4
+ * Mol*'s uniform theme and canvas renderer take a 24-bit `0xRRGGBB` integer.
5
+ * Agents naturally write CSS colours instead (`"red"`, `"#ff0000"`,
6
+ * `"rgb(255, 0, 0)"`), so normalize every accepted form here. The parser is
7
+ * pure and Node-safe: core tests and adapter tool handlers share it without
8
+ * pulling in Mol* or a DOM.
9
+ *
10
+ * @module @gcszhn/mol4agent-core/color
11
+ */
12
+ /** Syntax accepted by {@link parseColor}; also used in model-facing errors. */
13
+ export const COLOR_SYNTAX = 'a CSS color name (red, lightgrey), #rgb, #rrggbb, #rrggbbaa, 0xRRGGBB, '
14
+ + 'a bare hex value (B0B0B0), rgb()/rgba(), or a 24-bit integer (16711680)';
15
+ /**
16
+ * Parse one agent-supplied colour into a 24-bit `0xRRGGBB` integer.
17
+ *
18
+ * Alpha is accepted syntactically (`#rrggbbaa`, 4-digit hex, `rgba()`) but
19
+ * dropped because Mol* colours and the canvas background are opaque.
20
+ *
21
+ * @throws Error naming the offending value and {@link COLOR_SYNTAX} when the
22
+ * value is not a recognizable colour.
23
+ */
24
+ export function parseColor(value) {
25
+ if (typeof value === 'number')
26
+ return parseNumericColor(value);
27
+ if (typeof value !== 'string')
28
+ throw invalidColor(value);
29
+ const text = value.trim().toLowerCase();
30
+ if (text.length === 0)
31
+ throw invalidColor(value);
32
+ const named = CSS_COLOR_NAMES[text];
33
+ if (named !== undefined)
34
+ return named;
35
+ if (text.startsWith('#'))
36
+ return parseHexDigits(text.slice(1), value);
37
+ if (text.startsWith('0x'))
38
+ return parseHexDigits(text.slice(2), value);
39
+ if (text.startsWith('rgb'))
40
+ return parseRgbFunction(text, value);
41
+ if ((text.length === 3 || text.length === 6 || text.length === 8) && /^[0-9a-f]+$/u.test(text)) {
42
+ return parseHexDigits(text, value);
43
+ }
44
+ throw invalidColor(value);
45
+ }
46
+ /** Render a normalized colour as `#rrggbb` for tool results and logs. */
47
+ export function formatColor(value) {
48
+ return `#${(value & 0xffffff).toString(16).padStart(6, '0')}`;
49
+ }
50
+ function parseNumericColor(value) {
51
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0)
52
+ throw invalidColor(value);
53
+ return value & 0xffffff;
54
+ }
55
+ function parseHexDigits(digits, original) {
56
+ if (!/^[0-9a-f]+$/u.test(digits))
57
+ throw invalidColor(original);
58
+ switch (digits.length) {
59
+ case 3: {
60
+ const [r, g, b] = digits;
61
+ return Number.parseInt(`${r}${r}${g}${g}${b}${b}`, 16);
62
+ }
63
+ case 4: {
64
+ // RGBA shorthand; the alpha nibble is ignored.
65
+ const [r, g, b] = digits;
66
+ return Number.parseInt(`${r}${r}${g}${g}${b}${b}`, 16);
67
+ }
68
+ case 6:
69
+ return Number.parseInt(digits, 16);
70
+ case 8:
71
+ // RRGGBBAA; Mol* colours have no alpha channel.
72
+ return Number.parseInt(digits.slice(0, 6), 16);
73
+ default:
74
+ throw invalidColor(original);
75
+ }
76
+ }
77
+ function parseRgbFunction(text, original) {
78
+ const match = /^rgba?\(([^)]*)\)$/u.exec(text);
79
+ if (match === null)
80
+ throw invalidColor(original);
81
+ const body = match[1].trim();
82
+ if (body.length === 0)
83
+ throw invalidColor(original);
84
+ const slash = body.split('/');
85
+ if (slash.length > 2)
86
+ throw invalidColor(original);
87
+ const channels = slash[0].trim().split(/[,\s]+/u).filter(Boolean);
88
+ if (channels.length !== 3 && channels.length !== 4)
89
+ throw invalidColor(original);
90
+ if (slash.length === 2 && channels.length !== 3)
91
+ throw invalidColor(original);
92
+ const [r, g, b] = channels.slice(0, 3).map(channel => parseRgbChannel(channel, original));
93
+ if (channels.length === 4)
94
+ parseAlpha(channels[3], original);
95
+ if (slash.length === 2)
96
+ parseAlpha(slash[1].trim(), original);
97
+ return (r << 16) | (g << 8) | b;
98
+ }
99
+ const NUMBER_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/u;
100
+ function parseRgbChannel(channel, original) {
101
+ const percent = channel.endsWith('%');
102
+ const value = parseNumber(percent ? channel.slice(0, -1) : channel);
103
+ if (value === undefined)
104
+ throw invalidColor(original);
105
+ const channelValue = percent ? (value / 100) * 255 : value;
106
+ return Math.max(0, Math.min(255, Math.round(channelValue)));
107
+ }
108
+ function parseAlpha(alpha, original) {
109
+ const percent = alpha.endsWith('%');
110
+ if (parseNumber(percent ? alpha.slice(0, -1) : alpha) === undefined)
111
+ throw invalidColor(original);
112
+ }
113
+ function parseNumber(text) {
114
+ if (!NUMBER_PATTERN.test(text))
115
+ return undefined;
116
+ return Number(text);
117
+ }
118
+ function invalidColor(value) {
119
+ const shown = typeof value === 'string' ? JSON.stringify(value) : String(value);
120
+ return new Error(`invalid color ${shown}; accepted: ${COLOR_SYNTAX}`);
121
+ }
122
+ /** CSS Color 4 named colours (the 148-name X11/CSS table). */
123
+ const CSS_COLOR_NAMES = {
124
+ aliceblue: 0xf0f8ff,
125
+ antiquewhite: 0xfaebd7,
126
+ aqua: 0x00ffff,
127
+ aquamarine: 0x7fffd4,
128
+ azure: 0xf0ffff,
129
+ beige: 0xf5f5dc,
130
+ bisque: 0xffe4c4,
131
+ black: 0x000000,
132
+ blanchedalmond: 0xffebcd,
133
+ blue: 0x0000ff,
134
+ blueviolet: 0x8a2be2,
135
+ brown: 0xa52a2a,
136
+ burlywood: 0xdeb887,
137
+ cadetblue: 0x5f9ea0,
138
+ chartreuse: 0x7fff00,
139
+ chocolate: 0xd2691e,
140
+ coral: 0xff7f50,
141
+ cornflowerblue: 0x6495ed,
142
+ cornsilk: 0xfff8dc,
143
+ crimson: 0xdc143c,
144
+ cyan: 0x00ffff,
145
+ darkblue: 0x00008b,
146
+ darkcyan: 0x008b8b,
147
+ darkgoldenrod: 0xb8860b,
148
+ darkgray: 0xa9a9a9,
149
+ darkgreen: 0x006400,
150
+ darkgrey: 0xa9a9a9,
151
+ darkkhaki: 0xbdb76b,
152
+ darkmagenta: 0x8b008b,
153
+ darkolivegreen: 0x556b2f,
154
+ darkorange: 0xff8c00,
155
+ darkorchid: 0x9932cc,
156
+ darkred: 0x8b0000,
157
+ darksalmon: 0xe9967a,
158
+ darkseagreen: 0x8fbc8f,
159
+ darkslateblue: 0x483d8b,
160
+ darkslategray: 0x2f4f4f,
161
+ darkslategrey: 0x2f4f4f,
162
+ darkturquoise: 0x00ced1,
163
+ darkviolet: 0x9400d3,
164
+ deeppink: 0xff1493,
165
+ deepskyblue: 0x00bfff,
166
+ dimgray: 0x696969,
167
+ dimgrey: 0x696969,
168
+ dodgerblue: 0x1e90ff,
169
+ firebrick: 0xb22222,
170
+ floralwhite: 0xfffaf0,
171
+ forestgreen: 0x228b22,
172
+ fuchsia: 0xff00ff,
173
+ gainsboro: 0xdcdcdc,
174
+ ghostwhite: 0xf8f8ff,
175
+ gold: 0xffd700,
176
+ goldenrod: 0xdaa520,
177
+ gray: 0x808080,
178
+ green: 0x008000,
179
+ greenyellow: 0xadff2f,
180
+ grey: 0x808080,
181
+ honeydew: 0xf0fff0,
182
+ hotpink: 0xff69b4,
183
+ indianred: 0xcd5c5c,
184
+ indigo: 0x4b0082,
185
+ ivory: 0xfffff0,
186
+ khaki: 0xf0e68c,
187
+ lavender: 0xe6e6fa,
188
+ lavenderblush: 0xfff0f5,
189
+ lawngreen: 0x7cfc00,
190
+ lemonchiffon: 0xfffacd,
191
+ lightblue: 0xadd8e6,
192
+ lightcoral: 0xf08080,
193
+ lightcyan: 0xe0ffff,
194
+ lightgoldenrodyellow: 0xfafad2,
195
+ lightgray: 0xd3d3d3,
196
+ lightgreen: 0x90ee90,
197
+ lightgrey: 0xd3d3d3,
198
+ lightpink: 0xffb6c1,
199
+ lightsalmon: 0xffa07a,
200
+ lightseagreen: 0x20b2aa,
201
+ lightskyblue: 0x87cefa,
202
+ lightslategray: 0x778899,
203
+ lightslategrey: 0x778899,
204
+ lightsteelblue: 0xb0c4de,
205
+ lightyellow: 0xffffe0,
206
+ lime: 0x00ff00,
207
+ limegreen: 0x32cd32,
208
+ linen: 0xfaf0e6,
209
+ magenta: 0xff00ff,
210
+ maroon: 0x800000,
211
+ mediumaquamarine: 0x66cdaa,
212
+ mediumblue: 0x0000cd,
213
+ mediumorchid: 0xba55d3,
214
+ mediumpurple: 0x9370db,
215
+ mediumseagreen: 0x3cb371,
216
+ mediumslateblue: 0x7b68ee,
217
+ mediumspringgreen: 0x00fa9a,
218
+ mediumturquoise: 0x48d1cc,
219
+ mediumvioletred: 0xc71585,
220
+ midnightblue: 0x191970,
221
+ mintcream: 0xf5fffa,
222
+ mistyrose: 0xffe4e1,
223
+ moccasin: 0xffe4b5,
224
+ navajowhite: 0xffdead,
225
+ navy: 0x000080,
226
+ oldlace: 0xfdf5e6,
227
+ olive: 0x808000,
228
+ olivedrab: 0x6b8e23,
229
+ orange: 0xffa500,
230
+ orangered: 0xff4500,
231
+ orchid: 0xda70d6,
232
+ palegoldenrod: 0xeee8aa,
233
+ palegreen: 0x98fb98,
234
+ paleturquoise: 0xafeeee,
235
+ palevioletred: 0xdb7093,
236
+ papayawhip: 0xffefd5,
237
+ peachpuff: 0xffdab9,
238
+ peru: 0xcd853f,
239
+ pink: 0xffc0cb,
240
+ plum: 0xdda0dd,
241
+ powderblue: 0xb0e0e6,
242
+ purple: 0x800080,
243
+ rebeccapurple: 0x663399,
244
+ red: 0xff0000,
245
+ rosybrown: 0xbc8f8f,
246
+ royalblue: 0x4169e1,
247
+ saddlebrown: 0x8b4513,
248
+ salmon: 0xfa8072,
249
+ sandybrown: 0xf4a460,
250
+ seagreen: 0x2e8b57,
251
+ seashell: 0xfff5ee,
252
+ sienna: 0xa0522d,
253
+ silver: 0xc0c0c0,
254
+ skyblue: 0x87ceeb,
255
+ slateblue: 0x6a5acd,
256
+ slategray: 0x708090,
257
+ slategrey: 0x708090,
258
+ snow: 0xfffafa,
259
+ springgreen: 0x00ff7f,
260
+ steelblue: 0x4682b4,
261
+ tan: 0xd2b48c,
262
+ teal: 0x008080,
263
+ thistle: 0xd8bfd8,
264
+ tomato: 0xff6347,
265
+ turquoise: 0x40e0d0,
266
+ violet: 0xee82ee,
267
+ wheat: 0xf5deb3,
268
+ white: 0xffffff,
269
+ whitesmoke: 0xf5f5f5,
270
+ yellow: 0xffff00,
271
+ yellowgreen: 0x9acd32,
272
+ };
package/lib/index.d.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  export * from './protocol.ts';
10
10
  export * from './formats.ts';
11
+ export * from './sources.ts';
11
12
  export { summarizeStructure } from './parse/index.ts';
12
13
  export { createMolViewer } from './viewer.ts';
13
14
  export type { MolViewer, MolViewerOptions } from './viewer.ts';
package/lib/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  export * from "./protocol.js";
10
10
  export * from "./formats.js";
11
+ export * from "./sources.js";
11
12
  export { summarizeStructure } from "./parse/index.js";
12
13
  export { createMolViewer } from "./viewer.js";
13
14
  export { compileSelector, selectorSchema } from "./select.js";
package/lib/protocol.d.ts CHANGED
@@ -128,7 +128,7 @@ export type MolCommand = {
128
128
  readonly action: 'reset';
129
129
  } | {
130
130
  readonly op: 'background';
131
- readonly color: string | 'theme';
131
+ readonly color: string | number | 'theme';
132
132
  } | {
133
133
  readonly op: 'measure';
134
134
  readonly kind: 'distance' | 'angle' | 'dihedral';
@@ -138,7 +138,7 @@ export type MolCommand = {
138
138
  readonly target: StructureSelector;
139
139
  readonly text?: string;
140
140
  };
141
- export type Mol4AgentErrorCode = 'INVALID_COMMAND' | 'UNSUPPORTED_FORMAT' | 'UNSUPPORTED_REPRESENTATION' | 'REPRESENT_FAILED' | 'NO_STRUCTURE' | 'LOAD_FAILED' | 'CAPTURE_FAILED' | 'SUMMARY_UNSUPPORTED' | 'DISPOSED';
141
+ export type Mol4AgentErrorCode = 'INVALID_COMMAND' | 'UNSUPPORTED_FORMAT' | 'UNSUPPORTED_REPRESENTATION' | 'REPRESENT_FAILED' | 'NO_STRUCTURE' | 'LOAD_FAILED' | 'CAPTURE_FAILED' | 'UNSUPPORTED_SOURCE' | 'INVALID_ENTRY_ID' | 'SUMMARY_UNSUPPORTED' | 'DISPOSED';
142
142
  /** Structured failure. Tools turn this into model-facing text instead of a stack trace. */
143
143
  export declare class Mol4AgentError extends Error {
144
144
  readonly code: Mol4AgentErrorCode;
@@ -183,10 +183,15 @@ export interface CaptureOptions {
183
183
  readonly width?: number;
184
184
  readonly height?: number;
185
185
  readonly transparent?: boolean;
186
- readonly background?: string;
186
+ readonly background?: string | number;
187
187
  }
188
188
  /** Narrow a parsed JSON value to a command op without validating every field. */
189
189
  export declare function isMolCommandOp(value: unknown): value is MolCommand['op'];
190
+ /**
191
+ * Colour parsing is part of the agent-facing protocol: adapters use the same
192
+ * accepted syntax to validate tool arguments and echo the resolved value.
193
+ */
194
+ export { COLOR_SYNTAX, formatColor, parseColor } from './color.ts';
190
195
  export declare function isMolFormat(value: unknown): value is MolFormat;
191
196
  export declare function isPresetName(value: unknown): value is PresetName;
192
197
  export declare function isStructureData(value: unknown): value is StructureData;
package/lib/protocol.js CHANGED
@@ -60,6 +60,11 @@ export class Mol4AgentError extends Error {
60
60
  export function isMolCommandOp(value) {
61
61
  return typeof value === 'string' && COMMAND_OPS.has(value);
62
62
  }
63
+ /**
64
+ * Colour parsing is part of the agent-facing protocol: adapters use the same
65
+ * accepted syntax to validate tool arguments and echo the resolved value.
66
+ */
67
+ export { COLOR_SYNTAX, formatColor, parseColor } from "./color.js";
63
68
  const COMMAND_OPS = new Set([
64
69
  'represent',
65
70
  'select',
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Online structure sources for `mol_fetch`.
3
+ *
4
+ * Core decides what an entry id means and where its bytes live. It never
5
+ * downloads anything: network access, filesystem writes, authorization, and
6
+ * session state belong to the adapter, which executes the returned plan.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/sources
9
+ */
10
+ import { type MolFormat } from './protocol.ts';
11
+ /** Databases `mol_fetch` can download from. The first is the default. */
12
+ export declare const SOURCE_DATABASES: readonly ["rcsb-pdb", "rcsb-cif", "rcsb-bcif", "alphafold", "pubchem", "chembl"];
13
+ export type SourceDatabase = (typeof SOURCE_DATABASES)[number];
14
+ /** Stable, model-facing facts about one source database. */
15
+ export interface SourceDatabaseInfo {
16
+ readonly label: string;
17
+ readonly description: string;
18
+ /** What `entry_id` must contain for this source. */
19
+ readonly entryHint: string;
20
+ readonly format: MolFormat;
21
+ }
22
+ export declare const SOURCE_DATABASE_INFO: Readonly<Record<SourceDatabase, SourceDatabaseInfo>>;
23
+ /**
24
+ * How an adapter obtains the bytes.
25
+ *
26
+ * `url` is either the file itself or, when `indexField` is set, a JSON index
27
+ * document. In the latter case the adapter reads `indexField` (a dot path such
28
+ * as `0.pdbUrl`) from that document and downloads the URL it names.
29
+ */
30
+ export interface SourceFetchPlan {
31
+ readonly url: string;
32
+ readonly indexField?: string;
33
+ }
34
+ /** One `mol_fetch` request, before the adapter touches the network. */
35
+ export interface SourceRequest {
36
+ readonly entryId: string;
37
+ /** Defaults to `rcsb-pdb`. */
38
+ readonly sourceDb?: SourceDatabase;
39
+ }
40
+ /** A validated download plan. */
41
+ export interface ResolvedSource {
42
+ readonly sourceDb: SourceDatabase;
43
+ /** Normalized entry id, e.g. `1CRN`, `P00533`, or `CHEMBL25`. */
44
+ readonly entryId: string;
45
+ readonly format: MolFormat;
46
+ /** Suggested file name when `target_path` names a directory. */
47
+ readonly fileName: string;
48
+ readonly plan: SourceFetchPlan;
49
+ /** One-line, model-facing description, e.g. `RCSB PDB entry 1CRN (PDB format)`. */
50
+ readonly description: string;
51
+ }
52
+ /** Normalize an agent-supplied source name; `undefined` selects `rcsb-pdb`. */
53
+ export declare function normalizeSourceDb(value: string | undefined): SourceDatabase;
54
+ /** Validate an entry id and build the adapter's fetch plan. */
55
+ export declare function resolveSource(request: SourceRequest): ResolvedSource;
56
+ /**
57
+ * Read a dot path from a JSON index document (numeric segments index arrays).
58
+ *
59
+ * Used by adapters for sources whose file URL is versioned, such as AlphaFold.
60
+ * Returns undefined when the path is missing or is not a string.
61
+ */
62
+ export declare function readSourceIndexField(payload: unknown, field: string): string | undefined;
63
+ export declare function isSourceDatabase(value: unknown): value is SourceDatabase;
64
+ /** Every source database id, in display order. */
65
+ export declare function sourceDatabases(): readonly SourceDatabase[];
package/lib/sources.js ADDED
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Online structure sources for `mol_fetch`.
3
+ *
4
+ * Core decides what an entry id means and where its bytes live. It never
5
+ * downloads anything: network access, filesystem writes, authorization, and
6
+ * session state belong to the adapter, which executes the returned plan.
7
+ *
8
+ * @module @gcszhn/mol4agent-core/sources
9
+ */
10
+ import { Mol4AgentError } from "./protocol.js";
11
+ /** Databases `mol_fetch` can download from. The first is the default. */
12
+ export const SOURCE_DATABASES = [
13
+ 'rcsb-pdb',
14
+ 'rcsb-cif',
15
+ 'rcsb-bcif',
16
+ 'alphafold',
17
+ 'pubchem',
18
+ 'chembl',
19
+ ];
20
+ export const SOURCE_DATABASE_INFO = {
21
+ 'rcsb-pdb': {
22
+ label: 'RCSB PDB',
23
+ description: 'Experimental structure from the RCSB Protein Data Bank, in PDB format.',
24
+ entryHint: '4-character PDB entry id, e.g. 1crn',
25
+ format: 'pdb',
26
+ },
27
+ 'rcsb-cif': {
28
+ label: 'RCSB PDB (mmCIF)',
29
+ description: 'Experimental structure from the RCSB Protein Data Bank, in mmCIF format.',
30
+ entryHint: '4-character PDB entry id, e.g. 1crn',
31
+ format: 'mmcif',
32
+ },
33
+ 'rcsb-bcif': {
34
+ label: 'RCSB PDB (BinaryCIF)',
35
+ description: 'Experimental structure from the RCSB model server, in BinaryCIF format.',
36
+ entryHint: '4-character PDB entry id, e.g. 1crn',
37
+ format: 'bcif',
38
+ },
39
+ alphafold: {
40
+ label: 'AlphaFold DB',
41
+ description: 'Predicted protein structure from AlphaFold DB, in PDB format.',
42
+ entryHint: 'UniProt accession, e.g. P00533',
43
+ format: 'pdb',
44
+ },
45
+ pubchem: {
46
+ label: 'PubChem',
47
+ description: 'Small-molecule compound from PubChem, in 3D SDF format.',
48
+ entryHint: 'PubChem CID (2244) or compound name (aspirin)',
49
+ format: 'sdf',
50
+ },
51
+ chembl: {
52
+ label: 'ChEMBL',
53
+ description: 'Small-molecule compound from ChEMBL, in SDF format.',
54
+ entryHint: 'ChEMBL id, e.g. CHEMBL25 (a bare number gets the CHEMBL prefix)',
55
+ format: 'sdf',
56
+ },
57
+ };
58
+ /** Normalize an agent-supplied source name; `undefined` selects `rcsb-pdb`. */
59
+ export function normalizeSourceDb(value) {
60
+ if (value === undefined)
61
+ return 'rcsb-pdb';
62
+ const normalized = value.trim().toLowerCase();
63
+ if (normalized === '')
64
+ return 'rcsb-pdb';
65
+ if (isSourceDatabase(normalized))
66
+ return normalized;
67
+ throw new Mol4AgentError('UNSUPPORTED_SOURCE', `unknown source_db "${value}"; supported: ${SOURCE_DATABASES.join(', ')}`);
68
+ }
69
+ /** Validate an entry id and build the adapter's fetch plan. */
70
+ export function resolveSource(request) {
71
+ const sourceDb = normalizeSourceDb(request.sourceDb);
72
+ const info = SOURCE_DATABASE_INFO[sourceDb];
73
+ if (typeof request.entryId !== 'string' || request.entryId.trim() === '') {
74
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `entry_id is required for ${sourceDb} (${info.entryHint})`);
75
+ }
76
+ const entry = request.entryId.trim();
77
+ switch (sourceDb) {
78
+ case 'rcsb-pdb': {
79
+ const id = pdbEntryId(entry, sourceDb);
80
+ return {
81
+ sourceDb,
82
+ entryId: id,
83
+ format: 'pdb',
84
+ fileName: `${id}.pdb`,
85
+ plan: { url: `https://files.rcsb.org/download/${id}.pdb` },
86
+ description: `RCSB PDB entry ${id} (PDB format)`,
87
+ };
88
+ }
89
+ case 'rcsb-cif': {
90
+ const id = pdbEntryId(entry, sourceDb);
91
+ return {
92
+ sourceDb,
93
+ entryId: id,
94
+ format: 'mmcif',
95
+ fileName: `${id}.cif`,
96
+ plan: { url: `https://files.rcsb.org/download/${id}.cif` },
97
+ description: `RCSB PDB entry ${id} (mmCIF format)`,
98
+ };
99
+ }
100
+ case 'rcsb-bcif': {
101
+ const id = pdbEntryId(entry, sourceDb);
102
+ return {
103
+ sourceDb,
104
+ entryId: id,
105
+ format: 'bcif',
106
+ fileName: `${id}.bcif`,
107
+ plan: { url: `https://models.rcsb.org/${id}.bcif` },
108
+ description: `RCSB PDB entry ${id} (BinaryCIF format)`,
109
+ };
110
+ }
111
+ case 'alphafold': {
112
+ const accession = uniprotAccession(entry);
113
+ return {
114
+ sourceDb,
115
+ entryId: accession,
116
+ format: 'pdb',
117
+ fileName: `AF-${accession}-F1-model.pdb`,
118
+ plan: {
119
+ url: `https://alphafold.ebi.ac.uk/api/prediction/${accession}`,
120
+ indexField: '0.pdbUrl',
121
+ },
122
+ description: `AlphaFold DB prediction for UniProt ${accession} (PDB format)`,
123
+ };
124
+ }
125
+ case 'pubchem': {
126
+ const compound = pubchemCompound(entry);
127
+ return {
128
+ sourceDb,
129
+ entryId: compound.entryId,
130
+ format: 'sdf',
131
+ fileName: compound.fileName,
132
+ plan: { url: compound.url },
133
+ description: `PubChem compound ${compound.entryId} (3D SDF)`,
134
+ };
135
+ }
136
+ case 'chembl': {
137
+ const id = chemblId(entry);
138
+ return {
139
+ sourceDb,
140
+ entryId: id,
141
+ format: 'sdf',
142
+ fileName: `${id}.sdf`,
143
+ plan: { url: `https://www.ebi.ac.uk/chembl/api/data/molecule/${id}.sdf` },
144
+ description: `ChEMBL molecule ${id} (SDF)`,
145
+ };
146
+ }
147
+ }
148
+ }
149
+ /**
150
+ * Read a dot path from a JSON index document (numeric segments index arrays).
151
+ *
152
+ * Used by adapters for sources whose file URL is versioned, such as AlphaFold.
153
+ * Returns undefined when the path is missing or is not a string.
154
+ */
155
+ export function readSourceIndexField(payload, field) {
156
+ let current = payload;
157
+ for (const segment of field.split('.')) {
158
+ if (Array.isArray(current)) {
159
+ const index = Number(segment);
160
+ if (!Number.isInteger(index) || index < 0)
161
+ return undefined;
162
+ current = current[index];
163
+ continue;
164
+ }
165
+ if (typeof current !== 'object' || current === null)
166
+ return undefined;
167
+ current = current[segment];
168
+ }
169
+ return typeof current === 'string' ? current : undefined;
170
+ }
171
+ export function isSourceDatabase(value) {
172
+ return typeof value === 'string' && SOURCE_DATABASES.includes(value);
173
+ }
174
+ /** Every source database id, in display order. */
175
+ export function sourceDatabases() {
176
+ return SOURCE_DATABASES;
177
+ }
178
+ const PDB_ENTRY_ID = /^[0-9][A-Z0-9]{3}$/u;
179
+ const UNIPROT_ACCESSION = /^(?:[A-Z0-9]{6}|[A-Z0-9]{10})$/u;
180
+ const CHEMBL_ID = /^CHEMBL[0-9]+$/u;
181
+ const MAX_PUBCHEM_NAME = 120;
182
+ function pdbEntryId(entry, sourceDb) {
183
+ const id = entry.toUpperCase();
184
+ if (!PDB_ENTRY_ID.test(id)) {
185
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a PDB entry id for ${sourceDb}; expected 4 characters like 1crn`);
186
+ }
187
+ return id;
188
+ }
189
+ function uniprotAccession(entry) {
190
+ // Accept the AlphaFold file stem (`AF-P00533-F1`) as well as the bare accession.
191
+ const stem = /^AF-([A-Z0-9]{6}|[A-Z0-9]{10})-F[0-9]+$/u.exec(entry.toUpperCase());
192
+ const accession = stem?.[1] ?? entry.toUpperCase();
193
+ if (!UNIPROT_ACCESSION.test(accession)) {
194
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a UniProt accession for alphafold; expected 6 or 10 characters like P00533`);
195
+ }
196
+ return accession;
197
+ }
198
+ function chemblId(entry) {
199
+ const value = entry.toUpperCase();
200
+ const id = /^[0-9]+$/u.test(value) ? `CHEMBL${value}` : value;
201
+ if (!CHEMBL_ID.test(id)) {
202
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `"${entry}" is not a ChEMBL id; expected CHEMBL25 or a numeric id like 25`);
203
+ }
204
+ return id;
205
+ }
206
+ function pubchemCompound(entry) {
207
+ const cid = /^(?:cid:?[ \t]*)?[0-9]+$/iu.test(entry);
208
+ if (cid) {
209
+ const id = entry.replace(/^cid:?[ \t]*/iu, '');
210
+ return {
211
+ entryId: id,
212
+ url: `https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${id}/SDF?record_type=3d`,
213
+ fileName: `pubchem-${id}.sdf`,
214
+ };
215
+ }
216
+ if (entry.length > MAX_PUBCHEM_NAME) {
217
+ throw new Mol4AgentError('INVALID_ENTRY_ID', `PubChem compound name is too long (${entry.length} characters; limit ${MAX_PUBCHEM_NAME})`);
218
+ }
219
+ if (/[\u0000-\u001f\u007f]/u.test(entry)) {
220
+ throw new Mol4AgentError('INVALID_ENTRY_ID', 'PubChem compound name contains control characters');
221
+ }
222
+ const slug = entry
223
+ .toLowerCase()
224
+ .replaceAll(/[^a-z0-9]+/gu, '-')
225
+ .replaceAll(/^-+|-+$/gu, '');
226
+ return {
227
+ entryId: entry,
228
+ url: `https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/${encodeURIComponent(entry)}/SDF?record_type=3d`,
229
+ fileName: `pubchem-${slug === '' ? 'compound' : slug.slice(0, 48)}.sdf`,
230
+ };
231
+ }
package/lib/viewer.d.ts CHANGED
@@ -2,7 +2,7 @@ import { type CaptureOptions, type CommandResult, type MolCommand, type Structur
2
2
  export interface MolViewerOptions {
3
3
  readonly container: HTMLElement;
4
4
  readonly theme?: 'light' | 'dark';
5
- readonly background?: string;
5
+ readonly background?: string | number;
6
6
  }
7
7
  export interface ViewerDiagnostics {
8
8
  readonly canvas: {
package/lib/viewer.js CHANGED
@@ -23,18 +23,20 @@ import { summarizeStructure } from "./parse/index.js";
23
23
  import { molstarFormatOf } from "./formats.js";
24
24
  import { COLOR_THEMES, Mol4AgentError, REPRESENTATION_TYPES, } from "./protocol.js";
25
25
  import { compileSelector, selectorSchema } from "./select.js";
26
+ import { formatColor, parseColor } from "./color.js";
26
27
  let globalComponentSeq = 0;
27
28
  /** Create the official Mol* viewer inside `options.container`. */
28
29
  export async function createMolViewer(options) {
30
+ let theme = options.theme ?? 'dark';
31
+ const themeBackground = () => (theme === 'dark' ? '#101418' : '#ffffff');
32
+ // Validate adapter-provided background before mounting anything.
33
+ const background = resolveColor(options.background ?? themeBackground());
29
34
  const host = document.createElement('div');
30
35
  host.style.cssText = 'position:relative;width:100%;height:100%;min-height:0;overflow:hidden;';
31
36
  options.container.appendChild(host);
32
37
  // The document body can mount before the sidebar gives it a size. Mol* needs
33
38
  // a real box for its UI and camera; wait for one, then keep following resizes.
34
39
  await waitForHostSize(host, 3000);
35
- let theme = options.theme ?? 'dark';
36
- const themeBackground = () => (theme === 'dark' ? '#101418' : '#ffffff');
37
- const background = options.background ?? themeBackground();
38
40
  const themeStyle = document.createElement('style');
39
41
  themeStyle.dataset.mol4agentTheme = theme;
40
42
  themeStyle.textContent = theme === 'dark' ? darkCss : lightCss;
@@ -73,7 +75,7 @@ export async function createMolViewer(options) {
73
75
  host.remove();
74
76
  throw error;
75
77
  }
76
- plugin.canvas3d?.setProps({ renderer: { backgroundColor: toColor(background) } });
78
+ plugin.canvas3d?.setProps({ renderer: { backgroundColor: Color(background) } });
77
79
  let pendingFocus;
78
80
  const focusLoaded = () => {
79
81
  if (pendingFocus === undefined)
@@ -205,7 +207,7 @@ export async function createMolViewer(options) {
205
207
  themeStyle.dataset.mol4agentTheme = next;
206
208
  themeStyle.textContent = next === 'dark' ? darkCss : lightCss;
207
209
  plugin.canvas3d?.setProps({
208
- renderer: { backgroundColor: toColor(themeBackground()) },
210
+ renderer: { backgroundColor: Color(resolveColor(themeBackground())) },
209
211
  });
210
212
  plugin.canvas3d?.requestDraw();
211
213
  },
@@ -220,6 +222,9 @@ export async function createMolViewer(options) {
220
222
  throw new Mol4AgentError('CAPTURE_FAILED', 'viewport screenshot helper is unavailable');
221
223
  const width = captureOptions?.width ?? 1024;
222
224
  const height = captureOptions?.height ?? 768;
225
+ const captureBackground = captureOptions?.background === undefined
226
+ ? undefined
227
+ : resolveColor(captureOptions.background);
223
228
  const previousBackground = plugin.canvas3d?.props.renderer.backgroundColor;
224
229
  try {
225
230
  helper.behaviors.values.next({
@@ -227,8 +232,8 @@ export async function createMolViewer(options) {
227
232
  resolution: { name: 'custom', params: { width, height } },
228
233
  transparent: captureOptions?.transparent ?? false,
229
234
  });
230
- if (captureOptions?.background !== undefined && plugin.canvas3d !== undefined) {
231
- plugin.canvas3d.setProps({ renderer: { backgroundColor: toColor(captureOptions.background) } });
235
+ if (captureBackground !== undefined && plugin.canvas3d !== undefined) {
236
+ plugin.canvas3d.setProps({ renderer: { backgroundColor: Color(captureBackground) } });
232
237
  }
233
238
  const uri = await helper.getImageDataUri();
234
239
  const comma = uri.indexOf(',');
@@ -281,6 +286,13 @@ async function executeCommand(plugin, command, hasStructure, theme) {
281
286
  if (style.color !== undefined && !COLOR_THEMES.includes(style.color)) {
282
287
  return invalid(command.op, `unknown colour theme "${style.color}"; supported: ${COLOR_THEMES.join(', ')}`);
283
288
  }
289
+ // Normalize once, before touching the scene: a bad color must fail the
290
+ // command instead of reaching Mol* and painting the structure black.
291
+ const resolvedColor = style.colorParams?.value === undefined
292
+ ? undefined
293
+ : resolveColor(style.colorParams.value);
294
+ const colorParams = resolvedColor === undefined ? undefined : { value: resolvedColor };
295
+ const colorSuffix = resolvedColor === undefined ? '' : ` ${formatColor(resolvedColor)}`;
284
296
  const structures = plugin.managers.structure.hierarchy.current.structures;
285
297
  if (structures.length === 0) {
286
298
  return { ok: false, op: command.op, code: 'NO_STRUCTURE', message: 'no structure is loaded' };
@@ -298,7 +310,7 @@ async function executeCommand(plugin, command, hasStructure, theme) {
298
310
  const rep = await plugin.builders.structure.representation.addRepresentation(component, {
299
311
  type: (style.type ?? 'ball-and-stick'),
300
312
  color: (style.color ?? 'uniform'),
301
- ...(style.colorParams === undefined ? {} : { colorParams: style.colorParams }),
313
+ ...(colorParams === undefined ? {} : { colorParams: colorParams }),
302
314
  }, { tag: 'mol4agent-selection' });
303
315
  if (rep !== undefined)
304
316
  targeted += 1;
@@ -315,7 +327,7 @@ async function executeCommand(plugin, command, hasStructure, theme) {
315
327
  return {
316
328
  ok: true,
317
329
  op: command.op,
318
- message: `applied ${style.type ?? 'ball-and-stick'} / ${style.color ?? 'uniform'} to ${command.target.kind}`,
330
+ message: `applied ${style.type ?? 'ball-and-stick'} / ${style.color ?? 'uniform'}${colorSuffix} to ${command.target.kind}`,
319
331
  };
320
332
  }
321
333
  const previousComponents = structures.flatMap(structure => [...structure.components]);
@@ -330,7 +342,7 @@ async function executeCommand(plugin, command, hasStructure, theme) {
330
342
  await plugin.builders.structure.representation.applyPreset(structure.cell, 'polymer-and-ligand', {
331
343
  theme: {
332
344
  globalName: style.color ?? 'chain-id',
333
- ...(style.colorParams === undefined ? {} : { globalColorParams: { value: style.colorParams.value } }),
345
+ ...(colorParams === undefined ? {} : { globalColorParams: colorParams }),
334
346
  },
335
347
  });
336
348
  added += 1;
@@ -348,7 +360,7 @@ async function executeCommand(plugin, command, hasStructure, theme) {
348
360
  const rep = await plugin.builders.structure.representation.addRepresentation(component, {
349
361
  type: (style.type ?? 'cartoon'),
350
362
  color: (style.color ?? 'chain-id'),
351
- ...(style.colorParams === undefined ? {} : { colorParams: style.colorParams }),
363
+ ...(colorParams === undefined ? {} : { colorParams: colorParams }),
352
364
  });
353
365
  if (rep !== undefined)
354
366
  added += 1;
@@ -374,7 +386,7 @@ async function executeCommand(plugin, command, hasStructure, theme) {
374
386
  console.warn('[mol4agent] could not remove the previous representation', reason);
375
387
  }
376
388
  plugin.canvas3d?.requestDraw();
377
- return { ok: true, op: command.op, message: `applied ${style.type ?? 'cartoon'} / ${style.color ?? 'chain-id'}` };
389
+ return { ok: true, op: command.op, message: `applied ${style.type ?? 'cartoon'} / ${style.color ?? 'chain-id'}${colorSuffix}` };
378
390
  }
379
391
  case 'select': {
380
392
  const compiled = compileSelector(command.target);
@@ -410,10 +422,10 @@ async function executeCommand(plugin, command, hasStructure, theme) {
410
422
  if (plugin.canvas3d === undefined) {
411
423
  return { ok: false, op: command.op, code: 'INVALID_COMMAND', message: 'canvas is unavailable' };
412
424
  }
413
- const color = command.color === 'theme' ? toColor(theme === 'dark' ? '#101418' : '#ffffff') : toColor(command.color);
414
- plugin.canvas3d.setProps({ renderer: { backgroundColor: color } });
425
+ const color = resolveColor(command.color === 'theme' ? (theme === 'dark' ? '#101418' : '#ffffff') : command.color);
426
+ plugin.canvas3d.setProps({ renderer: { backgroundColor: Color(color) } });
415
427
  plugin.canvas3d.requestDraw();
416
- return { ok: true, op: command.op, message: `background ${command.color}` };
428
+ return { ok: true, op: command.op, message: `background ${formatColor(color)}` };
417
429
  }
418
430
  case 'measure': {
419
431
  const structure = firstStructure(plugin);
@@ -474,12 +486,13 @@ function firstStructure(plugin) {
474
486
  function invalid(op, message) {
475
487
  return { ok: false, op, code: 'INVALID_COMMAND', message };
476
488
  }
477
- function toColor(value) {
478
- const trimmed = value.trim();
479
- if (/^#[0-9a-f]{6}$/iu.test(trimmed) || /^#[0-9a-f]{8}$/iu.test(trimmed)) {
480
- return Color(Number.parseInt(trimmed.slice(1), 16));
489
+ function resolveColor(value) {
490
+ try {
491
+ return parseColor(value);
492
+ }
493
+ catch (error) {
494
+ throw new Mol4AgentError('INVALID_COMMAND', error instanceof Error ? error.message : String(error));
481
495
  }
482
- return Color(0xffffff);
483
496
  }
484
497
  function decodeBase64(value) {
485
498
  const binary = atob(value);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gcszhn/mol4agent-core",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Harness-neutral Mol* viewer engine: bytes + explicit format in, commands out.",
6
6
  "main": "./lib/index.js",
@@ -21,6 +21,11 @@
21
21
  "import": "./lib/parse/index.js",
22
22
  "default": "./lib/parse/index.js"
23
23
  },
24
+ "./sources": {
25
+ "types": "./lib/sources.d.ts",
26
+ "import": "./lib/sources.js",
27
+ "default": "./lib/sources.js"
28
+ },
24
29
  "./react": {
25
30
  "types": "./lib/react.d.ts",
26
31
  "import": "./lib/react.js",