@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/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
- /** Resolve a caller-supplied relative path and refuse anything outside the workspace. */
42
- function withinWorkspace(workspace, candidate) {
43
- const absolute = resolve(workspace, candidate);
44
- const root = resolve(workspace);
45
- if (absolute !== root && !absolute.startsWith(`${root}/`))
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
- return absolute;
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) {
@@ -91,21 +142,50 @@ function firstLine(text, max = 80) {
91
142
  * `python3` is probed here only to answer "can the glossary build scripts run";
92
143
  * the OSQP/Sage probes reuse the same command shape as the corresponding tools.
93
144
  */
94
- async function probeEnvironment() {
145
+ async function probeEnvironment(svc) {
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 = svc?.resolvePythonExecutable?.() ?? 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).trim().split('\n')[0] } : {}),
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
- // PyYAML is what the bundled glossary_build.py actually needs; version alone
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
- { id: 'latexmk', label: 'latexmk', enables: '数学 Beamer 幻灯片编译', args: ['--version'] },
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.id,
126
- label: binary.label,
127
- enables: binary.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
- // The osqp solver stack: probe the import, not the CLI (there is none).
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);
@@ -366,7 +460,7 @@ export function registerHttp(ctx, connection) {
366
460
  methods: ['GET'],
367
461
  requestBody: 'buffered',
368
462
  fetch: guard(async () => {
369
- const rows = await probeEnvironment();
463
+ const rows = await probeEnvironment(ctx);
370
464
  const ready = rows.filter(row => row.state === 'ready').length;
371
465
  return json({ rows, ready, total: rows.length, workspace: ctx.workspace() });
372
466
  }),
@@ -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 withExamples = terms.filter(term => (term.examples?.length ?? 0) > 0).length;
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 withWrite(absolute, async () => {
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 writeFile(absolute, JSON.stringify(result.document, null, 2) + '\n', 'utf8');
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: statsFor(result.document),
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 withWrite(absolute, async () => {
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 writeFile(absolute, JSON.stringify(result.document, null, 2) + '\n', 'utf8');
628
- return json({ removed: termId, stats: statsFor(result.document), document: result.document });
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,26 @@ 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
+ ...(service?.resolvePythonExecutable !== undefined
56
+ ? { resolvePythonExecutable: service.resolvePythonExecutable.bind(service) }
57
+ : {}),
55
58
  }, connection);
56
59
  });
57
60
  };
@@ -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 '../core/index.ts';
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 { accessSync, constants, readdirSync } from 'node:fs';
5
- import { homedir } from 'node:os';
6
- import { delimiter, isAbsolute, join, resolve } from 'node:path';
7
- 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';
4
+ import { isAbsolute, resolve } from 'node:path';
5
+ import { VeryMathError, isVeryMathError } from "../core/index.js";
6
+ import { bundledSkillsDir, checkGate, computeTopology, dependencySummary, executableSearchDirs, findExcerpt, focusClosure, loadManifest, mergeBatches, mergeStructures, parsePaperBatch, parsePaperStructure, readCorpusDocWindow, renderMermaid, resolveCorpusRoot, resolveExecutable, resolveSageExecutable, sageSearchDirs, searchSageRefs, termsFor, upsertTerms } from "../core/index.js";
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.0",
3
+ "version": "0.7.2",
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",
@@ -23,6 +23,7 @@
23
23
  "cordis.patch.yml",
24
24
  "README.md",
25
25
  "README_EN.md",
26
+ "DEVELOPMENT.md",
26
27
  "LICENSE",
27
28
  "NOTICE.md",
28
29
  "UPSTREAM.json",
@@ -57,29 +58,36 @@
57
58
  },
58
59
  "peerDependencies": {
59
60
  "@deepseek-ai/cordis": ">=4.0.5 <4.2.0",
60
- "@deepseek-ai/dsh-fs": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
61
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
62
- "@deepseek-ai/dsh-skill": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
63
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
61
+ "@deepseek-ai/dsh-fs": ">=0.2.1-rc.5 <0.3.0-0 || >=0.2.2-rc.1 <0.2.3-0",
62
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0-0 || >=0.2.2-rc.1 <0.2.3-0",
63
+ "@deepseek-ai/dsh-skill": ">=0.2.1-rc.5 <0.3.0-0 || >=0.2.2-rc.1 <0.2.3-0",
64
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0-0 || >=0.2.2-rc.1 <0.2.3-0",
64
65
  "@deepseek-ai/schemastery": ">=3.18.5 <3.19.0 || 3.19.0"
65
66
  },
66
67
  "devDependencies": {
67
68
  "@deepseek-ai/cordis": "4.1.0",
68
- "@deepseek-ai/dsh-fs": "0.2.2-rc.1",
69
- "@deepseek-ai/dsh-fs-local": "0.2.2-rc.1",
70
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
71
- "@deepseek-ai/dsh-skill": "0.2.2-rc.1",
72
- "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
73
- "@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.1",
74
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
69
+ "@deepseek-ai/dsh-fs": "0.2.2-rc.3",
70
+ "@deepseek-ai/dsh-fs-local": "0.2.2-rc.3",
71
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
72
+ "@deepseek-ai/dsh-scope": "0.2.2-rc.3",
73
+ "@deepseek-ai/dsh-skill": "0.2.2-rc.3",
74
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.3",
75
+ "@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.3",
76
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
77
+ "@deepseek-ai/dsh-util-values": "0.2.2-rc.3",
75
78
  "@deepseek-ai/schemastery": "3.19.0",
76
79
  "@testing-library/dom": "10.4.2",
77
80
  "@testing-library/react": "16.3.3",
78
81
  "@types/js-yaml": "4.0.9",
79
82
  "@types/node": "24.19.2",
83
+ "@types/react": "19.3.0",
84
+ "@types/react-dom": "19.3.0",
80
85
  "jsdom": "31.0.0",
86
+ "react": "19.3.1",
87
+ "react-dom": "19.3.1",
88
+ "semver": "7.8.6",
81
89
  "typescript": "6.0.3",
82
- "vitest": "4.1.8"
90
+ "vitest": "4.1.12"
83
91
  },
84
92
  "keywords": [
85
93
  "dsh",