@louisultra/dsh-verymath 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,76 @@
3
3
  All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
+ ## [0.7.2] - 2026-11-23
7
+
8
+ ### Fixed
9
+
10
+ - **The Python tool and the environment panel could still disagree.** After
11
+ 0.7.1 moved executable discovery into `core/exec.ts`, the panel used that
12
+ resolver but `ctx.verymath.resolvePython()` still spawned the bare configured
13
+ name. A desktop app that inherited no login-shell `PATH` could therefore find
14
+ a conda interpreter in the panel and fail the glossary tools, and a configured
15
+ `pythonExecutable`/`DSH_OFFICE_PYTHON` was invisible to the panel. Python
16
+ resolution now goes through the same absolute-path search on both surfaces,
17
+ and the runtime owns the configured-interpreter lookup the panel calls.
18
+ - The tool module imported `core` through its published package specifier while
19
+ building from the same package. That depended on a TypeScript path alias and
20
+ made the EduWork package copy diverge; it now imports the sibling core module
21
+ directly.
22
+ - A path whose parent component is a regular file reports `ENOTDIR` on some
23
+ platforms. It is now treated as "the glossary does not exist yet" just like
24
+ `ENOENT`, instead of surfacing an I/O error that blocks a legitimate first
25
+ write.
26
+ - The glossary coverage audit still described the upstream suite as partially
27
+ testing bundled scripts. It now records what `test:upstream` really checks;
28
+ the default runtime probe exercises the bundled build path separately.
29
+ - The same audit claimed every bundled glossary script was byte-identical to
30
+ upstream. `glossary_export.py` has a local pyright-comment header; the
31
+ provenance note now states that exception instead of overclaiming.
32
+ - The DSH peer range did not actually admit `0.2.2-rc.3`: npm reports
33
+ `>=0.2.1-rc.5 <0.3.0-0` as `1` for newer `0.2.2` pre-releases, so the old
34
+ `|| 0.2.2-rc.1` clause made the upstream target look incompatible. The
35
+ explicit pre-release branch now covers `>=0.2.2-rc.1 <0.2.3-0`, with a
36
+ manifest regression test covering both the runtime and its boundaries.
37
+
38
+ ### Tests
39
+
40
+ - Added a PATH-starved conda fallback regression and a panel/runtime
41
+ configured-interpreter test. The runtime probe now also asserts that
42
+ `verymath_python_check` and the panel resolver return the same executable.
43
+ - Added the development guide that the README already pointed to, and included
44
+ it in the npm package. It records the current 185-test/16-check baseline,
45
+ upstream-suite scope, unpacked behavior, and package verification commands.
46
+ - Upgraded Vitest from 4.1.8 to 4.1.12, clearing the direct development-only
47
+ advisory for the mock path-traversal issue. The DSH development baseline is
48
+ now `0.2.2-rc.3`, matching EduWork 0.4.14; a clean `npm ci` and the full
49
+ dependency audit both pass without `--legacy-peer-deps`.
50
+ - Declared `@deepseek-ai/dsh-scope`, `@deepseek-ai/dsh-util-values`, React and
51
+ the React testing types as direct development dependencies. They were only
52
+ transitive before, which hid missing packages in a clean DSH `rc.3` install.
53
+ - Added `semver` as a development dependency for an executable check of the
54
+ supported DSH peers; it is not part of the production dependency surface.
55
+
56
+ ## [0.7.1] - 2026-11-11
57
+
58
+ ### Fixed
59
+
60
+ - **The panel and the tools could disagree about the same machine.** The
61
+ environment tab spawned a bare `sage`, while `verymath_sage_check` resolved it
62
+ through the conda environment directories — so a machine with
63
+ `~/.verymath/miniforge/envs/sage` showed "SageMath missing" in the panel and
64
+ "available" in the tool. Executable discovery now lives in `core/exec.ts` and
65
+ both surfaces use it; `tool` re-exports the same functions for compatibility.
66
+ - Panel writes used `writeFile`, which truncates before writing: a concurrent
67
+ reader (the panel polling, or a chat tool call landing mid-write) could see a
68
+ half-written document and report "not a valid glossary". Writes now go through a
69
+ sibling temp file plus `rename`.
70
+ - The environment probe ran its seven checks sequentially, so the tab could sit on
71
+ "probing…" for up to twenty seconds and read as a hang. The independent probes
72
+ now run concurrently.
73
+ - The read route and the write routes returned two different `stats` shapes; both
74
+ now use one `glossaryStats`, so the panel's counters do not jump after an edit.
75
+
6
76
  ## [0.7.0] - 2026-11-11
7
77
 
8
78
  ### Added
@@ -74,7 +144,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
74
144
  client errors, not 500s; the paper route returns topology plus an SVG that
75
145
  actually contains the entity labels.
76
146
 
77
- @@## [0.5.0] - 2026-11-11
147
+ ## [0.5.0] - 2026-11-11
78
148
 
79
149
  ### Added
80
150
 
package/DEVELOPMENT.md ADDED
@@ -0,0 +1,61 @@
1
+ # Development and validation
2
+
3
+ Requires Node.js `24.22.1+` (verified on 24.22.2). Development dependencies pin
4
+ DSH `0.2.2-rc.3`, the runtime bundled with EduWork 0.4.14; the peer range also
5
+ covers `0.2.1-rc.5`, `0.2.2-rc.1` and later `0.2.x`.
6
+
7
+ ```sh
8
+ npm ci
9
+ npm run check
10
+ ```
11
+
12
+ `lib/` and `node_modules/` are generated and not committed. Installation uses the
13
+ built `lib/` tree.
14
+
15
+ ## What `npm run check` covers
16
+
17
+ The command runs type checking, a production build, **185 Vitest tests** in 14
18
+ files, and **16 runtime probe checks**. The probe mounts the real
19
+ `ctx.verymath` service, tool registry, skill registry and native executor. It
20
+ executes the tools against a synthetic workspace, including glossary alias
21
+ creation, correction by `term_id`, whole-batch rollback, path-alias cache
22
+ invalidation, concurrent writes, and batch paper-graph merging. It does not call
23
+ a remote model or require network access.
24
+
25
+ ## Upstream glossary suite
26
+
27
+ When the sibling upstream clone exists, run its 19 Python tests with:
28
+
29
+ ```sh
30
+ npm run test:upstream
31
+ ```
32
+
33
+ This command expects `research/AI4Math-MathTool/` next to the plugin's parent
34
+ directory. The upstream tests load scripts relative to their own test file, so
35
+ this gate verifies upstream behaviour, not the bundled copies. The default
36
+ `npm run check` separately executes the bundled build script; the vendored
37
+ scripts are tracked against their upstream commit in `UPSTREAM.json`.
38
+
39
+ ## Not covered
40
+
41
+ Python, SageMath, TeX Live, Lean/elan and MATLAB are installed by the user and
42
+ are not bundled. Tests prove probe and fallback behaviour, not arbitrary
43
+ execution inside those environments. Real-model task chains are outside
44
+ `npm run check` and are recorded in [`docs/capability-examples.md`](docs/capability-examples.md).
45
+ Windows is not exercised by CI.
46
+
47
+ ## Package contents
48
+
49
+ `package.json` `files` controls the tarball: `lib`, `skills`,
50
+ `docs/capability-examples.md`, `docs/examples`, `cordis.patch.yml`, both
51
+ READMEs, this guide, `NOTICE.md`, `UPSTREAM.json`, and `CHANGELOG.md`. Source and
52
+ test files are excluded. Verify a release candidate with:
53
+
54
+ ```sh
55
+ npm pack --dry-run --json
56
+ ```
57
+
58
+ The dry run must still contain `lib/index.js`, `lib/client.js`,
59
+ `cordis.patch.yml`, all 16 `skills/*/SKILL.md` files, and the documentation
60
+ listed above. The current `0.7.2` candidate is 279 entries; both the production
61
+ and full development dependency trees audit clean with DSH `0.2.2-rc.3`.
package/NOTICE.md CHANGED
@@ -10,8 +10,9 @@ This package contains code and skill content adapted from third-party sources.
10
10
  - Adapted commit: recorded in `UPSTREAM.json`
11
11
  - Changes: SKILL.md trigger text and script invocation guidance adapted for the
12
12
  DSH tool surface (`verymath_glossary_*` tools); Python scripts are included
13
- verbatim. Skill content and scripts remain under the upstream MIT license;
14
- this NOTICE and UPSTREAM.json record the provenance.
13
+ with behaviour unchanged, except that `glossary_export.py` has a local
14
+ pyright-comment header. Skill content and scripts remain under the upstream
15
+ MIT license; this NOTICE and UPSTREAM.json record the provenance.
15
16
 
16
17
  ## VeryMath AI4Math-Paper-Reading (`math-paper-reading`, `graph-theory-paper-reading`, `after-ocr`)
17
18
 
package/README.md CHANGED
@@ -90,7 +90,9 @@
90
90
 
91
91
  ## 安装与使用
92
92
 
93
- 要求 Node.js `24.22.1+` 与 DSH `0.2.x`:peer 覆盖 `0.2.1-rc.5` 到 `0.2.x` 并显式包含 `0.2.2-rc.1`,开发依赖锁定 `0.2.2-rc.1`。运行探针会检测宿主是否装载了工具执行器,据此自适应 0.2.1 的单调用与 0.2.2 的批量接口。
93
+ 要求 Node.js `24.22.1+` 与 DSH `0.2.x`:开发依赖与运行探针锁定 EduWork 0.4.14 所用的 `0.2.2-rc.3`,peer 范围同时覆盖 `0.2.1-rc.5`、`0.2.2-rc.1` 与后续 `0.2.x`。运行探针会检测宿主是否装载了工具执行器,据此自适应 0.2.1 的单调用与 0.2.2 的批量接口。
94
+
95
+ Python 解释器按“插件配置 → `DSH_OFFICE_PYTHON` → PATH → 常见 conda/Homebrew 目录”解析一次,工具与面板共用同一个绝对路径;从 Finder 启动、没有登录 shell PATH 的桌面应用也能找到 conda 环境里的 Python。
94
96
 
95
97
  ```sh
96
98
  dsh plugin --profile <你的profile> add @louisultra/dsh-verymath
@@ -111,7 +113,7 @@ dsh plugin --profile <你的profile> add ./louisultra-dsh-verymath-<version>.tgz
111
113
 
112
114
  - **查询与论文校验**:无需任何外部依赖。
113
115
  - **术语库构建/导出**(`verymath_glossary_build`):需要本地 Python 3 与上游脚本依赖(`PyYAML`;Excel 导出另需 `openpyxl`,Web 管理界面另需 `Flask`)。`verymath_python_check` 只能确认 `python3` 可用;上游依赖缺失时由脚本报错(如 `No module named 'yaml'`),按需 `pip install PyYAML openpyxl Flask`。插件不捆绑 Python。
114
- - **平台**:仅在 macOS(Apple Silicon)验证过(DSH CLI 沙箱 + EduWork 0.4.3 桌面端实际装载)。**Windows 未测试**:代码依赖 Node 与 Python 的 PATH;外部二进制按 PATH 与 PATHEXT 解析(不再指向 macOS 固定路径),但未在 Windows 上实测,涉及 TeX、MATLAB、osqp 等外部环境的场景尤其如此。
116
+ - **平台**:仅在 macOS(Apple Silicon)验证过,包括 DSH CLI 沙箱、EduWork 0.4.13 桌面端和 DSH `0.2.2-rc.3` 工具链。**Windows 未测试**:解释器按 PATH 与常见 conda 目录解析,外部二进制按 PATH 与 PATHEXT 解析(不再指向 macOS 固定路径),但未在 Windows 上实测,涉及 TeX、MATLAB、osqp 等外部环境的场景尤其如此。
115
117
 
116
118
  ## 持续集成
117
119
 
@@ -129,6 +131,8 @@ npm run test:upstream # 上游 math-glossary 离线测试(需把 VeryMath 的
129
131
  # 克隆到与本仓库同级的 research/ 下;仅开发机可用,不随 npm 包分发)
130
132
  ```
131
133
 
134
+ 更完整的构建、探针、上游测试与打包说明见 [`DEVELOPMENT.md`](DEVELOPMENT.md)。
135
+
132
136
  ## 许可与来源
133
137
 
134
138
  本包 MIT 许可(`LICENSE`)。技能内容与 Python 脚本改编自 VeryMath 的 MIT 项目,来源提交与适配范围见 `UPSTREAM.json`,归属详情见 `NOTICE.md`。感谢 VeryMath 团队与上游贡献者。
package/README_EN.md CHANGED
@@ -90,7 +90,9 @@ Skills carry the methodology; tools carry deterministic execution. The plugin co
90
90
 
91
91
  ## Installation and usage
92
92
 
93
- Requires Node.js `24.22.1+` and DSH `0.2.x`: the peer range covers `0.2.1-rc.5` through `0.2.x` and names `0.2.2-rc.1` explicitly, and the development dependencies pin `0.2.2-rc.1`. The runtime probe detects whether the host mounted a tool executor and adapts to the 0.2.1 single-call and 0.2.2 batch interfaces accordingly.
93
+ Requires Node.js `24.22.1+` and DSH `0.2.x`: development dependencies and the runtime probe pin `0.2.2-rc.3`, the version bundled with EduWork 0.4.14, while the peer range also covers `0.2.1-rc.5`, `0.2.2-rc.1` and later `0.2.x`. The runtime probe detects whether the host mounted a tool executor and adapts to the 0.2.1 single-call and 0.2.2 batch interfaces accordingly.
94
+
95
+ Python is resolved once per runtime through the plugin setting, `DSH_OFFICE_PYTHON`, PATH and the common conda/Homebrew directories. The tools and the panel receive the same absolute interpreter path, including when a desktop app starts without a login-shell PATH.
94
96
 
95
97
  ```sh
96
98
  dsh plugin --profile <your-profile> add @louisultra/dsh-verymath
@@ -111,7 +113,7 @@ Then just ask in a session, e.g. "look up the Chinese term for manifold" or "rea
111
113
 
112
114
  - **Query and paper validation**: no external dependencies.
113
115
  - **Glossary build/export** (`verymath_glossary_build`): requires a local Python 3 plus the upstream script dependencies (`PyYAML`; Excel export additionally needs `openpyxl`, the web UI needs `Flask`). `verymath_python_check` only confirms that `python3` is available; a missing upstream dependency surfaces as a script error (for example `No module named 'yaml'`), so install what you need with `pip install PyYAML openpyxl Flask`. The plugin does not bundle Python.
114
- - **Platforms**: verified on macOS (Apple Silicon) (DSH CLI sandbox + the EduWork 0.4.3 desktop app itself); Windows should work (Node and Python on PATH) but is not yet tested — external binaries are now resolved through PATH and PATHEXT rather than a macOS-only path, though that has not been exercised on Windows. Feedback welcome.
116
+ - **Platforms**: verified on macOS (Apple Silicon), including the DSH CLI sandbox, the EduWork 0.4.13 desktop app and the DSH `0.2.2-rc.3` toolchain. Windows is not yet tested: interpreters are resolved through PATH and the common conda directories, and external binaries through PATH and PATHEXT rather than a macOS-only path, but neither has been exercised on Windows. Feedback welcome.
115
117
 
116
118
  ## Continuous integration
117
119
 
@@ -127,6 +129,9 @@ npm run test:runtime # real DSH API probe (synthetic data, no model calls)
127
129
  npm run check # all of the above
128
130
  ```
129
131
 
132
+ See [`DEVELOPMENT.md`](DEVELOPMENT.md) for the full build, probe, upstream-test
133
+ and packaging notes.
134
+
130
135
  ## License and provenance
131
136
 
132
137
  This package is MIT licensed (`LICENSE`). Skill content and Python scripts are adapted from VeryMath's MIT projects; the adapted commits and paths are recorded in `UPSTREAM.json`, with attribution details in `NOTICE.md`. Thanks to the VeryMath team and upstream contributors.
package/UPSTREAM.json CHANGED
@@ -12,7 +12,7 @@
12
12
  "skills/math-glossary/tests/",
13
13
  "skills/matlab-runner/ (SKILL.md + references + examples, with DSH MCP setup notes)"
14
14
  ],
15
- "adaptationNotes": "SKILL.md routing and script-invocation text adapted for DSH tool names (verymath_glossary_*); Python scripts included verbatim, so alias-row ids (`en__N`) are produced by the same algorithm upstream uses; tests adapted to run from the skill directory. matlab-runner bundled after user installed MATLAB R2025b; MathWorks official MCP server v0.14.0 wired via dsh-mcp-client (5 tools match the skill capability list). One sentence added to SKILL.md rule 6 (added 0.4.0) explains the DSH tool contract that the bundled scripts do not cover: adding another translation omits term_id and creates an alias row, correcting a translation passes the term_id returned by a query."
15
+ "adaptationNotes": "SKILL.md routing and script-invocation text adapted for DSH tool names (verymath_glossary_*); Python scripts have unchanged behavior and all but `glossary_export.py` are byte-for-byte upstream. That file adds a local pyright-comment header for openpyxl stubs; alias-row ids (`en__N`) still use the upstream algorithm. Tests are adapted to run from the skill directory. matlab-runner bundled after user installed MATLAB R2025b; MathWorks official MCP server v0.14.0 wired via dsh-mcp-client (5 tools match the skill capability list). One sentence added to SKILL.md rule 6 (added 0.4.0) explains the DSH tool contract that the bundled scripts do not cover: adding another translation omits term_id and creates an alias row, correcting a translation passes the term_id returned by a query."
16
16
  },
17
17
  {
18
18
  "repository": "https://github.com/VeryMath/AI4Math-Paper-Reading",
package/lib/client.js CHANGED
@@ -228,7 +228,13 @@ window.__ModuleLoader__.load({
228
228
  const [busy, setBusy] = useState(false)
229
229
  const [error, setError] = useState('')
230
230
 
231
- useEffect(() => { setDraft(draftFor(props.term)) }, [props.term])
231
+ // Reset the draft only when a *different* row is edited. Depending on the whole
232
+ // `props.term` object reset the draft whenever a background refresh produced a
233
+ // new object for the same term, silently discarding what the user had typed
234
+ // (the list reloads after every save).
235
+ const termId = props.term === undefined ? '' : props.term.term_id
236
+
237
+ useEffect(() => { setDraft(draftFor(props.term)) }, [termId])
232
238
 
233
239
  const field = (key) => (event) => setDraft((prev) => ({ ...prev, [key]: event.target.value }))
234
240
  const input = (key, placeholder, extra) => h('input', {
@@ -283,12 +289,11 @@ window.__ModuleLoader__.load({
283
289
 
284
290
  function TermRow(props) {
285
291
  const term = props.term
286
- const [editing, setEditing] = useState(false)
287
- if (editing) {
292
+ if (props.editing) {
288
293
  return h(TermEditor, {
289
294
  term,
290
295
  onSave: props.onUpsert,
291
- onDone: () => setEditing(false),
296
+ onDone: props.onDoneEditing,
292
297
  })
293
298
  }
294
299
  return h('div', { style: S.card },
@@ -297,13 +302,13 @@ window.__ModuleLoader__.load({
297
302
  h('span', { style: { color: 'var(--dsh-text-tertiary, #999)' } }, '→'),
298
303
  h('span', null, term.cn),
299
304
  h('span', { style: { ...S.code, marginLeft: 'auto' } }, term.term_id),
300
- h('button', { onClick: () => setEditing(true), style: { ...S.btn, padding: '2px 8px' } }, '编辑'),
305
+ h('button', { onClick: () => props.onStartEditing(term.term_id), style: { ...S.btn, padding: '2px 8px' } }, '编辑'),
301
306
  h('button', {
302
307
  onClick: async () => {
303
308
  if (!window.confirm(`删除 ${term.term_id}(${term.en} / ${term.cn})?此操作直接改 glossary.json。`)) return
304
309
  try { await props.onDelete(term.term_id) } catch (cause) { window.alert(String(cause && cause.message ? cause.message : cause)) }
305
310
  },
306
- style: { ...S.deleteBtn },
311
+ style: { ...S.btnDanger },
307
312
  }, '删除'),
308
313
  ),
309
314
  h('div', { style: { ...S.hint, display: 'flex', gap: 10, flexWrap: 'wrap' } },
@@ -325,8 +330,10 @@ window.__ModuleLoader__.load({
325
330
  const [selected, setSelected] = useState('')
326
331
  const [query, setQuery] = useState('')
327
332
  const [showGaps, setShowGaps] = useState(false)
333
+ // One editor at a time: two open forms on the same document invite saving a
334
+ // stale draft over a fresh edit.
328
335
  const [adding, setAdding] = useState(false)
329
- const [tick, setTick] = useState(0)
336
+ const [editingId, setEditingId] = useState('')
330
337
 
331
338
  const glossaries = (list.data && list.data.glossaries) || []
332
339
  useEffect(() => {
@@ -338,8 +345,7 @@ window.__ModuleLoader__.load({
338
345
  : `/api/verymath/glossary?path=${encodeURIComponent(selected)}&q=${encodeURIComponent(query)}`
339
346
  const result = useEndpoint(endpoint)
340
347
 
341
- const refresh = useCallback(() => { setTick((value) => value + 1); list.reload(); result.reload() }, [list.reload, result.reload])
342
- void tick
348
+ const refresh = useCallback(() => { list.reload(); result.reload() }, [list.reload, result.reload])
343
349
 
344
350
  const upsert = useCallback(async (payload) => {
345
351
  await postJson('/api/verymath/glossary/upsert', { path: selected, terms: [payload] })
@@ -370,7 +376,7 @@ window.__ModuleLoader__.load({
370
376
  h('div', { style: S.toolbar },
371
377
  h('select', { value: selected, onChange: (event) => setSelected(event.target.value), style: S.select },
372
378
  ...glossaries.map((item) => h('option', { key: item.path, value: item.path }, `${item.path}(${item.terms} 条)`))),
373
- h('button', { onClick: () => setAdding(true), style: S.btnPrimary }, '新增术语'),
379
+ h('button', { onClick: () => { setEditingId(''); setAdding(true) }, style: S.btnPrimary }, '新增术语'),
374
380
  h('button', { onClick: refresh, style: S.btn }, '刷新'),
375
381
  ),
376
382
  h('div', { style: S.stat },
@@ -407,21 +413,33 @@ window.__ModuleLoader__.load({
407
413
  }),
408
414
  adding ? h(TermEditor, { term: undefined, onSave: upsert, onDone: () => setAdding(false) }) : null,
409
415
  h('div', { style: { marginTop: 12 } },
410
- result.status === 'loading' ? h(Loading, null) : null,
416
+ // Stale-while-revalidate: a reload must NOT unmount the list. Rendering only
417
+ // on `status === 'ready'` tore down the open editor on every 刷新 (and on the
418
+ // reload that follows a save), which discarded the user's un-saved input.
419
+ result.status === 'loading' && result.data === undefined ? h(Loading, null) : null,
420
+ result.status === 'loading' && result.data !== undefined
421
+ ? h('div', { style: { ...S.hint, marginBottom: 6 } }, '刷新中…')
422
+ : null,
411
423
  result.status === 'failed' ? h(Failure, { message: result.error, onRetry: result.reload }) : null,
412
- result.status === 'ready' && query.trim().length > 0 && terms.length === 0
424
+ result.data !== undefined && query.trim().length > 0 && terms.length === 0
413
425
  ? h(Empty, null, `没有匹配「${query}」。试试英文词根,或换个子领域名。`)
414
426
  : null,
415
- result.status === 'ready' && terms.length > 0
427
+ result.data !== undefined && terms.length > 0
416
428
  ? h('div', null,
417
429
  h('div', { style: { ...S.hint, marginBottom: 8 } },
418
430
  `命中 ${result.data.matched} 条${result.data.truncated ? `,只显示前 ${terms.length} 条` : ''}`),
419
431
  ...terms.map((term) => h(TermRow, {
420
- key: term.term_id, term, onUpsert: upsert, onDelete: remove,
432
+ key: term.term_id,
433
+ term,
434
+ editing: editingId === term.term_id,
435
+ onStartEditing: (id) => { setAdding(false); setEditingId(id) },
436
+ onDoneEditing: () => setEditingId(''),
437
+ onUpsert: upsert,
438
+ onDelete: remove,
421
439
  })),
422
440
  )
423
441
  : null,
424
- result.status === 'ready' && query.trim().length === 0 && terms.length === 0
442
+ result.data !== undefined && query.trim().length === 0 && terms.length === 0
425
443
  ? h('div', { style: { ...S.hint, marginTop: 8 } }, '输入关键词开始查;或点上面的「新增术语」。')
426
444
  : null,
427
445
  ),
@@ -0,0 +1,31 @@
1
+ /** Executable search path: the inherited PATH first, then platform fallbacks. */
2
+ export declare function executableSearchDirs(): string[];
3
+ /**
4
+ * Search path for the SageMath probe only. `sage` is normally installed as a
5
+ * *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
6
+ * directories are not where it lives; this adds `<root>/envs/<name>/bin` for each
7
+ * known distribution root. Kept separate from the generic search path so TeX and
8
+ * other lookups do not start probing unrelated environment trees.
9
+ */
10
+ export declare function sageSearchDirs(): string[];
11
+ /**
12
+ * Resolve an executable name to an absolute path. Resolving in-process avoids
13
+ * `which`/`where`, which are not both available and which cannot see the fallback
14
+ * directories above. On Windows the `PATHEXT` suffixes are tried.
15
+ * @param name - bare executable name, or a path containing a separator.
16
+ * @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
17
+ * @returns the resolved absolute path, or undefined when nothing is executable.
18
+ */
19
+ export declare function resolveExecutable(name: string, searchDirs?: readonly string[]): string | undefined;
20
+ /**
21
+ * Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
22
+ * SageMath search path (PATH, TeX/conda base dirs, named conda environments).
23
+ * An override that is not executable is ignored rather than reported as found.
24
+ */
25
+ export declare function resolveSageExecutable(): string | undefined;
26
+ /**
27
+ * Resolve a Python interpreter: the configured executable, then `python3`, then
28
+ * `python`, each through the shared search path so a conda install is found too.
29
+ * @param configured - explicit path or name from plugin config / `DSH_OFFICE_PYTHON`.
30
+ */
31
+ export declare function resolvePythonExecutable(configured?: string): string | undefined;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Executable discovery for the tools and the browser panel.
3
+ *
4
+ * Lives in `core` rather than `tool` because two surfaces need the same answer:
5
+ * `verymath_sage_check` / `verymath_beamer_check` in the tool layer, and the
6
+ * panel's environment route. When they disagreed, the panel reported SageMath
7
+ * missing while the tool reported it available — the panel spawned a bare
8
+ * `sage`, the tool resolved it through the conda environment directories.
9
+ *
10
+ * Resolution is in-process (no `which`/`where`): a desktop app launched from
11
+ * Finder inherits no login-shell `PATH`, so distribution directories have to be
12
+ * probed explicitly.
13
+ *
14
+ * @module @louisultra/dsh-verymath/core
15
+ */
16
+ import { accessSync, constants, readdirSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { delimiter, isAbsolute, join } from 'node:path';
19
+ /**
20
+ * Directories a TeX distribution installs into without adding them to the
21
+ * inherited PATH. MacTeX's `/Library/TeX/texbin` is commonly invisible to a bare
22
+ * spawn from a desktop app.
23
+ */
24
+ function texBinFallbackDirs() {
25
+ return process.platform === 'darwin' ? ['/Library/TeX/texbin'] : [];
26
+ }
27
+ /**
28
+ * Directories conda-style installs put `python3`/`sage` in but rarely add to the
29
+ * PATH a desktop app inherits. Derived from the home directory, so nothing here
30
+ * is machine-specific.
31
+ */
32
+ function condaBinFallbackDirs() {
33
+ const home = homedir();
34
+ return ['miniforge3', 'mambaforge', 'miniconda3', 'anaconda3', 'micromamba']
35
+ .map(name => join(home, name, 'bin'));
36
+ }
37
+ /** Conda distribution roots this package knows about, including its own documented layout. */
38
+ function condaRoots() {
39
+ const home = homedir();
40
+ return [
41
+ join(home, '.verymath', 'miniforge'),
42
+ join(home, 'miniforge3'),
43
+ join(home, 'mambaforge'),
44
+ join(home, 'miniconda3'),
45
+ join(home, 'anaconda3'),
46
+ ];
47
+ }
48
+ /** Executable search path: the inherited PATH first, then platform fallbacks. */
49
+ export function executableSearchDirs() {
50
+ const fromEnv = (process.env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
51
+ return [...new Set([...fromEnv, ...texBinFallbackDirs(), ...condaBinFallbackDirs()])];
52
+ }
53
+ /**
54
+ * Search path for the SageMath probe only. `sage` is normally installed as a
55
+ * *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
56
+ * directories are not where it lives; this adds `<root>/envs/<name>/bin` for each
57
+ * known distribution root. Kept separate from the generic search path so TeX and
58
+ * other lookups do not start probing unrelated environment trees.
59
+ */
60
+ export function sageSearchDirs() {
61
+ const dirs = [...executableSearchDirs()];
62
+ for (const root of condaRoots()) {
63
+ const envsDir = join(root, 'envs');
64
+ let names;
65
+ try {
66
+ names = readdirSync(envsDir).sort((left, right) => left.localeCompare(right));
67
+ }
68
+ catch {
69
+ continue;
70
+ }
71
+ for (const name of names)
72
+ dirs.push(join(envsDir, name, 'bin'));
73
+ }
74
+ return [...new Set(dirs)];
75
+ }
76
+ /** Whether `candidate` exists and the current user may execute it. */
77
+ function isExecutableFile(candidate) {
78
+ try {
79
+ accessSync(candidate, constants.X_OK);
80
+ return true;
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /**
87
+ * Resolve an executable name to an absolute path. Resolving in-process avoids
88
+ * `which`/`where`, which are not both available and which cannot see the fallback
89
+ * directories above. On Windows the `PATHEXT` suffixes are tried.
90
+ * @param name - bare executable name, or a path containing a separator.
91
+ * @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
92
+ * @returns the resolved absolute path, or undefined when nothing is executable.
93
+ */
94
+ export function resolveExecutable(name, searchDirs = executableSearchDirs()) {
95
+ if (isAbsolute(name) || name.includes('/') || name.includes('\\')) {
96
+ return isExecutableFile(name) ? name : undefined;
97
+ }
98
+ const extensions = process.platform === 'win32'
99
+ ? ['', ...(process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((ext) => ext.length > 0)]
100
+ : [''];
101
+ for (const dir of searchDirs) {
102
+ for (const extension of extensions) {
103
+ const candidate = join(dir, name + extension);
104
+ if (isExecutableFile(candidate))
105
+ return candidate;
106
+ }
107
+ }
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
112
+ * SageMath search path (PATH, TeX/conda base dirs, named conda environments).
113
+ * An override that is not executable is ignored rather than reported as found.
114
+ */
115
+ export function resolveSageExecutable() {
116
+ const override = process.env.VERYMATH_SAGE;
117
+ if (override !== undefined && override.trim().length > 0) {
118
+ const resolved = resolveExecutable(override.trim(), []);
119
+ if (resolved !== undefined)
120
+ return resolved;
121
+ }
122
+ return resolveExecutable('sage', sageSearchDirs());
123
+ }
124
+ /**
125
+ * Resolve a Python interpreter: the configured executable, then `python3`, then
126
+ * `python`, each through the shared search path so a conda install is found too.
127
+ * @param configured - explicit path or name from plugin config / `DSH_OFFICE_PYTHON`.
128
+ */
129
+ export function resolvePythonExecutable(configured) {
130
+ const candidates = [...new Set([configured, 'python3', 'python'].filter((name) => name !== undefined && name.length > 0))];
131
+ for (const candidate of candidates) {
132
+ const resolved = resolveExecutable(candidate);
133
+ if (resolved !== undefined)
134
+ return resolved;
135
+ }
136
+ return undefined;
137
+ }
@@ -10,6 +10,7 @@ import z from '@deepseek-ai/schemastery';
10
10
  import { type GlossaryHit, type GlossaryQueryOptions, type GlossaryTerm } from './glossary.ts';
11
11
  export { VeryMathError, isVeryMathError, isErrnoCode } from './error.ts';
12
12
  export { bundledSkillsDir } from './paths.ts';
13
+ export { executableSearchDirs, sageSearchDirs, resolveExecutable, resolveSageExecutable, resolvePythonExecutable, } from './exec.ts';
13
14
  export { VeryMathSkillProvider } from './skills.ts';
14
15
  export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, deleteTerm, validateGlossaryInvariants } from './glossary.ts';
15
16
  export type { GlossaryHit, GlossaryQueryOptions, GlossaryTerm, TermUpsert, UpsertResult, DeleteResult } from './glossary.ts';
@@ -111,6 +112,12 @@ export declare class VeryMathRuntime extends Service {
111
112
  hits: GlossaryHit[];
112
113
  total: number;
113
114
  }>;
115
+ /**
116
+ * Resolve the configured Python interpreter without running it. The browser
117
+ * panel uses the same config and fallback search as the tools, so a configured
118
+ * `pythonExecutable`/`DSH_OFFICE_PYTHON` cannot make the two surfaces disagree.
119
+ */
120
+ resolvePythonExecutable(): string | undefined;
114
121
  /**
115
122
  * Locate a Python interpreter able to run the upstream `math-glossary`
116
123
  * scripts: the configured executable, then `python3`, then `python`.
package/lib/core/index.js CHANGED
@@ -11,11 +11,13 @@ import { spawn } from 'node:child_process';
11
11
  import { readFile } from 'node:fs/promises';
12
12
  import { normalize } from 'node:path';
13
13
  import { isErrnoCode, VeryMathError } from "./error.js";
14
+ import { resolveExecutable, resolvePythonExecutable } from "./exec.js";
14
15
  import { parseGlossary, queryGlossary, validateGlossaryInvariants } from "./glossary.js";
15
16
  import { bundledSkillsDir } from "./paths.js";
16
17
  import { VeryMathSkillProvider } from "./skills.js";
17
18
  export { VeryMathError, isVeryMathError, isErrnoCode } from "./error.js";
18
19
  export { bundledSkillsDir } from "./paths.js";
20
+ export { executableSearchDirs, sageSearchDirs, resolveExecutable, resolveSageExecutable, resolvePythonExecutable, } from "./exec.js";
19
21
  export { VeryMathSkillProvider } from "./skills.js";
20
22
  export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, deleteTerm, validateGlossaryInvariants } from "./glossary.js";
21
23
  export { parsePaperStructure, parsePaperBatch, dependencySummary } from "./paper.js";
@@ -80,7 +82,11 @@ export class VeryMathRuntime extends Service {
80
82
  // Only a genuinely absent file means "there is no glossary yet". Treating
81
83
  // every read failure that way let an EACCES/EIO/abort turn into "start from
82
84
  // an empty glossary", and the next write then replaced the real document.
83
- if (isErrnoCode(error, 'ENOENT')) {
85
+ // ENOENT/ENOTDIR mean "there is no document at this path". Other read
86
+ // failures (permissions, I/O, cancellation) must not be mistaken for an
87
+ // empty glossary, because the upsert tool would then replace a real file
88
+ // with only the terms in that request.
89
+ if (isErrnoCode(error, 'ENOENT') || isErrnoCode(error, 'ENOTDIR')) {
84
90
  throw new VeryMathError(`cannot read glossary at ${key}: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_GLOSSARY_UNAVAILABLE', { cause: error });
85
91
  }
86
92
  if (error instanceof Error && error.name === 'AbortError')
@@ -153,6 +159,14 @@ export class VeryMathRuntime extends Service {
153
159
  const { terms } = await this.loadGlossary(path, signal);
154
160
  return queryGlossary(terms, query, { limit: this.config.queryMaxHits, ...queryOptions });
155
161
  }
162
+ /**
163
+ * Resolve the configured Python interpreter without running it. The browser
164
+ * panel uses the same config and fallback search as the tools, so a configured
165
+ * `pythonExecutable`/`DSH_OFFICE_PYTHON` cannot make the two surfaces disagree.
166
+ */
167
+ resolvePythonExecutable() {
168
+ return resolvePythonExecutable(this.config.pythonExecutable);
169
+ }
156
170
  /**
157
171
  * Locate a Python interpreter able to run the upstream `math-glossary`
158
172
  * scripts: the configured executable, then `python3`, then `python`.
@@ -167,9 +181,12 @@ export class VeryMathRuntime extends Service {
167
181
  async probePython() {
168
182
  const candidates = [...new Set([this.config.pythonExecutable, 'python3', 'python'])];
169
183
  for (const candidate of candidates) {
170
- const probe = await this.runPython(candidate, ['--version'], 5_000).catch(() => undefined);
184
+ const resolved = resolveExecutable(candidate);
185
+ if (resolved === undefined)
186
+ continue;
187
+ const probe = await this.runPython(resolved, ['--version'], 5_000).catch(() => undefined);
171
188
  if (probe !== undefined && probe.exitCode === 0)
172
- return candidate;
189
+ return resolved;
173
190
  }
174
191
  return undefined;
175
192
  }
package/lib/http.d.ts CHANGED
@@ -16,9 +16,37 @@ export interface HttpContext {
16
16
  readonly workspace: () => string;
17
17
  /** Host logger; absent in some hosts. */
18
18
  readonly log?: (message: string) => void;
19
+ /**
20
+ * The `ctx.verymath` write lock. Sharing it with the tool layer is the point:
21
+ * two independent chains (panel and tool) let a concurrent read-modify-write
22
+ * from each side drop the other's update on the same document.
23
+ */
24
+ readonly withWrite?: <T>(path: string, task: () => Promise<T>) => Promise<T>;
25
+ /**
26
+ * Drop the service's glossary query cache. Without this the panel writes a
27
+ * document and the chat tool keeps answering from the pre-write snapshot.
28
+ */
29
+ readonly invalidateGlossaryCache?: () => void;
30
+ /**
31
+ * Resolve the configured Python interpreter. The runtime owns the plugin
32
+ * config (`pythonExecutable`/`DSH_OFFICE_PYTHON`), so the panel asks it
33
+ * instead of running a second resolver with different inputs.
34
+ */
35
+ readonly resolvePythonExecutable?: () => string | undefined;
19
36
  }
20
- /** Resolve a caller-supplied relative path and refuse anything outside the workspace. */
21
- declare function withinWorkspace(workspace: string, candidate: string): string | undefined;
37
+ /**
38
+ * Resolve a caller-supplied relative path and refuse anything outside the workspace.
39
+ *
40
+ * Two details matter here:
41
+ * * the separator is `sep`, not `/` — on Windows the string form is
42
+ * `C:\ws\glossary.json`, so a `/`-suffixed prefix matched nothing and every
43
+ * panel write was refused;
44
+ * * the result is compared after `realpath`, so a symlink inside the workspace
45
+ * that points outside it cannot be used to read or overwrite an outside file.
46
+ * A path that does not exist yet (a new glossary) is compared lexically, since
47
+ * there is nothing to resolve.
48
+ */
49
+ declare function withinWorkspace(workspace: string, candidate: string): Promise<string | undefined>;
22
50
  /**
23
51
  * Register the panel's routes. Returns false when the host exposes no exact-fetch
24
52
  * table (headless / CLI), so the panel half degrades away instead of making the