Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1621 lines (1516 loc) · 83.4 KB
/
Copy pathserver.ts
File metadata and controls
1621 lines (1516 loc) · 83.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// catpad's server (catpad: a category theory notepad). Three files, no
// dependencies: `bun server.ts`, with the agent in agent.ts and the history in
// history.ts.
//
// browser ⇄ WebSocket ⇄ this ⇄ lean --server (the Lean language server)
// ⇄ tectonic + pdftocairo (TikZ → PDF → SVG)
// ⇄ the agent (agent.ts), whose tools act on the pad
// MCP client ⇄ POST /mcp ⇄ the same tools
//
// The browser sends the whole buffer on every edit. It becomes the text of one
// document in the language server, which re-elaborates what changed and
// reports diagnostics. Each `diagram` command reports what it bound as a JSON
// diagnostic (see lean/Prelude.lean); that JSON becomes TikZ, the TikZ becomes
// an SVG, and the SVG's elements are tagged with the index of the item they
// draw, so the browser can tie a click on an arrow to the Lean term the arrow
// is bound to. Hover, the goal at the cursor and completion are the language
// server's own, passed through.
//
// The server also keeps the pad: the buffer, the notes, and the last finished
// check (messages, diagrams, and how each diagram's TeX went). The agent's
// tools read and write it. When the agent changes the buffer the server checks
// it itself, page or no page, and tells every page.
//
// Information runs both ways along one line, and through the same stations:
//
// notes ─▶ agent ─▶ buffer ─▶ Lean ─▶ spec ─▶ TikZ ─▶ picture (left to right)
// agent ◀─ report ◀─ states ◀─ Lean ◀─ buffer ◀─ op ◀─ picture (right to left)
//
// Left to right is derivation: each station is computed from the one before
// it and from nothing else. Right to left is editing: a drawing operation on
// the picture is carried out on the spec and printed into the buffer
// (draw.ts), and from there it goes left to right again like any other edit.
// So the picture is never changed directly, a drawing is checked by the same
// Lean as typing, and the buffer stays the one thing that is stored.
//
// Whoever changes the buffer (the user typing, the user drawing, the agent, a
// restore from the history) goes through `setCode`, which is also where the
// history hears of it. The states everything here can be in are named in
// web/machine.js.
//
// CATPAD_LEAN_DIR a built Lake project with Mathlib, to use instead of
// the kit catpad comes with (setup.ts, kit.ts)
// CATPAD_SANDBOX=0 run Lean without a sandbox (bwrap on Linux, sandbox-exec on macOS)
// CATPAD_DATA the projects and their histories (see paths.ts)
// CATPAD_DEBUG=1 log what the language server and the agent report
// LEAN_TIMEOUT_MS how long one check may take (60000)
// PORT 8792
// and the agent's, in agent.ts.
import { spawn, type Subprocess } from "bun";
import { createHash } from "crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "fs";
import { homedir, tmpdir } from "os";
import { basename, delimiter, join } from "path";
import { pathToFileURL } from "url";
import { Agent, BACKENDS, probeAgents, readPrompt, readTemplate, settingsForPage, testChoice, TOOLS, TOOL_NAMES, type AgentChoice, type AgentEvent, type Selection, type ToolResult } from "./agent";
import { applyOp, diagramHead, itemLine, resolveRequest, type Item, type Op, type Spec } from "./draw";
import { History, type Check, type Kind } from "./history";
import { DATA, IN_APP, ROOT, VERSION } from "./paths";
import { drawTools, install as installTool, installing, leanSource, missing, requirements } from "./setup";
import { claim } from "./lock";
import { parseProject, Projects, serializeProject, type ProjectInfo } from "./projects";
import { Updates } from "./update";
import { diagramState, machine, stateOf, tallyText } from "./web/machine.js";
// Where Lean and Mathlib are: the kit's folder, or a Lake project (setup.ts).
const leanWhere = () => { const s = leanSource(); return !s ? null : "kit" in s ? s.kit.dir : s.project; };
const PORT = Number(process.env.PORT ?? 8792);
const CACHE = join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "catpad");
// Whether catpad sets itself up when something is missing: unpacks the kit,
// and fetches Mathlib into a Lake project that has none. The app does, since
// nobody runs run.sh for it.
const AUTO_SETUP = process.env.CATPAD_AUTO_SETUP ? process.env.CATPAD_AUTO_SETUP !== "0" : IN_APP;
// One server per data directory (lock.ts). The app's main process claims it
// before it loads this file; run from source, this file does.
if (!IN_APP) {
const c = claim(DATA, PORT);
if (!c.ok) {
console.error(`catpad is already running on the projects in ${DATA} (process ${c.pid}${c.port ? `, http://127.0.0.1:${c.port}/` : ""}). Stop it first, or set CATPAD_DATA to another directory.`);
process.exit(1);
}
}
const DEBUG = !!process.env.CATPAD_DEBUG && process.env.CATPAD_DEBUG !== "0";
const BWRAP = ["/usr/bin/bwrap", "/bin/bwrap"].find((p) => existsSync(p));
const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
const WIN = process.platform === "win32";
// Lean's own executable, and the PATH it runs with (its toolchain's bin, and the system's).
const leanExe = (sysroot: string) => join(sysroot, "bin", WIN ? "lean.exe" : "lean");
const leanPATH = (sysroot: string) => [join(sysroot, "bin"), WIN ? join(process.env.SystemRoot ?? "C:\\Windows", "System32") : "/usr/bin"].join(delimiter);
// bubblewrap can be installed and still not able to make a sandbox: some
// distributions keep user namespaces from programs they have no profile for.
// Lean would then never start, so the sandbox is tried once, as it is used below.
function bwrapWorks(): boolean {
if (!BWRAP) return false;
try {
const r = Bun.spawnSync([
BWRAP, "--unshare-all", "--die-with-parent", "--ro-bind", "/usr", "/usr",
...["/lib", "/lib64", "/bin"].flatMap((d) => (existsSync(d) ? ["--symlink", `usr${d}`, d] : [])),
"--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "/usr/bin/true",
], { stdout: "ignore", stderr: "pipe" });
if (r.exitCode !== 0) console.error(`lean: bubblewrap is installed and cannot make a sandbox here (${r.stderr.toString().trim().split("\n")[0]}). Lean runs without one.`);
return r.exitCode === 0;
} catch {
return false;
}
}
const SANDBOX: "bwrap" | "sandbox-exec" | null =
process.env.CATPAD_SANDBOX === "0" ? null
: process.platform === "linux" && bwrapWorks() ? "bwrap"
: process.platform === "darwin" && existsSync(SANDBOX_EXEC) ? "sandbox-exec"
: null;
const TIMEOUT_MS = Number(process.env.LEAN_TIMEOUT_MS ?? 60000); // how long one check may take
mkdirSync(join(CACHE, "tex"), { recursive: true });
const sha = (s: string) => createHash("sha256").update(s).digest("hex").slice(0, 16);
// ---------- Lean ----------
interface Pos { line: number; ch: number }
interface Msg { severity: string; text: string; line?: number; ch?: number; endLine?: number; endCh?: number }
// The document the language server sees is this line and then the buffer, so
// the buffer's line n is the document's line n + 1.
const HEADER = "import Mathlib import Diagram\n";
// `roots`: the directories Lean reads from, for the sandbox to let it.
interface LeanEnv { leanPath: string; sysroot: string; prelude: string; roots: string[] }
// What Lean is doing while it is neither ready nor failed, for the page to say.
let leanNote: string | null = null;
// Fetches Mathlib into the Lean project: `lake update`, whose post-update hook
// downloads Mathlib's prebuilt cache (several GB, once). A project directory
// that does not exist yet is made from the lakefile and toolchain catpad ships.
async function setupLean(LEAN_DIR: string) {
mkdirSync(LEAN_DIR, { recursive: true });
if (!existsSync(join(LEAN_DIR, "lakefile.lean")))
for (const f of ["lakefile.toml", "lean-toolchain"]) if (!existsSync(join(LEAN_DIR, f))) copyFileSync(join(ROOT, "lean", f), join(LEAN_DIR, f));
leanNote = "Setting up Lean: downloading Mathlib and its cache (several GB, once)";
console.log(`lean: running lake update in ${LEAN_DIR}. ${leanNote}.`);
const p = spawn(["lake", "update"], { cwd: LEAN_DIR, stdout: "pipe", stderr: "pipe" });
const tail: string[] = [];
const watch = async (s: ReadableStream<Uint8Array>) => {
const dec = new TextDecoder();
for await (const chunk of s) for (const line of dec.decode(chunk, { stream: true }).split(/\r|\n/)) {
if (!line.trim()) continue;
tail.push(line);
if (tail.length > 20) tail.shift();
leanNote = `Setting up Lean (once): ${line.trim().slice(0, 120)}`;
}
};
await Promise.all([watch(p.stdout), watch(p.stderr)]);
const code = await p.exited;
leanNote = null;
if (code !== 0) throw new Error(`lake update failed in ${LEAN_DIR}:\n${tail.join("\n")}`);
}
// LEAN_PATH and the toolchain as Lake sets them for a Lake project.
async function projectEnv(LEAN_DIR: string): Promise<{ leanPath: string; sysroot: string }> {
const setup = `cd ${LEAN_DIR} && lake exe cache get && lake build`;
const hasLakefile = () => ["lakefile.toml", "lakefile.lean"].some((f) => existsSync(join(LEAN_DIR, f)));
if (!Bun.which("lake")) throw new Error(`There is no \`lake\` on PATH to run the Lean project ${LEAN_DIR}. Install elan, or unset CATPAD_LEAN_DIR to use the Lean catpad comes with.`);
if (AUTO_SETUP && (!hasLakefile() || !existsSync(join(LEAN_DIR, ".lake/packages/mathlib")))) await setupLean(LEAN_DIR);
if (!existsSync(LEAN_DIR)) throw new Error(`The Lean project ${LEAN_DIR} does not exist. Set CATPAD_LEAN_DIR to a Lake project with Mathlib built.`);
if (!hasLakefile())
throw new Error(`${LEAN_DIR} has no lakefile, so it is not a Lake project. Set CATPAD_LEAN_DIR to a Lake project with Mathlib built.`);
// Without this check `lake env` would start cloning Mathlib, silently, for many minutes.
if (!existsSync(join(LEAN_DIR, ".lake/packages/mathlib")))
throw new Error(`Mathlib is not downloaded in ${LEAN_DIR}. Run: ${setup}`);
// Lake's environment, printed by this same bun, so it needs no shell (there is none on Windows).
const p = spawn(["lake", "env", process.execPath, "-e", 'process.stdout.write(process.env.LEAN_PATH + "\\n" + process.env.LEAN_SYSROOT)'], { cwd: LEAN_DIR, stdout: "pipe", stderr: "pipe", env: { ...process.env, BUN_BE_BUN: "1" } });
const text = await new Response(p.stdout).text();
if ((await p.exited) !== 0) throw new Error(`lake env failed in ${LEAN_DIR}: ${await new Response(p.stderr).text()}`);
const [leanPath, sysroot] = text.split("\n");
if (!leanPath.split(delimiter).some((d) => d && existsSync(join(d, "Mathlib.olean"))))
throw new Error(`Mathlib is not built in ${LEAN_DIR} (no Mathlib.olean on its LEAN_PATH). Run: ${setup}`);
return { leanPath, sysroot };
}
// Lean and Mathlib, from the kit or from a Lake project (setup.ts), plus
// lean/Prelude.lean compiled to a module named Diagram (once per version of it).
async function leanEnv(): Promise<LeanEnv> {
const from = leanSource();
if (!from) throw new Error("Lean is not set up yet.");
const { leanPath, sysroot } = "kit" in from ? { leanPath: from.kit.leanPath.join(delimiter), sysroot: from.kit.sysroot } : await projectEnv(from.project);
const roots = "kit" in from ? [from.kit.dir] : [sysroot, from.project];
const src = readFileSync(join(ROOT, "lean/Prelude.lean"), "utf8");
const prelude = join(CACHE, "lean", sha(src + leanPath + sysroot));
if (!existsSync(join(prelude, "Diagram.olean"))) {
mkdirSync(prelude, { recursive: true });
copyFileSync(join(ROOT, "lean/Prelude.lean"), join(prelude, "Diagram.lean"));
const t = Date.now();
console.log("lean: compiling the prelude (once per version of it)...");
const c = spawn([leanExe(sysroot), "-o", "Diagram.olean.part", "-i", "Diagram.ilean", "Diagram.lean"], { cwd: prelude, env: { ...(WIN ? process.env : {}), LEAN_PATH: leanPath, LEAN_SYSROOT: sysroot, PATH: leanPATH(sysroot) }, stdout: "pipe", stderr: "pipe" });
const out = (await new Response(c.stdout).text()) + (await new Response(c.stderr).text());
if ((await c.exited) !== 0) throw new Error("lean/Prelude.lean doesn't compile:\n" + out);
await Bun.write(join(prelude, "Diagram.olean"), Bun.file(join(prelude, "Diagram.olean.part")));
console.log(`lean: compiled the prelude in ${((Date.now() - t) / 1000).toFixed(1)} s`);
}
return { leanPath, sysroot, prelude, roots };
}
const real = (p: string) => { try { return realpathSync(p); } catch { return p; } };
const sbString = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
// The macOS sandbox for Lean, in the Seatbelt profile language. Everything is
// allowed except: the network; writing anywhere but the temporary directories;
// and reading the contents of any file under the home directory other than the
// toolchain, the Lean project and the compiled prelude. Names and metadata stay
// readable, because Lean resolves its search path with realpath and stat.
function seatbeltProfile(readable: string[]): string {
const home = real(homedir());
const tmp = real(tmpdir());
return [
"(version 1)",
"(allow default)",
"(deny network*)",
"(deny file-write*)",
`(allow file-write* (subpath "/private/tmp") (subpath "/private/var/folders") (subpath ${sbString(tmp)})`,
' (literal "/dev/null") (literal "/dev/zero") (literal "/dev/dtracehelper") (regex #"^/dev/tty") (regex #"^/dev/fd/"))',
`(deny file-read-data (subpath ${sbString(home)}))`,
`(allow file-read-data ${[...new Set(readable.map(real))].map((p) => `(subpath ${sbString(p)})`).join(" ")})`,
"",
].join("\n");
}
type Listener = (ev: { type: "progress"; version: number; line: number } | { type: "done"; version: number; ms: number; messages: Msg[]; failed?: boolean } | { type: "down" }) => void;
// One `lean --server` and one document in it.
class Lean {
private env!: LeanEnv;
private proc: Subprocess<"pipe", "pipe", "ignore"> | null = null;
private nextId = 0;
private pending = new Map<number, (r: any) => void>();
private uri = "";
// The process: stopped → starting → ready → stopped again when it exits or
// is killed. A start that fails is `failed`, and can be tried again.
private life = machine("lean", "stopped", {
stopped: { START: "starting", FAIL: "failed" },
starting: { UP: "ready", FAIL: "failed", EXIT: "stopped" },
ready: { EXIT: "stopped" },
failed: { START: "starting", EXIT: "failed" },
});
// The document in it: closed until the first buffer is sent, then
// elaborating, then elaborated, and elaborating again with every new text
// (or when Lean finds it has more to do after all).
private doc = machine("document", "closed", {
closed: { SEND: "elaborating" },
elaborating: { SEND: "elaborating", MORE: "elaborating", DONE: "elaborated", CLOSE: "closed" },
elaborated: { SEND: "elaborating", MORE: "elaborating", DONE: "elaborated", CLOSE: "closed" },
});
version = 0;
private sentAt = 0;
private took = 0;
private text = "";
private diagnostics: any[] = [];
private doneTimer: Timer | undefined;
private watchdog: Timer | undefined;
error: string | null = null;
listener: Listener = () => {};
private starting: Promise<void> | null = null;
// The buffer Lean has now (or is checking), and whether it has finished with it.
get code(): string | null { return this.doc.is("closed") ? null : this.text.slice(HEADER.length); }
get finished(): boolean { return this.doc.is("elaborated"); }
get ready(): boolean { return this.life.is("ready"); }
get phase(): string { return this.life.state; }
// Starts Lean unless it is running. Callers that arrive while it is starting wait for the same start.
start(): Promise<void> {
if (this.ready && this.proc) return Promise.resolve();
return (this.starting ??= (async () => {
this.life.send("START");
try {
this.env ??= await leanEnv();
await this.spawn();
this.life.send("UP");
this.error = null;
} catch (e: any) {
this.life.send("FAIL");
this.error = String(e.message ?? e);
console.error(this.error);
} finally {
this.starting = null;
}
})());
}
private async spawn() {
const { leanPath, sysroot, prelude, roots } = this.env;
const env = { LEAN_PATH: [leanPath, prelude].join(delimiter), LEAN_SYSROOT: sysroot, HOME: "/tmp", PATH: leanPATH(sysroot) };
const lean = leanExe(sysroot);
// The buffer can run `#eval` with IO, so Lean runs sandboxed when it can.
// On Linux, bubblewrap, as the Academy's does: no network, a read-only view
// of /usr, the toolchain, the Lean project and the prelude, a throwaway
// /tmp, and nothing else of this machine's files. On macOS, sandbox-exec:
// no network, writes only to the temporary directories, and no reading of
// files under the home directory except the toolchain, the project and the
// prelude (see seatbeltProfile).
const ro = (p: string) => (existsSync(p) ? ["--ro-bind", p, p] : []);
let cmd: string[];
let procEnv: Record<string, string>;
if (SANDBOX === "bwrap") {
cmd = [
BWRAP!, "--unshare-all", "--die-with-parent", "--new-session",
...ro("/usr"),
...["/lib", "/lib64", "/bin"].flatMap((d) => (existsSync(d) ? ["--symlink", `usr${d}`, d] : [])),
...roots.flatMap(ro), ...ro(prelude), ...ro("/etc/localtime"),
"--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--chdir", "/tmp", "--clearenv",
...Object.entries(env).flatMap(([k, v]) => ["--setenv", k, v]),
lean, "--server",
];
procEnv = {};
} else if (SANDBOX === "sandbox-exec") {
const readable = [...roots, prelude, ...leanPath.split(delimiter).filter(Boolean)];
cmd = [SANDBOX_EXEC, "-p", seatbeltProfile(readable), lean, "--server"];
procEnv = { ...env, HOME: real(tmpdir()) };
} else {
cmd = [lean, "--server"];
// Windows has no sandbox for Lean, and its programs want the rest of the environment (SystemRoot, TEMP).
procEnv = WIN ? { ...(process.env as Record<string, string>), ...env, HOME: homedir() } : { ...env, HOME: homedir() };
}
// Outside bubblewrap the document sits in a directory with no lakefile,
// so the server takes its search path from LEAN_PATH.
const cwd = SANDBOX === "bwrap" ? "/tmp" : prelude;
this.uri = SANDBOX === "bwrap" ? `file://${cwd}/Catpad.lean` : pathToFileURL(join(cwd, "Catpad.lean")).href;
const proc = spawn(cmd, { cwd: prelude, env: procEnv, stdin: "pipe", stdout: "pipe", stderr: "ignore" });
this.proc = proc;
this.doc.send("CLOSE");
this.text = "";
this.pending.clear();
this.read(proc);
proc.exited.then(() => {
if (this.proc !== proc) return;
this.proc = null;
this.life.send("EXIT");
for (const done of this.pending.values()) done(null);
this.pending.clear();
this.listener({ type: "down" });
});
const init = await this.request("initialize", { processId: process.pid, rootUri: null, capabilities: {} });
if (!init) throw new Error(`lean --server did not start${SANDBOX ? ` under ${SANDBOX} (CATPAD_SANDBOX=0 runs it without one)` : ""}`);
this.notify("initialized", {});
}
stop() {
clearTimeout(this.watchdog);
clearTimeout(this.doneTimer);
const p = this.proc;
this.proc = null;
this.life.send("EXIT");
this.doc.send("CLOSE");
try { p?.kill(9); } catch {}
}
private write(m: object) {
const body = JSON.stringify({ jsonrpc: "2.0", ...m });
this.proc?.stdin.write(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);
this.proc?.stdin.flush();
}
private notify(method: string, params: object) { this.write({ method, params }); }
private request(method: string, params: object): Promise<any> {
return new Promise((done) => {
if (!this.proc) return done(null);
const id = ++this.nextId;
this.pending.set(id, done);
this.write({ id, method, params });
});
}
private async read(proc: Subprocess<"pipe", "pipe", "ignore">) {
let buf = Buffer.alloc(0);
for await (const chunk of proc.stdout) {
buf = Buffer.concat([buf, chunk]);
for (;;) {
const h = buf.indexOf("\r\n\r\n");
if (h < 0) break;
const len = Number(/Content-Length: (\d+)/i.exec(buf.subarray(0, h).toString())?.[1]);
if (buf.length < h + 4 + len) break;
let m: any;
try { m = JSON.parse(buf.subarray(h + 4, h + 4 + len).toString()); } catch { m = {}; }
buf = buf.subarray(h + 4 + len);
this.receive(m);
}
}
}
private receive(m: any) {
if (DEBUG && m.method) console.log(`lean: ${m.method} v${m.params?.version ?? m.params?.textDocument?.version} ${m.params?.diagnostics?.length ?? JSON.stringify(m.params?.processing?.map((p: any) => p.range.start.line) ?? "")} (current v${this.version})`);
if (m.id != null && !m.method) {
this.pending.get(m.id)?.(m.error ? null : m.result);
this.pending.delete(m.id);
} else if (m.id != null) {
this.write({ id: m.id, result: null }); // the server asking the client something (registerCapability, refresh)
} else if (m.method === "textDocument/publishDiagnostics" && m.params.version === this.version) {
this.diagnostics = m.params.diagnostics;
if (this.finished) this.finish();
} else if (m.method === "$/lean/fileProgress" && m.params.textDocument.version === this.version) {
const processing: any[] = m.params.processing;
clearTimeout(this.doneTimer);
if (processing.length) {
this.doc.send("MORE");
this.listener({ type: "progress", version: this.version, line: Math.max(0, Math.min(...processing.map((p) => p.range.start.line)) - 1) });
} else {
// Nothing left to elaborate. The last diagnostics can trail this by a moment.
this.doneTimer = setTimeout(() => { if (this.doc.send("DONE")) this.finish(); }, 40);
}
}
}
private finish() {
const messages: Msg[] = this.diagnostics
.filter((d) => d.severity !== 4)
.map((d) => ({
severity: d.severity === 1 ? "error" : d.severity === 2 ? "warning" : "information",
text: d.message,
line: Math.max(0, d.range.start.line - 1), ch: d.range.start.line < 1 ? 0 : d.range.start.character,
endLine: Math.max(0, d.range.end.line - 1), endCh: d.range.end.line < 1 ? 0 : d.range.end.character,
}))
.sort((a, b) => a.line! - b.line! || a.ch! - b.ch!);
clearTimeout(this.watchdog);
this.took ||= Date.now() - this.sentAt;
if (DEBUG) console.log(`lean: v${this.version} done, ${this.took} ms, ${messages.length} messages`);
this.listener({ type: "done", version: this.version, ms: this.took, messages });
}
// Replaces the buffer. Returns the document version this text has.
async check(code: string): Promise<number> {
if (!this.ready || !this.proc) await this.start();
if (!this.ready || !this.proc) throw new Error(this.error ?? "Lean did not start");
const text = HEADER + code;
if (!this.doc.is("closed") && text === this.text) {
// Nothing changed, so Lean will say nothing new. Report what it said about this text.
if (this.finished) setTimeout(() => this.finished && this.finish(), 0);
return this.version;
}
this.text = text;
this.version++;
if (DEBUG) console.log(`lean: sending v${this.version + 0}: ${text.length} chars, ${text.split("\n").length} lines, document ${this.doc.state}, uri=${this.uri}`);
this.sentAt = Date.now();
const first = this.doc.is("closed");
this.doc.send("SEND");
this.diagnostics = [];
this.took = 0;
clearTimeout(this.doneTimer);
// A buffer Lean can't finish (an `#eval` that loops) would hold a core
// forever. Past the limit Lean is stopped and started again.
clearTimeout(this.watchdog);
const version = this.version;
this.watchdog = setTimeout(async () => {
if (version !== this.version || this.finished) return;
console.error(`lean: v${version} ran past ${TIMEOUT_MS / 1000} s, restarting`);
this.stop();
this.listener({ type: "done", version, ms: TIMEOUT_MS, failed: true, messages: [{ severity: "error", text: `Lean ran past ${TIMEOUT_MS / 1000} s on this buffer, so it was stopped and is starting again. Change the buffer to check it again.`, line: 0, ch: 0 }] });
await this.start();
}, TIMEOUT_MS);
const textDocument = { uri: this.uri, version: this.version };
if (first) this.notify("textDocument/didOpen", { textDocument: { ...textDocument, languageId: "lean4", text } });
else this.notify("textDocument/didChange", { textDocument, contentChanges: [{ text }] });
return this.version;
}
private at(p: Pos) { return { textDocument: { uri: this.uri }, position: { line: p.line + 1, character: p.ch } }; }
async hover(p: Pos): Promise<{ text: string; range?: any } | null> {
const r = await this.request("textDocument/hover", this.at(p));
const text = typeof r?.contents === "string" ? r.contents : r?.contents?.value;
if (!text) return null;
const g = r.range;
return { text, range: g && { line: g.start.line - 1, ch: g.start.character, endLine: g.end.line - 1, endCh: g.end.character } };
}
async goal(p: Pos): Promise<string[] | null> {
const r = await this.request("$/lean/plainGoal", this.at(p));
return r?.goals ?? null;
}
// Lean answers with every name that could go here, unfiltered; `prefix` is what has been typed of it.
async complete(p: Pos, prefix: string): Promise<{ label: string; detail?: string }[]> {
const r = await this.request("textDocument/completion", this.at(p));
const items: any[] = r?.items ?? [];
const want = prefix.toLowerCase();
const rank = (label: string) => {
const l = label.toLowerCase();
return l === want ? 0 : l.startsWith(want) ? 1 : l.includes(want) ? 2 : 3;
};
return items
.map((i) => ({ label: String(i.label), detail: i.detail as string | undefined, rank: rank(String(i.label)), sort: String(i.sortText ?? i.label) }))
.filter((i) => i.rank < 3)
.sort((a, b) => a.rank - b.rank || a.label.length - b.label.length || (a.sort < b.sort ? -1 : 1))
.slice(0, 40)
.map(({ label, detail }) => ({ label, detail }));
}
}
// ---------- TikZ ----------
const TEX: Record<string, string> = {
"ℤ": "\\mathbb{Z}", "ℕ": "\\mathbb{N}", "ℚ": "\\mathbb{Q}", "ℝ": "\\mathbb{R}", "ℂ": "\\mathbb{C}",
"×": "\\times ", "→": "\\to ", "←": "\\leftarrow ", "↔": "\\leftrightarrow ", "⟶": "\\longrightarrow ", "⥤": "\\Rightarrow ",
"∘": "\\circ ", "≫": "\\gg ", "⊗": "\\otimes ", "⊕": "\\oplus ", "≃": "\\simeq ", "≅": "\\cong ", "≌": "\\simeq ",
"⁻¹": "^{-1}", "·": "\\cdot ", "•": "\\bullet ", "∣": "\\mid ", "≤": "\\le ", "≥": "\\ge ", "≠": "\\ne ",
"∀": "\\forall ", "∃": "\\exists ", "∧": "\\wedge ", "∨": "\\vee ", "¬": "\\neg ", "λ": "\\lambda ", "↦": "\\mapsto ",
"⟨": "\\langle ", "⟩": "\\rangle ", "∈": "\\in ", "⊆": "\\subseteq ", "∪": "\\cup ", "∩": "\\cap ", "⊤": "\\top ", "⊥": "\\bot ",
"𝟙": "\\mathbb{1}", "𝟭": "\\mathbb{1}", "Λ": "\\Lambda ", "∑": "\\sum ", "∏": "\\prod ", "↑": "", "⇑": "",
"α": "\\alpha ", "β": "\\beta ", "γ": "\\gamma ", "δ": "\\delta ", "ε": "\\varepsilon ", "η": "\\eta ", "θ": "\\theta ",
"ι": "\\iota ", "κ": "\\kappa ", "μ": "\\mu ", "ν": "\\nu ", "π": "\\pi ", "ρ": "\\rho ", "σ": "\\sigma ", "τ": "\\tau ",
"φ": "\\varphi ", "χ": "\\chi ", "ψ": "\\psi ", "ω": "\\omega ", "Γ": "\\Gamma ", "Δ": "\\Delta ", "Σ": "\\Sigma ", "Φ": "\\Phi ", "Ω": "\\Omega ",
"{": "\\{", "}": "\\}", "#": "\\#", "%": "\\%", "&": "\\&", "$": "\\$", "~": "\\sim ", "\\": "\\backslash ", "_": "\\_",
};
const SUB = "₀₁₂₃₄₅₆₇₈₉";
// A pretty-printed Lean term as TeX math. Good enough for a default label;
// `tex r"..."` on the item overrides it.
export function texify(term: string, script = false): string {
let out = "";
const cs = Array.from(term.replace(/\s+/g, " "));
for (let i = 0; i < cs.length; ) {
const two = cs[i] + (cs[i + 1] ?? "");
if (TEX[two] != null) { out += TEX[two]; i += 2; continue; }
if (/[A-Za-z]/.test(cs[i])) {
let j = i;
while (j < cs.length && /[A-Za-z0-9_.'!?]/.test(cs[j])) j++;
let word = cs.slice(i, j).join("");
let sub = "";
while (j < cs.length && SUB.includes(cs[j])) sub += SUB.indexOf(cs[j++]);
const esc = word.replace(/_/g, "\\_");
out += (word.length === 1 ? word : `\\mathrm{${esc}}`) + (sub ? `_{${sub}}` : "");
i = j;
continue;
}
if (SUB.includes(cs[i])) { out += `_{${SUB.indexOf(cs[i])}}`; i++; continue; }
if (TEX[cs[i]] != null) out += TEX[cs[i]];
else if (cs[i] === " ") {
// A space is an application when it sits between two operands; around an operator it is nothing.
if (/[A-Za-z0-9_'.)\]₀-₉]/.test(cs[i - 1] ?? "") && /[A-Za-z0-9(\[]/.test(cs[i + 1] ?? "")) out += "\\ ";
else if (script) out += "\\,"; // TeX drops the space around operators in script size, where arrow labels are set
}
else if (cs[i].codePointAt(0)! < 128) out += cs[i];
else out += "?";
i++;
}
return out;
}
// Item k is drawn in the colour (1, 2, k + 3). Nothing else in the picture is
// that colour, so the colour says which SVG elements belong to which item.
const MAX_ITEMS = 250;
// One column and one row of the diagram's grid, in cm; and in TeX points,
// which are the SVG's units, for the page to turn a drag into coordinates.
const XCM = 4.2, YCM = 2.6;
const UNIT = { x: XCM * 28.3465, y: YCM * 28.3465 };
// The picture says what state each item is in as well as what it is. An
// object that is not bound (or whose term does not elaborate) is its name in
// a dashed box. An arrow with no term is dotted and labelled `?`. The colour
// of a state is the page's to choose (style.css), since every element knows
// its item.
export function tikz(spec: Spec): string {
const items = spec.items.slice(0, MAX_ITEMS);
const node = new Map<string, string>(); // an object's name → its TikZ node
const mid = new Map<string, string>(); // a named arrow → the node at its middle, where 2-cells attach
const n = (x: number) => Number(x.toFixed(4));
const L: string[] = [
"\\documentclass[tikz,border=8pt]{standalone}",
"\\usepackage{amsmath,amssymb}",
"\\usetikzlibrary{cd}",
...items.map((_, k) => `\\definecolor{k${k}}{RGB}{1,2,${k + 3}}`),
"\\begin{document}",
`\\begin{tikzpicture}[x=${XCM}cm,y=${YCM}cm]`,
];
const cd = (k: number) => `\\path[commutative diagrams/.cd, every arrow, every label, /tikz/color=k${k}]`;
items.forEach((it, k) => {
if (it.kind !== "obj") return;
if (!node.has(it.id!)) node.set(it.id!, `n${k}`);
const bound = stateOf(it) === "ok" && it.term != null;
const box = bound ? "" : `, draw=k${k}, densely dashed, rounded corners=2pt, inner sep=4pt`;
L.push(`\\node[text=k${k}${box}] (n${k}) at (${n(it.col!)},${n(-it.row!)}) {$${it.tex ?? texify(bound ? it.term! : String(it.id))}$};`);
});
// An empty diagram is still a place to draw in.
if (!node.size) L.push("\\path (0,0) rectangle (1,-1);");
items.forEach((it, k) => {
const hole = stateOf(it) === "hole";
if (it.kind === "hom") {
const a = node.get(it.src!), b = node.get(it.tgt!);
if (!a || !b) return;
// An arrow from an object to itself is a loop: above it, or below with a negative bend.
const loop = `/tikz/every loop/.style={/tikz/min distance=11mm}, /tikz/loop ${it.bend! < 0 ? "below" : "above"}`;
const edge = [a === b ? loop : it.bend ? `/tikz/bend left=${n(it.bend)}` : "", it.dashed ? "dashed" : "", hole ? "/tikz/densely dotted" : ""].filter(Boolean).join(", ");
const label = it.tex ?? (it.term != null ? texify(it.term, true) : "?");
L.push(`${cd(k)} (${a}) edge[${edge}] node[${it.swap ? "swap" : ""}] {$${label}$} node[/tikz/auto=false, /tikz/anchor=center, /tikz/pos=0.5, /tikz/inner sep=2pt] (m${k}) {} (${b});`);
if (it.name && !mid.has(it.name)) mid.set(it.name, `m${k}`);
} else if (it.kind === "cell") {
const a = mid.get(it.src!), b = mid.get(it.tgt!);
if (!a || !b || a === b) return;
// The double line is the edge's own: TikZ starts every path single again.
const edge = ["/tikz/commutative diagrams/Rightarrow", "/tikz/shorten <=2pt", "/tikz/shorten >=2pt", it.bend ? `/tikz/bend left=${n(it.bend)}` : "", it.dashed ? "dashed" : "", hole ? "/tikz/densely dotted" : ""].filter(Boolean).join(", ");
const label = it.tex ?? (it.term != null ? texify(it.term, true) : "?");
L.push(`${cd(k)} (${a}) edge[${edge}] node[${it.swap ? "swap" : ""}] {$${label}$} (${b});`);
} else if (it.kind === "comm") {
L.push(`\\node[text=k${k}] at (${n(it.col!)},${n(-it.row!)}) {$${it.tex ?? (hole ? "\\circlearrowright^{?}" : "\\circlearrowright")}$};`);
}
});
L.push("\\end{tikzpicture}", "\\end{document}", "");
return L.join("\n");
}
// pdftocairo's SVG, with every element tagged by the item it draws
// (`data-k`), colours turned into `currentColor`, and ids made unique so
// several diagrams can share a page. White is the gap of a double arrow (a
// 2-cell's ⇒), and becomes the card's own background.
export function tagSvg(svg: string, key: string): string {
const colour = (v: string): string | null => {
const m = v.match(/^rgb\(([\d.]+)%, ?([\d.]+)%, ?([\d.]+)%\)$/);
if (!m) return null;
const [r, g, b] = [m[1], m[2], m[3]].map((p) => Math.round(Number(p) * 2.55));
if (r === 255 && g === 255 && b === 255) return "gap";
if (r === 0 && g === 0 && b === 0) return "";
if (r === 1 && g === 2 && b >= 3) return String(b - 3);
return null;
};
return svg
.replace(/<\?xml[^>]*\?>\s*/, "")
.replace(/<(g|path|use|rect|circle|polygon)\b([^>]*?)(\/?)>/g, (tag, el, attrs, close) => {
let k: string | null = null;
const a = attrs.replace(/\b(fill|stroke)="(rgb\([^"]*\))"/g, (all: string, prop: string, v: string) => {
const c = colour(v);
if (c == null) return all;
if (c === "gap") return `${prop}="var(--panel, white)"`;
if (c !== "") k = c;
return `${prop}="currentColor"`;
});
return `<${el}${a}${k != null ? ` data-k="${k}"` : ""}${close}>`;
})
.replace(/\bid="/g, `id="${key}-`)
.replace(/href="#/g, `href="#${key}-`)
.replace(/url\(#/g, `url(#${key}-`)
.replace(/(<svg\b[^>]*?)\swidth="([\d.]+)pt" height="([\d.]+)pt"/, '$1 data-w="$2" data-h="$3"');
}
type Rendered = { svg?: string; error?: string };
const rendering = new Map<string, Promise<Rendered>>();
function render(src: string): Promise<Rendered> {
const key = "d" + sha(src);
let p = rendering.get(key);
if (p) return p;
p = (async () => {
const dir = join(CACHE, "tex", key);
const out = join(dir, "d.tagged.svg");
if (existsSync(out)) return { svg: readFileSync(out, "utf8") };
const tools = drawTools();
if (!tools) return { error: "The tools that draw diagrams are not set up yet." };
const env = { ...process.env, ...tools.env };
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "d.tex"), src);
const run = async (...more: string[]) => {
const tex = spawn([tools.tectonic, "--reruns", "0", "--chatter", "minimal", ...more, "d.tex"], { cwd: dir, env, stdout: "pipe", stderr: "pipe" });
const log = (await new Response(tex.stderr).text()) + (await new Response(tex.stdout).text());
return { ok: (await tex.exited) === 0, log };
};
// The kit carries the TeX files the diagrams use, so tectonic is told to
// look nowhere else: a diagram draws with no network, and at once. A label
// may still ask for a file the kit does not have (a font nobody used
// before); only then is tectonic let out to fetch it.
let tex = await run(...(tools.cached ? ["--only-cached"] : []));
if (!tex.ok && tools.cached && !/^! /m.test(tex.log)) tex = await run();
if (!tex.ok) {
const lines = tex.log.split("\n").filter((l) => /^error|^!|^l\.\d+/.test(l));
return { error: (lines.length ? lines : tex.log.trim().split("\n").slice(-6)).join("\n") };
}
const cairo = spawn([tools.pdftocairo, "-svg", "d.pdf", "d.svg"], { cwd: dir, env, stdout: "ignore", stderr: "pipe" });
if ((await cairo.exited) !== 0) return { error: await new Response(cairo.stderr).text() };
const svg = tagSvg(readFileSync(join(dir, "d.svg"), "utf8"), key);
writeFileSync(out, svg);
return { svg };
})().catch((e) => ({ error: String(e?.message ?? e) }));
rendering.set(key, p);
p.then((r) => { if (r.error) rendering.delete(key); });
if (rendering.size > 500) rendering.delete(rendering.keys().next().value!);
return p;
}
// ---------- the pad ----------
const MARK = "⟦diagram⟧";
const lean = new Lean();
for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(sig, () => process.exit(0));
// However the process ends (a signal, the app quitting, an update restarting
// it), the pad is written to its project and Lean goes with it.
process.on("exit", () => {
try { persistNow(); } catch {}
agent.stop();
lean.stop();
});
// Installs one thing catpad needs (setup.ts), with its output line by line to
// every page, and its latest line where the page says what Lean is doing.
// With the kit there, Lean starts, the pages check again, and the diagrams draw.
async function setupOne(id: string): Promise<string | null> {
broadcast({ type: "setup", items: requirements(), busy: id });
const err = await installTool(id, (line) => {
console.log(`setup ${id}: ${line}`);
leanNote = line.slice(0, 160);
broadcast({ type: "setup-log", id, line });
});
leanNote = null;
broadcast({ type: "setup", items: requirements(), done: id, error: err, busy: null });
if (!err && id === "kit" && !lean.ready) await lean.start();
if (!err) broadcast({ type: "status", ready: lean.ready, error: lean.error });
return err;
}
if (leanSource()) lean.start();
// One finished check of one version of the buffer.
interface Checked {
version: number;
code: string;
ms: number;
failed: boolean;
messages: Msg[];
specs: Spec[];
sources: string[];
renders: Promise<Rendered>[];
rendered: (Rendered | undefined)[]; // `renders`, as each one arrives
}
const pad = {
code: "", // the buffer, as whoever wrote it last set it (see setCode)
known: false, // whether anyone has set it since the server started
notes: "",
last: null as Checked | null, // the latest finished check of Lean's current version
// The buffer as the agent last read or wrote it. write_lean refuses to
// overwrite a buffer the user changed after that.
agentSeen: null as string | null,
// The buffer at the end of the agent's last turn, for "has the user changed it since".
afterTurn: null as string | null,
// Whether the pad was put back from its history since the agent's last turn.
restored: false,
// What was drawn in the diagram pane, one line per operation: since the
// agent's last turn (it is told), and since the last commit (the commit says).
drawn: [] as string[],
uncommitted: [] as { title: string; what: string }[],
};
// Who changed the buffer. `user` typed in the editor, `diagram` is the user
// drawing in the diagram pane, `agent` is a tool call, `restore` is a commit
// coming back from the history.
type By = "user" | "diagram" | "agent" | "restore";
// Every change to the buffer goes through here, whichever way it travelled,
// so that the pad, the pages, the agent's view of the buffer and the history
// hear of it in one place. A page that typed the text has it already. Any
// other change is sent to every page, which takes it as an edit.
function setCode(code: string, by: By, more: { title?: string; what?: string; focus?: { d: number; k: number | null } | null } = {}) {
const changed = code !== pad.code || !pad.known;
pad.code = code;
pad.known = true;
if (changed) persistSoon();
if (by === "agent") pad.agentSeen = code;
if (by === "diagram" && more.what) {
pad.drawn.push(`${JSON.stringify(more.title ?? "")}: ${more.what}`);
pad.uncommitted.push({ title: more.title ?? "", what: more.what });
}
if (by === "restore") {
pad.agentSeen = null;
pad.afterTurn = null;
pad.restored = true;
pad.drawn = [];
pad.uncommitted = [];
return; // the restore tells the pages itself, with the rest of the commit
}
if (by !== "user") broadcast({ type: "buffer", code, by, focus: more.focus ?? null });
// A stroke of a drawing is a whole step, so it is committed as soon as Lean
// and TeX have drawn it (strokes faster than that share a commit). Typing
// is committed when it pauses.
if (by === "diagram") void save("edit");
else if (changed) saveSoon();
}
// The check of the buffer as it is now: how far Lean and TeX have got with it.
//
// down Lean is not running: it is starting, or it could not start
// checking Lean has not finished with this text (or has not been sent it)
// rendering Lean has, so the diagrams' items and states are known; TeX has not
// settled both have
type PadCheck = { state: "down" | "checking" } | { state: "rendering" | "settled"; checked: Checked };
function padCheck(): PadCheck {
const c = pad.last;
if (c && c.code === pad.code && c.version === lean.version && lean.finished)
return { state: c.rendered.some((r) => !r) ? "rendering" : "settled", checked: c };
return { state: lean.ready ? "checking" : "down" };
}
// What the agent knows of the buffer when a turn starts.
//
// first it has not had a turn since catpad started or the conversation was reset
// restored the pad was put back from its history since its last turn
// same nobody has changed the buffer since its last turn
// typed the user has, in the editor
// drawn the user has, in the diagram pane (and perhaps in the editor too)
type AgentView = "first" | "restored" | "same" | "typed" | "drawn";
function agentView(): AgentView {
if (pad.restored) return "restored";
if (pad.afterTurn == null) return "first";
if (pad.drawn.length) return "drawn";
return pad.afterTurn === pad.code ? "same" : "typed";
}
// A range the prelude reported, moved from the document's lines to the buffer's.
const shift = (r: any) => (r ? { ...r, line: r.line - 1, endLine: r.endLine - 1 } : r);
function digest(ev: { version: number; ms: number; messages: Msg[]; failed?: boolean }, code: string): Checked {
const specs: Spec[] = [];
const messages = ev.messages.filter((x) => {
if (x.severity !== "information" || !x.text.startsWith(MARK)) return true;
try {
const spec = JSON.parse(x.text.slice(MARK.length));
spec.range = shift(spec.range);
spec.titleAt = shift(spec.titleAt);
for (const it of spec.items) for (const k of ["range", "item", "decl", "at"]) it[k] = shift(it[k]);
specs.push(spec);
} catch {}
return false;
});
const sources = specs.map(tikz);
const renders = sources.map(render);
const rendered: (Rendered | undefined)[] = sources.map(() => undefined);
renders.forEach((p, i) => p.then((r) => { rendered[i] = r; }));
return { version: ev.version, code, ms: ev.ms, failed: !!ev.failed, messages, specs, sources, renders, rendered };
}
// Waiting for a check to finish. Lean can report "done" more than once as
// trailing diagnostics arrive, so a waiter resolves once no more has come for
// SETTLE_MS, and after the diagrams' TeX is rendered.
type Outcome = { ok: true; checked: Checked } | { ok: false; reason: string };
const SETTLE_MS = 300;
interface Waiter { version: number; timer?: Timer; deadline: Timer; resolve: (o: Outcome) => void }
const waiters = new Set<Waiter>();
function settle(w: Waiter) {
clearTimeout(w.timer);
w.timer = setTimeout(async () => {
const c = pad.last;
if (!c || c.version !== w.version) return;
await Promise.all(c.renders);
if (!waiters.has(w)) return;
if (lean.version !== w.version || pad.last !== c) {
if (lean.version !== w.version) finishWaiter(w, { ok: false, reason: superseded });
else settle(w); // another "done" came in while TeX ran
return;
}
finishWaiter(w, { ok: true, checked: c });
}, SETTLE_MS);
}
function finishWaiter(w: Waiter, o: Outcome) {
if (!waiters.delete(w)) return;
clearTimeout(w.timer);
clearTimeout(w.deadline);
w.resolve(o);
}
const superseded = "The buffer changed (the user edited it) before Lean finished checking this version. Call read_pad to see the buffer as it is now.";
function waitFor(version: number): Promise<Outcome> {
return new Promise((resolve) => {
const w: Waiter = {
version, resolve,
deadline: setTimeout(() => finishWaiter(w, { ok: false, reason: `Lean did not finish checking within ${(TIMEOUT_MS + 20000) / 1000} s.` }), TIMEOUT_MS + 20000),
};
waiters.add(w);
if (lean.version !== version) finishWaiter(w, { ok: false, reason: superseded });
else if (pad.last?.version === version && lean.finished) settle(w);
});
}
// Sends a buffer to Lean. Every caller goes through here, so a new version
// supersedes whoever was waiting for an older one.
async function submit(code: string): Promise<number> {
const v = await lean.check(code);
for (const w of waiters) if (w.version < v) finishWaiter(w, { ok: false, reason: superseded });
return v;
}
// The check of the buffer as it is now, starting one if nobody has.
async function current(): Promise<Outcome> {
for (let attempt = 0; attempt < 3; attempt++) {
let v: number;
const now = padCheck().state;
if (now === "rendering" || now === "settled" || (lean.code === pad.code && lean.ready)) v = lean.version;
else {
try { v = await submit(pad.code); } catch (e: any) { return { ok: false, reason: String(e?.message ?? e) }; }
}
const o = await waitFor(v);
if (o.ok || o.reason !== superseded) return o;
}
return { ok: false, reason: "The user keeps editing the buffer; Lean has not caught up. Try again in a moment." };
}
// ---------- sockets ----------
const sockets = new Set<any>();
const broadcast = (m: object) => { const s = JSON.stringify(m); for (const ws of sockets) ws.send(s); };
// There is one document, so one page drives it at a time: whichever sent the
// last buffer. `seq` is that page's own counter for the buffer.
let owner: { ws: any; seq: number; version: number } | null = null;
let lastProgress = 0;
lean.listener = (ev) => {
if (ev.type === "down") {
// Lean went away (it ran out of memory, or was killed). Start another; the page asks again when it is up.
console.error("lean: the language server exited, starting another");
broadcast({ type: "status", ready: false });
for (const w of waiters) finishWaiter(w, { ok: false, reason: "The Lean server exited (out of memory, or killed). It is starting again; try again in a moment." });
setTimeout(() => lean.start().then(() => broadcast({ type: "status", ready: lean.ready, error: lean.error })), 500);
return;
}
if (ev.type === "progress") {
for (const w of waiters) if (w.version === ev.version) clearTimeout(w.timer);
if (!owner || ev.version !== owner.version) return;
if (Date.now() - lastProgress < 80) return;
lastProgress = Date.now();
owner.ws.send(JSON.stringify({ type: "progress", seq: owner.seq, line: ev.line }));
return;
}
const code = ev.version === lean.version ? lean.code ?? "" : "";
const c = digest(ev, code);
if (ev.version === lean.version) pad.last = c;
for (const w of waiters) if (w.version === ev.version) settle(w);
if (!owner || ev.version !== owner.version) return;
const { ws, seq } = owner;
ws.send(JSON.stringify({ type: "lean", seq, ms: c.ms, failed: c.failed, messages: c.messages, diagrams: c.specs.map((s, i) => ({ ...s, key: "d" + sha(c.sources[i]), tikz: c.sources[i], unit: UNIT })) }));
c.renders.forEach(async (p, index) => {
const out = await p;
ws.send(JSON.stringify({ type: "svg", seq, index, key: "d" + sha(c.sources[index]), ...out }));
});
};
// ---------- the agent's tools ----------
const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
const numbered = (code: string) => {
const lines = code.split("\n");
const w = String(lines.length).length;
return lines.map((l, i) => `${String(i + 1).padStart(w)} | ${l}`).join("\n");
};
const string) => s.replace(/\s+/g, " ").trim();
const cut = (s: string, n: number) => (s.length > n ? s.slice(0, n) + `\n… (${s.length - n} more characters)` : s);
function counts(c: Checked) {
const errors = c.messages.filter((m) => m.severity === "error").length;
const warnings = c.messages.filter((m) => m.severity === "warning").length;
return { errors, warnings };
}
// What Lean made of the buffer, for the agent. Lines are 1-based like the
// editor's gutter, columns 0-based.
async function report(c: Checked): Promise<string> {
const lines = c.code.split("\n");
const { errors, warnings } = counts(c);
const infos = c.messages.length - errors - warnings;
const rendered = await Promise.all(c.renders);
const texErrors = rendered.filter((r) => r.error).length;
const out: string[] = [];
out.push(
(errors ? `Lean: ${plural(errors, "error")}` : "Lean: no errors") +
(warnings ? `, ${plural(warnings, "warning")}` : "") +
(infos ? `, ${plural(infos, "info message")}` : "") +
`. ${plural(c.specs.length, "diagram")}` +
(texErrors ? `, ${texErrors} failed to render` : "") +
`. (${c.ms} ms)`,
);
if (c.failed) out.push("The check did not finish: see the error below.");
if (c.messages.length) {
out.push("", "Messages (line:column, lines 1-based, columns 0-based):");
const shown = c.messages.slice(0, 40);
for (const m of shown) {
const l = (m.line ?? 0) + 1;
out.push(`- ${l}:${m.ch ?? 0} ${m.severity}: ${cut(m.text.trim(), 1500).replace(/\n/g, "\n ")}`);
const src = lines[m.line ?? 0];
if (src != null && src.trim()) out.push(` ${l} | ${src}`);
}
if (c.messages.length > shown.length) out.push(`- … and ${c.messages.length - shown.length} more`);
}
if (c.specs.length) {
out.push("", "Diagrams (each item: its line, what it is bound to, and [its state: ok, hole, open, MISMATCH or ERROR, with the reason]):");
c.specs.forEach((s, i) => {
out.push(diagramHead(s, i));
for (const it of s.items) out.push(" - " + itemLine(it, c.code));
const rr = rendered[i];
out.push(rr.error ? ` TeX failed: ${cut(rr.error.trim(), 600).replace(/\n/g, "\n ")}` : " TeX: rendered.");
});
}
return out.join("\n");
}