@louisultra/dsh-verymath 0.7.0 → 0.7.1
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 +20 -0
- package/lib/client.js +33 -15
- package/lib/core/exec.d.ts +31 -0
- package/lib/core/exec.js +137 -0
- package/lib/core/index.d.ts +1 -0
- package/lib/core/index.js +1 -0
- package/lib/http.d.ts +24 -2
- package/lib/http.js +146 -74
- package/lib/index.d.ts +0 -11
- package/lib/index.js +11 -11
- package/lib/tool/index.d.ts +2 -23
- package/lib/tool/index.js +7 -112
- package/package.json +1 -1
- package/skills/math-glossary/scripts/glossary_export.py +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,26 @@
|
|
|
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.1] - 2026-11-11
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- **The panel and the tools could disagree about the same machine.** The
|
|
11
|
+
environment tab spawned a bare `sage`, while `verymath_sage_check` resolved it
|
|
12
|
+
through the conda environment directories — so a machine with
|
|
13
|
+
`~/.verymath/miniforge/envs/sage` showed "SageMath missing" in the panel and
|
|
14
|
+
"available" in the tool. Executable discovery now lives in `core/exec.ts` and
|
|
15
|
+
both surfaces use it; `tool` re-exports the same functions for compatibility.
|
|
16
|
+
- Panel writes used `writeFile`, which truncates before writing: a concurrent
|
|
17
|
+
reader (the panel polling, or a chat tool call landing mid-write) could see a
|
|
18
|
+
half-written document and report "not a valid glossary". Writes now go through a
|
|
19
|
+
sibling temp file plus `rename`.
|
|
20
|
+
- The environment probe ran its seven checks sequentially, so the tab could sit on
|
|
21
|
+
"probing…" for up to twenty seconds and read as a hang. The independent probes
|
|
22
|
+
now run concurrently.
|
|
23
|
+
- The read route and the write routes returned two different `stats` shapes; both
|
|
24
|
+
now use one `glossaryStats`, so the panel's counters do not jump after an edit.
|
|
25
|
+
|
|
6
26
|
## [0.7.0] - 2026-11-11
|
|
7
27
|
|
|
8
28
|
### Added
|
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
|
-
|
|
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
|
-
|
|
287
|
-
if (editing) {
|
|
292
|
+
if (props.editing) {
|
|
288
293
|
return h(TermEditor, {
|
|
289
294
|
term,
|
|
290
295
|
onSave: props.onUpsert,
|
|
291
|
-
onDone:
|
|
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: () =>
|
|
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.
|
|
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 [
|
|
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(() => {
|
|
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
|
-
|
|
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.
|
|
424
|
+
result.data !== undefined && query.trim().length > 0 && terms.length === 0
|
|
413
425
|
? h(Empty, null, `没有匹配「${query}」。试试英文词根,或换个子领域名。`)
|
|
414
426
|
: null,
|
|
415
|
-
result.
|
|
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,
|
|
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.
|
|
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;
|
package/lib/core/exec.js
ADDED
|
@@ -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
|
+
}
|
package/lib/core/index.d.ts
CHANGED
|
@@ -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';
|
package/lib/core/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import { bundledSkillsDir } from "./paths.js";
|
|
|
16
16
|
import { VeryMathSkillProvider } from "./skills.js";
|
|
17
17
|
export { VeryMathError, isVeryMathError, isErrnoCode } from "./error.js";
|
|
18
18
|
export { bundledSkillsDir } from "./paths.js";
|
|
19
|
+
export { executableSearchDirs, sageSearchDirs, resolveExecutable, resolveSageExecutable, resolvePythonExecutable, } from "./exec.js";
|
|
19
20
|
export { VeryMathSkillProvider } from "./skills.js";
|
|
20
21
|
export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, deleteTerm, validateGlossaryInvariants } from "./glossary.js";
|
|
21
22
|
export { parsePaperStructure, parsePaperBatch, dependencySummary } from "./paper.js";
|
package/lib/http.d.ts
CHANGED
|
@@ -16,9 +16,31 @@ 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;
|
|
19
30
|
}
|
|
20
|
-
/**
|
|
21
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Resolve a caller-supplied relative path and refuse anything outside the workspace.
|
|
33
|
+
*
|
|
34
|
+
* Two details matter here:
|
|
35
|
+
* * the separator is `sep`, not `/` — on Windows the string form is
|
|
36
|
+
* `C:\ws\glossary.json`, so a `/`-suffixed prefix matched nothing and every
|
|
37
|
+
* panel write was refused;
|
|
38
|
+
* * the result is compared after `realpath`, so a symlink inside the workspace
|
|
39
|
+
* that points outside it cannot be used to read or overwrite an outside file.
|
|
40
|
+
* A path that does not exist yet (a new glossary) is compared lexically, since
|
|
41
|
+
* there is nothing to resolve.
|
|
42
|
+
*/
|
|
43
|
+
declare function withinWorkspace(workspace: string, candidate: string): Promise<string | undefined>;
|
|
22
44
|
/**
|
|
23
45
|
* Register the panel's routes. Returns false when the host exposes no exact-fetch
|
|
24
46
|
* table (headless / CLI), so the panel half degrades away instead of making the
|
package/lib/http.js
CHANGED
|
@@ -20,12 +20,33 @@
|
|
|
20
20
|
*
|
|
21
21
|
* @module @louisultra/dsh-verymath/http
|
|
22
22
|
*/
|
|
23
|
-
import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
24
|
-
import { basename, join, resolve } from 'node:path';
|
|
23
|
+
import { readdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
24
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
25
25
|
import { spawn } from 'node:child_process';
|
|
26
26
|
import { fileURLToPath } from 'node:url';
|
|
27
|
-
import { computeTopology, focusClosure, mergeBatches, parseGlossary, parsePaperStructure, queryGlossary, deleteTerm, upsertTerms, validateGlossaryInvariants, VeryMathError, } from "./core/index.js";
|
|
27
|
+
import { computeTopology, focusClosure, mergeBatches, parseGlossary, parsePaperStructure, queryGlossary, deleteTerm, resolveExecutable, resolvePythonExecutable, resolveSageExecutable, upsertTerms, validateGlossaryInvariants, VeryMathError, } from "./core/index.js";
|
|
28
28
|
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
|
|
29
|
+
/**
|
|
30
|
+
* Write a JSON document atomically.
|
|
31
|
+
*
|
|
32
|
+
* `writeFile` truncates before writing, so a concurrent reader (the panel polling,
|
|
33
|
+
* or a chat tool call landing mid-write) can observe a half-written file and report
|
|
34
|
+
* "not a valid glossary". Writing a sibling temp file and renaming it makes the
|
|
35
|
+
* swap atomic on the same filesystem.
|
|
36
|
+
*/
|
|
37
|
+
async function writeJsonAtomic(path, value) {
|
|
38
|
+
const temp = `${path}.verymath-tmp-${process.pid}-${Date.now()}`;
|
|
39
|
+
try {
|
|
40
|
+
await writeFile(temp, JSON.stringify(value, null, 2) + '\n', 'utf8');
|
|
41
|
+
await rename(temp, path);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
// A failed rename (permissions, cross-device) must not leave the temp file
|
|
45
|
+
// behind: it would show up in the workspace and in the panel's own scans.
|
|
46
|
+
await unlink(temp).catch(() => undefined);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
29
50
|
function json(body, status = 200) {
|
|
30
51
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
|
|
31
52
|
}
|
|
@@ -38,13 +59,43 @@ function safeUrl(request) {
|
|
|
38
59
|
return undefined;
|
|
39
60
|
}
|
|
40
61
|
}
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Resolve a caller-supplied relative path and refuse anything outside the workspace.
|
|
64
|
+
*
|
|
65
|
+
* Two details matter here:
|
|
66
|
+
* * the separator is `sep`, not `/` — on Windows the string form is
|
|
67
|
+
* `C:\ws\glossary.json`, so a `/`-suffixed prefix matched nothing and every
|
|
68
|
+
* panel write was refused;
|
|
69
|
+
* * the result is compared after `realpath`, so a symlink inside the workspace
|
|
70
|
+
* that points outside it cannot be used to read or overwrite an outside file.
|
|
71
|
+
* A path that does not exist yet (a new glossary) is compared lexically, since
|
|
72
|
+
* there is nothing to resolve.
|
|
73
|
+
*/
|
|
74
|
+
async function withinWorkspace(workspace, candidate) {
|
|
75
|
+
const root = await realpath(resolve(workspace)).catch(() => resolve(workspace));
|
|
76
|
+
const absolute = resolve(root, candidate);
|
|
77
|
+
if (absolute !== root && !absolute.startsWith(`${root}${sep}`))
|
|
46
78
|
return undefined;
|
|
47
|
-
|
|
79
|
+
// Resolve the deepest **existing** ancestor and re-append the missing segments.
|
|
80
|
+
// Checking only the full path let `ws/linkdir/new.json` through when `linkdir` is
|
|
81
|
+
// a symlink to somewhere outside: the file does not exist yet, so `realpath`
|
|
82
|
+
// failed and the lexical check was all that ran.
|
|
83
|
+
const missing = [];
|
|
84
|
+
let probe = absolute;
|
|
85
|
+
for (;;) {
|
|
86
|
+
const resolved = await realpath(probe).catch(() => undefined);
|
|
87
|
+
if (resolved !== undefined) {
|
|
88
|
+
const full = missing.length === 0 ? resolved : join(resolved, ...missing.reverse());
|
|
89
|
+
if (full !== root && !full.startsWith(`${root}${sep}`))
|
|
90
|
+
return undefined;
|
|
91
|
+
return full;
|
|
92
|
+
}
|
|
93
|
+
const parent = dirname(probe);
|
|
94
|
+
if (parent === probe)
|
|
95
|
+
return undefined;
|
|
96
|
+
missing.push(basename(probe));
|
|
97
|
+
probe = parent;
|
|
98
|
+
}
|
|
48
99
|
}
|
|
49
100
|
/** Run one short command; never throws. */
|
|
50
101
|
function run(executable, args, timeoutMs = 8_000) {
|
|
@@ -92,20 +143,49 @@ function firstLine(text, max = 80) {
|
|
|
92
143
|
* the OSQP/Sage probes reuse the same command shape as the corresponding tools.
|
|
93
144
|
*/
|
|
94
145
|
async function probeEnvironment() {
|
|
146
|
+
// All probes run concurrently: seven sequential spawns made the panel sit on
|
|
147
|
+
// "probing…" for up to twenty seconds, which reads as a hang.
|
|
148
|
+
const check = (executable, args, timeoutMs = 8_000) => run(executable, args, timeoutMs).catch(() => ({ ok: false, stdout: '', stderr: 'probe failed' }));
|
|
149
|
+
const checkResolved = async (name, args, timeoutMs = 8_000) => {
|
|
150
|
+
const executable = resolveExecutable(name);
|
|
151
|
+
if (executable === undefined)
|
|
152
|
+
return { ok: false, stdout: '', stderr: 'not found' };
|
|
153
|
+
return await check(executable, args, timeoutMs);
|
|
154
|
+
};
|
|
155
|
+
const pythonExecutable = resolvePythonExecutable();
|
|
156
|
+
const pythonProbe = pythonExecutable === undefined
|
|
157
|
+
? Promise.resolve({ ok: false, stdout: '', stderr: 'not found' })
|
|
158
|
+
: check(pythonExecutable, ['--version'], 5_000);
|
|
159
|
+
const binaryProbes = ['latexmk', 'xelatex'].map(async (name) => ({ name, result: await checkResolved(name, ['--version']) }));
|
|
160
|
+
const [python, ...binaries] = await Promise.all([pythonProbe, ...binaryProbes]);
|
|
161
|
+
// The deeper checks need Python, so they start once it is known to exist.
|
|
162
|
+
const [yaml, osqp, sage, lean] = await Promise.all([
|
|
163
|
+
python.ok && pythonExecutable !== undefined
|
|
164
|
+
? check(pythonExecutable, ['-c', 'import yaml, sys; sys.stdout.write(yaml.__version__)'])
|
|
165
|
+
: Promise.resolve(undefined),
|
|
166
|
+
python.ok && pythonExecutable !== undefined
|
|
167
|
+
? check(pythonExecutable, ['-c', 'import osqp, numpy; print(osqp.__version__)'], 10_000)
|
|
168
|
+
: Promise.resolve(undefined),
|
|
169
|
+
// Resolve through the same helper the tool uses; a bare `sage` missed conda
|
|
170
|
+
// environments and made the panel disagree with `verymath_sage_check`.
|
|
171
|
+
(async () => {
|
|
172
|
+
const executable = resolveSageExecutable();
|
|
173
|
+
if (executable === undefined)
|
|
174
|
+
return undefined;
|
|
175
|
+
return await check(executable, ['--version'], 10_000);
|
|
176
|
+
})(),
|
|
177
|
+
checkResolved('lean', ['--version']),
|
|
178
|
+
]);
|
|
95
179
|
const rows = [];
|
|
96
|
-
const python = await run('python3', ['--version'], 5_000);
|
|
97
180
|
rows.push({
|
|
98
181
|
id: 'python',
|
|
99
182
|
label: 'Python 3',
|
|
100
183
|
enables: '术语库构建 / OCR 扫描 / OSQP / Lean 禁用词检测',
|
|
101
184
|
state: python.ok ? 'ready' : 'missing',
|
|
102
|
-
...(python.ok ? { detail: (python.stdout || python.stderr)
|
|
185
|
+
...(python.ok ? { detail: firstLine(python.stdout || python.stderr) } : {}),
|
|
103
186
|
...(python.ok ? {} : { hint: 'macOS: xcode-select --install 或 brew install python3;Windows: python.org 安装包' }),
|
|
104
187
|
});
|
|
105
|
-
|
|
106
|
-
// does not prove the scripts will run.
|
|
107
|
-
if (python.ok) {
|
|
108
|
-
const yaml = await run('python3', ['-c', 'import yaml, sys; sys.stdout.write(yaml.__version__)'], 8_000);
|
|
188
|
+
if (yaml !== undefined) {
|
|
109
189
|
rows.push({
|
|
110
190
|
id: 'pyyaml',
|
|
111
191
|
label: 'PyYAML',
|
|
@@ -115,24 +195,18 @@ async function probeEnvironment() {
|
|
|
115
195
|
...(yaml.ok ? {} : { hint: 'python3 -m pip install PyYAML' }),
|
|
116
196
|
});
|
|
117
197
|
}
|
|
118
|
-
const binaries
|
|
119
|
-
|
|
120
|
-
{ id: 'xelatex', label: 'xelatex', enables: '中文 / 双语 Beamer 模板', args: ['--version'] },
|
|
121
|
-
];
|
|
122
|
-
for (const binary of binaries) {
|
|
123
|
-
const result = await run(binary.id, binary.args, 8_000);
|
|
198
|
+
for (const [index, binary] of binaries.entries()) {
|
|
199
|
+
const enables = index === 0 ? '数学 Beamer 幻灯片编译' : '中文 / 双语 Beamer 模板';
|
|
124
200
|
rows.push({
|
|
125
|
-
id: binary.
|
|
126
|
-
label: binary.
|
|
127
|
-
enables
|
|
128
|
-
state: result.ok ? 'ready' : 'missing',
|
|
129
|
-
...(result.ok ? { detail: firstLine(result.stdout || result.stderr) } : {}),
|
|
130
|
-
...(result.ok ? {} : { hint: 'macOS: brew install --cask mactex-no-gui;Linux: texlive-full' }),
|
|
201
|
+
id: binary.name,
|
|
202
|
+
label: binary.name,
|
|
203
|
+
enables,
|
|
204
|
+
state: binary.result.ok ? 'ready' : 'missing',
|
|
205
|
+
...(binary.result.ok ? { detail: firstLine(binary.result.stdout || binary.result.stderr) } : {}),
|
|
206
|
+
...(binary.result.ok ? {} : { hint: 'macOS: brew install --cask mactex-no-gui;Linux: texlive-full' }),
|
|
131
207
|
});
|
|
132
208
|
}
|
|
133
|
-
|
|
134
|
-
if (python.ok) {
|
|
135
|
-
const osqp = await run('python3', ['-c', 'import osqp, numpy; print(osqp.__version__)'], 10_000);
|
|
209
|
+
if (osqp !== undefined) {
|
|
136
210
|
rows.push({
|
|
137
211
|
id: 'osqp',
|
|
138
212
|
label: 'OSQP 求解栈',
|
|
@@ -142,16 +216,14 @@ async function probeEnvironment() {
|
|
|
142
216
|
...(osqp.ok ? {} : { hint: "python3 -m pip install 'osqp>=1,<2' numpy scipy" }),
|
|
143
217
|
});
|
|
144
218
|
}
|
|
145
|
-
const sage = await run('sage', ['--version'], 10_000);
|
|
146
219
|
rows.push({
|
|
147
220
|
id: 'sage',
|
|
148
221
|
label: 'SageMath',
|
|
149
222
|
enables: '本机 Sage 执行(文档查询不需要它)',
|
|
150
|
-
state: sage.ok ? 'ready' : 'missing',
|
|
151
|
-
...(sage.ok ? { detail: firstLine(sage.stdout, 60) } : {}),
|
|
152
|
-
...(sage.ok ? {} : { hint: 'conda create -n sage sage=10.9,或设置 VERYMATH_SAGE 指向 sage 可执行文件' }),
|
|
223
|
+
state: sage !== undefined && sage.ok ? 'ready' : 'missing',
|
|
224
|
+
...(sage !== undefined && sage.ok ? { detail: firstLine(sage.stdout, 60) } : {}),
|
|
225
|
+
...(sage !== undefined && sage.ok ? {} : { hint: 'conda create -n sage sage=10.9,或设置 VERYMATH_SAGE 指向 sage 可执行文件' }),
|
|
153
226
|
});
|
|
154
|
-
const lean = await run('lean', ['--version'], 8_000);
|
|
155
227
|
rows.push({
|
|
156
228
|
id: 'lean',
|
|
157
229
|
label: 'Lean 4',
|
|
@@ -162,6 +234,26 @@ async function probeEnvironment() {
|
|
|
162
234
|
});
|
|
163
235
|
return rows;
|
|
164
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* The stats shape both the read route and the write routes return.
|
|
239
|
+
*
|
|
240
|
+
* Gaps are what makes the numbers actionable: "3 without examples" is trivia, the
|
|
241
|
+
* ids are a to-do list the panel can show.
|
|
242
|
+
*/
|
|
243
|
+
function glossaryStats(terms) {
|
|
244
|
+
const missingExamples = terms.filter(term => (term.examples?.length ?? 0) === 0).map(term => term.term_id);
|
|
245
|
+
const missingField = terms.filter(term => (term.field?.length ?? 0) === 0).map(term => term.term_id);
|
|
246
|
+
return {
|
|
247
|
+
total: terms.length,
|
|
248
|
+
withExamples: terms.filter(term => (term.examples?.length ?? 0) > 0).length,
|
|
249
|
+
aliases: terms.filter(term => term.term_id.includes('__')).length,
|
|
250
|
+
fields: [...new Set(terms.flatMap(term => term.field ?? []))].sort((left, right) => left.localeCompare(right)),
|
|
251
|
+
missingExamples: missingExamples.slice(0, 40),
|
|
252
|
+
missingField: missingField.slice(0, 40),
|
|
253
|
+
missingExampleCount: missingExamples.length,
|
|
254
|
+
missingFieldCount: missingField.length,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
165
257
|
/** Find glossary documents under the workspace (bounded depth, bounded count). */
|
|
166
258
|
async function findGlossaries(workspace) {
|
|
167
259
|
const found = [];
|
|
@@ -335,6 +427,8 @@ export function registerHttp(ctx, connection) {
|
|
|
335
427
|
* second write drops the first.
|
|
336
428
|
*/
|
|
337
429
|
const writeChains = new Map();
|
|
430
|
+
/** Prefer the service's chain so panel and tool writes cannot interleave. */
|
|
431
|
+
const writeLock = (key, task) => ctx.withWrite !== undefined ? ctx.withWrite(key, task) : withWrite(key, task);
|
|
338
432
|
const withWrite = async (key, task) => {
|
|
339
433
|
const previous = writeChains.get(key) ?? Promise.resolve();
|
|
340
434
|
const run = previous.then(task, task);
|
|
@@ -390,7 +484,7 @@ export function registerHttp(ctx, connection) {
|
|
|
390
484
|
return json({ error: 'invalid request url' }, 400);
|
|
391
485
|
const relative = url.searchParams.get('path') ?? '';
|
|
392
486
|
const query = (url.searchParams.get('q') ?? '').trim();
|
|
393
|
-
const absolute = withinWorkspace(ctx.workspace(), relative);
|
|
487
|
+
const absolute = await withinWorkspace(ctx.workspace(), relative);
|
|
394
488
|
if (absolute === undefined)
|
|
395
489
|
return json({ error: 'path escapes the workspace' }, 400);
|
|
396
490
|
let terms;
|
|
@@ -401,23 +495,7 @@ export function registerHttp(ctx, connection) {
|
|
|
401
495
|
catch (error) {
|
|
402
496
|
return json({ error: `not a valid glossary: ${error instanceof Error ? error.message : String(error)}` }, 400);
|
|
403
497
|
}
|
|
404
|
-
const
|
|
405
|
-
const fields = [...new Set(terms.flatMap(term => term.field ?? []))].sort((left, right) => left.localeCompare(right));
|
|
406
|
-
const aliases = terms.filter(term => term.term_id.includes('__')).length;
|
|
407
|
-
// Gaps are what makes the stats actionable: a count of "3 without
|
|
408
|
-
// examples" is trivia, the actual terms are a to-do list.
|
|
409
|
-
const missingExamples = terms.filter(term => (term.examples?.length ?? 0) === 0).map(term => term.term_id);
|
|
410
|
-
const missingField = terms.filter(term => (term.field?.length ?? 0) === 0).map(term => term.term_id);
|
|
411
|
-
const stats = {
|
|
412
|
-
total: terms.length,
|
|
413
|
-
withExamples,
|
|
414
|
-
aliases,
|
|
415
|
-
fields,
|
|
416
|
-
missingExamples: missingExamples.slice(0, 40),
|
|
417
|
-
missingField: missingField.slice(0, 40),
|
|
418
|
-
missingExampleCount: missingExamples.length,
|
|
419
|
-
missingFieldCount: missingField.length,
|
|
420
|
-
};
|
|
498
|
+
const stats = glossaryStats(terms);
|
|
421
499
|
if (query.length === 0)
|
|
422
500
|
return json({ stats, terms: [], matched: 0, truncated: false });
|
|
423
501
|
const { hits, total } = queryGlossary(terms, query, { limit: 60 });
|
|
@@ -452,7 +530,7 @@ export function registerHttp(ctx, connection) {
|
|
|
452
530
|
return json({ error: 'invalid request url' }, 400);
|
|
453
531
|
const relative = url.searchParams.get('path') ?? '';
|
|
454
532
|
const focus = (url.searchParams.get('focus') ?? '').trim();
|
|
455
|
-
const absolute = withinWorkspace(ctx.workspace(), relative);
|
|
533
|
+
const absolute = await withinWorkspace(ctx.workspace(), relative);
|
|
456
534
|
if (absolute === undefined)
|
|
457
535
|
return json({ error: 'path escapes the workspace' }, 400);
|
|
458
536
|
let structure;
|
|
@@ -550,18 +628,6 @@ export function registerHttp(ctx, connection) {
|
|
|
550
628
|
return { error: `request body is not valid JSON: ${error instanceof Error ? error.message : String(error)}` };
|
|
551
629
|
}
|
|
552
630
|
};
|
|
553
|
-
const statsFor = (terms) => {
|
|
554
|
-
const missingExamples = terms.filter(term => (term.examples?.length ?? 0) === 0).length;
|
|
555
|
-
const missingField = terms.filter(term => (term.field?.length ?? 0) === 0).length;
|
|
556
|
-
return {
|
|
557
|
-
total: terms.length,
|
|
558
|
-
withExamples: terms.filter(term => (term.examples?.length ?? 0) > 0).length,
|
|
559
|
-
aliases: terms.filter(term => term.term_id.includes('__')).length,
|
|
560
|
-
fields: [...new Set(terms.flatMap(term => term.field ?? []))].sort((left, right) => left.localeCompare(right)),
|
|
561
|
-
missingExampleCount: missingExamples,
|
|
562
|
-
missingFieldCount: missingField,
|
|
563
|
-
};
|
|
564
|
-
};
|
|
565
631
|
// Add a term, or correct/remove one. The same core functions the chat tool uses
|
|
566
632
|
// run here, so the panel and the agent cannot drift apart in behaviour.
|
|
567
633
|
register({
|
|
@@ -573,13 +639,13 @@ export function registerHttp(ctx, connection) {
|
|
|
573
639
|
if ('error' in body)
|
|
574
640
|
return json({ error: body.error }, 400);
|
|
575
641
|
const relative = typeof body.body.path === 'string' ? body.body.path : '';
|
|
576
|
-
const absolute = withinWorkspace(ctx.workspace(), relative);
|
|
642
|
+
const absolute = await withinWorkspace(ctx.workspace(), relative);
|
|
577
643
|
if (absolute === undefined)
|
|
578
644
|
return json({ error: 'path escapes the workspace' }, 400);
|
|
579
645
|
const requests = Array.isArray(body.body.terms) ? body.body.terms : [];
|
|
580
646
|
if (requests.length === 0)
|
|
581
647
|
return json({ error: 'terms must be a non-empty array' }, 400);
|
|
582
|
-
return await
|
|
648
|
+
return await writeLock(absolute, async () => {
|
|
583
649
|
const loaded = await loadForWrite(absolute);
|
|
584
650
|
if ('error' in loaded)
|
|
585
651
|
return json({ error: loaded.error }, 400);
|
|
@@ -592,11 +658,14 @@ export function registerHttp(ctx, connection) {
|
|
|
592
658
|
// caller's input, so they are 400 with the core's own message.
|
|
593
659
|
return json({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
594
660
|
}
|
|
595
|
-
await
|
|
661
|
+
await writeJsonAtomic(absolute, result.document);
|
|
662
|
+
// The chat tool reads through this cache; leaving it means the panel edit is
|
|
663
|
+
// invisible to the agent until something else touches the file.
|
|
664
|
+
ctx.invalidateGlossaryCache?.();
|
|
596
665
|
return json({
|
|
597
666
|
added: [...result.added],
|
|
598
667
|
updated: [...result.updated],
|
|
599
|
-
stats:
|
|
668
|
+
stats: glossaryStats(result.document),
|
|
600
669
|
document: result.document,
|
|
601
670
|
});
|
|
602
671
|
});
|
|
@@ -612,20 +681,23 @@ export function registerHttp(ctx, connection) {
|
|
|
612
681
|
return json({ error: body.error }, 400);
|
|
613
682
|
const relative = typeof body.body.path === 'string' ? body.body.path : '';
|
|
614
683
|
const termId = typeof body.body.term_id === 'string' ? body.body.term_id : '';
|
|
615
|
-
const absolute = withinWorkspace(ctx.workspace(), relative);
|
|
684
|
+
const absolute = await withinWorkspace(ctx.workspace(), relative);
|
|
616
685
|
if (absolute === undefined)
|
|
617
686
|
return json({ error: 'path escapes the workspace' }, 400);
|
|
618
687
|
if (termId.length === 0)
|
|
619
688
|
return json({ error: 'term_id is required' }, 400);
|
|
620
|
-
return await
|
|
689
|
+
return await writeLock(absolute, async () => {
|
|
621
690
|
const loaded = await loadForWrite(absolute);
|
|
622
691
|
if ('error' in loaded)
|
|
623
692
|
return json({ error: loaded.error }, 400);
|
|
624
693
|
const result = deleteTerm(loaded.terms, termId);
|
|
625
694
|
if (!result.removed)
|
|
626
695
|
return json({ error: `no term with term_id ${JSON.stringify(termId)}` }, 404);
|
|
627
|
-
await
|
|
628
|
-
|
|
696
|
+
await writeJsonAtomic(absolute, result.document);
|
|
697
|
+
// The chat tool reads through this cache; leaving it means the panel edit is
|
|
698
|
+
// invisible to the agent until something else touches the file.
|
|
699
|
+
ctx.invalidateGlossaryCache?.();
|
|
700
|
+
return json({ removed: termId, stats: glossaryStats(result.document), document: result.document });
|
|
629
701
|
});
|
|
630
702
|
}),
|
|
631
703
|
});
|
package/lib/index.d.ts
CHANGED
|
@@ -23,15 +23,4 @@ export * as tool from './tool/index.ts';
|
|
|
23
23
|
export declare const name = "verymath-client";
|
|
24
24
|
/** `connection` is optional on purpose: see the apply comment. */
|
|
25
25
|
export declare const inject: string[];
|
|
26
|
-
/**
|
|
27
|
-
* Mount point for the bare-name loader entry.
|
|
28
|
-
*
|
|
29
|
-
* It registers the panel's HTTP routes and nothing else: the service and the
|
|
30
|
-
* tools are mounted from `./core` and `./tool`, and the browser half is served by
|
|
31
|
-
* the host from `dsh.client`.
|
|
32
|
-
*
|
|
33
|
-
* `connection` is looked up with `ctx.inject`, not `ctx.get`: at apply time the
|
|
34
|
-
* service may not exist yet, and a `ctx.get` that quietly returns undefined
|
|
35
|
-
* leaves every route unregistered — the panel then shows 404 for all of them.
|
|
36
|
-
*/
|
|
37
26
|
export declare const apply: (ctx: Context) => void;
|
package/lib/index.js
CHANGED
|
@@ -35,23 +35,23 @@ function resolveWorkspace(ctx) {
|
|
|
35
35
|
}
|
|
36
36
|
return process.cwd();
|
|
37
37
|
}
|
|
38
|
-
/**
|
|
39
|
-
* Mount point for the bare-name loader entry.
|
|
40
|
-
*
|
|
41
|
-
* It registers the panel's HTTP routes and nothing else: the service and the
|
|
42
|
-
* tools are mounted from `./core` and `./tool`, and the browser half is served by
|
|
43
|
-
* the host from `dsh.client`.
|
|
44
|
-
*
|
|
45
|
-
* `connection` is looked up with `ctx.inject`, not `ctx.get`: at apply time the
|
|
46
|
-
* service may not exist yet, and a `ctx.get` that quietly returns undefined
|
|
47
|
-
* leaves every route unregistered — the panel then shows 404 for all of them.
|
|
48
|
-
*/
|
|
49
38
|
export const apply = (ctx) => {
|
|
50
39
|
ctx.inject(['connection'], (inner) => {
|
|
51
40
|
const connection = optionalService(inner, 'connection');
|
|
41
|
+
// The routes must share the service's write lock and cache instead of keeping
|
|
42
|
+
// their own: two independent lock chains let a panel write and a tool write drop
|
|
43
|
+
// each other's update, and an un-invalidated cache leaves the agent answering
|
|
44
|
+
// from the pre-write snapshot.
|
|
45
|
+
const service = optionalService(inner, 'verymath');
|
|
52
46
|
registerHttp({
|
|
53
47
|
workspace: () => resolveWorkspace(inner),
|
|
54
48
|
log: (message) => inner.logger?.warn?.(message),
|
|
49
|
+
...(service?.withGlossaryWrite !== undefined
|
|
50
|
+
? { withWrite: service.withGlossaryWrite.bind(service) }
|
|
51
|
+
: {}),
|
|
52
|
+
...(service?.invalidateAllGlossaries !== undefined
|
|
53
|
+
? { invalidateGlossaryCache: service.invalidateAllGlossaries.bind(service) }
|
|
54
|
+
: {}),
|
|
55
55
|
}, connection);
|
|
56
56
|
});
|
|
57
57
|
};
|
package/lib/tool/index.d.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { Context } from '@deepseek-ai/cordis';
|
|
8
8
|
import z from '@deepseek-ai/schemastery';
|
|
9
|
+
import { executableSearchDirs, resolveExecutable, resolveSageExecutable, sageSearchDirs } from '@louisultra/dsh-verymath/core';
|
|
10
|
+
export { executableSearchDirs, resolveExecutable, resolveSageExecutable, sageSearchDirs };
|
|
9
11
|
export declare const name = "tool-verymath";
|
|
10
12
|
export declare const inject: string[];
|
|
11
13
|
/** Config for the tool layer. */
|
|
@@ -17,28 +19,5 @@ export interface Config {
|
|
|
17
19
|
readonly glossaryHome?: string;
|
|
18
20
|
}
|
|
19
21
|
export declare const Config: z<Config>;
|
|
20
|
-
/**
|
|
21
|
-
* Search path for the SageMath probe only. `sage` is normally installed as a
|
|
22
|
-
* *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
|
|
23
|
-
* directories above are not where it lives; this adds `<root>/envs/<name>/bin`
|
|
24
|
-
* for each known distribution root. Kept separate from the generic search path
|
|
25
|
-
* so TeX and other lookups do not start probing unrelated environment trees.
|
|
26
|
-
*/
|
|
27
|
-
export declare function sageSearchDirs(): string[];
|
|
28
|
-
/**
|
|
29
|
-
* Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
|
|
30
|
-
* SageMath search path (PATH, TeX/conda base dirs, named conda environments).
|
|
31
|
-
* An override that is not executable is ignored rather than reported as found.
|
|
32
|
-
*/
|
|
33
|
-
export declare function resolveSageExecutable(): string | undefined;
|
|
34
|
-
/**
|
|
35
|
-
* Resolve an executable name to an absolute path. Resolving in-process avoids
|
|
36
|
-
* `which`/`where`, which are not both available and which cannot see the TeX
|
|
37
|
-
* fallback directories above. On Windows the `PATHEXT` suffixes are tried.
|
|
38
|
-
* @param name - bare executable name, or a path containing a separator.
|
|
39
|
-
* @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
|
|
40
|
-
* @returns the resolved absolute path, or undefined when nothing is executable.
|
|
41
|
-
*/
|
|
42
|
-
export declare function resolveExecutable(name: string, searchDirs?: readonly string[]): string | undefined;
|
|
43
22
|
/** Register the VeryMath glossary and paper tools. */
|
|
44
23
|
export declare const apply: (ctx: Context, config?: Config) => void;
|
package/lib/tool/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import z from '@deepseek-ai/schemastery';
|
|
2
2
|
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
3
3
|
import { spawn } from 'node:child_process';
|
|
4
|
-
import {
|
|
5
|
-
import { homedir } from 'node:os';
|
|
6
|
-
import { delimiter, isAbsolute, join, resolve } from 'node:path';
|
|
4
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
7
5
|
import { VeryMathError, isVeryMathError } from '@louisultra/dsh-verymath/core';
|
|
8
|
-
import { bundledSkillsDir, checkGate, computeTopology, dependencySummary, findExcerpt, focusClosure, loadManifest, mergeBatches, mergeStructures, parsePaperBatch, parsePaperStructure, readCorpusDocWindow, renderMermaid, resolveCorpusRoot, searchSageRefs, termsFor, upsertTerms } from '@louisultra/dsh-verymath/core';
|
|
6
|
+
import { bundledSkillsDir, checkGate, computeTopology, dependencySummary, executableSearchDirs, findExcerpt, focusClosure, loadManifest, mergeBatches, mergeStructures, parsePaperBatch, parsePaperStructure, readCorpusDocWindow, renderMermaid, resolveCorpusRoot, resolveExecutable, resolveSageExecutable, sageSearchDirs, searchSageRefs, termsFor, upsertTerms } from '@louisultra/dsh-verymath/core';
|
|
7
|
+
// Re-exported for the tool-level tests and for callers that imported these from
|
|
8
|
+
// the tool module before they moved into `core`. There is exactly one
|
|
9
|
+
// implementation now — two copies used to drift, which is how the panel ended up
|
|
10
|
+
// reporting SageMath missing while `verymath_sage_check` found it.
|
|
11
|
+
export { executableSearchDirs, resolveExecutable, resolveSageExecutable, sageSearchDirs };
|
|
9
12
|
export const name = 'tool-verymath';
|
|
10
13
|
export const inject = ['tools', 'verymath', 'fs'];
|
|
11
14
|
export const Config = z.object({
|
|
@@ -119,114 +122,6 @@ function probeCommand(executable, args, timeoutMs = 5_000) {
|
|
|
119
122
|
});
|
|
120
123
|
}
|
|
121
124
|
/**
|
|
122
|
-
* Directories a TeX distribution installs into without adding them to the
|
|
123
|
-
* inherited PATH. Desktop applications launched from Finder or the Start menu
|
|
124
|
-
* do not read the login shell profile, so MacTeX's `/Library/TeX/texbin` is
|
|
125
|
-
* commonly invisible to a bare `spawn(name)` even when the toolchain is
|
|
126
|
-
* installed. Nothing here is required: an empty result just means PATH decides.
|
|
127
|
-
*/
|
|
128
|
-
function texBinFallbackDirs() {
|
|
129
|
-
return process.platform === 'darwin' ? ['/Library/TeX/texbin'] : [];
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Directories conda-style installs put `python3`/`sage` in but rarely add to the
|
|
133
|
-
* PATH a desktop app inherits: a macOS app launched from Finder reads no login
|
|
134
|
-
* shell profile, so a `sage` installed under `~/miniforge3` is invisible even
|
|
135
|
-
* though the user "has SageMath installed". Derived from the home directory, so
|
|
136
|
-
* nothing here is machine-specific.
|
|
137
|
-
*/
|
|
138
|
-
function condaBinFallbackDirs() {
|
|
139
|
-
const home = homedir();
|
|
140
|
-
return ['miniforge3', 'mambaforge', 'miniconda3', 'anaconda3', 'micromamba']
|
|
141
|
-
.map(name => join(home, name, 'bin'));
|
|
142
|
-
}
|
|
143
|
-
/** Conda distribution roots this package knows about, including its own docs' layout. */
|
|
144
|
-
function condaRoots() {
|
|
145
|
-
const home = homedir();
|
|
146
|
-
return [
|
|
147
|
-
join(home, '.verymath', 'miniforge'),
|
|
148
|
-
join(home, 'miniforge3'),
|
|
149
|
-
join(home, 'mambaforge'),
|
|
150
|
-
join(home, 'miniconda3'),
|
|
151
|
-
join(home, 'anaconda3'),
|
|
152
|
-
];
|
|
153
|
-
}
|
|
154
|
-
/** Executable search path: the inherited PATH first, then platform fallbacks. */
|
|
155
|
-
function executableSearchDirs() {
|
|
156
|
-
const fromEnv = (process.env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
|
|
157
|
-
return [...new Set([...fromEnv, ...texBinFallbackDirs(), ...condaBinFallbackDirs()])];
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Search path for the SageMath probe only. `sage` is normally installed as a
|
|
161
|
-
* *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
|
|
162
|
-
* directories above are not where it lives; this adds `<root>/envs/<name>/bin`
|
|
163
|
-
* for each known distribution root. Kept separate from the generic search path
|
|
164
|
-
* so TeX and other lookups do not start probing unrelated environment trees.
|
|
165
|
-
*/
|
|
166
|
-
export function sageSearchDirs() {
|
|
167
|
-
const dirs = [...executableSearchDirs()];
|
|
168
|
-
for (const root of condaRoots()) {
|
|
169
|
-
const envsDir = join(root, 'envs');
|
|
170
|
-
let names;
|
|
171
|
-
try {
|
|
172
|
-
names = readdirSync(envsDir).sort((left, right) => left.localeCompare(right));
|
|
173
|
-
}
|
|
174
|
-
catch {
|
|
175
|
-
continue;
|
|
176
|
-
}
|
|
177
|
-
for (const name of names)
|
|
178
|
-
dirs.push(join(envsDir, name, 'bin'));
|
|
179
|
-
}
|
|
180
|
-
return [...new Set(dirs)];
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
|
|
184
|
-
* SageMath search path (PATH, TeX/conda base dirs, named conda environments).
|
|
185
|
-
* An override that is not executable is ignored rather than reported as found.
|
|
186
|
-
*/
|
|
187
|
-
export function resolveSageExecutable() {
|
|
188
|
-
const override = process.env.VERYMATH_SAGE;
|
|
189
|
-
if (override !== undefined && override.trim().length > 0) {
|
|
190
|
-
const resolved = resolveExecutable(override.trim(), []);
|
|
191
|
-
if (resolved !== undefined)
|
|
192
|
-
return resolved;
|
|
193
|
-
}
|
|
194
|
-
return resolveExecutable('sage', sageSearchDirs());
|
|
195
|
-
}
|
|
196
|
-
/** Whether `candidate` exists and the current user may execute it. */
|
|
197
|
-
function isExecutableFile(candidate) {
|
|
198
|
-
try {
|
|
199
|
-
accessSync(candidate, constants.X_OK);
|
|
200
|
-
return true;
|
|
201
|
-
}
|
|
202
|
-
catch {
|
|
203
|
-
return false;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Resolve an executable name to an absolute path. Resolving in-process avoids
|
|
208
|
-
* `which`/`where`, which are not both available and which cannot see the TeX
|
|
209
|
-
* fallback directories above. On Windows the `PATHEXT` suffixes are tried.
|
|
210
|
-
* @param name - bare executable name, or a path containing a separator.
|
|
211
|
-
* @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
|
|
212
|
-
* @returns the resolved absolute path, or undefined when nothing is executable.
|
|
213
|
-
*/
|
|
214
|
-
export function resolveExecutable(name, searchDirs = executableSearchDirs()) {
|
|
215
|
-
if (isAbsolute(name) || name.includes('/') || name.includes('\\')) {
|
|
216
|
-
return isExecutableFile(name) ? name : undefined;
|
|
217
|
-
}
|
|
218
|
-
const extensions = process.platform === 'win32'
|
|
219
|
-
? ['', ...(process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((ext) => ext.length > 0)]
|
|
220
|
-
: [''];
|
|
221
|
-
for (const dir of searchDirs) {
|
|
222
|
-
for (const extension of extensions) {
|
|
223
|
-
const candidate = join(dir, name + extension);
|
|
224
|
-
if (isExecutableFile(candidate))
|
|
225
|
-
return candidate;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
return undefined;
|
|
229
|
-
}
|
|
230
125
|
/**
|
|
231
126
|
* Probe the math-beamer TeX toolchain: latexmk and xelatex binaries (resolved on
|
|
232
127
|
* PATH, then in the distribution's own bin directory, followed by a `--version`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@louisultra/dsh-verymath",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "VeryMath capabilities for DSH: 16 bundled math skills and 14 tools covering paper reading, bilingual glossary, writing, Beamer, optimization, computation, Lean formalization, research workflows, Sage doc lookup and MATLAB. Community plugin for issue ECNU/EduWork#152.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
# DSH bundling note (not upstream): openpyxl's stubs type Worksheet/worksheet cells as
|
|
2
|
+
# Optional, so six reportOptionalMemberAccess / reportAttributeAccessIssue findings fire on
|
|
3
|
+
# code that is correct at runtime (the upstream test suite exercises this path and passes).
|
|
4
|
+
# Scoped to this file only; behaviour is unchanged.
|
|
5
|
+
# pyright: reportOptionalMemberAccess=false, reportAttributeAccessIssue=false
|
|
1
6
|
"""术语库 Excel 导入导出工具。"""
|
|
2
7
|
|
|
3
8
|
from __future__ import annotations
|