@gcszhn/mol4agent-core 0.0.0-stage → 0.1.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,361 @@
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
+
32
+ ## Install
33
+
34
+ ```sh
35
+ pnpm add @gcszhn/mol4agent-core molstar
36
+ # only when using the React binding:
37
+ pnpm add react
38
+ ```
39
+
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.
44
+
45
+ Build and pack:
46
+
47
+ ```sh
48
+ pnpm --filter @gcszhn/mol4agent-core build
49
+ # emits lib/*.js + lib/*.d.ts
50
+ ```
51
+
52
+ Package `exports` point at `lib`, and the npm `files` allowlist includes only
53
+ `lib` plus the READMEs. `src/`, `AGENTS.md`, and build scripts are not packed;
54
+ `prepack` builds first.
55
+
56
+ ## Entrypoints
57
+
58
+ | Import | Exports |
59
+ |---|---|
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 |
62
+ | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`, `summarizePdbLike`, `summarizeCif`, `summarizeSdf`, `summarizeMol2`, `summarizeXyz`, `summarizeGro` |
63
+ | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
64
+
65
+ ## `createMolViewer`
66
+
67
+ ```ts
68
+ import { createMolViewer } from '@gcszhn/mol4agent-core'
69
+
70
+ const viewer = await createMolViewer({
71
+ container, // HTMLElement with a real width/height
72
+ theme: 'dark', // 'light' | 'dark'; default dark
73
+ background: '#101418', // optional; default follows theme
74
+ })
75
+
76
+ await viewer.load({ data: bytes, format: 'pdb', label: '1crn.pdb' })
77
+ await viewer.apply([
78
+ { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } },
79
+ { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true },
80
+ ])
81
+ const png = await viewer.capture({ width: 1024, height: 768 })
82
+ viewer.dispose()
83
+ ```
84
+
85
+ `createMolViewer` waits up to 3 s for the container to get a non-zero box, mounts
86
+ the official Mol* UI, and follows later resizes. It injects Mol*'s light/dark
87
+ stylesheet once per viewer and removes it on `dispose()`.
88
+
89
+ ### `MolViewerOptions`
90
+
91
+ | Field | Type | Meaning |
92
+ |---|---|---|
93
+ | `container` | `HTMLElement` | Host element; the viewer fills it with `position:relative;width:100%;height:100%` |
94
+ | `theme` | `'light' \| 'dark'` | Initial Mol* skin and canvas background |
95
+ | `background` | `string` | Optional explicit canvas background |
96
+
97
+ ### `MolViewer`
98
+
99
+ | Method | Signature | Meaning |
100
+ |---|---|---|
101
+ | `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. |
102
+ | `summary` | `() => StructureSummary \| undefined` | Summary of the current structure, when loaded |
103
+ | `execute` | `(command: MolCommand) => Promise<CommandResult>` | Run one command; failures are returned as `{ ok: false, code, message }` |
104
+ | `apply` | `(commands: readonly MolCommand[]) => Promise<readonly CommandResult[]>` | Run commands in order |
105
+ | `capture` | `(options?: CaptureOptions) => Promise<Uint8Array>` | Render the viewport to PNG |
106
+ | `setTheme` | `(theme: 'light' \| 'dark') => void` | Swap UI skin and canvas background without rebuilding |
107
+ | `resize` | `() => void` | Ask Mol* to re-measure the viewport |
108
+ | `diagnostics` | `() => ViewerDiagnostics` | Canvas/host sizes and Mol* hierarchy counts |
109
+ | `dispose` | `() => void` | Unmount the UI, remove styles, release Mol* |
110
+
111
+ ### `ViewerDiagnostics`
112
+
113
+ ```ts
114
+ {
115
+ canvas: { width, height, clientWidth, clientHeight },
116
+ host: { clientWidth, clientHeight },
117
+ structures: number,
118
+ components: number,
119
+ representations: number,
120
+ atoms: number,
121
+ }
122
+ ```
123
+
124
+ ## Data protocol
125
+
126
+ ### `StructureData`
127
+
128
+ ```ts
129
+ interface StructureData {
130
+ data: string | Uint8Array
131
+ format: MolFormat
132
+ binary?: boolean // adapter override; default from the format table
133
+ label?: string // display only; core never derives it from a path
134
+ }
135
+ ```
136
+
137
+ `MolFormat` values:
138
+
139
+ | format | Mol* parser | binary by default |
140
+ |---|---|---|
141
+ | `pdb`, `pdbqt`, `pqr` | `pdb` / `pdbqt` / `pqr` | no |
142
+ | `mmcif` | `mmcif` | no |
143
+ | `bcif` | `mmcif` | **yes** |
144
+ | `mol`, `sdf` | `mol` / `sdf` | no |
145
+ | `mol2`, `xyz`, `gro` | same name | no |
146
+
147
+ Text formats are decoded with a non-fatal UTF-8 decoder when an adapter passes
148
+ bytes. This matters for DSH: its workspace reader returns `Uint8Array` even for
149
+ `.pdb`; without decoding, Mol* would parse the PDB as a Binary data object and
150
+ produce an empty hierarchy.
151
+
152
+ ## Commands
153
+
154
+ `MolCommand` is a discriminated union. All examples are JSON-serializable and
155
+ can be stored in a session log, then replayed after `load()`.
156
+
157
+ | `op` | Fields | Effect |
158
+ |---|---|---|
159
+ | `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. |
160
+ | `select` | `target`, `mode?: 'select' \| 'highlight'`, `focus?` | Apply Mol* selection interactivity; `focus` moves the camera |
161
+ | `clear-selection` | `mode?` | Clear select/highlight interactivity |
162
+ | `focus` | optional `target` | Focus camera on the selection or the whole structure |
163
+ | `camera` | `action: 'reset'` | Reset the camera |
164
+ | `background` | `color: string \| 'theme'` | Set the canvas background |
165
+ | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`, `targets` 2/3/4 | Add a measurement |
166
+ | `label` | `target`, optional `text` | Add a 3D label |
167
+
168
+ Examples:
169
+
170
+ ```ts
171
+ { op: 'represent', style: { type: 'cartoon', color: 'chain-id' } }
172
+ { op: 'represent', style: { type: 'ball-and-stick', color: 'element-symbol' } }
173
+ { op: 'select', target: { kind: 'ligand' }, mode: 'highlight', focus: true }
174
+ { op: 'select', target: { kind: 'residues', chain: 'A', start: 10, end: 25 } }
175
+ { op: 'focus', target: { kind: 'chain', chain: 'B' } }
176
+ { op: 'camera', action: 'reset' }
177
+ { op: 'background', color: '#101418' }
178
+ { op: 'measure', kind: 'distance', targets: [
179
+ { kind: 'residue', chain: 'A', index: 42 },
180
+ { kind: 'residue', chain: 'A', index: 87 },
181
+ ] }
182
+ { op: 'label', target: { kind: 'ligand' }, text: 'ATP' }
183
+ ```
184
+
185
+ ### `StyleSpec`
186
+
187
+ ```ts
188
+ {
189
+ type?: 'cartoon' | 'ball-and-stick' | 'licorice' | 'spacefill' | 'line'
190
+ | 'point' | 'surface' | 'gaussian-surface' | 'molecular-surface'
191
+ color?: 'chain-id' | 'element-symbol' | 'residue-name' | 'uniform'
192
+ | 'secondary-structure' | 'entity-id' | 'molecule-type' | 'hydrophobicity'
193
+ colorParams?: { value?: string | number }
194
+ quality?: 'low' | 'medium' | 'high' | 'auto' // reserved; Mol* auto quality is used
195
+ }
196
+ ```
197
+
198
+ ### `CommandResult`
199
+
200
+ ```ts
201
+ type CommandResult =
202
+ | { ok: true; op: MolCommand['op']; message?: string; data?: unknown }
203
+ | { ok: false; op: MolCommand['op']; code: Mol4AgentErrorCode; message: string }
204
+ ```
205
+
206
+ Error codes: `INVALID_COMMAND`, `UNSUPPORTED_FORMAT`, `UNSUPPORTED_REPRESENTATION`,
207
+ `REPRESENT_FAILED`, `NO_STRUCTURE`, `LOAD_FAILED`, `CAPTURE_FAILED`,
208
+ `SUMMARY_UNSUPPORTED`, `DISPOSED`.
209
+
210
+ ## Selectors
211
+
212
+ Selectors are the stable agent-facing shape; adapters pass them through and core
213
+ compiles them to Mol* selection queries or element schemas.
214
+
215
+ | Selector | Meaning |
216
+ |---|---|
217
+ | `{ kind: 'all' }` | Every atom |
218
+ | `{ kind: 'polymer' }` | Polymer atoms |
219
+ | `{ kind: 'protein' }` | Protein polymer |
220
+ | `{ kind: 'nucleic' }` | Nucleic acid polymer |
221
+ | `{ kind: 'ligand' }` | Non-polymer ligands (ATP, HEM, ...) |
222
+ | `{ kind: 'water' }` | Water |
223
+ | `{ kind: 'ion' }` | Ions |
224
+ | `{ kind: 'chain', chain }` | One chain |
225
+ | `{ kind: 'residue', chain?, index, auth? }` | One residue; `auth` selects author numbering |
226
+ | `{ kind: 'residues', chain?, start, end, auth? }` | Inclusive residue range |
227
+ | `{ kind: 'comp', compId }` | All residues with a component id |
228
+ | `{ kind: 'schema', schema }` | Low-level subset of `StructureElement.Schema` |
229
+
230
+ `schema` fields: `auth_asym_id`, `label_asym_id`, `auth_seq_id`, `label_seq_id`,
231
+ `label_comp_id`, `auth_comp_id`, `beg_auth_seq_id`, `end_auth_seq_id`,
232
+ `beg_label_seq_id`, `end_label_seq_id`, `label_atom_id`, `auth_atom_id`,
233
+ `type_symbol`.
234
+
235
+ ```ts
236
+ import { compileSelector, selectorSchema } from '@gcszhn/mol4agent-core'
237
+
238
+ const compiled = compileSelector({ kind: 'ligand' })
239
+ const schema = selectorSchema({ kind: 'residues', chain: 'A', start: 10, end: 25 })
240
+ ```
241
+
242
+ ## Summaries
243
+
244
+ `summarizeStructure` parses bytes without a viewer. It is useful for `mol_info`
245
+ and for giving the model chain/residue/ligand facts before opening a heavy 3D
246
+ viewer. It works in Node and the browser.
247
+
248
+ ```ts
249
+ import { summarizeStructure } from '@gcszhn/mol4agent-core/parse'
250
+
251
+ const summary = summarizeStructure({ data: pdbText, format: 'pdb', label: '1atp.pdb' })
252
+ // { atomCount, residueCount, modelCount, chains, ligands, complete, ... }
253
+ ```
254
+
255
+ `StructureSummary`:
256
+
257
+ ```ts
258
+ {
259
+ format: MolFormat
260
+ label?: string
261
+ title?: string
262
+ atomCount: number
263
+ residueCount: number
264
+ modelCount: number
265
+ chains: { id, kind, atoms, residues, compIds }[]
266
+ ligands: { compId, count }[]
267
+ complete: boolean // false only for a viewer fallback summary; summarizeStructure throws for BCIF
268
+ }
269
+ ```
270
+
271
+ BCIF can be rendered but not summarized from raw bytes yet; `summarizeStructure`
272
+ throws `SUMMARY_UNSUPPORTED`. A post-load viewer fallback may still expose
273
+ `complete: false`.
274
+
275
+ ## Capture
276
+
277
+ ```ts
278
+ const png = await viewer.capture({
279
+ width: 1024, // optional; default 1024
280
+ height: 768, // optional; default 768
281
+ transparent: true, // optional
282
+ background: '#101418', // optional
283
+ })
284
+ ```
285
+
286
+ `capture` uses Mol*'s viewport screenshot helper. Width/height default to
287
+ 1024×768. A failed render rejects with `CAPTURE_FAILED`.
288
+
289
+ `measure` and `label` accept `chain`, `residue`, `residues`, `comp`, or `schema`
290
+ selectors; semantic categories such as `ligand`/`protein` cannot be converted to
291
+ a single atom position and return `INVALID_COMMAND`.
292
+
293
+ Per-selection styling is additive:
294
+
295
+ ```ts
296
+ // gray cartoon for the rest
297
+ { op: 'represent', style: { type: 'cartoon', color: 'uniform', colorParams: { value: 0x808080 } } }
298
+ // red sticks for one interface range
299
+ { op: 'represent',
300
+ style: { type: 'ball-and-stick', color: 'uniform', colorParams: { value: 0xff0000 } },
301
+ target: { kind: 'residues', chain: 'A', start: 28, end: 54 } }
302
+ ```
303
+
304
+ A global `cartoon` uses the `polymer-and-ligand` preset; `colorParams` is passed
305
+ through its theme so `uniform` colors work. A targeted `represent` creates a
306
+ separate selection component and does not remove other representations.
307
+
308
+ ## React binding
309
+
310
+ ```tsx
311
+ import { Mol4AgentViewer } from '@gcszhn/mol4agent-core/react'
312
+
313
+ <Mol4AgentViewer
314
+ scene={{ data, commands }}
315
+ theme="dark"
316
+ onViewer={viewer => { /* keep for capture */ }}
317
+ style={{ height: 600 }}
318
+ />
319
+ ```
320
+
321
+ The component owns the viewer lifecycle. **Memoize `scene`**; changing the object
322
+ reloads the structure and replays commands. The DSH adapter chooses not to use
323
+ this binding because it needs session-projection fidelity, per-tab caching, and a
324
+ custom capture path.
325
+
326
+ ## Internal flow
327
+
328
+ ```mermaid
329
+ sequenceDiagram
330
+ participant A as Adapter
331
+ participant C as core
332
+ participant M as Molstar
333
+
334
+ A->>C: createMolViewer(container, theme)
335
+ C->>M: createPluginUI(DefaultPluginUISpec)
336
+ A->>C: load(data, format, label)
337
+ C->>M: rawData -> parseTrajectory -> applyPreset
338
+ A->>C: execute(represent, style)
339
+ C->>M: representation preset / addRepresentation
340
+ A->>C: execute(select, target)
341
+ C->>M: applyStructureInteractivity
342
+ A->>C: capture(width, height)
343
+ C->>M: viewportScreenshot
344
+ M-->>C: image
345
+ C-->>A: PNG Uint8Array
346
+ ```
347
+
348
+ ## Status
349
+
350
+ - `protocol`, `formats`, `parse/*`, `viewer`, `select`, `react` are implemented
351
+ and typechecked.
352
+ - Verified in headless Chrome + SwiftShader with real 1CRN PDB/CIF, 1ATP, and a
353
+ PubChem aspirin SDF: official UI, load, cartoon/polymer-and-ligand, ligand
354
+ highlight, focus, and PNG capture.
355
+ - The DSH adapter bundles core into one client script; see
356
+ [`packages/deepseek-harness`](../deepseek-harness).
357
+
358
+ See [`docs/architecture.md`](../../docs/architecture.md) for the overall
359
+ architecture; implementation details live in this package's README/AGENTS and
360
+ in [`packages/deepseek-harness/README.md`](../deepseek-harness/README.md) for
361
+ DSH.