@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.
package/lib/http.js ADDED
@@ -0,0 +1,707 @@
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, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';
24
+ import { basename, dirname, join, resolve, sep } 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, resolveExecutable, resolvePythonExecutable, resolveSageExecutable, upsertTerms, validateGlossaryInvariants, VeryMathError, } from "./core/index.js";
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
+ }
50
+ function json(body, status = 200) {
51
+ return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
52
+ }
53
+ /** Parse the request URL without throwing; a malformed URL is a client error, not a 500. */
54
+ function safeUrl(request) {
55
+ try {
56
+ return new URL(request.url);
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
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}`))
78
+ return undefined;
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
+ }
99
+ }
100
+ /** Run one short command; never throws. */
101
+ function run(executable, args, timeoutMs = 8_000) {
102
+ return new Promise((resolvePromise) => {
103
+ let child;
104
+ let settled = false;
105
+ let timer;
106
+ const settle = (value) => {
107
+ if (settled)
108
+ return;
109
+ settled = true;
110
+ if (timer !== undefined)
111
+ clearTimeout(timer);
112
+ resolvePromise(value);
113
+ };
114
+ try {
115
+ child = spawn(executable, [...args], { stdio: ['ignore', 'pipe', 'pipe'] });
116
+ }
117
+ catch {
118
+ settle({ ok: false, stdout: '', stderr: 'failed to spawn' });
119
+ return;
120
+ }
121
+ const out = [];
122
+ const err = [];
123
+ child.stdout?.on('data', (chunk) => out.push(chunk));
124
+ child.stderr?.on('data', (chunk) => err.push(chunk));
125
+ child.on('error', (error) => settle({ ok: false, stdout: '', stderr: error.message }));
126
+ child.on('close', (code) => settle({ ok: code === 0, stdout: Buffer.concat(out).toString(), stderr: Buffer.concat(err).toString() }));
127
+ timer = setTimeout(() => {
128
+ child.kill('SIGKILL');
129
+ settle({ ok: false, stdout: Buffer.concat(out).toString(), stderr: 'timed out' });
130
+ }, timeoutMs);
131
+ });
132
+ }
133
+ /** First non-empty line of a command's output, trimmed to a displayable width. */
134
+ function firstLine(text, max = 80) {
135
+ const line = text.trim().split('\n')[0] ?? '';
136
+ return line.slice(0, max);
137
+ }
138
+ /**
139
+ * Probe the local toolchain. Each check is independent and never throws: a
140
+ * missing tool is a fact to display, not an error.
141
+ *
142
+ * `python3` is probed here only to answer "can the glossary build scripts run";
143
+ * the OSQP/Sage probes reuse the same command shape as the corresponding tools.
144
+ */
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
+ ]);
179
+ const rows = [];
180
+ rows.push({
181
+ id: 'python',
182
+ label: 'Python 3',
183
+ enables: '术语库构建 / OCR 扫描 / OSQP / Lean 禁用词检测',
184
+ state: python.ok ? 'ready' : 'missing',
185
+ ...(python.ok ? { detail: firstLine(python.stdout || python.stderr) } : {}),
186
+ ...(python.ok ? {} : { hint: 'macOS: xcode-select --install 或 brew install python3;Windows: python.org 安装包' }),
187
+ });
188
+ if (yaml !== undefined) {
189
+ rows.push({
190
+ id: 'pyyaml',
191
+ label: 'PyYAML',
192
+ enables: 'verymath_glossary_build(CSV/YAML → glossary.json)',
193
+ state: yaml.ok ? 'ready' : 'missing',
194
+ ...(yaml.ok ? { detail: yaml.stdout.trim() } : {}),
195
+ ...(yaml.ok ? {} : { hint: 'python3 -m pip install PyYAML' }),
196
+ });
197
+ }
198
+ for (const [index, binary] of binaries.entries()) {
199
+ const enables = index === 0 ? '数学 Beamer 幻灯片编译' : '中文 / 双语 Beamer 模板';
200
+ rows.push({
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' }),
207
+ });
208
+ }
209
+ if (osqp !== undefined) {
210
+ rows.push({
211
+ id: 'osqp',
212
+ label: 'OSQP 求解栈',
213
+ enables: 'verymath_osqp_solve(凸二次规划 + 独立 KKT 验证)',
214
+ state: osqp.ok ? 'ready' : 'missing',
215
+ ...(osqp.ok ? { detail: `osqp ${osqp.stdout.trim()}` } : {}),
216
+ ...(osqp.ok ? {} : { hint: "python3 -m pip install 'osqp>=1,<2' numpy scipy" }),
217
+ });
218
+ }
219
+ rows.push({
220
+ id: 'sage',
221
+ label: 'SageMath',
222
+ enables: '本机 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 可执行文件' }),
226
+ });
227
+ rows.push({
228
+ id: 'lean',
229
+ label: 'Lean 4',
230
+ enables: '补丁验收中的工具链校验(禁用词扫描不需要 Lean)',
231
+ state: lean.ok ? 'ready' : 'missing',
232
+ ...(lean.ok ? { detail: firstLine(lean.stdout, 60) } : {}),
233
+ ...(lean.ok ? {} : { hint: 'lean-setup 技能会给出 elan / lake / mathlib 的安装步骤' }),
234
+ });
235
+ return rows;
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
+ }
257
+ /** Find glossary documents under the workspace (bounded depth, bounded count). */
258
+ async function findGlossaries(workspace) {
259
+ const found = [];
260
+ const skip = new Set(['node_modules', '.git', 'lib', 'dist', 'build', '.next']);
261
+ const walk = async (dir, depth) => {
262
+ if (depth > 3 || found.length >= 50)
263
+ return;
264
+ let entries;
265
+ try {
266
+ entries = await readdir(dir, { withFileTypes: true });
267
+ }
268
+ catch {
269
+ return;
270
+ }
271
+ for (const entry of entries) {
272
+ if (found.length >= 50)
273
+ return;
274
+ if (entry.name.startsWith('.') || skip.has(entry.name))
275
+ continue;
276
+ const path = join(dir, entry.name);
277
+ if (entry.isDirectory()) {
278
+ await walk(path, depth + 1);
279
+ continue;
280
+ }
281
+ if (!entry.isFile() || !entry.name.endsWith('.json'))
282
+ continue;
283
+ if (!/glossary/i.test(entry.name) && !/术语/.test(entry.name))
284
+ continue;
285
+ try {
286
+ const raw = await readFile(path, 'utf8');
287
+ const terms = parseGlossary(JSON.parse(raw));
288
+ validateGlossaryInvariants(terms);
289
+ const info = await stat(path);
290
+ found.push({ path: path.slice(workspace.length + 1), terms: terms.length, updatedAt: new Date(info.mtimeMs).toISOString().slice(0, 10) });
291
+ }
292
+ catch {
293
+ // A file named *glossary* that does not parse is not a glossary; skip it.
294
+ }
295
+ }
296
+ };
297
+ await walk(workspace, 0);
298
+ return found.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
299
+ }
300
+ /** Find math-paper-reading structure artifacts under the workspace. */
301
+ async function findStructures(workspace) {
302
+ const found = [];
303
+ const skip = new Set(['node_modules', '.git', 'lib', 'dist', 'build']);
304
+ const walk = async (dir, depth) => {
305
+ if (depth > 3 || found.length >= 50)
306
+ return;
307
+ let entries;
308
+ try {
309
+ entries = await readdir(dir, { withFileTypes: true });
310
+ }
311
+ catch {
312
+ return;
313
+ }
314
+ for (const entry of entries) {
315
+ if (found.length >= 50)
316
+ return;
317
+ if (entry.name.startsWith('.') || skip.has(entry.name))
318
+ continue;
319
+ const path = join(dir, entry.name);
320
+ if (entry.isDirectory()) {
321
+ await walk(path, depth + 1);
322
+ continue;
323
+ }
324
+ if (!entry.isFile() || !entry.name.endsWith('.json'))
325
+ continue;
326
+ if (!/_structure/i.test(entry.name))
327
+ continue;
328
+ try {
329
+ const structure = parsePaperStructure(JSON.parse(await readFile(path, 'utf8')));
330
+ found.push({
331
+ path: path.slice(workspace.length + 1),
332
+ title: structure.paper.title,
333
+ entities: structure.entities?.length ?? 0,
334
+ });
335
+ }
336
+ catch {
337
+ // Same reasoning as glossaries: unreadable artifacts are not listed.
338
+ }
339
+ }
340
+ };
341
+ await walk(workspace, 0);
342
+ return found;
343
+ }
344
+ /**
345
+ * Lay out the dependency graph for the panel.
346
+ *
347
+ * Coordinates are returned instead of a rendered SVG string so the client can
348
+ * draw it with real elements: a node then reacts to clicks (show its statement,
349
+ * its dependents, its reading position) and the panel never needs
350
+ * `dangerouslySetInnerHTML` for untrusted labels.
351
+ */
352
+ function graphLayout(structure) {
353
+ const { entities } = mergeBatches(structure);
354
+ const topology = computeTopology(structure);
355
+ const levels = topology.bottomUpLevels.length > 0 ? topology.bottomUpLevels : [entities.map(entity => entity.label)];
356
+ const nodeW = 176;
357
+ const nodeH = 38;
358
+ const gapX = 26;
359
+ const gapY = 40;
360
+ const widest = Math.max(...levels.map(level => level.length), 1);
361
+ const width = Math.max(380, widest * (nodeW + gapX) + gapX);
362
+ const nodes = [];
363
+ let y = 18;
364
+ const position = new Map();
365
+ for (const level of levels) {
366
+ const totalW = level.length * (nodeW + gapX) - gapX;
367
+ let x = Math.max(gapX, (width - totalW) / 2);
368
+ for (const label of level) {
369
+ position.set(label, { x, y });
370
+ x += nodeW + gapX;
371
+ }
372
+ y += nodeH + gapY;
373
+ }
374
+ for (const entity of entities) {
375
+ const at = position.get(entity.label);
376
+ if (at === undefined)
377
+ continue;
378
+ const metric = topology.metrics.find(item => item.label === entity.label);
379
+ nodes.push({
380
+ id: entity.label,
381
+ label: entity.label,
382
+ type: entity.type,
383
+ x: at.x,
384
+ y: at.y,
385
+ width: nodeW,
386
+ height: nodeH,
387
+ shared: entity.shared_node === true,
388
+ inDegree: metric?.inDegree ?? 0,
389
+ outDegree: metric?.outDegree ?? 0,
390
+ supportsMainTheorem: metric?.supportsMainTheorem ?? false,
391
+ statement: entity.statement,
392
+ });
393
+ }
394
+ const edges = [];
395
+ for (const entity of entities) {
396
+ if (!position.has(entity.label))
397
+ continue;
398
+ for (const dependency of entity.dependencies ?? []) {
399
+ if (!position.has(dependency))
400
+ continue;
401
+ edges.push({ from: entity.label, to: dependency, uncertain: false, external: false });
402
+ }
403
+ for (const dependency of entity.uncertain_dependencies ?? []) {
404
+ const target = dependency.split(' [')[0]?.trim() ?? '';
405
+ if (!position.has(target))
406
+ continue;
407
+ edges.push({ from: entity.label, to: target, uncertain: true, external: false });
408
+ }
409
+ for (const ref of entity.external_refs ?? []) {
410
+ edges.push({ from: entity.label, to: `EXT:${ref}`, uncertain: false, external: true });
411
+ }
412
+ }
413
+ return { nodes, edges, width, height: Math.max(180, y + 10) };
414
+ }
415
+ /**
416
+ * Register the panel's routes. Returns false when the host exposes no exact-fetch
417
+ * table (headless / CLI), so the panel half degrades away instead of making the
418
+ * plugin unloadable.
419
+ */
420
+ export function registerHttp(ctx, connection) {
421
+ const register = connection?.fetch?.register;
422
+ if (typeof register !== 'function')
423
+ return false;
424
+ /**
425
+ * Serialize read-modify-write cycles per document. Without this two panel
426
+ * actions fired quickly (edit two rows) both read the same snapshot and the
427
+ * second write drops the first.
428
+ */
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);
432
+ const withWrite = async (key, task) => {
433
+ const previous = writeChains.get(key) ?? Promise.resolve();
434
+ const run = previous.then(task, task);
435
+ const chained = run.then(() => undefined, () => undefined);
436
+ writeChains.set(key, chained);
437
+ try {
438
+ return await run;
439
+ }
440
+ finally {
441
+ if (writeChains.get(key) === chained)
442
+ writeChains.delete(key);
443
+ }
444
+ };
445
+ const guard = (handler) => async (request) => {
446
+ try {
447
+ return await handler(request);
448
+ }
449
+ catch (error) {
450
+ const message = error instanceof VeryMathError
451
+ ? `${error.code}: ${error.message}`
452
+ : error instanceof Error ? error.message : String(error);
453
+ ctx.log?.(`verymath panel route failed: ${message}`);
454
+ return json({ error: message }, 500);
455
+ }
456
+ };
457
+ // Environment readiness: what works right now, and what to install otherwise.
458
+ register({
459
+ path: '/api/verymath/env',
460
+ methods: ['GET'],
461
+ requestBody: 'buffered',
462
+ fetch: guard(async () => {
463
+ const rows = await probeEnvironment();
464
+ const ready = rows.filter(row => row.state === 'ready').length;
465
+ return json({ rows, ready, total: rows.length, workspace: ctx.workspace() });
466
+ }),
467
+ });
468
+ // Available glossary documents, so the panel can offer a picker instead of
469
+ // asking the user to type a path.
470
+ register({
471
+ path: '/api/verymath/glossaries',
472
+ methods: ['GET'],
473
+ requestBody: 'buffered',
474
+ fetch: guard(async () => json({ glossaries: await findGlossaries(ctx.workspace()) })),
475
+ });
476
+ // Query one glossary. `path` is workspace-relative and confined to it.
477
+ register({
478
+ path: '/api/verymath/glossary',
479
+ methods: ['GET'],
480
+ requestBody: 'buffered',
481
+ fetch: guard(async (request) => {
482
+ const url = safeUrl(request);
483
+ if (url === undefined)
484
+ return json({ error: 'invalid request url' }, 400);
485
+ const relative = url.searchParams.get('path') ?? '';
486
+ const query = (url.searchParams.get('q') ?? '').trim();
487
+ const absolute = await withinWorkspace(ctx.workspace(), relative);
488
+ if (absolute === undefined)
489
+ return json({ error: 'path escapes the workspace' }, 400);
490
+ let terms;
491
+ try {
492
+ terms = parseGlossary(JSON.parse(await readFile(absolute, 'utf8')));
493
+ validateGlossaryInvariants(terms);
494
+ }
495
+ catch (error) {
496
+ return json({ error: `not a valid glossary: ${error instanceof Error ? error.message : String(error)}` }, 400);
497
+ }
498
+ const stats = glossaryStats(terms);
499
+ if (query.length === 0)
500
+ return json({ stats, terms: [], matched: 0, truncated: false });
501
+ const { hits, total } = queryGlossary(terms, query, { limit: 60 });
502
+ return json({
503
+ stats,
504
+ matched: total,
505
+ truncated: total > hits.length,
506
+ terms: hits.map(hit => ({
507
+ term_id: hit.term.term_id,
508
+ en: hit.term.en,
509
+ cn: hit.term.cn,
510
+ matchedBy: hit.matchedBy,
511
+ ...(hit.term.pos !== undefined ? { pos: hit.term.pos } : {}),
512
+ ...(hit.term.field !== undefined ? { field: hit.term.field } : {}),
513
+ ...(hit.term.source !== undefined ? { source: hit.term.source } : {}),
514
+ ...(hit.term.examples !== undefined ? { examples: hit.term.examples.slice(0, 2) } : {}),
515
+ updatedAt: hit.term.updated_at,
516
+ })),
517
+ });
518
+ }),
519
+ });
520
+ const listStructures = guard(async () => json({ structures: await findStructures(ctx.workspace()) }));
521
+ register({ path: '/api/verymath/structures', methods: ['GET'], requestBody: 'buffered', fetch: listStructures });
522
+ // Dependency graph of one structure artifact: topology digest + inline SVG.
523
+ register({
524
+ path: '/api/verymath/paper',
525
+ methods: ['GET'],
526
+ requestBody: 'buffered',
527
+ fetch: guard(async (request) => {
528
+ const url = safeUrl(request);
529
+ if (url === undefined)
530
+ return json({ error: 'invalid request url' }, 400);
531
+ const relative = url.searchParams.get('path') ?? '';
532
+ const focus = (url.searchParams.get('focus') ?? '').trim();
533
+ const absolute = await withinWorkspace(ctx.workspace(), relative);
534
+ if (absolute === undefined)
535
+ return json({ error: 'path escapes the workspace' }, 400);
536
+ let structure;
537
+ try {
538
+ structure = parsePaperStructure(JSON.parse(await readFile(absolute, 'utf8')));
539
+ }
540
+ catch (error) {
541
+ return json({ error: `not a valid structure artifact: ${error instanceof Error ? error.message : String(error)}` }, 400);
542
+ }
543
+ const { entities, report } = mergeBatches(structure);
544
+ const topology = computeTopology(structure);
545
+ const layout = graphLayout(structure);
546
+ return json({
547
+ title: structure.paper.title,
548
+ entities: entities.length,
549
+ sharedNodes: [...report.sharedNodes],
550
+ cycles: topology.cycles.map(cycle => [...cycle.labels]),
551
+ isolated: [...topology.isolated],
552
+ longestChain: [...topology.longestChain],
553
+ topDownOrder: [...topology.topDownOrder],
554
+ bottomUpLevels: topology.bottomUpLevels.map(level => [...level]),
555
+ metrics: entities.map(entity => ({
556
+ label: entity.label,
557
+ type: entity.type,
558
+ inDegree: topology.metrics.find(metric => metric.label === entity.label)?.inDegree ?? 0,
559
+ outDegree: topology.metrics.find(metric => metric.label === entity.label)?.outDegree ?? 0,
560
+ sharedNode: entity.shared_node === true,
561
+ supportsMainTheorem: topology.metrics.find(metric => metric.label === entity.label)?.supportsMainTheorem ?? false,
562
+ })),
563
+ ...(focus.length > 0 ? { focus: focusClosure(structure, focus) } : {}),
564
+ graph: layout,
565
+ });
566
+ }),
567
+ });
568
+ // Bundled skills, read from the package the same way the host skill registry
569
+ // does, so the panel shows exactly what a session can invoke.
570
+ register({
571
+ path: '/api/verymath/skills',
572
+ methods: ['GET'],
573
+ requestBody: 'buffered',
574
+ fetch: guard(async () => {
575
+ // `fileURLToPath`, not `URL.pathname`: a pathname is percent-encoded, so an
576
+ // install directory containing a space (`Application Support`, or any user
577
+ // name with one) would resolve to a directory that does not exist.
578
+ const moduleDir = fileURLToPath(new URL('.', import.meta.url));
579
+ // One level up from both `lib/` (published) and `src/` (tests).
580
+ const skillsDir = resolve(moduleDir, '..', 'skills');
581
+ const result = [];
582
+ let entries;
583
+ try {
584
+ entries = await readdir(skillsDir, { withFileTypes: true });
585
+ }
586
+ catch {
587
+ return json({ skills: [], error: 'skills directory not found in the package' });
588
+ }
589
+ for (const entry of entries) {
590
+ if (!entry.isDirectory() || entry.name.startsWith('.'))
591
+ continue;
592
+ try {
593
+ const raw = await readFile(join(skillsDir, entry.name, 'SKILL.md'), 'utf8');
594
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(raw);
595
+ const front = match?.[1] ?? '';
596
+ const name = /^name:\s*(.+)$/m.exec(front)?.[1]?.trim().replace(/^["']|["']$/g, '') ?? entry.name;
597
+ const description = /^description:\s*(.+)$/m.exec(front)?.[1]?.trim().replace(/^["']|["']$/g, '') ?? '';
598
+ const files = (await readdir(join(skillsDir, entry.name), { withFileTypes: true })).length;
599
+ result.push({ name, description, files });
600
+ }
601
+ catch {
602
+ // A directory without SKILL.md is not a skill.
603
+ }
604
+ }
605
+ result.sort((left, right) => left.name.localeCompare(right.name));
606
+ return json({ skills: result });
607
+ }),
608
+ });
609
+ /** Read and validate a glossary document from disk, or explain why not. */
610
+ const loadForWrite = async (absolute) => {
611
+ try {
612
+ const terms = parseGlossary(JSON.parse(await readFile(absolute, 'utf8')));
613
+ validateGlossaryInvariants(terms);
614
+ return { terms };
615
+ }
616
+ catch (error) {
617
+ return { error: `not a valid glossary: ${error instanceof Error ? error.message : String(error)}` };
618
+ }
619
+ };
620
+ const readBody = async (request) => {
621
+ try {
622
+ const parsed = await request.json();
623
+ if (typeof parsed !== 'object' || parsed === null)
624
+ return { error: 'request body must be a JSON object' };
625
+ return { body: parsed };
626
+ }
627
+ catch (error) {
628
+ return { error: `request body is not valid JSON: ${error instanceof Error ? error.message : String(error)}` };
629
+ }
630
+ };
631
+ // Add a term, or correct/remove one. The same core functions the chat tool uses
632
+ // run here, so the panel and the agent cannot drift apart in behaviour.
633
+ register({
634
+ path: '/api/verymath/glossary/upsert',
635
+ methods: ['POST'],
636
+ requestBody: 'buffered',
637
+ fetch: guard(async (request) => {
638
+ const body = await readBody(request);
639
+ if ('error' in body)
640
+ return json({ error: body.error }, 400);
641
+ const relative = typeof body.body.path === 'string' ? body.body.path : '';
642
+ const absolute = await withinWorkspace(ctx.workspace(), relative);
643
+ if (absolute === undefined)
644
+ return json({ error: 'path escapes the workspace' }, 400);
645
+ const requests = Array.isArray(body.body.terms) ? body.body.terms : [];
646
+ if (requests.length === 0)
647
+ return json({ error: 'terms must be a non-empty array' }, 400);
648
+ return await writeLock(absolute, async () => {
649
+ const loaded = await loadForWrite(absolute);
650
+ if ('error' in loaded)
651
+ return json({ error: loaded.error }, 400);
652
+ let result;
653
+ try {
654
+ result = upsertTerms(loaded.terms, requests);
655
+ }
656
+ catch (error) {
657
+ // Ambiguous matches, unknown term_id, duplicate pairs — all are the
658
+ // caller's input, so they are 400 with the core's own message.
659
+ return json({ error: error instanceof Error ? error.message : String(error) }, 400);
660
+ }
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?.();
665
+ return json({
666
+ added: [...result.added],
667
+ updated: [...result.updated],
668
+ stats: glossaryStats(result.document),
669
+ document: result.document,
670
+ });
671
+ });
672
+ }),
673
+ });
674
+ register({
675
+ path: '/api/verymath/glossary/delete',
676
+ methods: ['POST'],
677
+ requestBody: 'buffered',
678
+ fetch: guard(async (request) => {
679
+ const body = await readBody(request);
680
+ if ('error' in body)
681
+ return json({ error: body.error }, 400);
682
+ const relative = typeof body.body.path === 'string' ? body.body.path : '';
683
+ const termId = typeof body.body.term_id === 'string' ? body.body.term_id : '';
684
+ const absolute = await withinWorkspace(ctx.workspace(), relative);
685
+ if (absolute === undefined)
686
+ return json({ error: 'path escapes the workspace' }, 400);
687
+ if (termId.length === 0)
688
+ return json({ error: 'term_id is required' }, 400);
689
+ return await writeLock(absolute, async () => {
690
+ const loaded = await loadForWrite(absolute);
691
+ if ('error' in loaded)
692
+ return json({ error: loaded.error }, 400);
693
+ const result = deleteTerm(loaded.terms, termId);
694
+ if (!result.removed)
695
+ return json({ error: `no term with term_id ${JSON.stringify(termId)}` }, 404);
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 });
701
+ });
702
+ }),
703
+ });
704
+ return true;
705
+ }
706
+ /** Exported for tests: the workspace-confinement rule the routes rely on. */
707
+ export { withinWorkspace, basename as _basename };