visualproof 0.5.0 → 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.
Files changed (107) hide show
  1. package/README.md +2 -2
  2. package/dist/assets/tips/phone-fingers.light.mp4 +0 -0
  3. package/dist/assets/tips/phone-fingers.light.webp +0 -0
  4. package/dist/assets/tips/tour-agent.webp +0 -0
  5. package/dist/assets/tips/tour-arrange.webp +0 -0
  6. package/dist/assets/tips/tour-artwork.webp +0 -0
  7. package/dist/assets/tips/tour-checks.webp +0 -0
  8. package/dist/assets/tips/tour-keys.webp +0 -0
  9. package/dist/assets/tips/tour-library.webp +0 -0
  10. package/dist/assets/tips/tour-project.webp +0 -0
  11. package/dist/assets/tips/tour-review.webp +0 -0
  12. package/dist/assets/tips/tour-share.webp +0 -0
  13. package/dist/assets/tips/tour-source.webp +0 -0
  14. package/dist/assets/tips/tour-target.webp +0 -0
  15. package/dist/assets/tips/tour-view.webp +0 -0
  16. package/dist/assets/tips/tour.json +125 -115
  17. package/dist/assets/tips/tour.webp +0 -0
  18. package/dist/extractor/Extract.lean +13 -3
  19. package/dist/mcp/visualproof-mcp.mjs +20 -9
  20. package/dist/server/access.js +28 -0
  21. package/dist/server/agent.js +130 -2819
  22. package/dist/server/agentactivity.js +72 -0
  23. package/dist/server/agentadvice.js +115 -0
  24. package/dist/server/agentdocs.js +1 -1
  25. package/dist/server/agententry.js +180 -0
  26. package/dist/server/agentexport.js +469 -0
  27. package/dist/server/agentfollow.js +384 -0
  28. package/dist/server/agentgraph.js +128 -0
  29. package/dist/server/agentlean.js +144 -0
  30. package/dist/server/agentlibrary.js +1 -1
  31. package/dist/server/agentplaces.js +242 -0
  32. package/dist/server/agentread.js +569 -0
  33. package/dist/server/agenttalk.js +282 -0
  34. package/dist/server/agenttcb.js +378 -0
  35. package/dist/server/agentviews.js +2 -2
  36. package/dist/server/app.js +377 -0
  37. package/dist/server/appaccess.js +127 -0
  38. package/dist/server/appagent.js +110 -0
  39. package/dist/server/appgraph.js +176 -0
  40. package/dist/server/appshare.js +179 -0
  41. package/dist/server/appsite.js +120 -0
  42. package/dist/server/apptalk.js +178 -0
  43. package/dist/server/artcmd.js +1 -1
  44. package/dist/server/askfollow.js +1 -1
  45. package/dist/server/deploy.js +204 -53
  46. package/dist/server/events.js +1 -1
  47. package/dist/server/history.js +51 -3
  48. package/dist/server/historyapi.js +34 -2
  49. package/dist/server/hover.js +11 -7
  50. package/dist/server/identity.js +1 -1
  51. package/dist/server/invites.js +113 -20
  52. package/dist/server/libraryroute.js +3 -3
  53. package/dist/server/live.js +186 -30
  54. package/dist/server/main.js +31 -1613
  55. package/dist/server/mcptools.js +33 -20
  56. package/dist/server/options.js +350 -0
  57. package/dist/server/outside.js +311 -0
  58. package/dist/server/pastdoc.js +22 -3
  59. package/dist/server/presence.js +3 -3
  60. package/dist/server/project.js +28 -4
  61. package/dist/server/prompt.js +8 -3
  62. package/dist/server/readonlygate.js +4 -4
  63. package/dist/server/reviewapi.js +51 -17
  64. package/dist/server/send.js +259 -0
  65. package/dist/server/talk.js +238 -116
  66. package/dist/server/tokens.js +13 -5
  67. package/dist/server/view.js +3 -1
  68. package/dist/server/views.js +1 -1
  69. package/dist/shared/artrecipe.js +3 -3
  70. package/dist/shared/build.js +35 -1
  71. package/dist/shared/collab.js +9 -1
  72. package/dist/shared/comment.js +1 -1
  73. package/dist/shared/doc/build.js +30 -14
  74. package/dist/shared/doc/latex.js +7 -2
  75. package/dist/shared/doc/model.js +4 -2
  76. package/dist/shared/doc/sections.js +21 -4
  77. package/dist/shared/keys.js +66 -37
  78. package/dist/shared/lostfound.js +1 -0
  79. package/dist/shared/mentions.js +83 -0
  80. package/dist/shared/outside.js +16 -0
  81. package/dist/shared/pastgraph.js +11 -2
  82. package/dist/shared/query.js +13 -4
  83. package/dist/shared/review.js +91 -21
  84. package/dist/shared/reviewqueue.js +6 -1
  85. package/dist/shared/scope.js +1 -1
  86. package/dist/web/bundle/app.js +51289 -49853
  87. package/dist/web/index.html +45 -9
  88. package/dist/web/src/reviewqueue.js +52 -19
  89. package/dist/web/src/selection.js +1 -1
  90. package/dist/web/src/theme.js +1 -1
  91. package/dist/web/src/trust.js +271 -0
  92. package/dist/web/src/visitors.js +1 -1
  93. package/dist/web/style.css +181 -70
  94. package/docs/agent-api/README.md +13 -11
  95. package/docs/agent-api/advice.md +8 -2
  96. package/docs/agent-api/export.md +9 -6
  97. package/docs/agent-api/following.md +11 -12
  98. package/docs/agent-api/history.md +6 -3
  99. package/docs/agent-api/mcp.md +15 -15
  100. package/docs/agent-api/notes.md +1 -1
  101. package/docs/agent-api/reading.md +10 -4
  102. package/docs/agent-api/requests.md +12 -15
  103. package/docs/agent-api/talking.md +60 -55
  104. package/docs/agent-api/tcb.md +21 -21
  105. package/docs/agent-api/views.md +3 -4
  106. package/docs/agent-api/words.md +8 -8
  107. package/package.json +2 -1
@@ -0,0 +1,384 @@
1
+ // Following (docs/agent-api/following.md; AgentSpec decisions 1 and 7, CollabSpec decision 4), the
2
+ // endpoints of server/agent.ts: who is on the page and where each one looks (the companion), where the
3
+ // agent looks itself, which those following it see, and a link that opens exactly that; and a place
4
+ // in words, as the companion and the conversations tell it (placeOf).
5
+ import { ACTIVITY_KINDS, ACTIVITY_WHO, cleanView, MAX_PINNED, SCHEMES, validName } from "../shared/collab.js";
6
+ import { addressOf, readRegion, showing, writeSnapshot } from "../shared/sharesnap.js";
7
+ import { parseQuery, printQuery, QueryError } from "../shared/query.js";
8
+ import { fileOf, linkOf } from "../shared/library.js";
9
+ import { PROJECT, titleOfScope, viewTitle } from "../shared/views.js";
10
+ import { focusOf, titleContext } from "./agentviews.js";
11
+ import { agentKey } from "./presence.js";
12
+ import { View } from "./agentgraph.js";
13
+ import { body, clampInt, fail, needAgent, ok, str, whoOf } from "./agent.js";
14
+ /** Who is on the page and where each one is (AgentSpec decision 7): every person, with the place
15
+ * of their liveliest page, and the agents present; and how many private readers are here, who
16
+ * are not listed (CollabSpec decision 8). With `wait`, the answer waits until someone comes,
17
+ * goes or moves (the revision is not `since` any more), up to that many seconds. */
18
+ export async function companion(api, a) {
19
+ const P = api.world.presence;
20
+ const rawSince = a.query.get("since");
21
+ const wait = clampInt(a.query.get("wait"), 0, 0, MAX_COMPANION_WAIT);
22
+ let since = null;
23
+ if (rawSince !== null && rawSince.trim() !== "") {
24
+ since = Number(rawSince);
25
+ if (!Number.isInteger(since) || since < 0)
26
+ return fail(400, "since is a revision: the rev of an earlier answer.", "GET /api/agent/companion answers with rev; ask ?wait=30&since=<that rev> to wait for the next change.");
27
+ }
28
+ if (wait > 0)
29
+ await P.waitChange(since ?? P.rev, wait * 1000);
30
+ const mine = a.caller.kind === "agent" && a.caller.name ? agentKey(whoOf(a.caller)) : null;
31
+ const peers = P.list();
32
+ const people = new Map();
33
+ const agents = [];
34
+ for (const p of peers) {
35
+ if (p.agent) {
36
+ agents.push({ name: p.name, idle: p.idle, ...(p.talk ? { state: p.talk.state, ...(p.talk.status ? { status: p.talk.status } : {}), lastSeen: p.talk.lastSeen } : {}), ...(p.id === mine ? { you: true } : {}), place: p.view ? placeOf(api, p.view) : null });
37
+ continue;
38
+ }
39
+ const key = p.name ? `n:${p.name}` : `s:${p.id}`;
40
+ people.set(key, [...(people.get(key) ?? []), p]);
41
+ }
42
+ const out = [...people.values()].map((ps) => {
43
+ ps.sort((x, y) => Number(x.idle) - Number(y.idle));
44
+ const p = ps[0];
45
+ return { name: p.name, ...(p.verified ? { verified: true } : {}), idle: ps.every((x) => x.idle), pages: ps.length, place: p.view ? placeOf(api, p.view) : null };
46
+ });
47
+ out.sort((x, y) => Number(x.idle) - Number(y.idle) || (x.name ?? "\uffff").localeCompare(y.name ?? "\uffff"));
48
+ // the person who shared with this agent, and whether they are here: the prompt does not say
49
+ // where they are, this does
50
+ const by = a.caller.token?.by;
51
+ const sharedBy = by ? { name: by, here: out.some((p) => p.name === by) } : null;
52
+ return ok({
53
+ rev: P.rev,
54
+ ...(since !== null ? { changed: P.rev !== since } : {}),
55
+ now: new Date().toISOString(),
56
+ ...(sharedBy ? { sharedBy } : {}),
57
+ ...(sharedBy && !sharedBy.here ? { sharedByNote: `${by}, who shared with you, has no page open now: go on with what they asked; ?wait=60&since=<rev> tells you when someone comes.` } : {}),
58
+ people: out,
59
+ privateCount: P.privateCount(),
60
+ agents,
61
+ note: "privateCount: how many people are here privately — not listed, not followable, nothing known of where they are. Each person's place is that of their liveliest page: the view, the tool (how a click selects), what is selected (a query), the declaration their panel tells of, whether its source window is open (and collapsed), the source windows they pinned (pinned: declaration, collapsed), and, where their page says them, Activity (open, kind, who, mine: whose targets), the lost-and-found (lostAndFound.open), the colouring (kind or status), edges — all of which those following them see too. idle: no input for five minutes, or the page in the background. verified: invited by a personal link, so the name is theirs. To look where someone looks, POST /api/agent/view with their view and declaration; ?wait=<s>&since=<rev> waits for the next change (at most 60 s).",
62
+ });
63
+ }
64
+ /** A page's or an agent's place, as the companion tells it (and a conversation's message, where
65
+ * its writer was): with its source windows, the one following the selection and those pinned,
66
+ * each collapsed or not (decided 2026-10-09: what a follower's windows mirror), the build it
67
+ * browses in the Time Machine (HistorySpec decision 18), and what else those following it see
68
+ * (CollabSpec decision 4, the owner's decision of 2026-10-11): Activity and its filters, the
69
+ * lost-and-found, the colouring, the edges — each where the page says it (an agent says none). */
70
+ export function placeOf(api, v) {
71
+ const on = v.view ? api.world.views.book.get(v.view) : undefined;
72
+ const titles = titleContext(api.world);
73
+ // a view nobody keeps that the server forgot is called by its query, as a page calls it
74
+ const title = on ? viewTitle(on, titles) : v.scope ? titleOfScope(v.scope, titles) : v.view ? null : "Project";
75
+ const tool = TOOL_NAMES[v.mode] ?? v.mode;
76
+ const words = (on && on.id !== PROJECT ? `the view ${JSON.stringify(title)}` : v.scope ? `a view on ${v.scope}` : "the Project view") +
77
+ (on?.targets ? `, ${on.targets.join(" and ")}'s view` : "") +
78
+ (v.focus !== undefined ? (v.focus ? `, focused on ${v.focus} for themselves` : ", with no focus for themselves") : "") +
79
+ (v.sel ? `, ${v.source ? "reading the source of" : "looking at"} ${v.sel}` : "") +
80
+ (v.selection ? `, with ${v.selection} selected` : "") +
81
+ (v.pinned?.length ? `, with the source of ${v.pinned.map((w) => w.decl).join(", ")} pinned` : "");
82
+ const built = v.history ? api.world.history?.get(v.history.snapshot)?.at ?? null : null;
83
+ const then = v.history ? `, in the Time Machine at snapshot ${v.history.snapshot}${built ? ` (built ${built})` : ""}` : "";
84
+ // the panels and the board besides, in words where they are not as a page starts
85
+ const a = v.activity;
86
+ const shownBy = a?.open
87
+ ? `, with Activity open${a.kind !== "all" ? ` on ${ACTIVITY_WORDS[a.kind]}` : ""}${a.who !== "all" ? `, ${a.who} only` : ""}${a.mine ? `, on ${a.mine}'s targets` : ""}`
88
+ : v.lostFound?.open
89
+ ? ", with the lost-and-found open"
90
+ : "";
91
+ const drawn = (v.scheme ? `, coloured by ${v.scheme}` : "") + (v.edges === false ? ", edges hidden" : "");
92
+ return {
93
+ view: v.view ?? PROJECT,
94
+ viewTitle: title,
95
+ ...(on?.targets ? { targets: [...on.targets] } : {}),
96
+ ...(v.scope ? { scope: v.scope } : {}),
97
+ mode: v.mode,
98
+ tool,
99
+ selection: v.selection ?? null,
100
+ declaration: v.sel,
101
+ source: v.source,
102
+ sourceCollapsed: v.source && v.sourceCollapsed === true,
103
+ pinned: (v.pinned ?? []).map((w) => ({ declaration: w.decl, collapsed: w.collapsed })),
104
+ ...(v.history ? { history: { snapshot: v.history.snapshot, built } } : {}),
105
+ ...(v.activity ? { activity: { ...v.activity } } : {}),
106
+ ...(v.lostFound ? { lostAndFound: { open: v.lostFound.open } } : {}),
107
+ ...(v.scheme ? { colouring: v.scheme } : {}),
108
+ ...(v.edges !== undefined ? { edges: v.edges } : {}),
109
+ inWords: words + then + shownBy + drawn + ".",
110
+ };
111
+ }
112
+ export function viewPost(api, a) {
113
+ const no = needAgent(a.caller);
114
+ if (no)
115
+ return no;
116
+ const me = whoOf(a.caller);
117
+ const b = body(a);
118
+ if (b.leave === true) {
119
+ // an agent with a token that leaves is offline until it listens or asks again — unless its
120
+ // MCP server says it is a session that a newer one replaced, which goes on
121
+ if (a.caller.token && api.world.talk && !api.world.talk.left(a.caller.token.id, a.session ?? null))
122
+ return ok({ ok: true, left: false, note: "Another session of your token listens now: it stays." });
123
+ api.world.presence.drop(agentKey(me));
124
+ return ok({ ok: true, left: true });
125
+ }
126
+ const p = goingTo(api, a, b);
127
+ if ("status" in p)
128
+ return p;
129
+ const { place: clean, temporary } = p;
130
+ api.world.presence.agentBeat(me, clean);
131
+ // what people who follow it see, said in words: the view, whose view it is (ViewSpec decision
132
+ // 29), and the review's focus there — the agent's own, else the view's (decision 28)
133
+ const on = clean.view ? api.world.views.book.get(clean.view) : undefined;
134
+ const review = on?.targets ?? null;
135
+ const focus = clean.focus !== undefined ? clean.focus : on ? focusOf(api.world, on) : null;
136
+ const board = (on && on.id !== PROJECT ? `the view ${JSON.stringify(viewTitle(on, titleContext(api.world)))}` : "the Project view: everything") +
137
+ (review ? `, ${review.join(" and ")}'s view` : "") +
138
+ (focus ? `, the review focused on ${focus} with its strip (its whole review set, what the board does not hold shown as visitors)` : "");
139
+ const paperFile = clean.paper ? fileOf(api.world.review.data, clean.paper.file) : null;
140
+ const sel = (clean.sel ? `, looking at ${clean.sel}${clean.source ? " with its source open" : ""}` : "") +
141
+ (clean.selection ? `, with ${clean.selection} selected` : "") +
142
+ (paperFile ? `, with the reference window on ${JSON.stringify(paperFile.title)}${clean.paper.page ? ` at page ${clean.paper.page}` : ""}${clean.paper.link ? ", the link lit" : ""}` : "");
143
+ return ok({
144
+ ok: true,
145
+ view: clean,
146
+ reviewView: review,
147
+ followersSee: `${board}${sel}.`,
148
+ ...(temporary ? { temporary: true, note: `${temporary} had no view: you are on a temporary view of its TCB, linked to it, as a person's click on it opens. The link lasts as long as the view: it goes when nobody is on it, unless someone keeps it — pins, folds or names it (views/arrange, views/rename) — and with it the link. POST /api/agent/views/link {id, target} links ${temporary} to another view.` } : {}),
149
+ });
150
+ }
151
+ /** Where the agent would be with the fields of `b` over its own place, each checked as POST view
152
+ * takes it: where POST view puts it, and what POST view/link makes a link to. */
153
+ function goingTo(api, a, b) {
154
+ const v = api.graph();
155
+ if (!(v instanceof View))
156
+ return v;
157
+ const was = api.world.presence.agentView(whoOf(a.caller)) ?? { mode: "tcb", sel: null, source: false, clusterMode: "namespace", cam: null, view: null, scope: null, tabs: [] };
158
+ const next = { ...was, cam: null };
159
+ if (b.mode !== undefined) {
160
+ if (typeof b.mode !== "string" || !Object.hasOwn(TOOL_NAMES, b.mode))
161
+ return fail(400, "mode is plain, deps, tcb, keys or apps.", "deps, tcb and keys are the steps of Rests on: what it uses, its TCB, the key declarations in its TCB; apps is what uses it.");
162
+ next.mode = b.mode;
163
+ }
164
+ /** On a view (ViewSpec.md), as a page is: people following go to it, and a view nobody keeps
165
+ * lives while the agent is there. */
166
+ const onView = (id) => {
167
+ const w = api.world.views.book.get(id);
168
+ if (!w)
169
+ return fail(404, `There is no view ${id}.`, "GET /api/agent/views lists them; POST /api/agent/views/open opens one on a query.");
170
+ Object.assign(next, { view: w.id, scope: w.kept ? null : printQuery(w.scope), clusterMode: w.clustering, tabs: [...new Set([...next.tabs, w.id])].slice(-20) });
171
+ return null;
172
+ };
173
+ if (b.view !== undefined) {
174
+ const bad = b.view === null ? onView(PROJECT) : typeof b.view === "string" ? onView(b.view) : fail(400, "view is a view's id, or null for the Project.", "GET /api/agent/views lists them.");
175
+ if (bad)
176
+ return bad;
177
+ }
178
+ // a target with no view, asked for (`review`): the view nobody keeps a click on it opens
179
+ let temporary = null;
180
+ if (b.review !== undefined) {
181
+ // a target's view, the one it is linked to (ViewSpec decision 29), as a click on the target
182
+ // opens it; with none, a view nobody keeps of its TCB, linked to it while it lasts (the owner's
183
+ // decision of 2026-10-11)
184
+ if (b.review === null) {
185
+ if (next.view && api.world.views.book.get(next.view)?.targets)
186
+ onView(PROJECT);
187
+ }
188
+ else {
189
+ const t = api.find(v, str(b.review), "review");
190
+ if (typeof t !== "number")
191
+ return t;
192
+ const target = v.g.nodes[t].name;
193
+ if (!api.world.review.data.targets[target])
194
+ return fail(400, `${target} is not a target: it has no view of its own.`, "GET /api/agent/targets lists the targets; POST /api/agent/views/open opens a view on tcb(<name>) for anything else.");
195
+ const linked = api.world.views.book.viewOf(target);
196
+ if (!linked)
197
+ temporary = target;
198
+ const bad = onView((linked ?? api.world.views.openTarget(target, a.caller.name, true)).id);
199
+ if (bad)
200
+ return bad;
201
+ next.mode = "tcb";
202
+ }
203
+ }
204
+ if (b.sel !== undefined) {
205
+ if (b.sel === null)
206
+ next.sel = null;
207
+ else {
208
+ const j = api.find(v, str(b.sel), "sel");
209
+ if (typeof j !== "number")
210
+ return j;
211
+ next.sel = v.g.nodes[j].name;
212
+ }
213
+ }
214
+ if (b.selection !== undefined) {
215
+ // what a page selects is a query (web/src/selection.ts): people who follow select the same
216
+ if (b.selection === null)
217
+ next.selection = null;
218
+ else {
219
+ const hint = "A query's text, its parts joined by or: decl(A.b) or tcb(A.c) or tcb(ns(A.D) except external).";
220
+ if (typeof b.selection !== "string")
221
+ return fail(400, "selection is a query's text, or null.", hint);
222
+ try {
223
+ next.selection = printQuery(parseQuery(b.selection));
224
+ }
225
+ catch (e) {
226
+ if (!(e instanceof QueryError))
227
+ throw e;
228
+ return fail(400, `selection: at ${e.at + 1}, ${e.message}.`, hint);
229
+ }
230
+ }
231
+ }
232
+ if (b.source !== undefined)
233
+ next.source = b.source === true;
234
+ // its own focus on its view, as a person's (ViewSpec decision 28): those following it take it;
235
+ // on another view it starts from that view's own
236
+ if (b.focus !== undefined) {
237
+ // a tool's arguments say "view" and "none" where JSON says false and null
238
+ if (b.focus === false || b.focus === "view")
239
+ delete next.focus;
240
+ else if (b.focus === null || b.focus === "none")
241
+ next.focus = null;
242
+ else {
243
+ const t = api.find(v, str(b.focus), "focus");
244
+ if (typeof t !== "number")
245
+ return t;
246
+ const target = v.g.nodes[t].name;
247
+ if (!Object.hasOwn(api.world.review.data.targets, target))
248
+ return fail(400, `${target} is not a target: nothing can be focused on it.`, "GET /api/agent/targets lists the targets.");
249
+ next.focus = target;
250
+ }
251
+ }
252
+ else if (next.view !== was.view)
253
+ delete next.focus;
254
+ // the reference window shown to those who follow (AttachmentSpec decision 20): a link's place,
255
+ // or a file of the library at a page; null closes it
256
+ if (b.paper !== undefined) {
257
+ const p = paperOf(api.world.review.data, b.paper);
258
+ if (typeof p === "string")
259
+ return fail(400, p, "paper is {link} (a link's id: its file at its place, lit), or {file, page?} (a file's SHA-256 and a page from 1), or null to close the window.");
260
+ if (p)
261
+ next.paper = p;
262
+ else
263
+ delete next.paper;
264
+ }
265
+ return { place: cleanView(next), temporary };
266
+ }
267
+ /** A link to what the agent looks at, or to a place it gives over its own, as a person's Share makes
268
+ * one with Exactly what I see (CollabSpec decision 7, the owner's decision of 2026-10-12): the
269
+ * address, and after it a snapshot of everything followed, which the page that opens it applies
270
+ * once. It moves nobody, the agent neither. It holds no key: it opens for whoever is let in. */
271
+ export async function viewLink(api, a) {
272
+ const no = needAgent(a.caller);
273
+ if (no)
274
+ return no;
275
+ const b = body(a);
276
+ const p = goingTo(api, a, b);
277
+ if ("status" in p)
278
+ return p;
279
+ const v = api.graph();
280
+ if (!(v instanceof View))
281
+ return v;
282
+ const place = { ...p.place };
283
+ // what a page shows besides, which an agent's own place says nothing of: each as given, checked
284
+ const bool = (k) => {
285
+ if (b[k] === undefined)
286
+ return null;
287
+ if (typeof b[k] !== "boolean")
288
+ return fail(400, `${k} is true or false.`, "Leave it out for what the opener's page shows of its own.");
289
+ place[k] = b[k];
290
+ return null;
291
+ };
292
+ // (proofEdges, said until 2026-10-15, is no more: left as it is, as any word not known)
293
+ const bad = bool("sourceCollapsed") ?? bool("edges");
294
+ if (bad)
295
+ return bad;
296
+ if (b.lostFound !== undefined) {
297
+ if (typeof b.lostFound !== "boolean")
298
+ return fail(400, "lostFound is true (open) or false.", "The lost-and-found has no filters.");
299
+ place.lostFound = { open: b.lostFound };
300
+ }
301
+ if (b.scheme !== undefined) {
302
+ if (!SCHEMES.includes(b.scheme))
303
+ return fail(400, `scheme is ${SCHEMES.join(" or ")}.`, "The legend's colouring: by kind, or by the review's status.");
304
+ place.scheme = b.scheme;
305
+ }
306
+ if (b.activity !== undefined) {
307
+ const o = b.activity && typeof b.activity === "object" ? b.activity : null;
308
+ const kind = o?.kind ?? "all", who = o?.who ?? "all";
309
+ if (!o || typeof o.open !== "boolean" || !ACTIVITY_KINDS.includes(kind) || !ACTIVITY_WHO.includes(who) || (o.mine !== undefined && (typeof o.mine !== "string" || !validName(o.mine))))
310
+ return fail(400, "activity is {open, kind?, who?, mine?}.", `open: true or false; kind: ${ACTIVITY_KINDS.join(", ")}; who: ${ACTIVITY_WHO.join(", ")}; mine: the name whose targets "My targets" keeps to.`);
311
+ place.activity = { open: o.open, kind, who, ...(o.mine !== undefined ? { mine: o.mine } : {}) };
312
+ }
313
+ if (b.pinned !== undefined) {
314
+ if (!Array.isArray(b.pinned) || b.pinned.length > MAX_PINNED)
315
+ return fail(400, `pinned is a list of at most ${MAX_PINNED} windows, [{name, collapsed?}].`, "Each a source window pinned on a declaration, the first pinned first.");
316
+ const pinned = [];
317
+ for (const w of b.pinned) {
318
+ const i = api.find(v, w && typeof w === "object" ? str(w.name) : null, "pinned's name");
319
+ if (typeof i !== "number")
320
+ return i;
321
+ pinned.push({ decl: v.g.nodes[i].name, collapsed: w.collapsed === true });
322
+ }
323
+ place.pinned = pinned;
324
+ }
325
+ if (b.history !== undefined && b.history !== null) {
326
+ const id = b.history;
327
+ if (!Number.isInteger(id) || !api.world.history?.get(id))
328
+ return fail(404, `There is no snapshot ${String(id)}.`, "history is a snapshot's id (GET /api/agent/history): the link opens the Time Machine at that build; null or left out for none.");
329
+ place.history = { snapshot: id };
330
+ }
331
+ let region = null;
332
+ if (b.region !== undefined && b.region !== null) {
333
+ region = readRegion(b.region);
334
+ if (!region)
335
+ return fail(400, "region is [x, y, w, h]: a centre and a width and height, in the board's world.", "Leave it out, and the opener's page frames the board as for any link.");
336
+ }
337
+ const view = cleanView(place);
338
+ const exact = b.exact !== false;
339
+ // the build a view nobody keeps shows travels with its query, in the address
340
+ const rec = view.view ? api.world.views.book.get(view.view) : undefined;
341
+ const address = addressOf({ ...view, version: rec && !rec.kept ? rec.version ?? null : null });
342
+ const shown = region ? showing(region) : null;
343
+ const snap = exact ? await writeSnapshot({ ...view, cam: shown?.cam ?? null }, shown?.screen ?? null) : null;
344
+ const link = `${a.base ?? ""}/#${address}${snap ? `&snap=${snap}` : ""}`;
345
+ const { tabs: _tabs, cam: _cam, ...carried } = view;
346
+ return ok({
347
+ ok: true,
348
+ link,
349
+ exact,
350
+ carries: exact ? { ...carried, ...(region ? { region } : {}) } : { view: view.view, scope: view.scope, mode: view.mode, selection: view.selection ?? null, sel: view.sel },
351
+ length: link.length,
352
+ note: "It holds no key: it opens for whoever is let in already — the people on this page. Opened, the page shows what it carries once, the region given framed on the opener's screen, and the reader is free after; what is no longer there is said in a line. To let someone new in, a person sends the guest link from Share.",
353
+ ...(p.temporary ? { temporary: true } : {}),
354
+ });
355
+ }
356
+ /** the longest the companion waits for someone to move, in seconds */
357
+ const MAX_COMPANION_WAIT = 60;
358
+ /** the tools, how a click selects, as the page names them (web/src/page.ts, MODE_NAME) */
359
+ /** The page's tools by name (web/src/page.ts): the modes Selection and Used by, and the three steps
360
+ * of the mode Rests on, Uses, TCB and Keys (ViewSpec decision 20). */
361
+ const TOOL_NAMES = { plain: "Selection", deps: "Uses", tcb: "TCB", keys: "Keys", apps: "Used by" };
362
+ /** Activity's kinds of event, as its filters name them (web/src/activity.ts) */
363
+ const ACTIVITY_WORDS = { review: "Review", build: "Builds", change: "Changes" };
364
+ /** What `view {paper}` asks the reference window to show: a link's place, or a file at a page; null to
365
+ * close it; or why it cannot. */
366
+ function paperOf(d, raw) {
367
+ if (raw === null || raw === false)
368
+ return null;
369
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
370
+ return "paper is an object.";
371
+ const o = raw;
372
+ if (o.link !== undefined) {
373
+ const l = typeof o.link === "string" ? linkOf(d, o.link) : null;
374
+ if (!l)
375
+ return `There is no link ${String(o.link)}.`;
376
+ return { file: l.file, ...(l.page ? { page: l.page } : {}), link: l.id };
377
+ }
378
+ const f = typeof o.file === "string" ? fileOf(d, o.file) : null;
379
+ if (!f)
380
+ return `The library has no file ${String(o.file)}.`;
381
+ if (o.page !== undefined && (!Number.isInteger(o.page) || o.page < 1 || (f.pages && o.page > f.pages)))
382
+ return `page is 1 to ${f.pages ?? "its last"}.`;
383
+ return { file: f.sha, ...(o.page !== undefined ? { page: o.page } : f.type === "pdf" ? { page: 1 } : {}) };
384
+ }
@@ -0,0 +1,128 @@
1
+ // The graph on show as the agents' API reads it (server/agent.ts and the modules of its endpoints):
2
+ // its declarations and their search index, each module's file and imports, and what the API works
3
+ // out of it and keeps — the Project's layout by its hidden levels, TCBs, review orders.
4
+ import { gunzipSync } from "node:zlib";
5
+ import { inTargets, reviewQueue, TCB_SITES } from "../shared/reviewqueue.js";
6
+ import { SearchIndex } from "../shared/search.js";
7
+ import { Graph } from "../shared/viewgraph.js";
8
+ import { layoutKey, wholeLayout } from "../shared/board.js";
9
+ /** The graph on show, as the API reads it: built from the server's prepared view once per
10
+ * version. The page's review route reads it too (server/reviewapi.ts). */
11
+ export class View {
12
+ version;
13
+ meta;
14
+ g;
15
+ index;
16
+ /** each module's source file (relative to the project), the hash of the text it was compiled
17
+ * from, and what it imports */
18
+ modules = new Map();
19
+ /** per module of the outside world, the project's modules that import it directly, those with
20
+ * the fewest imports first: where Lean is asked about an outside name (leanTarget) */
21
+ importers = null;
22
+ /** the project's root module, which imports all of it: where Lean is asked about a name that is
23
+ * not under any declaration of the graph */
24
+ root;
25
+ /** per way of clustering and levels hidden, the Project's layout and what each of its clusters
26
+ * holds directly (-1: the top), for laying out */
27
+ projects = new Map();
28
+ tcbs = new Map();
29
+ orders = new Map();
30
+ orderKey = "";
31
+ shared = null;
32
+ constructor(version, metaGz, edgesGz) {
33
+ this.version = version;
34
+ this.meta = JSON.parse(gunzipSync(metaGz).toString("utf8"));
35
+ const raw = gunzipSync(edgesGz);
36
+ this.g = new Graph(this.meta, new Int32Array(new Uint8Array(raw).buffer));
37
+ this.index = new SearchIndex(this.meta.nodes, this.meta.projectCount);
38
+ for (const m of this.meta.modules) {
39
+ this.modules.set(m.name, { file: m.file, compiled: m.compiled ?? null, imports: m.imports });
40
+ }
41
+ this.root = this.meta.project.roots.find((r) => this.modules.has(r)) ?? null;
42
+ }
43
+ /** A module of the project's graph where declaration `i` of the outside world is known, and
44
+ * why that one: one that imports its module directly (the fewest imports first), else that of a
45
+ * declaration of the project that refers to it, else the root module, which imports everything
46
+ * the project does. Lean is only ever asked where a module of the graph is imported. */
47
+ homeOf(i) {
48
+ const n = this.g.nodes[i];
49
+ if (!this.importers) {
50
+ this.importers = new Map();
51
+ for (const [name, m] of [...this.modules].sort((a, b) => a[1].imports.length - b[1].imports.length))
52
+ for (const imp of m.imports)
53
+ if (!this.modules.has(imp))
54
+ this.importers.set(imp, [...(this.importers.get(imp) ?? []), name]);
55
+ }
56
+ const direct = this.importers.get(n.module)?.[0];
57
+ if (direct)
58
+ return { module: direct, why: `${direct}, a module of the project that imports ${n.module}, where ${n.name} is declared` };
59
+ for (let e = this.g.inStart[i]; e < this.g.inStart[i + 1]; e++) {
60
+ const u = this.g.inSrc[e];
61
+ if (!this.g.isExt(u))
62
+ return { module: this.g.nodes[u].module, why: `that of ${this.g.nodes[u].name}, a declaration of the project that refers to ${n.name}` };
63
+ }
64
+ return this.root ? { module: this.root, why: "the project's root module, which imports all of it" } : null;
65
+ }
66
+ /** The Project view's layout by `mode` with the levels `hidden` hidden (ViewSpec decision 24): the
67
+ * server's, their circles taken out, as the pages show it. */
68
+ projectLayout(mode, hidden) {
69
+ return this.project(mode, hidden).L;
70
+ }
71
+ /** What a cluster of the Project's layout (projectLayout) holds directly, its declarations and
72
+ * its clusters (-1: the top). */
73
+ inside(mode, hidden, c) {
74
+ return this.project(mode, hidden).children.get(c) ?? { nodes: [], clusters: [] };
75
+ }
76
+ project(mode, hidden) {
77
+ const key = `${mode}\u0000${layoutKey("", hidden)}`;
78
+ let p = this.projects.get(key);
79
+ if (!p) {
80
+ const L = wholeLayout(this.meta.layouts[mode], this.g.nodes, mode, hidden);
81
+ const m = new Map();
82
+ const at = (k) => {
83
+ let x = m.get(k);
84
+ if (!x)
85
+ m.set(k, (x = { nodes: [], clusters: [] }));
86
+ return x;
87
+ };
88
+ L.cluster.forEach((k, i) => at(k).nodes.push(i));
89
+ L.clusters.forEach((cl, k) => at(cl.parent).clusters.push(k));
90
+ // the levels change seldom: the last few are enough
91
+ if (this.projects.size >= 8)
92
+ this.projects.clear();
93
+ this.projects.set(key, (p = { L, children: m }));
94
+ }
95
+ return p;
96
+ }
97
+ /** A declaration's TCB (statement and body references, itself included). */
98
+ tcb(i) {
99
+ let t = this.tcbs.get(i);
100
+ if (!t) {
101
+ t = this.g.reach([i], TCB_SITES, "out");
102
+ if (this.tcbs.size > 64)
103
+ this.tcbs.clear();
104
+ this.tcbs.set(i, t);
105
+ }
106
+ return t;
107
+ }
108
+ /** `root`'s review in review order, the page's (shared/reviewqueue.ts): its review set
109
+ * holds, and the axioms beside it. Worked out again only when the targets or the trusted
110
+ * prefixes change, as on the page. */
111
+ order(root, d) {
112
+ const g = this.g;
113
+ const key = Object.keys(d.targets).sort().join("\n") + "\n\n" + d.trusted.join("\n");
114
+ if (key !== this.orderKey) {
115
+ this.orders.clear();
116
+ this.shared = null;
117
+ this.orderKey = key;
118
+ }
119
+ let o = this.orders.get(root);
120
+ if (!o) {
121
+ const targets = Object.keys(d.targets).map((n) => g.byName.get(n)).filter((i) => i !== undefined);
122
+ this.shared ??= inTargets(g, targets);
123
+ o = reviewQueue(g, d, root, this.shared);
124
+ this.orders.set(root, o);
125
+ }
126
+ return o;
127
+ }
128
+ }
@@ -0,0 +1,144 @@
1
+ // What Lean itself says of a name, the endpoints of server/agent.ts that ask Lean's language server
2
+ // (server/hover.ts): its hover (describe) and what `#print` shows of it (print), asked where a module
3
+ // of the project's graph is imported, and only there — the module is chosen from the graph, and only
4
+ // a name that passes isDeclName is ever written into Lean source.
5
+ import { isDeclName } from "./hover.js";
6
+ import { View } from "./agentgraph.js";
7
+ import { clampInt, fail, flag, ok } from "./agent.js";
8
+ /** The name Lean is asked about and the module imported to ask it: `module` when given (a module
9
+ * of the project's graph), else the declaration's own; for a name the graph does not hold — a
10
+ * constructor, a field, something a macro generated, all folded into the declaration that owns
11
+ * them — the module of the nearest declaration its name is under; else the project's root
12
+ * module, which imports all of it. A declaration of the outside world is asked about where a
13
+ * module of the project imports it (View.homeOf): only the graph's own modules (meta.modules)
14
+ * are ever imported. Only a name that passes isDeclName gets this far: it is written into Lean
15
+ * source. */
16
+ function leanTarget(api, v, q) {
17
+ const name = (q.get("name") ?? "").trim();
18
+ if (!name)
19
+ return fail(400, "name is missing.", "Give name=<a full Lean name>; GET /api/agent/search?q=<words> finds a declaration.");
20
+ if (!isDeclName(name))
21
+ return fail(400, "name is not a Lean name.", "Give a full dotted name and nothing else, e.g. Nat.Prime.eq_one_or_self_of_dvd.");
22
+ const given = q.get("module")?.trim() || null;
23
+ if (given) {
24
+ if (!isDeclName(given) || !v.modules.has(given))
25
+ return fail(400, `${given.slice(0, 300)} is not a module of the project's graph.`, "Give one of the project's modules, or leave module out: the declaration's own is used (for one of the outside world, a module of the project that imports it).");
26
+ return { name, module: given, chosen: "given" };
27
+ }
28
+ const i = v.g.byName.get(name);
29
+ // a notation unit is asked about by its Lean constant: its name is not one
30
+ if (i !== undefined) {
31
+ const lean = v.g.nodes[i].leanName;
32
+ const t = leanHome(api, v, lean ?? name, i, "its own");
33
+ return lean && "module" in t ? { ...t, unit: name } : t;
34
+ }
35
+ // generated from the command that writes a declaration: asked where that one is
36
+ const u = v.g.foldedInto.get(name);
37
+ if (u !== undefined)
38
+ return leanHome(api, v, name, u, `that of ${v.g.nodes[u].name}, the declaration its command writes`, v.g.nodes[u].name);
39
+ for (let k = name.lastIndexOf("."); k > 0; k = name.lastIndexOf(".", k - 1)) {
40
+ const j = v.g.byName.get(name.slice(0, k));
41
+ if (j !== undefined)
42
+ return leanHome(api, v, name, j, `that of ${v.g.nodes[j].name}, the declaration it is under`, v.g.nodes[j].name);
43
+ }
44
+ if (v.root)
45
+ return { name, module: v.root, chosen: "the project's root module, which imports all of it" };
46
+ return api.find(v, name);
47
+ }
48
+ /** Lean asked about `name` where declaration `j` is known: its own module (`own` says so), or for
49
+ * one of the outside world a module of the project that imports it (View.homeOf). */
50
+ export function leanHome(api, v, name, j, own, under) {
51
+ if (!v.g.isExt(j))
52
+ return { name, module: v.g.nodes[j].module, chosen: own, ...(under ? { under } : {}) };
53
+ const h = v.homeOf(j);
54
+ if (!h)
55
+ return fail(404, `There is no module of the project to ask Lean about ${name} in.`, "Give module=<a module of the project that imports it>.");
56
+ return { name, module: h.module, chosen: h.why, ...(under ? { under } : {}) };
57
+ }
58
+ /** Lean says it knows no such name where the module is imported: what was meant, from the graph. */
59
+ function unknownToLean(api, v, t, said) {
60
+ const guesses = [...(t.under ? [t.under] : []), ...api.guess(v, t.name)].filter((x, k, xs) => xs.indexOf(x) === k).slice(0, 5);
61
+ return fail(404, `Lean knows no ${t.name} where ${t.module} is imported.`, t.under
62
+ ? `GET /api/agent/print?name=${encodeURIComponent(t.under)} lists what ${t.under} holds (a structure's fields and constructor); or give the module that declares the name.`
63
+ : guesses.length ? `Did you mean ${guesses[0]}? Or give the module that declares it.` : "Give the module that declares it, or check the name with GET /api/agent/search.", { didYouMean: guesses, ...(said ? { lean: said } : {}) });
64
+ }
65
+ /** Lean is still loading a module's imports: ask again. */
66
+ function loading(api, module, pending) {
67
+ return fail(503, `Lean is still loading the imports of ${module}.`, "Ask again in a few seconds (Retry-After); the first question about a module can take a minute.", { pending, retryAfter: 5 }, { "retry-after": "5" });
68
+ }
69
+ export async function describe(api, a) {
70
+ const v = api.graph();
71
+ if (!(v instanceof View))
72
+ return v;
73
+ const t = leanTarget(api, v, a.query);
74
+ if (!("module" in t))
75
+ return t;
76
+ return describeOf(api, v, t, clampInt(a.query.get("wait"), 20_000, 1000, MAX_WAIT));
77
+ }
78
+ export async function describeOf(api, v, t, wait) {
79
+ if (!api.lean)
80
+ return fail(503, "There is no Lean to ask here.", "GET /api/agent/declaration gives the statement and docstring from the graph.");
81
+ const r = await api.lean.describe(t.module, t.name, wait);
82
+ if (r.pending)
83
+ return loading(api, t.module, r.pending);
84
+ if (r.error)
85
+ return fail(502, `Lean could not answer: ${r.error}`, "GET /api/agent/declaration gives the statement and docstring from the graph.");
86
+ if (!r.contents)
87
+ return unknownToLean(api, v, t, r.refused);
88
+ return ok({ name: t.name, ...(t.unit ? { unit: t.unit } : {}), module: t.module, moduleChosen: t.chosen, inGraph: !!t.unit || v.g.byName.has(t.name), lean: r.contents });
89
+ }
90
+ export async function print(api, a) {
91
+ const v = api.graph();
92
+ if (!(v instanceof View))
93
+ return v;
94
+ const t = leanTarget(api, v, a.query);
95
+ if (!("module" in t))
96
+ return t;
97
+ return printOf(api, v, t, flag(a.query.get("proofs")), clampInt(a.query.get("wait"), 20_000, 1000, MAX_WAIT));
98
+ }
99
+ /** What `#print` shows: the elaborated declaration with its value, every name in full. */
100
+ export async function printOf(api, v, t, proofs, wait) {
101
+ if (!api.lean)
102
+ return fail(503, "There is no Lean to ask here.", "GET /api/agent/source gives the declaration's text.");
103
+ const r = await api.lean.print(t.module, t.name, proofs, wait);
104
+ if (r.pending)
105
+ return loading(api, t.module, r.pending);
106
+ if (r.error || !r.messages)
107
+ return fail(502, `Lean could not answer: ${r.error ?? "no messages"}`, "GET /api/agent/source gives the declaration's text.");
108
+ const errors = r.messages.filter((m) => m.severity === "error");
109
+ if (errors.length) {
110
+ if (errors.some((m) => /unknown (constant|identifier)/i.test(m.text)))
111
+ return unknownToLean(api, v, t, errors[0].text);
112
+ return fail(422, `Lean could not print ${t.name}: ${errors[0].text.slice(0, 500)}`, "GET /api/agent/describe gives its signature; /api/agent/source its text.", { lean: errors.map((m) => m.text.slice(0, 2000)) });
113
+ }
114
+ let text = r.messages.filter((m) => m.severity === "information").map((m) => m.text).join("\n\n");
115
+ const length = text.length;
116
+ // cut at a line's end where there is one near the bound
117
+ if (length > MAX_PRINT) {
118
+ const nl = text.lastIndexOf("\n", MAX_PRINT);
119
+ text = text.slice(0, nl > MAX_PRINT * 0.8 ? nl : MAX_PRINT);
120
+ }
121
+ const warnings = r.messages.filter((m) => m.severity === "warning").map((m) => m.text);
122
+ // what the value is made of that the same command generated (a `module`'s code, a structure's
123
+ // projections): not shown here, and only asked for by name
124
+ const unit = v.g.byName.get(t.unit ?? t.name) ?? v.g.foldedInto.get(t.name);
125
+ const seeAlso = unit === undefined ? [] : (v.g.nodes[unit].also ?? []).filter((x) => x !== t.name && text.includes(x)).slice(0, 20);
126
+ return ok({
127
+ name: t.name,
128
+ // asked by a notation unit's name: `name` is its Lean constant, what Lean answered about
129
+ ...(t.unit ? { unit: t.unit } : {}),
130
+ module: t.module,
131
+ moduleChosen: t.chosen,
132
+ inGraph: !!t.unit || v.g.byName.has(t.name),
133
+ proofs,
134
+ lean: text,
135
+ ...(length > text.length ? { truncated: { shown: text.length, length }, note: proofs ? "Cut short: leave proofs out to see the statement and the definitions' values whole." : "Cut short." } : {}),
136
+ ...(warnings.length ? { warnings } : {}),
137
+ ...(seeAlso.length ? { seeAlso, seeAlsoNote: `This refers to ${seeAlso.join(", ")}, which Lean generated from the same command: GET /api/agent/print?name=<each> shows ${seeAlso.length > 1 ? "them" : "it"}.` } : {}),
138
+ });
139
+ }
140
+ /** the longest Lean is waited for, per question (per request, where one asks several) */
141
+ export const MAX_WAIT = 60_000;
142
+ /** the most of what `#print` says that an answer carries, in UTF-16 units: a theorem's proof term,
143
+ * printed with `proofs=1`, can run to megabytes */
144
+ export const MAX_PRINT = 50_000;