visualproof 0.6.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 (60) hide show
  1. package/README.md +2 -2
  2. package/dist/extractor/Extract.lean +13 -3
  3. package/dist/server/agent.js +102 -2879
  4. package/dist/server/agentactivity.js +72 -0
  5. package/dist/server/agentadvice.js +115 -0
  6. package/dist/server/agentdocs.js +1 -1
  7. package/dist/server/agententry.js +180 -0
  8. package/dist/server/agentexport.js +469 -0
  9. package/dist/server/agentfollow.js +384 -0
  10. package/dist/server/agentgraph.js +128 -0
  11. package/dist/server/agentlean.js +144 -0
  12. package/dist/server/agentlibrary.js +1 -1
  13. package/dist/server/agentplaces.js +242 -0
  14. package/dist/server/agentread.js +569 -0
  15. package/dist/server/agenttalk.js +282 -0
  16. package/dist/server/agenttcb.js +378 -0
  17. package/dist/server/agentviews.js +2 -2
  18. package/dist/server/app.js +377 -0
  19. package/dist/server/appaccess.js +127 -0
  20. package/dist/server/appagent.js +110 -0
  21. package/dist/server/appgraph.js +176 -0
  22. package/dist/server/appshare.js +179 -0
  23. package/dist/server/appsite.js +120 -0
  24. package/dist/server/apptalk.js +178 -0
  25. package/dist/server/artcmd.js +1 -1
  26. package/dist/server/events.js +1 -1
  27. package/dist/server/history.js +51 -3
  28. package/dist/server/historyapi.js +34 -2
  29. package/dist/server/hover.js +11 -7
  30. package/dist/server/identity.js +1 -1
  31. package/dist/server/libraryroute.js +3 -3
  32. package/dist/server/live.js +61 -2
  33. package/dist/server/main.js +17 -1746
  34. package/dist/server/options.js +350 -0
  35. package/dist/server/outside.js +311 -0
  36. package/dist/server/pastdoc.js +22 -3
  37. package/dist/server/project.js +28 -4
  38. package/dist/server/send.js +259 -0
  39. package/dist/server/talk.js +13 -7
  40. package/dist/server/tokens.js +3 -3
  41. package/dist/server/view.js +3 -1
  42. package/dist/server/views.js +1 -1
  43. package/dist/shared/artrecipe.js +3 -3
  44. package/dist/shared/collab.js +1 -1
  45. package/dist/shared/comment.js +1 -1
  46. package/dist/shared/doc/build.js +30 -14
  47. package/dist/shared/doc/latex.js +7 -2
  48. package/dist/shared/doc/model.js +4 -2
  49. package/dist/shared/doc/sections.js +21 -4
  50. package/dist/shared/outside.js +16 -0
  51. package/dist/shared/pastgraph.js +11 -2
  52. package/dist/shared/scope.js +1 -1
  53. package/dist/web/bundle/app.js +49580 -49284
  54. package/dist/web/src/selection.js +1 -1
  55. package/dist/web/src/theme.js +1 -1
  56. package/dist/web/src/visitors.js +1 -1
  57. package/docs/agent-api/export.md +8 -5
  58. package/docs/agent-api/history.md +3 -1
  59. package/docs/agent-api/reading.md +8 -2
  60. package/package.json +1 -1
@@ -113,8 +113,8 @@ export function memoryProblem(world, v, mode, m, past = null) {
113
113
  }
114
114
  return null;
115
115
  }
116
- /** How far from its parent's centre something of radius `r` may be placed (as server/agent.ts and
117
- * the page keep a drop inside its parent's circle); Infinity at the top. */
116
+ /** How far from its parent's centre something of radius `r` may be placed (as server/agentplaces.ts
117
+ * and the page keep a drop inside its parent's circle); Infinity at the top. */
118
118
  function roomIn(L, parent, r) {
119
119
  if (parent < 0)
120
120
  return Infinity;
@@ -0,0 +1,377 @@
1
+ // The server's answers to requests (server/main.ts serves them, the tests too): each request let in
2
+ // or not, in the order SECURITY.md relies on — the name it was sent to, a write only from a page of
3
+ // this server's own, an agent's token before the key, a personal or a read-only link, the key, then
4
+ // what a read-only reader may ask — and answered by its route. The route is here, in one place; what
5
+ // answers each request is by area: who comes in and who they are (server/appaccess.ts), Share
6
+ // (server/appshare.ts), people on the page with one another (server/apptalk.ts), what pages record
7
+ // in the site (server/appsite.ts), the agents' API and the exported document (server/appagent.ts),
8
+ // the project as pages read it (server/appgraph.ts); server/send.ts sends the answers.
9
+ import { join } from "node:path";
10
+ import { WEB, WEBFONTS, bundleDir } from "./pipeline.js";
11
+ import { Live } from "./live.js";
12
+ import { LeanHover } from "./hover.js";
13
+ import { Identities } from "./identity.js";
14
+ import { validSession } from "../shared/collab.js";
15
+ import { Access, fromOwnPage, hostAllowed, KEY_PATH, urlHost } from "./access.js";
16
+ import { asksForPage, sendAccessPage } from "./accesspage.js";
17
+ import { INVITE_PATH, taken } from "./invites.js";
18
+ import { AgentApi } from "./agent.js";
19
+ import { bearerOf, looksLikeToken } from "./tokens.js";
20
+ import { Exporter } from "./export.js";
21
+ import { pdfjsAsset } from "./libraryroute.js";
22
+ import { packageVersion } from "./doctor.js";
23
+ import { READONLY_PATH } from "./readonly.js";
24
+ import { sendMedia, TIP_PATH, TIPS_DIR, tipClips, tourData, tourVtt } from "./media.js";
25
+ import { withoutReasons } from "../shared/timeline.js";
26
+ import { Updates } from "./updates.js";
27
+ import { serveFilm } from "./film.js";
28
+ import { readOnlyAllows, ReadOnlyBounds } from "./readonlygate.js";
29
+ import { readBody, refused, sendFile, sendJson, sendRevision, sendText, TooLarge, tooLarge } from "./send.js";
30
+ import { endedWords, enter, enterReadOnly, identity, identityGet, refuseHost, revokedWords } from "./appaccess.js";
31
+ import { shareAgents, sharePeople, shareReadOnly } from "./appshare.js";
32
+ import { ask, chat, chatNew, presence } from "./apptalk.js";
33
+ import { history, layoutUndo, libraryRequest, reviewPost, views } from "./appsite.js";
34
+ import { agentRoute, exportRoute } from "./appagent.js";
35
+ import { git, graphParts, hover, source, status } from "./appgraph.js";
36
+ /** The server's answers to requests: exported so that the tests serve them as the server does. */
37
+ export class App {
38
+ live;
39
+ hover;
40
+ ids;
41
+ /** how long a read of the project's git (GET /api/git) is kept, whoever asks: git is run at most
42
+ * once in that time, so what readers cost the server is bounded (CollabSpec decision 11); 0 in
43
+ * the tests */
44
+ gitFreshMs = 3000;
45
+ gitRead = null;
46
+ /** the agents' API (server/agent.ts), and what agents may change */
47
+ agents;
48
+ /** who may come in at all (server/access.ts); null: anyone who reaches the port */
49
+ access;
50
+ /** the exported document's typesetting (server/export.ts, ExportSpec.md); null: no export here */
51
+ exporter;
52
+ /** the address people reach the server at, for the prompt Share makes (--public-url); null: the
53
+ * one the person's browser used */
54
+ publicUrl;
55
+ /** --public: whoever comes without the key or a link of their own reads only (CollabSpec
56
+ * decision 11) */
57
+ publicRead;
58
+ /** without a key, the names this server answers besides its addresses and localhost
59
+ * (server/access.ts, hostAllowed): --public-url's host and every --allowed-host; null: every
60
+ * name, the key keeping everyone else out */
61
+ hostNames;
62
+ /** the names refused as Host, said once each in the server's console (a few: whoever asks
63
+ * chooses them) */
64
+ refusedHosts = new Set();
65
+ /** the read-only readers' requests, by the read-only link they came by, or "public" */
66
+ readOnlyOf = new WeakMap();
67
+ /** what read-only readers may cost the server: Lean's answers, their documents */
68
+ bounds;
69
+ /** VisualProof's own releases as this server follows them (server/updates.ts); null: the
70
+ * version alone is told (a test's server) */
71
+ updates = null;
72
+ constructor(live, hover, ids, agents, access, exporter = null, publicUrl = null, publicRead = false, allowedHosts = []) {
73
+ this.live = live;
74
+ this.hover = hover;
75
+ this.ids = ids;
76
+ this.agents = agents;
77
+ this.access = access;
78
+ // a personal link says who its holder is (CollabSpec decision 9); behind a proxy that signs
79
+ // people in, the proxy does, and there are no personal links
80
+ ids.invites = ids.header ? null : live.invites;
81
+ this.exporter = exporter;
82
+ // agents typeset as people do (ExportSpec decision 11), through their API
83
+ agents.exporter = exporter;
84
+ this.publicUrl = publicUrl;
85
+ this.publicRead = publicRead && access !== null;
86
+ this.hostNames = access ? null : [...(publicUrl ? [urlHost(publicUrl)] : []), ...allowedHosts];
87
+ this.bounds = new ReadOnlyBounds((id) => this.exporter?.job(id)?.state === "running");
88
+ }
89
+ /** Whether a request is told all of the server's own releases (UpdateSpec decision 11): someone
90
+ * let in fully; not a read-only reader, nor an agent. */
91
+ toldAll(req) {
92
+ return this.readOnlyOf.get(req) === undefined && this.ids.kind(req) !== "agent";
93
+ }
94
+ /** The answer to a request that needs a name and has none: the page asks for one (`who`). Where
95
+ * the name the page gives is a personal link holder's, it says so, and the page asks for
96
+ * another. */
97
+ nameless(req, what) {
98
+ const holder = this.ids.taken(req);
99
+ return { error: holder ? `${taken(holder)} (Click your name.)` : `Say who you are first: ${what}.`, who: true };
100
+ }
101
+ /** A request's JSON body, or why it has none. A body larger than `limit` is answered here and
102
+ * now, 413 (as the agents' API words its errors under /api/agent), and the connection closed
103
+ * after it, without reading the rest; whoever asked for the body is told `too large`, and what
104
+ * it answers after is not sent (sendJson). */
105
+ async json(req, limit) {
106
+ let text;
107
+ try {
108
+ text = await readBody(req, limit);
109
+ }
110
+ catch (e) {
111
+ const res = this.responses.get(req);
112
+ if (!(e instanceof TooLarge) || !res)
113
+ return { error: e instanceof Error ? e.message : String(e) };
114
+ const size = limit >= 1 << 20 ? `${Math.round(limit / (1 << 20))} MB` : `${Math.round(limit / 1024)} KB`;
115
+ const agent = (req.url ?? "").startsWith("/api/agent");
116
+ tooLarge(req, res, { error: `The body is larger than ${size}, as much as this request takes.`, ...(agent ? { hint: "Send less at once: fewer items per request (POST /api/agent/opinions takes 100 at most), or split the request." } : {}) });
117
+ return { error: "too large" };
118
+ }
119
+ try {
120
+ return { body: JSON.parse(text) };
121
+ }
122
+ catch {
123
+ return { error: "not JSON" };
124
+ }
125
+ }
126
+ /** each request's response, for what answers a request while reading it (a body too large) */
127
+ responses = new WeakMap();
128
+ /** Answer a request; whatever goes wrong in answering it is answered too, 500 with what it was,
129
+ * rather than left hanging or taking the server down. */
130
+ handle(req, res) {
131
+ this.responses.set(req, res);
132
+ this.route(req, res).catch((e) => {
133
+ console.error(`${req.method} ${req.url?.slice(0, 200)}: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`);
134
+ const agent = (req.url ?? "").startsWith("/api/agent");
135
+ if (!res.headersSent)
136
+ sendJson(res, { error: e instanceof Error ? e.message : String(e), ...(agent ? { hint: "This is the server's fault; the request may work again." } : {}) }, 500);
137
+ else
138
+ res.destroy();
139
+ });
140
+ }
141
+ async route(req, res) {
142
+ const url = new URL(req.url ?? "/", "http://localhost");
143
+ const path = url.pathname;
144
+ const live = this.live;
145
+ // without a key, only the names this server is reached at (CollabSpec decision 12, the owner's
146
+ // decision of 2026-10-18): a page whose own name was made to resolve to this machine (DNS
147
+ // rebinding) is refused whatever it asks — the page, its data, the event stream, the agents'
148
+ // API, the MCP server's file
149
+ if (this.hostNames && !hostAllowed(req.headers.host, this.hostNames))
150
+ return refuseHost(this, req, res, path);
151
+ // what may write, only from a page of this server's own (server/access.ts, fromOwnPage): a page
152
+ // of another site, or of another port of this host, would send this server's cookies with it
153
+ if (!fromOwnPage(req.method, req.headers, this.publicUrl))
154
+ return sendJson(res, { error: "A page of another site cannot change anything here." }, 403);
155
+ // every route; whatever one throws, handle() answers
156
+ {
157
+ // an agent's own token (server/tokens.ts) lets it into its API alone: the page and the page's
158
+ // API answer it as they answer an outsider. A token that ended says so, to whoever held it.
159
+ const bearer = bearerOf(req.headers.authorization);
160
+ if (bearer && looksLikeToken(bearer)) {
161
+ const t = live.tokens.check(bearer);
162
+ if (!t)
163
+ return sendJson(res, this.access ? { error: "not found" } : { error: "This token is not one of this server's.", hint: "Check that it was copied whole (vpa_…), or ask the person who shared with you for a new one." }, this.access ? 404 : 401);
164
+ if ("ended" in t)
165
+ return sendJson(res, {
166
+ error: t.ended === "revoked" ? `This token was revoked by ${t.record.revokedBy} at ${t.record.revoked}.` : `This token expired at ${t.record.expires}.`,
167
+ hint: "Ask the person who shared with you for a new one (Share, then AI agent, in the page).",
168
+ }, 401);
169
+ if (path !== "/api/agent" && !path.startsWith("/api/agent/"))
170
+ return sendJson(res, { error: "not found" }, 404);
171
+ return agentRoute(this, req, res, url, t.ok);
172
+ }
173
+ // a personal link (CollabSpec decision 9, server/invites.ts): it lets its holder in, as who
174
+ // it says, and its cookie does from then on; a revoked one's cookie is forgotten, and lets
175
+ // nobody in
176
+ if (path.startsWith(INVITE_PATH))
177
+ return enter(this, req, res, path.slice(INVITE_PATH.length), path);
178
+ // a read-only link (CollabSpec decision 11, server/readonly.ts): its cookie lets its holder
179
+ // read, where nothing else lets them in
180
+ if (path.startsWith(READONLY_PATH))
181
+ return enterReadOnly(this, req, res, path.slice(READONLY_PATH.length), path);
182
+ const link = this.ids.link(req);
183
+ // a link that ended: its cookie is forgotten as a page loads, once the page has said so. Not
184
+ // before: the page's requests meanwhile are told (a browser the key lets in too, as a guest,
185
+ // by /api/identity: web/src/people.ts); and the browser that made a link anew has the new
186
+ // cookie under the same name, which a request of its pages still on its way with the old one
187
+ // would answer with the forgetting after it
188
+ const forget = link && "ended" in link && (path === "/" || path === "/index.html" || asksForPage(req, path));
189
+ const cookies = forget ? [live.invites.forget()] : [];
190
+ const ro = this.access && !this.ids.header ? live.readOnly.ofCookie(req.headers.cookie) : null;
191
+ if (ro && "ended" in ro)
192
+ cookies.push(live.readOnly.forget());
193
+ if (this.access) {
194
+ const a = link && "ok" in link && !path.startsWith(KEY_PATH) ? "in" : this.access.admit(req, path);
195
+ if (a === "out") {
196
+ // nothing lets them in to write: their read-only link does, or --public, to read
197
+ const reader = ro && "ok" in ro ? ro.ok.id : this.publicRead && !this.ids.header ? "public" : null;
198
+ // a page whose link was revoked, which nothing else lets in, is told so (CollabSpec
199
+ // decisions 9 and 11): its requests are answered 410 with who revoked it and when, and the
200
+ // page, reloaded, says the link no longer opens the site (decision 7: to a browser, the
201
+ // page of a link that does not, which names nobody); the cookie is forgotten there, once
202
+ // it has been said
203
+ const revoked = reader === null && this.ids.kind(req) !== "agent" ? (link && "ended" in link ? endedWords(link) : ro && "ended" in ro ? revokedWords(ro.link, "read-only") : null) : null;
204
+ if (revoked) {
205
+ if (asksForPage(req, path)) {
206
+ res.setHeader("set-cookie", cookies);
207
+ return sendAccessPage(res, "link");
208
+ }
209
+ if (path === "/" || path === "/index.html") {
210
+ res.setHeader("set-cookie", cookies);
211
+ return sendText(req, res, revoked + "\n", "text/plain; charset=utf-8", 410);
212
+ }
213
+ return sendJson(res, { error: revoked, revoked: true }, 410);
214
+ }
215
+ // nothing lets them in: a browser asking for a page is told the site is private, or that
216
+ // its link (`/k/…`, a key replaced) does not open it (CollabSpec decision 7, the owner's
217
+ // decision of 2026-10-18); anything else is answered as if there were nothing here
218
+ if (reader === null || this.ids.kind(req) === "agent") {
219
+ if (cookies.length)
220
+ res.setHeader("set-cookie", cookies);
221
+ if (asksForPage(req, path))
222
+ return sendAccessPage(res, path.startsWith(KEY_PATH) ? "link" : "private");
223
+ return sendJson(res, { error: "not found" }, 404);
224
+ }
225
+ // a link of the key's that is not the key, opened where the address, or a read-only link,
226
+ // lets them read: the page of a link that does not open the site, which says whether the
227
+ // address alone does (--public)
228
+ if (path.startsWith(KEY_PATH) && asksForPage(req, path)) {
229
+ if (cookies.length)
230
+ res.setHeader("set-cookie", cookies);
231
+ return sendAccessPage(res, "link", this.publicRead);
232
+ }
233
+ this.readOnlyOf.set(req, reader);
234
+ // the page renews a read-only link's cookie, as a personal link's
235
+ if (reader !== "public" && (path === "/" || path === "/index.html"))
236
+ cookies.push(live.readOnly.cookie(reader));
237
+ // what a read-only reader may ask; the rest is refused, whatever the page sends
238
+ if (!readOnlyAllows(req.method ?? "GET", path)) {
239
+ if (cookies.length)
240
+ res.setHeader("set-cookie", cookies);
241
+ return sendJson(res, { error: "This page is read-only: it changes nothing that is shared.", readOnly: true }, 403);
242
+ }
243
+ }
244
+ else if (a !== "in") {
245
+ // the link: the browser keeps the cookie, and the key leaves the address (a fragment
246
+ // after the key, a place in the page, comes along to "/")
247
+ res.writeHead(303, { location: "/", "set-cookie": [a.enter, ...cookies], "cache-control": "no-store", "referrer-policy": "no-referrer" });
248
+ return void res.end();
249
+ }
250
+ else {
251
+ // let in by the cookie every server used to share: the browser is given this one's own
252
+ const renew = this.access.renewal(req);
253
+ if (renew)
254
+ cookies.push(renew);
255
+ }
256
+ }
257
+ // the page renews a personal link's cookie: its holder stays in as long as they come back
258
+ if (link && "ok" in link && (path === "/" || path === "/index.html"))
259
+ cookies.push(live.invites.cookie(link.ok));
260
+ if (cookies.length)
261
+ res.setHeader("set-cookie", cookies);
262
+ if (path === "/" || path === "/index.html")
263
+ return sendFile(req, res, join(WEB, "index.html"));
264
+ if (path === "/style.css")
265
+ return sendFile(req, res, join(WEB, "style.css"));
266
+ // the fonts an artwork is drawn in (ExportSpec decision 19)
267
+ if (FONT_PATH.test(path))
268
+ return sendFile(req, res, join(WEBFONTS, path.slice("/fonts/".length)));
269
+ // the tips' clips and their key frames (GuideSpec decision 6), and which there are
270
+ if (path === "/tips/index.json")
271
+ return sendJson(res, { clips: tipClips() });
272
+ // the tour film, fetched by this server on its first play and kept checked in the cache
273
+ // (server/film.ts, UpdateSpec decision 14): else 503 while it comes, or 404, and the page shows
274
+ // its stills and captions; and its captions as WebVTT, for assistive technology
275
+ if (path === "/tips/tour.mp4" && !refused.has(res))
276
+ return void serveFilm(req, res, sendMedia);
277
+ if (path === "/tips/tour.en.vtt") {
278
+ const vtt = tourVtt(tourData());
279
+ if (vtt === null)
280
+ return sendJson(res, { error: "no captions" }, 404);
281
+ res.writeHead(200, { "content-type": "text/vtt; charset=utf-8", "cache-control": "no-cache" });
282
+ return void res.end(vtt);
283
+ }
284
+ if (TIP_PATH.test(path) && !refused.has(res))
285
+ return sendMedia(req, res, join(TIPS_DIR, path.slice("/tips/".length)));
286
+ // the page, and its workers: the one that lays out the Time Machine's past graphs
287
+ // (web/src/layoutworker.ts), the one that chooses the overview's edges (web/src/edgeworker.ts),
288
+ // and pdf.js's, which reads the library's PDFs for the reference window (AttachmentSpec decision 11)
289
+ if (/^\/(app|layout|edges|pdfworker)\.js(\.map)?$/.test(path))
290
+ return sendFile(req, res, join(bundleDir(), path.slice(1)));
291
+ if (path.startsWith("/pdfjs/"))
292
+ return pdfjsAsset(res, path);
293
+ if (path === "/api/status")
294
+ return status(this, req, res, url);
295
+ // VisualProof's own version, and what of its releases those let in fully are told (UpdateSpec
296
+ // decision 11): a read-only reader and an agent are told the version alone
297
+ if (path === "/api/updates")
298
+ return sendJson(res, this.updates?.status(this.toldAll(req)) ?? { running: packageVersion() });
299
+ // the link that lets someone in, for a page that shares where it is (web/src/share.ts); a
300
+ // request gets here only once it is in
301
+ // a read-only reader shares the link they came by, or the address alone (--public)
302
+ const reader = this.readOnlyOf.get(req);
303
+ if (path === "/api/share") {
304
+ if (reader !== undefined)
305
+ return sendJson(res, { path: reader === "public" ? "/" : (live.readOnly.get(reader)?.path ?? null), readOnly: true });
306
+ return sendJson(res, { path: this.access?.link ?? null, readOnlyLinks: !!this.access && !this.ids.header, public: this.publicRead });
307
+ }
308
+ if (path === "/api/share/readonly" || path.startsWith("/api/share/readonly/"))
309
+ return shareReadOnly(this, req, res, url);
310
+ if (path.startsWith("/api/share/agents"))
311
+ return shareAgents(this, req, res, url);
312
+ if (path === "/api/share/people" || path.startsWith("/api/share/people/"))
313
+ return sharePeople(this, req, res, url);
314
+ if (path === "/api/chat")
315
+ return chat(this, req, res, url);
316
+ if (path === "/api/chat/new")
317
+ return chatNew(this, req, res);
318
+ if (path === "/api/ask" || path === "/api/ask/answer")
319
+ return ask(this, req, res, url);
320
+ if (path === "/api/agent" || path.startsWith("/api/agent/"))
321
+ return agentRoute(this, req, res, url);
322
+ // the views, each a shared board (ViewSpec.md)
323
+ if (path === "/api/views" || path.startsWith("/api/views/"))
324
+ return views(this, req, res, url);
325
+ if (path === "/api/history" || path.startsWith("/api/history/"))
326
+ return history(this, req, res, url);
327
+ if (path === "/api/library" || path.startsWith("/api/library/"))
328
+ return libraryRequest(this, req, res, url, reader);
329
+ // an agent may use the page's own endpoints too: the same rules hold there (AgentSpec)
330
+ const agent = this.ids.kind(req) === "agent";
331
+ // the review (ReviewSpec.md): the whole of it, as a page takes it on, with the lines of its
332
+ // logs that cannot be read; tagged with its revision, compressed once a revision
333
+ if (path === "/api/review" && req.method === "GET")
334
+ return sendRevision(req, res, live.review, live.review.tag(), () => live.review.wholeText());
335
+ // the whole build status, tagged with its revision (the owner's decision of 2026-10-19): what
336
+ // changes after comes by the event stream
337
+ if (path === "/api/build" && req.method === "GET") {
338
+ const b = live.buildWhole();
339
+ return sendRevision(req, res, live, b.tag, () => b.text);
340
+ }
341
+ if (path === "/api/review" && req.method === "POST")
342
+ return reviewPost(this, req, res, agent);
343
+ if (path === "/api/export" || path.startsWith("/api/export/"))
344
+ return exportRoute(this, req, res, url, agent, reader !== undefined);
345
+ if (path === "/api/identity" && req.method === "GET")
346
+ return identityGet(this, req, res, link, reader);
347
+ if (path === "/api/identity" && req.method === "POST")
348
+ return identity(this, req, res);
349
+ if (path === "/api/presence" && req.method === "POST")
350
+ return presence(this, req, res, agent);
351
+ if (path === "/api/events") {
352
+ const session = url.searchParams.get("session");
353
+ // `build=delta`: the page takes the build status as changes (a page of 0.6.0 or later)
354
+ return live.subscribe(res, validSession(session) ? session : null, this.ids.person(req)?.id ?? null, reader ?? null, this.toldAll(req), url.searchParams.get("build") === "delta", this.ids.who(req));
355
+ }
356
+ // what happened (CollabSpec decision 5): what the server stored; the review's own history the
357
+ // page reads from the review
358
+ if (path === "/api/activity") {
359
+ const events = live.timeline.events.slice(-2000);
360
+ return sendJson(res, { events: this.toldAll(req) ? events : events.map(withoutReasons) });
361
+ }
362
+ if (path === "/api/layout/undo" && req.method === "POST")
363
+ return layoutUndo(this, req, res, agent);
364
+ if (path === "/api/git")
365
+ return git(this, res);
366
+ if (path === "/api/meta" || path === "/api/edges")
367
+ return graphParts(this, req, res, url);
368
+ if (path === "/api/hover" || path === "/api/hover/open" || path === "/api/hover/names" || path === "/api/hover/describe" || path === "/api/hover/print")
369
+ return hover(this, req, res, url, reader);
370
+ if (path === "/api/source")
371
+ return source(this, res, url);
372
+ sendJson(res, { error: "not found" }, 404);
373
+ }
374
+ }
375
+ }
376
+ /** an artwork's font file (assets/webfonts/) */
377
+ const FONT_PATH = /^\/fonts\/(source-sans-3|source-serif-4|jost)-[a-z-]+\.woff2$/;
@@ -0,0 +1,127 @@
1
+ // Who comes in, and who they are (the routes of server/app.ts): a request for a name this server is
2
+ // not reached by refused (CollabSpec decision 12), a personal link and a read-only link opened
3
+ // (decisions 9 and 11), what a link that ended is told, and who the reader is (/api/identity:
4
+ // decisions 3 and 9). Whether a request is let in at all, and in what order it is asked, is the
5
+ // route's (server/app.ts), as SECURITY.md describes it.
6
+ import { asksForPage, sendAccessPage } from "./accesspage.js";
7
+ import { invalidPersonName, Invites, taken } from "./invites.js";
8
+ import { sendJson, sendText } from "./send.js";
9
+ /** A personal link opened (CollabSpec decision 9): the browser is given the cookie that lets its
10
+ * holder in, as who the link says, and goes on to the page — the token leaves the address, and a
11
+ * place after it (a fragment) comes along. A revoked link says so; anything else is answered as
12
+ * any address nobody was given. On a server with a key, a browser is shown the page of a link
13
+ * that does not open the site instead (CollabSpec decision 7), which says neither which it was
14
+ * nor who revoked it — unless the key or a link of its own lets it in, and it may be told. */
15
+ export function enter(app, req, res, token, path) {
16
+ const c = app.ids.header ? null : app.live.invites.check(token);
17
+ if (c && "ok" in c) {
18
+ res.writeHead(303, { location: "/", "set-cookie": app.live.invites.cookie(c.ok), "cache-control": "no-store", "referrer-policy": "no-referrer" });
19
+ return void res.end();
20
+ }
21
+ if (app.access && asksForPage(req, path) && (!c || !letIn(app, req)))
22
+ return sendAccessPage(res, "link", app.publicRead);
23
+ if (c)
24
+ return sendText(req, res, endedWords(c) + "\n", "text/plain; charset=utf-8", 410);
25
+ sendJson(res, { error: "not found" }, 404);
26
+ }
27
+ /** A read-only link opened (CollabSpec decision 11): the browser is given the cookie that lets
28
+ * its holder read, and goes on to the page — the token leaves the address, and a place after it
29
+ * (a fragment) comes along. A revoked link says so; anything else, and any link on a server
30
+ * open to all or behind a sign-in, which have none, is answered as an address nobody was given;
31
+ * to a browser, on a server with a key, as a personal link's (enter). */
32
+ export function enterReadOnly(app, req, res, token, path) {
33
+ const c = app.access && !app.ids.header ? app.live.readOnly.check(token) : null;
34
+ if (c && "ok" in c) {
35
+ res.writeHead(303, { location: "/", "set-cookie": app.live.readOnly.cookie(c.ok.id), "cache-control": "no-store", "referrer-policy": "no-referrer" });
36
+ return void res.end();
37
+ }
38
+ if (app.access && asksForPage(req, path) && (!c || !letIn(app, req)))
39
+ return sendAccessPage(res, "link", app.publicRead);
40
+ if (c)
41
+ return sendText(req, res, revokedWords(c.link, "read-only") + "\n", "text/plain; charset=utf-8", 410);
42
+ sendJson(res, { error: "not found" }, 404);
43
+ }
44
+ /** Whether the key's cookie or a personal link in force lets a request in: someone who sees the
45
+ * site's people, and may be told who revoked a link. */
46
+ function letIn(app, req) {
47
+ return !!app.ids.person(req) || app.access?.admit(req, "/") === "in";
48
+ }
49
+ /** who the reader is (CollabSpec decisions 3 and 9): the name their page gives, the proxy's, or
50
+ * their personal link's — with the link, and whether the page's own name is a link holder's
51
+ * and not theirs; a link revoked says by whom, one made anew since this browser had it, when */
52
+ export function identityGet(app, req, res, link, reader) {
53
+ const person = app.ids.person(req);
54
+ const holder = app.ids.taken(req);
55
+ const ended = link && "ended" in link ? link : null;
56
+ if (reader !== undefined)
57
+ return sendJson(res, { mode: app.ids.mode, name: null, readOnly: { by: reader === "public" ? "public" : "link" } });
58
+ return sendJson(res, {
59
+ mode: app.ids.mode,
60
+ name: app.ids.who(req),
61
+ ...(person ? { person: Invites.info(person) } : {}),
62
+ ...(holder ? { taken: taken(holder) } : {}),
63
+ ...(ended?.ended === "revoked" ? { revoked: { by: ended.record.revokedBy, at: ended.record.revoked, name: ended.record.name } } : {}),
64
+ ...(ended?.ended === "replaced" ? { replaced: { at: ended.at, name: ended.record.name } } : {}),
65
+ });
66
+ }
67
+ /** Who the reader is (POST /api/identity {name}): the name someone invited by a personal link goes
68
+ * by from now on — kept with their link, and said in their review log, so that what they wrote
69
+ * shows under it — or, for a guest, whether a name is theirs to take: one a link's holder goes
70
+ * by is not (409). A guest's name is their page's own; nothing of it is kept here. */
71
+ export async function identity(app, req, res) {
72
+ if (app.ids.kind(req) === "agent")
73
+ return sendJson(res, { error: "An agent's name is its own: its token's, or the one it sends." }, 403);
74
+ if (app.ids.header)
75
+ return sendJson(res, { error: "Your name is the sign-in's, in front of this server: it cannot be changed here." }, 403);
76
+ const r = await app.json(req, 4096);
77
+ if (r.error !== undefined)
78
+ return sendJson(res, { error: `The body is ${r.error}.` }, 400);
79
+ const name = r.body?.name;
80
+ const bad = invalidPersonName(name);
81
+ if (bad)
82
+ return sendJson(res, { error: bad }, 400);
83
+ const n = name.trim();
84
+ const p = app.ids.person(req);
85
+ if (!p) {
86
+ const holder = app.live.invites.holder(n);
87
+ return holder ? sendJson(res, { error: taken(holder), taken: true }, 409) : sendJson(res, { ok: true, name: n });
88
+ }
89
+ const was = p.name;
90
+ const done = app.live.invites.rename(p.id, n);
91
+ if (typeof done === "string")
92
+ return sendJson(res, { error: done, taken: true }, 409);
93
+ // their log says so, where they have one: what they wrote shows under the new name everywhere.
94
+ // A log that cannot be written to now (a line to mend by hand) says it with their next line,
95
+ // which carries the name it is written under
96
+ if (done.name !== was)
97
+ app.live.review.named(p.id, done.name);
98
+ return sendJson(res, { ok: true, name: done.name, person: Invites.info(done) });
99
+ }
100
+ /** A request for a name this server without a key does not answer (CollabSpec decision 12): 403,
101
+ * saying which option lets the name in; and, once per name, the server's console says it too,
102
+ * for whoever runs it behind a proxy that forwards the name people reach it by. A browser asking
103
+ * for a page is shown a page that says so (the owner's decision of 2026-10-18), which does not
104
+ * repeat the name: it is the requester's, any text at all. */
105
+ export function refuseHost(app, req, res, path) {
106
+ const raw = req.headers.host ?? "";
107
+ const name = /^\[/.test(raw) ? raw : raw.replace(/:\d{1,5}$/, "");
108
+ const shown = /^[A-Za-z0-9._\-[\]:]{1,253}$/.test(name) ? name : null;
109
+ if (shown && app.refusedHosts.size < 20 && !app.refusedHosts.has(shown.toLowerCase())) {
110
+ app.refusedHosts.add(shown.toLowerCase());
111
+ console.error(`refused a request for ${shown}: without an access key this server answers only its addresses, localhost, --public-url's host and the --allowed-host names; --allowed-host ${shown} lets this one in`);
112
+ }
113
+ if (asksForPage(req, path))
114
+ return sendAccessPage(res, "host");
115
+ sendText(req, res, `This server answers only the names it is meant to be reached by${shown ? `, and ${shown} is not one of them` : ""}. Whoever runs it can let a name in with --allowed-host${shown ? ` ${shown}` : " <name>"}.\n`, "text/plain; charset=utf-8", 403);
116
+ }
117
+ /** What a revoked link's holder is told, opening it or on a page it had opened. */
118
+ export function revokedWords(r, kind) {
119
+ return `This ${kind} link was revoked by ${r.revokedBy} on ${(r.revoked ?? "").slice(0, 10)}. Ask whoever ${kind === "personal" ? "invited you" : "gave it to you"} for a new one.`;
120
+ }
121
+ /** What a personal link that lets nobody in any more is told (410): revoked, by whom and when, or
122
+ * made anew by its holder, and when (CollabSpec decision 9). */
123
+ export function endedWords(c) {
124
+ if (c.ended === "revoked")
125
+ return revokedWords(c.record, "personal");
126
+ return `This personal link was made anew on ${c.at.slice(0, 10)}: it lets nobody in any more. Open the new one instead (My personal link, in the menu under your name where it was made anew).`;
127
+ }
@@ -0,0 +1,110 @@
1
+ // The routes server/agent.ts answers (the App's, server/app.ts): the agents' door — a request under
2
+ // /api/agent read here, the agent it is from being who its token says, and answered there — and the
3
+ // exported document, which the page asks for under /api/export and agents under /api/agent/export,
4
+ // for the same answers.
5
+ import { validSession } from "../shared/collab.js";
6
+ import { readUpload } from "./libraryroute.js";
7
+ import { UPLOAD_PATH } from "./agentlibrary.js";
8
+ import { hostOf, sendDownload, sendGz, sendJson, sendText } from "./send.js";
9
+ import { exportFile, exportHead, exportJob, exportOutline, exportStart } from "./agentexport.js";
10
+ /** The exported document (ExportSpec decisions 5–16): POST /api/export starts typesetting the
11
+ * document of a view, `{view, settings, version?}` (a build the Time Machine shows the view at;
12
+ * left out, the view's own), and answers with its job at once; the page asks how the
13
+ * job is doing (GET /api/export/job) and fetches the PDF and the LaTeX sources once it is done
14
+ * (GET /api/export/file). The answers are the agents' API's (server/agent.ts), which has the same
15
+ * routes under /api/agent/; an agent that comes here is held to its one job at a time there too.
16
+ * The window shows the title and the author line the document will have (GET /api/export/head
17
+ * ?view=&version=: ExportSpec decisions 14 and 15), which only the server can tell: who dropped
18
+ * each pin is never sent to pages. */
19
+ export async function exportRoute(app, req, res, url, agent, readOnly = false) {
20
+ const path = url.pathname;
21
+ const api = app.agents;
22
+ // the document's outline, which the linear form draws: nothing is typeset for it
23
+ if (path === "/api/export/outline") {
24
+ const o = exportOutline(api, url.searchParams.get("view") ?? "", url.searchParams.get("version") ?? undefined);
25
+ return sendJson(res, o.body, o.status, o.headers);
26
+ }
27
+ if (!app.exporter)
28
+ return sendJson(res, { error: "This server does not export documents." }, 404);
29
+ let a;
30
+ if (path === "/api/export" && req.method === "POST") {
31
+ const caller = agent ? { name: app.ids.who(req), kind: "agent" } : null;
32
+ if (caller && !caller.name)
33
+ return sendJson(res, { error: "Say who you are first.", who: true }, 401);
34
+ const r = await app.json(req, 1 << 20);
35
+ if (r.error !== undefined)
36
+ return sendJson(res, { error: `The body is ${r.error}.` }, 400);
37
+ // read-only readers typeset one document at a time among them (CollabSpec decision 11): while
38
+ // one is being typeset, the others wait, even one the export's cache holds. The place is
39
+ // taken before the job starts, so that two requests at once cannot both start one.
40
+ if (readOnly) {
41
+ if (!app.bounds.mayExport())
42
+ return sendJson(res, { error: "Another document is being typeset for readers of this page: try again in a little while." }, 429, { "retry-after": "5" });
43
+ app.bounds.reserveExport();
44
+ }
45
+ let started;
46
+ try {
47
+ started = await exportStart(api, r.body, caller);
48
+ }
49
+ finally {
50
+ if (readOnly)
51
+ app.bounds.exportStarted(started?.body);
52
+ }
53
+ a = started;
54
+ }
55
+ else if (path === "/api/export/head")
56
+ a = exportHead(api, url.searchParams.get("view") ?? "", url.searchParams.get("version") ?? undefined);
57
+ else if (path === "/api/export/job")
58
+ a = exportJob(api, url.searchParams.get("id") ?? "", false);
59
+ else if (path === "/api/export/file")
60
+ a = exportFile(api, url.searchParams.get("id") ?? "", url.searchParams.get("what"));
61
+ else
62
+ return sendJson(res, { error: "not found" }, 404);
63
+ if (a.file)
64
+ return sendDownload(res, a.file);
65
+ // the agents' answer as it is: the page shows its error, and an agent that asked here its hint
66
+ sendJson(res, a.body, a.status, a.headers);
67
+ }
68
+ /** A request to the agents' API: read here, answered there. An agent with a token of its own is
69
+ * who its token says, whatever its headers say (server/tokens.ts). */
70
+ export async function agentRoute(app, req, res, url, token = null) {
71
+ const said = app.ids.who(req);
72
+ const caller = token
73
+ ? { name: token.name, kind: "agent", token: { id: token.id, by: token.by, level: token.level, expires: token.expires }, ...(said && said !== token.name ? { ignoredName: said } : {}) }
74
+ : { name: said, kind: app.ids.kind(req) };
75
+ let body = null;
76
+ if (req.method === "POST" && url.pathname.replace(/\/+$/, "") === UPLOAD_PATH) {
77
+ // a file for the library: its bytes as they come (server/agentlibrary.ts)
78
+ const bytes = await readUpload(req, res);
79
+ if (!bytes)
80
+ return;
81
+ body = { bytes };
82
+ }
83
+ else if (req.method === "POST") {
84
+ const r = await app.json(req, AGENT_BODY);
85
+ if (r.error !== undefined)
86
+ return sendJson(res, { error: `The body is ${r.error}.`, hint: "Send a JSON object, with content-type: application/json." }, 400);
87
+ body = r.body;
88
+ }
89
+ // a request that waits (the inbox, the companion) learns that its asker went away: an agent's
90
+ // wait for messages ends with its connection, so that none is handed to nobody
91
+ const away = new AbortController();
92
+ res.on("close", () => {
93
+ if (!res.writableFinished)
94
+ away.abort();
95
+ });
96
+ // the session an MCP server says it is (since 0.4.0): a wait from another is a new session's
97
+ const session = req.headers["x-visualproof-session"];
98
+ const a = await app.agents.handle({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body, caller, base: app.publicUrl ?? `http://${hostOf(req)}`, signal: away.signal, ...(validSession(session) ? { session } : {}) });
99
+ if (away.signal.aborted)
100
+ return;
101
+ if (a.text)
102
+ return sendText(req, res, a.text.body, a.text.type, a.status);
103
+ if (a.file)
104
+ return sendDownload(res, a.file);
105
+ if (a.gz)
106
+ return sendGz(req, res, a.gz.body, a.gz.type);
107
+ sendJson(res, a.body, a.status, a.headers);
108
+ }
109
+ /** the most an agent's request body may be (docs/agent-api/requests.md: 1 MB) */
110
+ const AGENT_BODY = 1 << 20;