@gcszhn/mol4agent-core 0.2.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
@@ -40,7 +40,7 @@ pnpm add @gcszhn/mol4agent-core molstar
40
40
  pnpm add react
41
41
  ```
42
42
 
43
- The package is published on npm as `@gcszhn/mol4agent-core@0.2.0`; inside this
43
+ The package is published on npm as `@gcszhn/mol4agent-core@0.3.0`; inside this
44
44
  monorepo, pnpm links the workspace copy instead. `molstar` and `react` are peer
45
45
  dependencies. The DSH adapter bundles Mol* into a single client script; a plain
46
46
  web app can use the package directly.
@@ -61,7 +61,7 @@ Package `exports` point at `lib`, and the npm `files` allowlist includes only
61
61
  | Import | Exports |
62
62
  |---|---|
63
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 |
64
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`, `StructureData`, `MolCommand`, `StructureSelector`, `StructureSummary`, `Mol4AgentError`, `parseColor` / `formatColor` / `COLOR_SYNTAX`, and the `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` guards |
65
65
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`, `summarizePdbLike`, `summarizeCif`, `summarizeSdf`, `summarizeMol2`, `summarizeXyz`, `summarizeGro` |
66
66
  | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`, `SOURCE_DATABASE_INFO`, `resolveSource`, `normalizeSourceDb`, `readSourceIndexField`, and the `isSourceDatabase` guard |
67
67
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`, `Mol4AgentViewerHandle`, `Mol4AgentScene` |
@@ -96,7 +96,7 @@ stylesheet once per viewer and removes it on `dispose()`.
96
96
  |---|---|---|
97
97
  | `container` | `HTMLElement` | Host element; the viewer fills it with `position:relative;width:100%;height:100%` |
98
98
  | `theme` | `'light' \| 'dark'` | Initial Mol* skin and canvas background |
99
- | `background` | `string` | Optional explicit canvas background |
99
+ | `background` | `string \| number` | Optional explicit canvas background (same colour syntax as `colorParams.value`) |
100
100
 
101
101
  ### `MolViewer`
102
102
 
@@ -165,7 +165,7 @@ can be stored in a session log, then replayed after `load()`.
165
165
  | `clear-selection` | `mode?` | Clear select/highlight interactivity |
166
166
  | `focus` | optional `target` | Focus camera on the selection or the whole structure |
167
167
  | `camera` | `action: 'reset'` | Reset the camera |
168
- | `background` | `color: string \| 'theme'` | Set the canvas background |
168
+ | `background` | `color: string \| number \| 'theme'` | Set the canvas background |
169
169
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`, `targets` 2/3/4 | Add a measurement |
170
170
  | `label` | `target`, optional `text` | Add a 3D label |
171
171
 
@@ -199,6 +199,32 @@ Examples:
199
199
  }
200
200
  ```
201
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
+
202
228
  ### `CommandResult`
203
229
 
204
230
  ```ts
@@ -321,7 +347,7 @@ const png = await viewer.capture({
321
347
  width: 1024, // optional; default 1024
322
348
  height: 768, // optional; default 768
323
349
  transparent: true, // optional
324
- background: '#101418', // optional
350
+ background: '#101418', // optional; colour names and integers also work
325
351
  })
326
352
  ```
327
353
 
package/README_zh.md CHANGED
@@ -40,7 +40,7 @@ pnpm add @gcszhn/mol4agent-core molstar
40
40
  pnpm add react
41
41
  ```
42
42
 
43
- 本包已发布到 npm(`@gcszhn/mol4agent-core@0.2.0`);在 monorepo 内 pnpm 会链接
43
+ 本包已发布到 npm(`@gcszhn/mol4agent-core@0.3.0`);在 monorepo 内 pnpm 会链接
44
44
  workspace 版本。`molstar` 和 `react` 是 peer dependencies。DSH 适配包把 Mol*
45
45
  打进单个 client bundle;普通 web 应用可以直接使用本包。
46
46
 
@@ -59,7 +59,7 @@ Package `exports` 指向 `lib`,npm `files` 只包含 `lib` 和 README;`src/`
59
59
  | Import | 导出 |
60
60
  |---|---|
61
61
  | `@gcszhn/mol4agent-core` | `createMolViewer`、协议类型、format 辅助函数、source 辅助函数、`summarizeStructure`、`compileSelector`、`selectorSchema` |
62
- | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
62
+ | `@gcszhn/mol4agent-core/protocol` | `MOL_FORMATS`、`StructureData`、`MolCommand`、`StructureSelector`、`StructureSummary`、`Mol4AgentError`、`parseColor` / `formatColor` / `COLOR_SYNTAX`,以及 `isMolFormat` / `isStructureData` / `isMolCommandOp` / `isPresetName` 守卫 |
63
63
  | `@gcszhn/mol4agent-core/parse` | `summarizeStructure`、`summarizePdbLike`、`summarizeCif`、`summarizeSdf`、`summarizeMol2`、`summarizeXyz`、`summarizeGro` |
64
64
  | `@gcszhn/mol4agent-core/sources` | `SOURCE_DATABASES`、`SOURCE_DATABASE_INFO`、`resolveSource`、`normalizeSourceDb`、`readSourceIndexField`,以及 `isSourceDatabase` 守卫 |
65
65
  | `@gcszhn/mol4agent-core/react` | `Mol4AgentViewer`、`Mol4AgentViewerHandle`、`Mol4AgentScene` |
@@ -94,7 +94,7 @@ viewer.dispose()
94
94
  |---|---|---|
95
95
  | `container` | `HTMLElement` | 宿主元素;viewer 用 `position:relative;width:100%;height:100%` 填满 |
96
96
  | `theme` | `'light' \| 'dark'` | 初始 Mol* 皮肤和画布背景 |
97
- | `background` | `string` | 可选,显式指定画布背景 |
97
+ | `background` | `string \| number` | 可选,显式指定画布背景(颜色语法同 `colorParams.value`) |
98
98
 
99
99
  ### `MolViewer`
100
100
 
@@ -162,7 +162,7 @@ interface StructureData {
162
162
  | `clear-selection` | `mode?` | 清除 select/highlight 交互 |
163
163
  | `focus` | 可选 `target` | 聚焦选择或整个结构 |
164
164
  | `camera` | `action: 'reset'` | 重置镜头 |
165
- | `background` | `color: string \| 'theme'` | 设置画布背景 |
165
+ | `background` | `color: string \| number \| 'theme'` | 设置画布背景 |
166
166
  | `measure` | `kind: 'distance' \| 'angle' \| 'dihedral'`,`targets` 2/3/4 个 | 添加测量 |
167
167
  | `label` | `target`,可选 `text` | 添加 3D 标签 |
168
168
 
@@ -196,6 +196,30 @@ interface StructureData {
196
196
  }
197
197
  ```
198
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
+
199
223
  ### `CommandResult`
200
224
 
201
225
  ```ts
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/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';
@@ -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',
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.2.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",