@louisultra/dsh-verymath 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/http.js ADDED
@@ -0,0 +1,635 @@
1
+ /**
2
+ * Host-side HTTP routes that back the browser panel.
3
+ *
4
+ * The panel runs in the renderer, so it cannot spawn processes or read files
5
+ * directly. Everything it shows therefore comes from these routes, which run in
6
+ * the host process and reuse the same core code the tools use — one
7
+ * implementation, two entry points (chat tool / panel).
8
+ *
9
+ * Three host facts were verified against the installed client packages rather
10
+ * than guessed:
11
+ * * routes come from `connection.fetch.register()`, and the service is only
12
+ * looked up through `ctx.inject(['connection'], …)` (at apply time it can be
13
+ * missing; `ctx.get('connection')` then silently yields nothing and every
14
+ * route 404s);
15
+ * * `requestBody: 'buffered'` must be explicit — without it the bridge treats
16
+ * the request as streaming and building a `Request` for a GET throws, which
17
+ * surfaces in the browser as an empty 400;
18
+ * * errors must be turned into structured JSON here, because a bare 500 gives
19
+ * the panel nothing to show.
20
+ *
21
+ * @module @louisultra/dsh-verymath/http
22
+ */
23
+ import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
24
+ import { basename, join, resolve } from 'node:path';
25
+ import { spawn } from 'node:child_process';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { computeTopology, focusClosure, mergeBatches, parseGlossary, parsePaperStructure, queryGlossary, deleteTerm, upsertTerms, validateGlossaryInvariants, VeryMathError, } from "./core/index.js";
28
+ const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
29
+ function json(body, status = 200) {
30
+ return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
31
+ }
32
+ /** Parse the request URL without throwing; a malformed URL is a client error, not a 500. */
33
+ function safeUrl(request) {
34
+ try {
35
+ return new URL(request.url);
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
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}/`))
46
+ return undefined;
47
+ return absolute;
48
+ }
49
+ /** Run one short command; never throws. */
50
+ function run(executable, args, timeoutMs = 8_000) {
51
+ return new Promise((resolvePromise) => {
52
+ let child;
53
+ let settled = false;
54
+ let timer;
55
+ const settle = (value) => {
56
+ if (settled)
57
+ return;
58
+ settled = true;
59
+ if (timer !== undefined)
60
+ clearTimeout(timer);
61
+ resolvePromise(value);
62
+ };
63
+ try {
64
+ child = spawn(executable, [...args], { stdio: ['ignore', 'pipe', 'pipe'] });
65
+ }
66
+ catch {
67
+ settle({ ok: false, stdout: '', stderr: 'failed to spawn' });
68
+ return;
69
+ }
70
+ const out = [];
71
+ const err = [];
72
+ child.stdout?.on('data', (chunk) => out.push(chunk));
73
+ child.stderr?.on('data', (chunk) => err.push(chunk));
74
+ child.on('error', (error) => settle({ ok: false, stdout: '', stderr: error.message }));
75
+ child.on('close', (code) => settle({ ok: code === 0, stdout: Buffer.concat(out).toString(), stderr: Buffer.concat(err).toString() }));
76
+ timer = setTimeout(() => {
77
+ child.kill('SIGKILL');
78
+ settle({ ok: false, stdout: Buffer.concat(out).toString(), stderr: 'timed out' });
79
+ }, timeoutMs);
80
+ });
81
+ }
82
+ /** First non-empty line of a command's output, trimmed to a displayable width. */
83
+ function firstLine(text, max = 80) {
84
+ const line = text.trim().split('\n')[0] ?? '';
85
+ return line.slice(0, max);
86
+ }
87
+ /**
88
+ * Probe the local toolchain. Each check is independent and never throws: a
89
+ * missing tool is a fact to display, not an error.
90
+ *
91
+ * `python3` is probed here only to answer "can the glossary build scripts run";
92
+ * the OSQP/Sage probes reuse the same command shape as the corresponding tools.
93
+ */
94
+ async function probeEnvironment() {
95
+ const rows = [];
96
+ const python = await run('python3', ['--version'], 5_000);
97
+ rows.push({
98
+ id: 'python',
99
+ label: 'Python 3',
100
+ enables: '术语库构建 / OCR 扫描 / OSQP / Lean 禁用词检测',
101
+ state: python.ok ? 'ready' : 'missing',
102
+ ...(python.ok ? { detail: (python.stdout || python.stderr).trim().split('\n')[0] } : {}),
103
+ ...(python.ok ? {} : { hint: 'macOS: xcode-select --install 或 brew install python3;Windows: python.org 安装包' }),
104
+ });
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);
109
+ rows.push({
110
+ id: 'pyyaml',
111
+ label: 'PyYAML',
112
+ enables: 'verymath_glossary_build(CSV/YAML → glossary.json)',
113
+ state: yaml.ok ? 'ready' : 'missing',
114
+ ...(yaml.ok ? { detail: yaml.stdout.trim() } : {}),
115
+ ...(yaml.ok ? {} : { hint: 'python3 -m pip install PyYAML' }),
116
+ });
117
+ }
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);
124
+ 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' }),
131
+ });
132
+ }
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);
136
+ rows.push({
137
+ id: 'osqp',
138
+ label: 'OSQP 求解栈',
139
+ enables: 'verymath_osqp_solve(凸二次规划 + 独立 KKT 验证)',
140
+ state: osqp.ok ? 'ready' : 'missing',
141
+ ...(osqp.ok ? { detail: `osqp ${osqp.stdout.trim()}` } : {}),
142
+ ...(osqp.ok ? {} : { hint: "python3 -m pip install 'osqp>=1,<2' numpy scipy" }),
143
+ });
144
+ }
145
+ const sage = await run('sage', ['--version'], 10_000);
146
+ rows.push({
147
+ id: 'sage',
148
+ label: 'SageMath',
149
+ 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 可执行文件' }),
153
+ });
154
+ const lean = await run('lean', ['--version'], 8_000);
155
+ rows.push({
156
+ id: 'lean',
157
+ label: 'Lean 4',
158
+ enables: '补丁验收中的工具链校验(禁用词扫描不需要 Lean)',
159
+ state: lean.ok ? 'ready' : 'missing',
160
+ ...(lean.ok ? { detail: firstLine(lean.stdout, 60) } : {}),
161
+ ...(lean.ok ? {} : { hint: 'lean-setup 技能会给出 elan / lake / mathlib 的安装步骤' }),
162
+ });
163
+ return rows;
164
+ }
165
+ /** Find glossary documents under the workspace (bounded depth, bounded count). */
166
+ async function findGlossaries(workspace) {
167
+ const found = [];
168
+ const skip = new Set(['node_modules', '.git', 'lib', 'dist', 'build', '.next']);
169
+ const walk = async (dir, depth) => {
170
+ if (depth > 3 || found.length >= 50)
171
+ return;
172
+ let entries;
173
+ try {
174
+ entries = await readdir(dir, { withFileTypes: true });
175
+ }
176
+ catch {
177
+ return;
178
+ }
179
+ for (const entry of entries) {
180
+ if (found.length >= 50)
181
+ return;
182
+ if (entry.name.startsWith('.') || skip.has(entry.name))
183
+ continue;
184
+ const path = join(dir, entry.name);
185
+ if (entry.isDirectory()) {
186
+ await walk(path, depth + 1);
187
+ continue;
188
+ }
189
+ if (!entry.isFile() || !entry.name.endsWith('.json'))
190
+ continue;
191
+ if (!/glossary/i.test(entry.name) && !/术语/.test(entry.name))
192
+ continue;
193
+ try {
194
+ const raw = await readFile(path, 'utf8');
195
+ const terms = parseGlossary(JSON.parse(raw));
196
+ validateGlossaryInvariants(terms);
197
+ const info = await stat(path);
198
+ found.push({ path: path.slice(workspace.length + 1), terms: terms.length, updatedAt: new Date(info.mtimeMs).toISOString().slice(0, 10) });
199
+ }
200
+ catch {
201
+ // A file named *glossary* that does not parse is not a glossary; skip it.
202
+ }
203
+ }
204
+ };
205
+ await walk(workspace, 0);
206
+ return found.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
207
+ }
208
+ /** Find math-paper-reading structure artifacts under the workspace. */
209
+ async function findStructures(workspace) {
210
+ const found = [];
211
+ const skip = new Set(['node_modules', '.git', 'lib', 'dist', 'build']);
212
+ const walk = async (dir, depth) => {
213
+ if (depth > 3 || found.length >= 50)
214
+ return;
215
+ let entries;
216
+ try {
217
+ entries = await readdir(dir, { withFileTypes: true });
218
+ }
219
+ catch {
220
+ return;
221
+ }
222
+ for (const entry of entries) {
223
+ if (found.length >= 50)
224
+ return;
225
+ if (entry.name.startsWith('.') || skip.has(entry.name))
226
+ continue;
227
+ const path = join(dir, entry.name);
228
+ if (entry.isDirectory()) {
229
+ await walk(path, depth + 1);
230
+ continue;
231
+ }
232
+ if (!entry.isFile() || !entry.name.endsWith('.json'))
233
+ continue;
234
+ if (!/_structure/i.test(entry.name))
235
+ continue;
236
+ try {
237
+ const structure = parsePaperStructure(JSON.parse(await readFile(path, 'utf8')));
238
+ found.push({
239
+ path: path.slice(workspace.length + 1),
240
+ title: structure.paper.title,
241
+ entities: structure.entities?.length ?? 0,
242
+ });
243
+ }
244
+ catch {
245
+ // Same reasoning as glossaries: unreadable artifacts are not listed.
246
+ }
247
+ }
248
+ };
249
+ await walk(workspace, 0);
250
+ return found;
251
+ }
252
+ /**
253
+ * Lay out the dependency graph for the panel.
254
+ *
255
+ * Coordinates are returned instead of a rendered SVG string so the client can
256
+ * draw it with real elements: a node then reacts to clicks (show its statement,
257
+ * its dependents, its reading position) and the panel never needs
258
+ * `dangerouslySetInnerHTML` for untrusted labels.
259
+ */
260
+ function graphLayout(structure) {
261
+ const { entities } = mergeBatches(structure);
262
+ const topology = computeTopology(structure);
263
+ const levels = topology.bottomUpLevels.length > 0 ? topology.bottomUpLevels : [entities.map(entity => entity.label)];
264
+ const nodeW = 176;
265
+ const nodeH = 38;
266
+ const gapX = 26;
267
+ const gapY = 40;
268
+ const widest = Math.max(...levels.map(level => level.length), 1);
269
+ const width = Math.max(380, widest * (nodeW + gapX) + gapX);
270
+ const nodes = [];
271
+ let y = 18;
272
+ const position = new Map();
273
+ for (const level of levels) {
274
+ const totalW = level.length * (nodeW + gapX) - gapX;
275
+ let x = Math.max(gapX, (width - totalW) / 2);
276
+ for (const label of level) {
277
+ position.set(label, { x, y });
278
+ x += nodeW + gapX;
279
+ }
280
+ y += nodeH + gapY;
281
+ }
282
+ for (const entity of entities) {
283
+ const at = position.get(entity.label);
284
+ if (at === undefined)
285
+ continue;
286
+ const metric = topology.metrics.find(item => item.label === entity.label);
287
+ nodes.push({
288
+ id: entity.label,
289
+ label: entity.label,
290
+ type: entity.type,
291
+ x: at.x,
292
+ y: at.y,
293
+ width: nodeW,
294
+ height: nodeH,
295
+ shared: entity.shared_node === true,
296
+ inDegree: metric?.inDegree ?? 0,
297
+ outDegree: metric?.outDegree ?? 0,
298
+ supportsMainTheorem: metric?.supportsMainTheorem ?? false,
299
+ statement: entity.statement,
300
+ });
301
+ }
302
+ const edges = [];
303
+ for (const entity of entities) {
304
+ if (!position.has(entity.label))
305
+ continue;
306
+ for (const dependency of entity.dependencies ?? []) {
307
+ if (!position.has(dependency))
308
+ continue;
309
+ edges.push({ from: entity.label, to: dependency, uncertain: false, external: false });
310
+ }
311
+ for (const dependency of entity.uncertain_dependencies ?? []) {
312
+ const target = dependency.split(' [')[0]?.trim() ?? '';
313
+ if (!position.has(target))
314
+ continue;
315
+ edges.push({ from: entity.label, to: target, uncertain: true, external: false });
316
+ }
317
+ for (const ref of entity.external_refs ?? []) {
318
+ edges.push({ from: entity.label, to: `EXT:${ref}`, uncertain: false, external: true });
319
+ }
320
+ }
321
+ return { nodes, edges, width, height: Math.max(180, y + 10) };
322
+ }
323
+ /**
324
+ * Register the panel's routes. Returns false when the host exposes no exact-fetch
325
+ * table (headless / CLI), so the panel half degrades away instead of making the
326
+ * plugin unloadable.
327
+ */
328
+ export function registerHttp(ctx, connection) {
329
+ const register = connection?.fetch?.register;
330
+ if (typeof register !== 'function')
331
+ return false;
332
+ /**
333
+ * Serialize read-modify-write cycles per document. Without this two panel
334
+ * actions fired quickly (edit two rows) both read the same snapshot and the
335
+ * second write drops the first.
336
+ */
337
+ const writeChains = new Map();
338
+ const withWrite = async (key, task) => {
339
+ const previous = writeChains.get(key) ?? Promise.resolve();
340
+ const run = previous.then(task, task);
341
+ const chained = run.then(() => undefined, () => undefined);
342
+ writeChains.set(key, chained);
343
+ try {
344
+ return await run;
345
+ }
346
+ finally {
347
+ if (writeChains.get(key) === chained)
348
+ writeChains.delete(key);
349
+ }
350
+ };
351
+ const guard = (handler) => async (request) => {
352
+ try {
353
+ return await handler(request);
354
+ }
355
+ catch (error) {
356
+ const message = error instanceof VeryMathError
357
+ ? `${error.code}: ${error.message}`
358
+ : error instanceof Error ? error.message : String(error);
359
+ ctx.log?.(`verymath panel route failed: ${message}`);
360
+ return json({ error: message }, 500);
361
+ }
362
+ };
363
+ // Environment readiness: what works right now, and what to install otherwise.
364
+ register({
365
+ path: '/api/verymath/env',
366
+ methods: ['GET'],
367
+ requestBody: 'buffered',
368
+ fetch: guard(async () => {
369
+ const rows = await probeEnvironment();
370
+ const ready = rows.filter(row => row.state === 'ready').length;
371
+ return json({ rows, ready, total: rows.length, workspace: ctx.workspace() });
372
+ }),
373
+ });
374
+ // Available glossary documents, so the panel can offer a picker instead of
375
+ // asking the user to type a path.
376
+ register({
377
+ path: '/api/verymath/glossaries',
378
+ methods: ['GET'],
379
+ requestBody: 'buffered',
380
+ fetch: guard(async () => json({ glossaries: await findGlossaries(ctx.workspace()) })),
381
+ });
382
+ // Query one glossary. `path` is workspace-relative and confined to it.
383
+ register({
384
+ path: '/api/verymath/glossary',
385
+ methods: ['GET'],
386
+ requestBody: 'buffered',
387
+ fetch: guard(async (request) => {
388
+ const url = safeUrl(request);
389
+ if (url === undefined)
390
+ return json({ error: 'invalid request url' }, 400);
391
+ const relative = url.searchParams.get('path') ?? '';
392
+ const query = (url.searchParams.get('q') ?? '').trim();
393
+ const absolute = withinWorkspace(ctx.workspace(), relative);
394
+ if (absolute === undefined)
395
+ return json({ error: 'path escapes the workspace' }, 400);
396
+ let terms;
397
+ try {
398
+ terms = parseGlossary(JSON.parse(await readFile(absolute, 'utf8')));
399
+ validateGlossaryInvariants(terms);
400
+ }
401
+ catch (error) {
402
+ return json({ error: `not a valid glossary: ${error instanceof Error ? error.message : String(error)}` }, 400);
403
+ }
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
+ };
421
+ if (query.length === 0)
422
+ return json({ stats, terms: [], matched: 0, truncated: false });
423
+ const { hits, total } = queryGlossary(terms, query, { limit: 60 });
424
+ return json({
425
+ stats,
426
+ matched: total,
427
+ truncated: total > hits.length,
428
+ terms: hits.map(hit => ({
429
+ term_id: hit.term.term_id,
430
+ en: hit.term.en,
431
+ cn: hit.term.cn,
432
+ matchedBy: hit.matchedBy,
433
+ ...(hit.term.pos !== undefined ? { pos: hit.term.pos } : {}),
434
+ ...(hit.term.field !== undefined ? { field: hit.term.field } : {}),
435
+ ...(hit.term.source !== undefined ? { source: hit.term.source } : {}),
436
+ ...(hit.term.examples !== undefined ? { examples: hit.term.examples.slice(0, 2) } : {}),
437
+ updatedAt: hit.term.updated_at,
438
+ })),
439
+ });
440
+ }),
441
+ });
442
+ const listStructures = guard(async () => json({ structures: await findStructures(ctx.workspace()) }));
443
+ register({ path: '/api/verymath/structures', methods: ['GET'], requestBody: 'buffered', fetch: listStructures });
444
+ // Dependency graph of one structure artifact: topology digest + inline SVG.
445
+ register({
446
+ path: '/api/verymath/paper',
447
+ methods: ['GET'],
448
+ requestBody: 'buffered',
449
+ fetch: guard(async (request) => {
450
+ const url = safeUrl(request);
451
+ if (url === undefined)
452
+ return json({ error: 'invalid request url' }, 400);
453
+ const relative = url.searchParams.get('path') ?? '';
454
+ const focus = (url.searchParams.get('focus') ?? '').trim();
455
+ const absolute = withinWorkspace(ctx.workspace(), relative);
456
+ if (absolute === undefined)
457
+ return json({ error: 'path escapes the workspace' }, 400);
458
+ let structure;
459
+ try {
460
+ structure = parsePaperStructure(JSON.parse(await readFile(absolute, 'utf8')));
461
+ }
462
+ catch (error) {
463
+ return json({ error: `not a valid structure artifact: ${error instanceof Error ? error.message : String(error)}` }, 400);
464
+ }
465
+ const { entities, report } = mergeBatches(structure);
466
+ const topology = computeTopology(structure);
467
+ const layout = graphLayout(structure);
468
+ return json({
469
+ title: structure.paper.title,
470
+ entities: entities.length,
471
+ sharedNodes: [...report.sharedNodes],
472
+ cycles: topology.cycles.map(cycle => [...cycle.labels]),
473
+ isolated: [...topology.isolated],
474
+ longestChain: [...topology.longestChain],
475
+ topDownOrder: [...topology.topDownOrder],
476
+ bottomUpLevels: topology.bottomUpLevels.map(level => [...level]),
477
+ metrics: entities.map(entity => ({
478
+ label: entity.label,
479
+ type: entity.type,
480
+ inDegree: topology.metrics.find(metric => metric.label === entity.label)?.inDegree ?? 0,
481
+ outDegree: topology.metrics.find(metric => metric.label === entity.label)?.outDegree ?? 0,
482
+ sharedNode: entity.shared_node === true,
483
+ supportsMainTheorem: topology.metrics.find(metric => metric.label === entity.label)?.supportsMainTheorem ?? false,
484
+ })),
485
+ ...(focus.length > 0 ? { focus: focusClosure(structure, focus) } : {}),
486
+ graph: layout,
487
+ });
488
+ }),
489
+ });
490
+ // Bundled skills, read from the package the same way the host skill registry
491
+ // does, so the panel shows exactly what a session can invoke.
492
+ register({
493
+ path: '/api/verymath/skills',
494
+ methods: ['GET'],
495
+ requestBody: 'buffered',
496
+ fetch: guard(async () => {
497
+ // `fileURLToPath`, not `URL.pathname`: a pathname is percent-encoded, so an
498
+ // install directory containing a space (`Application Support`, or any user
499
+ // name with one) would resolve to a directory that does not exist.
500
+ const moduleDir = fileURLToPath(new URL('.', import.meta.url));
501
+ // One level up from both `lib/` (published) and `src/` (tests).
502
+ const skillsDir = resolve(moduleDir, '..', 'skills');
503
+ const result = [];
504
+ let entries;
505
+ try {
506
+ entries = await readdir(skillsDir, { withFileTypes: true });
507
+ }
508
+ catch {
509
+ return json({ skills: [], error: 'skills directory not found in the package' });
510
+ }
511
+ for (const entry of entries) {
512
+ if (!entry.isDirectory() || entry.name.startsWith('.'))
513
+ continue;
514
+ try {
515
+ const raw = await readFile(join(skillsDir, entry.name, 'SKILL.md'), 'utf8');
516
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(raw);
517
+ const front = match?.[1] ?? '';
518
+ const name = /^name:\s*(.+)$/m.exec(front)?.[1]?.trim().replace(/^["']|["']$/g, '') ?? entry.name;
519
+ const description = /^description:\s*(.+)$/m.exec(front)?.[1]?.trim().replace(/^["']|["']$/g, '') ?? '';
520
+ const files = (await readdir(join(skillsDir, entry.name), { withFileTypes: true })).length;
521
+ result.push({ name, description, files });
522
+ }
523
+ catch {
524
+ // A directory without SKILL.md is not a skill.
525
+ }
526
+ }
527
+ result.sort((left, right) => left.name.localeCompare(right.name));
528
+ return json({ skills: result });
529
+ }),
530
+ });
531
+ /** Read and validate a glossary document from disk, or explain why not. */
532
+ const loadForWrite = async (absolute) => {
533
+ try {
534
+ const terms = parseGlossary(JSON.parse(await readFile(absolute, 'utf8')));
535
+ validateGlossaryInvariants(terms);
536
+ return { terms };
537
+ }
538
+ catch (error) {
539
+ return { error: `not a valid glossary: ${error instanceof Error ? error.message : String(error)}` };
540
+ }
541
+ };
542
+ const readBody = async (request) => {
543
+ try {
544
+ const parsed = await request.json();
545
+ if (typeof parsed !== 'object' || parsed === null)
546
+ return { error: 'request body must be a JSON object' };
547
+ return { body: parsed };
548
+ }
549
+ catch (error) {
550
+ return { error: `request body is not valid JSON: ${error instanceof Error ? error.message : String(error)}` };
551
+ }
552
+ };
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
+ // Add a term, or correct/remove one. The same core functions the chat tool uses
566
+ // run here, so the panel and the agent cannot drift apart in behaviour.
567
+ register({
568
+ path: '/api/verymath/glossary/upsert',
569
+ methods: ['POST'],
570
+ requestBody: 'buffered',
571
+ fetch: guard(async (request) => {
572
+ const body = await readBody(request);
573
+ if ('error' in body)
574
+ return json({ error: body.error }, 400);
575
+ const relative = typeof body.body.path === 'string' ? body.body.path : '';
576
+ const absolute = withinWorkspace(ctx.workspace(), relative);
577
+ if (absolute === undefined)
578
+ return json({ error: 'path escapes the workspace' }, 400);
579
+ const requests = Array.isArray(body.body.terms) ? body.body.terms : [];
580
+ if (requests.length === 0)
581
+ return json({ error: 'terms must be a non-empty array' }, 400);
582
+ return await withWrite(absolute, async () => {
583
+ const loaded = await loadForWrite(absolute);
584
+ if ('error' in loaded)
585
+ return json({ error: loaded.error }, 400);
586
+ let result;
587
+ try {
588
+ result = upsertTerms(loaded.terms, requests);
589
+ }
590
+ catch (error) {
591
+ // Ambiguous matches, unknown term_id, duplicate pairs — all are the
592
+ // caller's input, so they are 400 with the core's own message.
593
+ return json({ error: error instanceof Error ? error.message : String(error) }, 400);
594
+ }
595
+ await writeFile(absolute, JSON.stringify(result.document, null, 2) + '\n', 'utf8');
596
+ return json({
597
+ added: [...result.added],
598
+ updated: [...result.updated],
599
+ stats: statsFor(result.document),
600
+ document: result.document,
601
+ });
602
+ });
603
+ }),
604
+ });
605
+ register({
606
+ path: '/api/verymath/glossary/delete',
607
+ methods: ['POST'],
608
+ requestBody: 'buffered',
609
+ fetch: guard(async (request) => {
610
+ const body = await readBody(request);
611
+ if ('error' in body)
612
+ return json({ error: body.error }, 400);
613
+ const relative = typeof body.body.path === 'string' ? body.body.path : '';
614
+ const termId = typeof body.body.term_id === 'string' ? body.body.term_id : '';
615
+ const absolute = withinWorkspace(ctx.workspace(), relative);
616
+ if (absolute === undefined)
617
+ return json({ error: 'path escapes the workspace' }, 400);
618
+ if (termId.length === 0)
619
+ return json({ error: 'term_id is required' }, 400);
620
+ return await withWrite(absolute, async () => {
621
+ const loaded = await loadForWrite(absolute);
622
+ if ('error' in loaded)
623
+ return json({ error: loaded.error }, 400);
624
+ const result = deleteTerm(loaded.terms, termId);
625
+ if (!result.removed)
626
+ 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 });
629
+ });
630
+ }),
631
+ });
632
+ return true;
633
+ }
634
+ /** Exported for tests: the workspace-confinement rule the routes rely on. */
635
+ export { withinWorkspace, basename as _basename };
package/lib/index.d.ts CHANGED
@@ -7,11 +7,10 @@
7
7
  * package name**. The root entry exists because the host resolves a client
8
8
  * plugin's package manifest from the loader entry name: with only `/core` and
9
9
  * `/tool` entries the specifier lookup returns undefined, so `dsh.client` is
10
- * never read and the browser bundle is never served. Its `apply` is therefore
11
- * the whole reason this module is mountable.
10
+ * never read and the browser bundle is never served.
12
11
  *
13
- * This module also re-exports both halves so `import '@louisultra/dsh-verymath'`
14
- * gets the same surface as the subpaths.
12
+ * It also registers the routes that back the browser panel (see `./http`), so the
13
+ * panel and the chat tools read one implementation of the same logic.
15
14
  *
16
15
  * Upstream: VeryMath AI4Math repositories (MIT). See NOTICE.md and
17
16
  * UPSTREAM.json for per-repository provenance.
@@ -22,13 +21,17 @@ import type { Context } from '@deepseek-ai/cordis';
22
21
  export * as core from './core/index.ts';
23
22
  export * as tool from './tool/index.ts';
24
23
  export declare const name = "verymath-client";
25
- /** The root entry needs no services of its own; it only anchors the client bundle. */
24
+ /** `connection` is optional on purpose: see the apply comment. */
26
25
  export declare const inject: string[];
27
26
  /**
28
- * Mount point for the bare-name loader entry. Deliberately empty: the service and
29
- * the tools are mounted from `./core` and `./tool`, and the browser half is
30
- * served by the host from `dsh.client`. Keeping the function (rather than a
31
- * module without `apply`) means the host mounts an ordinary plugin instead of
32
- * warning about a module it cannot apply.
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.
33
36
  */
34
- export declare const apply: (_ctx: Context) => void;
37
+ export declare const apply: (ctx: Context) => void;