@louisultra/dsh-verymath 0.5.1 → 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.
@@ -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
+ }
@@ -133,3 +133,21 @@ export interface UpsertResult {
133
133
  * a correction would duplicate another row's `(en, cn)` pair.
134
134
  */
135
135
  export declare function upsertTerms(terms: readonly GlossaryTerm[], upserts: readonly TermUpsert[]): UpsertResult;
136
+ /** Result of removing one row. */
137
+ export interface DeleteResult {
138
+ /** Whether a row with that id existed. */
139
+ readonly removed: boolean;
140
+ /** The document after removal, re-sorted with contiguous idx. */
141
+ readonly document: GlossaryTerm[];
142
+ }
143
+ /**
144
+ * Remove one row by `term_id`, preserving the document invariants.
145
+ *
146
+ * Deletion is how a duplicate or a wrong alias gets resolved: there is no
147
+ * "merge" operation in the upstream contract, and the panel's job is to let a
148
+ * human drop the row they decided against rather than hand-edit JSON.
149
+ * @param terms - current glossary terms (any order).
150
+ * @param termId - exact id of the row to remove.
151
+ * @throws VeryMathError when the input document already breaks an invariant.
152
+ */
153
+ export declare function deleteTerm(terms: readonly GlossaryTerm[], termId: string): DeleteResult;
@@ -424,3 +424,23 @@ function nextTermId(byId, en) {
424
424
  occurrence += 1n;
425
425
  }
426
426
  }
427
+ /**
428
+ * Remove one row by `term_id`, preserving the document invariants.
429
+ *
430
+ * Deletion is how a duplicate or a wrong alias gets resolved: there is no
431
+ * "merge" operation in the upstream contract, and the panel's job is to let a
432
+ * human drop the row they decided against rather than hand-edit JSON.
433
+ * @param terms - current glossary terms (any order).
434
+ * @param termId - exact id of the row to remove.
435
+ * @throws VeryMathError when the input document already breaks an invariant.
436
+ */
437
+ export function deleteTerm(terms, termId) {
438
+ validateGlossaryInvariants(terms);
439
+ const remaining = terms.filter(term => term.term_id !== termId);
440
+ if (remaining.length === terms.length)
441
+ return { removed: false, document: sortGlossary([...terms]) };
442
+ // Re-sorting reassigns idx, so a deletion cannot leave a numbering hole.
443
+ const document = sortGlossary(remaining);
444
+ validateGlossaryInvariants(document);
445
+ return { removed: true, document };
446
+ }
@@ -10,9 +10,10 @@ 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
- export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, validateGlossaryInvariants } from './glossary.ts';
15
- export type { GlossaryHit, GlossaryQueryOptions, GlossaryTerm, TermUpsert, UpsertResult } from './glossary.ts';
15
+ export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, deleteTerm, validateGlossaryInvariants } from './glossary.ts';
16
+ export type { GlossaryHit, GlossaryQueryOptions, GlossaryTerm, TermUpsert, UpsertResult, DeleteResult } from './glossary.ts';
16
17
  export { parsePaperStructure, parsePaperBatch, dependencySummary } from './paper.ts';
17
18
  export { checkGate, checkGoalApproval, checkWorkstreamCompletion, checkFinalRender, loadGoals, listWorkstreams, hasSection, } from './gates.ts';
18
19
  export type { GateResult } from './gates.ts';
package/lib/core/index.js CHANGED
@@ -16,8 +16,9 @@ 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
- export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, validateGlossaryInvariants } from "./glossary.js";
21
+ export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, deleteTerm, validateGlossaryInvariants } from "./glossary.js";
21
22
  export { parsePaperStructure, parsePaperBatch, dependencySummary } from "./paper.js";
22
23
  export { checkGate, checkGoalApproval, checkWorkstreamCompletion, checkFinalRender, loadGoals, listWorkstreams, hasSection, } from "./gates.js";
23
24
  export { loadManifest, searchSageRefs, scoreRow, termsFor, findExcerpt, readCorpusDoc, readCorpusDocWindow, resolveCorpusRoot, defaultCorpusRoot, docPath, } from "./sage.js";
package/lib/http.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { basename } from 'node:path';
2
+ /** Minimal shape of the host connection service this module needs. */
3
+ export interface ConnectionLike {
4
+ readonly fetch?: {
5
+ readonly register?: (route: {
6
+ readonly path: string;
7
+ readonly methods: readonly string[];
8
+ readonly requestBody?: 'buffered' | 'streaming';
9
+ readonly fetch: (request: Request) => Promise<Response>;
10
+ }) => unknown;
11
+ };
12
+ }
13
+ /** What the routes need from the host context. */
14
+ export interface HttpContext {
15
+ /** Workspace root the panel browses (the session/agent cwd). */
16
+ readonly workspace: () => string;
17
+ /** Host logger; absent in some hosts. */
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
+ /**
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>;
44
+ /**
45
+ * Register the panel's routes. Returns false when the host exposes no exact-fetch
46
+ * table (headless / CLI), so the panel half degrades away instead of making the
47
+ * plugin unloadable.
48
+ */
49
+ export declare function registerHttp(ctx: HttpContext, connection: ConnectionLike | undefined): boolean;
50
+ /** Exported for tests: the workspace-confinement rule the routes rely on. */
51
+ export { withinWorkspace, basename as _basename };