@gcszhn/mol4agent-core 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GCS-ZHN
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,403 @@
1
- # Temporary Holding Version
1
+ # @gcszhn/mol4agent-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [English](README.md) | [中文](README_zh.md)
4
+
5
+ Harness-neutral molecular viewer engine. It mounts Mol*'s **official React UI**
6
+ (`createPluginUI` + `DefaultPluginUISpec`), owns the viewer lifecycle, commands,
7
+ selections, measurements, and PNG capture. It does **not** know about files,
8
+ paths, extensions, harness SDKs, sessions, or UI chrome.
9
+
10
+ ```text
11
+ adapter (DSH / ChatGPT/Codex)
12
+ |
13
+ +-- decides that a file is a molecule and maps it to MolFormat
14
+ +-- obtains the bytes (DSH: workspace path; ChatGPT/Codex: raw data)
15
+ |
16
+ v
17
+ viewer.load({ data, format, label })
18
+ |
19
+ v
20
+ core: createPluginUI -> Mol* state tree -> commands -> capture
21
+ ```
22
+
23
+ ## Boundary rules
24
+
25
+ - Input is always `StructureData { data: string | Uint8Array, format, binary?, label? }`.
26
+ - `format` is explicit; core never inspects a suffix or a MIME type.
27
+ - No filesystem, network, session, or harness package imports.
28
+ - Commands are JSON-serializable; **loading is a method, not a command**, because
29
+ adapter-owned bytes may not be serializable.
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.
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ pnpm add @gcszhn/mol4agent-core molstar
39
+ # only when using the React binding:
40
+ pnpm add react
41
+ ```
42
+
43
+ The package is published on npm as `@gcszhn/mol4agent-core@0.2.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.
47
+
48
+ Build and pack:
49
+
50
+ ```sh
51
+ pnpm --filter @gcszhn/mol4agent-core build
52
+ # emits lib/*.js + lib/*.d.ts
53
+ ```
54
+
55
+ Package `exports` point at `lib`, and the npm `files` allowlist includes only
56
+ `lib` plus the READMEs. `src/`, `AGENTS.md`, and build scripts are not packed;
57
+ `prepack` builds first.
58
+
59
+ ## Entrypoints
60
+
61
+ | Import | Exports |
62
+ |---|---|
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`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
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 |
67
+ | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
68
+
69
+ ## `createMolViewer`
70
+
71
+ ```ts
72
+ import { createMolViewer } from '@gcszhn/mol4agent-core'
73
+
74
+ const viewer = await createMolViewer({
75
+ container, // HTMLElement with a real width/height
76
+ theme: 'dark', // 'light' | 'dark'; default dark
77
+ background: '#101418', // optional; default follows theme
78
+ })
79
+
80
+ await viewer.load({ data: bytes, format: 'pdb', label: '1crn.pdb' })
81
+ await viewer.apply([
82
+ { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } },
83
+ { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true },
84
+ ])
85
+ const png = await viewer.capture({ width: 1024, height: 768 })
86
+ viewer.dispose()
87
+ ```
88
+
89
+ `createMolViewer` waits up to 3 s for the container to get a non-zero box, mounts
90
+ the official Mol* UI, and follows later resizes. It injects Mol*'s light/dark
91
+ stylesheet once per viewer and removes it on `dispose()`.
92
+
93
+ ### `MolViewerOptions`
94
+
95
+ | Field | Type | Meaning |
96
+ |---|---|---|
97
+ | `container` | `HTMLElement` | Host element; the viewer fills it with `position:relative;width:100%;height:100%` |
98
+ | `theme` | `'light' \| 'dark'` | Initial Mol* skin and canvas background |
99
+ | `background` | `string` | Optional explicit canvas background |
100
+
101
+ ### `MolViewer`
102
+
103
+ | Method | Signature | Meaning |
104
+ |---|---|---|
105
+ | `load` | `(data: StructureData, options?: { preset?: string }) => Promise<StructureSummary>` | Replace the displayed structure. Text formats passed as bytes are UTF-8 decoded; `binary` is respected. `preset` defaults to `default`; built-ins are `default`, `auto`, `illustrative`, `atomic-detail`, `polymer-and-ligand`, or an adapter-registered preset name. |
106
+ | `summary` | `() => StructureSummary \| undefined` | Summary of the current structure, when loaded |
107
+ | `execute` | `(command: MolCommand) => Promise<CommandResult>` | Run one command; failures are returned as `{ ok: false, code, message }` |
108
+ | `apply` | `(commands: readonly MolCommand[]) => Promise<readonly CommandResult[]>` | Run commands in order |
109
+ | `capture` | `(options?: CaptureOptions) => Promise<Uint8Array>` | Render the viewport to PNG |
110
+ | `setTheme` | `(theme: 'light' \| 'dark') => void` | Swap UI skin and canvas background without rebuilding |
111
+ | `resize` | `() => void` | Ask Mol* to re-measure the viewport |
112
+ | `diagnostics` | `() => ViewerDiagnostics` | Canvas/host sizes and Mol* hierarchy counts |
113
+ | `dispose` | `() => void` | Unmount the UI, remove styles, release Mol* |
114
+
115
+ ### `ViewerDiagnostics`
116
+
117
+ ```ts
118
+ {
119
+ canvas: { width, height, clientWidth, clientHeight },
120
+ host: { clientWidth, clientHeight },
121
+ structures: number,
122
+ components: number,
123
+ representations: number,
124
+ atoms: number,
125
+ }
126
+ ```
127
+
128
+ ## Data protocol
129
+
130
+ ### `StructureData`
131
+
132
+ ```ts
133
+ interface StructureData {
134
+ data: string | Uint8Array
135
+ format: MolFormat
136
+ binary?: boolean // adapter override; default from the format table
137
+ label?: string // display only; core never derives it from a path
138
+ }
139
+ ```
140
+
141
+ `MolFormat` values:
142
+
143
+ | format | Mol* parser | binary by default |
144
+ |---|---|---|
145
+ | `pdb`, `pdbqt`, `pqr` | `pdb` / `pdbqt` / `pqr` | no |
146
+ | `mmcif` | `mmcif` | no |
147
+ | `bcif` | `mmcif` | **yes** |
148
+ | `mol`, `sdf` | `mol` / `sdf` | no |
149
+ | `mol2`, `xyz`, `gro` | same name | no |
150
+
151
+ Text formats are decoded with a non-fatal UTF-8 decoder when an adapter passes
152
+ bytes. This matters for DSH: its workspace reader returns `Uint8Array` even for
153
+ `.pdb`; without decoding, Mol* would parse the PDB as a Binary data object and
154
+ produce an empty hierarchy.
155
+
156
+ ## Commands
157
+
158
+ `MolCommand` is a discriminated union. All examples are JSON-serializable and
159
+ can be stored in a session log, then replayed after `load()`.
160
+
161
+ | `op` | Fields | Effect |
162
+ |---|---|---|
163
+ | `represent` | `style: StyleSpec`, optional `target` | Without `target`, replace the scene representation. For `cartoon` (or omitted `type`) core uses Mol*'s `polymer-and-ligand` preset so HETATM ligands stay visible. With `target`, add the representation only to that selection (a new Mol* component), leaving the rest untouched. `quality` is accepted but not applied yet. |
164
+ | `select` | `target`, `mode?: 'select' \| 'highlight'`, `focus?` | Apply Mol* selection interactivity; `focus` moves the camera |
165
+ | `clear-selection` | `mode?` | Clear select/highlight interactivity |
166
+ | `focus` | optional `target` | Focus camera on the selection or the whole structure |
167
+ | `camera` | `action: 'reset'` | Reset the camera |
168
+ | `background` | `color: string \| 'theme'` | Set the canvas background |
169
+ | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`, `targets` 2/3/4 | Add a measurement |
170
+ | `label` | `target`, optional `text` | Add a 3D label |
171
+
172
+ Examples:
173
+
174
+ ```ts
175
+ { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } }
176
+ { op: 'represent', style: { type: 'ball-and-stick', color: 'element-symbol' } }
177
+ { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true }
178
+ { op: 'select', target: { kind: 'residues', chain: 'A', start: 10, end: 25 } }
179
+ { op: 'focus', target: { kind: 'chain', chain: 'B' } }
180
+ { op: 'camera', action: 'reset' }
181
+ { op: 'background', color: '#101418' }
182
+ { op: 'measure', kind: 'distance', targets: [
183
+ { kind: 'residue', chain: 'A', index: 42 },
184
+ { kind: 'residue', chain: 'A', index: 87 },
185
+ ] }
186
+ { op: 'label', target: { kind: 'ligand' }, text: 'ATP' }
187
+ ```
188
+
189
+ ### `StyleSpec`
190
+
191
+ ```ts
192
+ {
193
+ type?: 'cartoon' | 'ball-and-stick' | 'licorice' | 'spacefill' | 'line'
194
+ | 'point' | 'surface' | 'gaussian-surface' | 'molecular-surface'
195
+ color?: 'chain-id' | 'element-symbol' | 'residue-name' | 'uniform'
196
+ | 'secondary-structure' | 'entity-id' | 'molecule-type' | 'hydrophobicity'
197
+ colorParams?: { value?: string | number }
198
+ quality?: 'low' | 'medium' | 'high' | 'auto' // reserved; Mol* auto quality is used
199
+ }
200
+ ```
201
+
202
+ ### `CommandResult`
203
+
204
+ ```ts
205
+ type CommandResult =
206
+ | { ok: true; op: MolCommand['op']; message?: string; data?: unknown }
207
+ | { ok: false; op: MolCommand['op']; code: Mol4AgentErrorCode; message: string }
208
+ ```
209
+
210
+ Error codes: `INVALID_COMMAND`, `UNSUPPORTED_FORMAT`, `UNSUPPORTED_REPRESENTATION`,
211
+ `REPRESENT_FAILED`, `NO_STRUCTURE`, `LOAD_FAILED`, `CAPTURE_FAILED`,
212
+ `SUMMARY_UNSUPPORTED`, `UNSUPPORTED_SOURCE`, `INVALID_ENTRY_ID`, `DISPOSED`.
213
+
214
+ ## Selectors
215
+
216
+ Selectors are the stable agent-facing shape; adapters pass them through and core
217
+ compiles them to Mol* selection queries or element schemas.
218
+
219
+ | Selector | Meaning |
220
+ |---|---|
221
+ | `{ kind: 'all' }` | Every atom |
222
+ | `{ kind: 'polymer' }` | Polymer atoms |
223
+ | `{ kind: 'protein' }` | Protein polymer |
224
+ | `{ kind: 'nucleic' }` | Nucleic acid polymer |
225
+ | `{ kind: 'ligand' }` | Non-polymer ligands (ATP, HEM, ...) |
226
+ | `{ kind: 'water' }` | Water |
227
+ | `{ kind: 'ion' }` | Ions |
228
+ | `{ kind: 'chain', chain }` | One chain |
229
+ | `{ kind: 'residue', chain?, index, auth? }` | One residue; `auth` selects author numbering |
230
+ | `{ kind: 'residues', chain?, start, end, auth? }` | Inclusive residue range |
231
+ | `{ kind: 'comp', compId }` | All residues with a component id |
232
+ | `{ kind: 'schema', schema }` | Low-level subset of `StructureElement.Schema` |
233
+
234
+ `schema` fields: `auth_asym_id`, `label_asym_id`, `auth_seq_id`, `label_seq_id`,
235
+ `label_comp_id`, `auth_comp_id`, `beg_auth_seq_id`, `end_auth_seq_id`,
236
+ `beg_label_seq_id`, `end_label_seq_id`, `label_atom_id`, `auth_atom_id`,
237
+ `type_symbol`.
238
+
239
+ ```ts
240
+ import { compileSelector, selectorSchema } from '@gcszhn/mol4agent-core'
241
+
242
+ const compiled = compileSelector({ kind: 'ligand' })
243
+ const schema = selectorSchema({ kind: 'residues', chain: 'A', start: 10, end: 25 })
244
+ ```
245
+
246
+ ## Summaries
247
+
248
+ `summarizeStructure` parses bytes without a viewer. It is useful for `mol_info`
249
+ and for giving the model chain/residue/ligand facts before opening a heavy 3D
250
+ viewer. It works in Node and the browser.
251
+
252
+ ```ts
253
+ import { summarizeStructure } from '@gcszhn/mol4agent-core/parse'
254
+
255
+ const summary = summarizeStructure({ data: pdbText, format: 'pdb', label: '1atp.pdb' })
256
+ // { atomCount, residueCount, modelCount, chains, ligands, complete, ... }
257
+ ```
258
+
259
+ `StructureSummary`:
260
+
261
+ ```ts
262
+ {
263
+ format: MolFormat
264
+ label?: string
265
+ title?: string
266
+ atomCount: number
267
+ residueCount: number
268
+ modelCount: number
269
+ chains: { id, kind, atoms, residues, compIds }[]
270
+ ligands: { compId, count }[]
271
+ complete: boolean // false only for a viewer fallback summary; summarizeStructure throws for BCIF
272
+ }
273
+ ```
274
+
275
+ BCIF can be rendered but not summarized from raw bytes yet; `summarizeStructure`
276
+ throws `SUMMARY_UNSUPPORTED`. A post-load viewer fallback may still expose
277
+ `complete: false`.
278
+
279
+ ## Database sources
280
+
281
+ `mol_fetch` starts from an entry id instead of a local file. Core validates the
282
+ id and returns a download plan; it never performs the request or writes a file.
283
+ Adapters execute the plan with their own HTTPS and filesystem APIs.
284
+
285
+ ```ts
286
+ import { resolveSource } from '@gcszhn/mol4agent-core/sources'
287
+
288
+ resolveSource({ entryId: '1crn' })
289
+ // { sourceDb: 'rcsb-pdb', entryId: '1CRN', format: 'pdb',
290
+ // fileName: '1CRN.pdb',
291
+ // plan: { url: 'https://files.rcsb.org/download/1CRN.pdb' },
292
+ // description: 'RCSB PDB entry 1CRN (PDB format)' }
293
+
294
+ resolveSource({ entryId: 'P00533', sourceDb: 'alphafold' })
295
+ // plan: { url: 'https://alphafold.ebi.ac.uk/api/prediction/P00533',
296
+ // indexField: '0.pdbUrl' }
297
+ ```
298
+
299
+ | `source_db` | `entry_id` | Format |
300
+ |---|---|---|
301
+ | `rcsb-pdb` (default) | 4-character PDB id (`1crn`) | `pdb` |
302
+ | `rcsb-cif` | 4-character PDB id (`1crn`) | `mmcif` |
303
+ | `rcsb-bcif` | 4-character PDB id (`1crn`) | `bcif` |
304
+ | `alphafold` | UniProt accession (`P00533`) | `pdb` |
305
+ | `pubchem` | CID (`2244`) or compound name (`aspirin`) | `sdf` |
306
+ | `chembl` | `CHEMBL25`, or a bare number (`25`) | `sdf` |
307
+
308
+ `plan.indexField` marks a JSON index document: the adapter reads that dot path
309
+ and downloads the URL it names. AlphaFold file names are versioned, so
310
+ `0.pdbUrl` skips the API's array wrapper and selects the current PDB URL. Use
311
+ `readSourceIndexField(payload, field)` for that lookup.
312
+
313
+ `SOURCE_DATABASE_INFO` supplies the label, description, entry hint, and format
314
+ for tool descriptions. `normalizeSourceDb` enforces the closed list, and invalid
315
+ ids raise `Mol4AgentError` with `UNSUPPORTED_SOURCE` or `INVALID_ENTRY_ID`.
316
+
317
+ ## Capture
318
+
319
+ ```ts
320
+ const png = await viewer.capture({
321
+ width: 1024, // optional; default 1024
322
+ height: 768, // optional; default 768
323
+ transparent: true, // optional
324
+ background: '#101418', // optional
325
+ })
326
+ ```
327
+
328
+ `capture` uses Mol*'s viewport screenshot helper. Width/height default to
329
+ 1024×768. A failed render rejects with `CAPTURE_FAILED`.
330
+
331
+ `measure` and `label` accept `chain`, `residue`, `residues`, `comp`, or `schema`
332
+ selectors; semantic categories such as `ligand`/`protein` cannot be converted to
333
+ a single atom position and return `INVALID_COMMAND`.
334
+
335
+ Per-selection styling is additive:
336
+
337
+ ```ts
338
+ // gray cartoon for the rest
339
+ { op: 'represent', style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0x808080 } } }
340
+ // red sticks for one interface range
341
+ { op: 'represent',
342
+ style: { type: 'ball-and-stick', color: 'uniform', colorParams: { value: 0xff0000 } },
343
+ target: { kind: 'residues', chain: 'A', start: 28, end: 54 } }
344
+ ```
345
+
346
+ A global `cartoon` uses the `polymer-and-ligand` preset; `colorParams` is passed
347
+ through its theme so `uniform` colors work. A targeted `represent` creates a
348
+ separate selection component and does not remove other representations.
349
+
350
+ ## React binding
351
+
352
+ ```tsx
353
+ import { Mol4AgentViewer } from '@gcszhn/mol4agent-core/react'
354
+
355
+ <Mol4AgentViewer
356
+ scene={{ data, commands }}
357
+ theme="dark"
358
+ onViewer={viewer => { /* keep for capture */ }}
359
+ style={{ height: 600 }}
360
+ />
361
+ ```
362
+
363
+ The component owns the viewer lifecycle. **Memoize `scene`**; changing the object
364
+ reloads the structure and replays commands. The DSH adapter chooses not to use
365
+ this binding because it needs session-projection fidelity, per-tab caching, and a
366
+ custom capture path.
367
+
368
+ ## Internal flow
369
+
370
+ ```mermaid
371
+ sequenceDiagram
372
+ participant A as Adapter
373
+ participant C as core
374
+ participant M as Molstar
375
+
376
+ A->>C: createMolViewer(container, theme)
377
+ C->>M: createPluginUI(DefaultPluginUISpec)
378
+ A->>C: load(data, format, label)
379
+ C->>M: rawData -> parseTrajectory -> applyPreset
380
+ A->>C: execute(represent, style)
381
+ C->>M: representation preset / addRepresentation
382
+ A->>C: execute(select, target)
383
+ C->>M: applyStructureInteractivity
384
+ A->>C: capture(width, height)
385
+ C->>M: viewportScreenshot
386
+ M-->>C: image
387
+ C-->>A: PNG Uint8Array
388
+ ```
389
+
390
+ ## Status
391
+
392
+ - `protocol`, `formats`, `parse/*`, `sources`, `viewer`, `select`, `react` are
393
+ implemented and typechecked.
394
+ - Verified in headless Chrome + SwiftShader with real 1CRN PDB/CIF, 1ATP, and a
395
+ PubChem aspirin SDF: official UI, load, cartoon/polymer-and-ligand, ligand
396
+ highlight, focus, and PNG capture.
397
+ - The DSH adapter bundles core into one client script; see
398
+ [`packages/deepseek-harness`](../deepseek-harness).
399
+
400
+ See [`docs/architecture.md`](../../docs/architecture.md) for the overall
401
+ architecture; implementation details live in this package's README/AGENTS and
402
+ in [`packages/deepseek-harness/README.md`](../deepseek-harness/README.md) for
403
+ DSH.