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,469 @@
1
+ // The exported document (ExportSpec.md), the endpoints of server/agent.ts and the answers the page's
2
+ // Export takes too (server/appagent.ts): a view's document — its model as JSON, its head, its outline
3
+ // — at the view's own build or a past one (decision 16), typeset by XeLaTeX as a job (decision 11),
4
+ // one at a time per agent, and its files; and a link that opens the board as a picture (decision 20).
5
+ import { spawnSync } from "node:child_process";
6
+ import { childEnv } from "./children.js";
7
+ import { readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { addressOf } from "../shared/sharesnap.js";
10
+ import { encodeRecipe, readRecipe, RECIPE_PARAM, resolveRecipe, SAVE_PARAM } from "../shared/artrecipe.js";
11
+ import { evaluate } from "../shared/query.js";
12
+ import { authorLine, authorsOf, reviewTraces, viewTraces } from "../shared/doc/authors.js";
13
+ import { itemsShownOn } from "../shared/noteplace.js";
14
+ import { buildDoc, DocInputError, docNotes } from "../shared/doc/build.js";
15
+ import { boardSpots } from "./boardspots.js";
16
+ import { outlineOf } from "../shared/doc/outline.js";
17
+ import { outsideKeys, planDoc } from "../shared/doc/sections.js";
18
+ import { docFiles, figureFiles, figureNotes } from "./figures.js";
19
+ import { renderLatex } from "../shared/doc/latex.js";
20
+ import { readSettings, SETTINGS_HELP } from "../shared/doc/settings.js";
21
+ import { reviewThen } from "../shared/pastgraph.js";
22
+ import { fullWhen } from "../shared/titles.js";
23
+ import { docTitle, fixedScope, PROJECT } from "../shared/views.js";
24
+ import { titleContext } from "./agentviews.js";
25
+ import { SERVER_WRITER } from "./review.js";
26
+ import { lakeTextHash } from "./status.js";
27
+ import { View } from "./agentgraph.js";
28
+ import { body, fail, needAgent, ok } from "./agent.js";
29
+ /** The build the document of view `rec` is of (ExportSpec decision 16): the view's own where the
30
+ * request names none — the past build it is kept at, if it is (HistorySpec decision 19) — else
31
+ * the one `raw` names, as the Time Machine shows a view at another build than its own (null, 0 or
32
+ * the latest's id: the latest). Null for the latest build; or the answer why it cannot be had. */
33
+ function exportAt(api, rec, raw) {
34
+ if (raw === undefined || raw === "")
35
+ return api.world.views?.pastOf(rec) ?? null;
36
+ if (raw === null || raw === 0 || raw === "0" || raw === "null" || raw === "latest")
37
+ return null;
38
+ const id = typeof raw === "number" ? raw : typeof raw === "string" && /^\d{1,9}$/.test(raw) ? Number(raw) : NaN;
39
+ if (!Number.isInteger(id) || id < 0)
40
+ return fail(400, "version is a snapshot's id, or null for the latest build.", "GET /api/agent/history lists the snapshots; leave version out for the view's own build.");
41
+ const h = api.world.history;
42
+ if (!h?.get(id))
43
+ return fail(404, `There is no snapshot ${id}.`, "GET /api/agent/history lists them; leave version out for the view's own build.");
44
+ return id === h.latest()?.id ? null : id;
45
+ }
46
+ /** The build a document's title says (ViewSpec decision 25), for view `rec` printed at `at`
47
+ * (exportAt; `raw` what the request named): that build where it is a past one; the build the view
48
+ * is kept at where the request named none, as its title says it everywhere; none for the latest
49
+ * named. */
50
+ function titleVersion(api, rec, at, raw) {
51
+ return at ?? (raw === undefined || raw === "" ? rec.version : undefined);
52
+ }
53
+ /** The exported document's input as a request sends it, read and checked: the view, the settings
54
+ * and the build (ExportSpec decisions 7, 12 and 16), the view's board as its page draws it (the
55
+ * owner's decisions of 2026-10-12: the document's order, and the notes it shows) and what the
56
+ * figures of those notes need of the library; or the answer why not. What was asked of a
57
+ * document until 2026-10-09 — targets, a preset, a content — is refused, and told what to ask
58
+ * instead. */
59
+ async function docInput(api, view, settings, retired = {}, version) {
60
+ const old = ["targets", "preset", "content"].filter((k) => retired[k] !== undefined);
61
+ if (old.length)
62
+ return fail(400, `A document is a view's now (2026-10-09): ${old.join(", ")} ${old.length === 1 ? "is" : "are"} no longer taken.`, VIEW_HINT);
63
+ const v = api.graph();
64
+ if (!(v instanceof View))
65
+ return v;
66
+ if (typeof view !== "string" || !view)
67
+ return fail(400, "view is the id of the view to export.", VIEW_HINT);
68
+ const rec = api.world.views?.book.get(view);
69
+ if (!rec)
70
+ return fail(404, `There is no view ${view.slice(0, 200)}.`, "GET /api/agent/views lists them; POST /api/agent/views/open {scope} opens one on a query.");
71
+ const at = exportAt(api, rec, version);
72
+ if (at !== null && typeof at === "object")
73
+ return at;
74
+ const st = readSettings(settings);
75
+ if ("error" in st)
76
+ return fail(400, `${st.error}.`, `Settings: ${Object.entries(SETTINGS_HELP).map(([k, h]) => `${k} — ${h}`).join("; ")}.`);
77
+ const tv = titleVersion(api, rec, at, version);
78
+ const docView = {
79
+ id: rec.id,
80
+ name: rec.name,
81
+ ...(rec.targets ? { targets: [...rec.targets] } : {}),
82
+ scope: rec.scope,
83
+ clustering: rec.clustering,
84
+ hidden: [...rec.hidden[rec.clustering]],
85
+ authors: viewAuthors(api, rec, at, v),
86
+ ...(tv !== undefined ? { version: tv } : {}),
87
+ };
88
+ // the notes it may print, and what their images and clips need of the library
89
+ const notes = api.world.views?.book.notes ?? [];
90
+ const files = await docFiles(api.world.library, [...notes, ...(rec.notes ?? [])].map((n) => n.carries));
91
+ if (at !== null)
92
+ return pastInput(api, v, at, rec, docView, st.settings, files);
93
+ const root = api.world.project.root;
94
+ // each module's text as it is now, read once per document; outside the project, its package's
95
+ // file (ExportSpec decision 8: an outside key declaration is printed)
96
+ const source = (module) => {
97
+ const m = v.modules.get(module);
98
+ if (!m) {
99
+ const o = api.outsideText(module);
100
+ return o && { lines: o.lines, edited: o.edited, contexts: null, hash: o.hash };
101
+ }
102
+ const rel = api.world.project.files.get(module) ?? m?.file;
103
+ if (!rel)
104
+ return null;
105
+ try {
106
+ const text = readFileSync(join(root, rel), "utf8");
107
+ const hash = lakeTextHash(text);
108
+ return { lines: text.split("\n"), edited: !!m?.compiled && hash !== m.compiled, contexts: api.world.contextsOf?.(module) ?? null, hash };
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ };
114
+ const review = api.world.review.data;
115
+ return {
116
+ input: {
117
+ g: v.g,
118
+ review,
119
+ view: docView,
120
+ settings: st.settings,
121
+ source,
122
+ fileOf: (module) => v.modules.get(module)?.file ?? null,
123
+ outside: (module) => {
124
+ const o = v.modules.has(module) ? null : api.world.outsideFile?.(module);
125
+ return o ? { file: o.file.file, package: o.file.package.name } : null;
126
+ },
127
+ // a branch's build is of its commit, not of what is checked out meanwhile (DeploySpec)
128
+ build: { fingerprint: api.world.graph?.fingerprint ?? null, commit: shownOr(api.world.shownCommit?.(), root) },
129
+ ...(tv !== undefined ? { titles: titleContext(api.world) } : {}),
130
+ board: boardSpots({ g: v.g, review, rec, memory: api.world.views?.book.memoryOf(rec.id, rec.clustering) ?? null, whole: v.meta.layouts?.[rec.clustering], notes }),
131
+ files,
132
+ },
133
+ };
134
+ }
135
+ /** The input of the document of view `rec` at past build `at` (ExportSpec decision 16): its
136
+ * board's graph is that build's past graph, as the page makes it (server/pastdoc.ts), the review
137
+ * read there under the names then too, the board laid out as the Time Machine lays it out; its
138
+ * texts that build's, as the history keeps them. */
139
+ function pastInput(api, v, at, rec, view, settings, files) {
140
+ const h = api.world.history;
141
+ if (!h)
142
+ return fail(404, "This server keeps no history: it serves a saved graph, and has no past build to print.", "Export the view at the latest build: version null.");
143
+ // the texts of a build kept before the history kept them are found once, at start (HistorySpec
144
+ // decision 22): until then none would print
145
+ if (h.sourcesOf(at) === null)
146
+ return fail(503, `The source texts of snapshot ${at} are still being looked for: the server finds those of the builds kept before it kept texts once, as it starts.`, "Ask again in a few seconds.", { retryAfter: 5 }, { "retry-after": "5" });
147
+ const b = api.pasts.get(at, v.g, v.version, (m) => v.modules.get(m)?.file ?? null);
148
+ if (!b)
149
+ return fail(404, `There is no snapshot ${at}.`, "GET /api/agent/history lists them.");
150
+ const s = b.info;
151
+ const c = s.commit;
152
+ const review = reviewThen(api.world.review.data, b.past.nowName);
153
+ const board = boardSpots({
154
+ g: b.past.graph,
155
+ review,
156
+ rec,
157
+ memory: api.world.views?.book.memoryOf(rec.id, rec.clustering) ?? null,
158
+ whole: v.meta.layouts?.[rec.clustering],
159
+ past: { snapshot: at, nowName: b.past.nowName, now: v.g, nowReview: api.world.review.data },
160
+ notes: api.world.views?.book.notes ?? [],
161
+ });
162
+ return {
163
+ input: {
164
+ g: b.past.graph,
165
+ review,
166
+ view,
167
+ settings,
168
+ source: b.source,
169
+ fileOf: b.fileOf,
170
+ outside: b.outside,
171
+ build: { fingerprint: s.fingerprint, commit: c && { hash: c.hash, branch: c.branch, ...(c.dirty ? { dirty: true } : {}), ...(c.guessed ? { guessed: true } : {}) }, toolchain: s.toolchain },
172
+ past: { snapshot: at, at: s.at, when: fullWhen(s.at), ...(s.approx ? { approx: true } : {}) },
173
+ titles: titleContext(api.world),
174
+ board,
175
+ files,
176
+ },
177
+ };
178
+ }
179
+ /** The people who left a trace on view `rec`, in the order of their first (ExportSpec decision 15;
180
+ * shared/doc/authors.ts): from its record, who dropped its pins, and the timeline; and the review
181
+ * of what its document prints at build `at` (null: the latest), the declarations of the project it
182
+ * holds on that build's graph `v` or its past graph (the owner's decision, 2026-10-10). Someone
183
+ * invited by a personal link by the name they go by now, as the server's links say it, else the
184
+ * review's logs. */
185
+ function viewAuthors(api, rec, at, v) {
186
+ const people = new Map((api.world.people?.() ?? []).map((p) => [p.id, p.name]));
187
+ const logs = api.world.review.data.people;
188
+ const nameOf = (id) => people.get(id) ?? (Object.hasOwn(logs, id) ? logs[id].name : null);
189
+ const past = at === null ? null : api.pasts.get(at, v.g, v.version, (m) => v.modules.get(m)?.file ?? null);
190
+ const g = past ? past.past.graph : v.g;
191
+ const d = past ? reviewThen(api.world.review.data, past.past.nowName) : api.world.review.data;
192
+ const set = evaluate(rec.scope, { g, review: d });
193
+ const held = [];
194
+ for (let i = 0; i < g.projectCount; i++)
195
+ if (set[i])
196
+ held.push(g.nodes[i].name);
197
+ // the items it shows (AttachmentSpec decision 17, the owner's of 2026-10-11): every note of the
198
+ // project on the Project; elsewhere what its scope gives, against that build's clusters, the
199
+ // links and the declarations notes are attached to as that build names them, and what was added
200
+ // to it, less what was taken out
201
+ const shown = itemsShownOn(api.world.views?.book.notes ?? [], { all: fixedScope(rec), items: rec.items }, rec.clustering, g.nodes.filter((_, i) => set[i]), g.nodes, d.links, past?.past.nowName);
202
+ const traces = viewTraces(rec, api.world.views?.book.authors.get(rec.id), api.world.timeline.events, shown);
203
+ return authorsOf([...traces, ...reviewTraces(d, held)], nameOf, [SERVER_WRITER.name]);
204
+ }
205
+ /** What heads the document of view `view` (ExportSpec decisions 14 and 15) at the build `version`
206
+ * names (decision 16; left out, the view's own): its title and its author line as they print, for
207
+ * the page's Export window (GET /api/export/head). */
208
+ export function exportHead(api, view, version) {
209
+ const rec = view ? api.world.views?.book.get(view) : undefined;
210
+ if (!rec)
211
+ return fail(404, `There is no view ${view.slice(0, 200)}.`, "GET /api/agent/views lists them.");
212
+ const at = exportAt(api, rec, version);
213
+ if (at !== null && typeof at === "object")
214
+ return at;
215
+ const v = api.graph();
216
+ if (!(v instanceof View))
217
+ return v;
218
+ const authors = viewAuthors(api, rec, at, v);
219
+ const { version: _kept, ...base } = rec;
220
+ const tv = titleVersion(api, rec, at, version);
221
+ return ok({ view: rec.id, title: docTitle({ ...base, ...(tv !== undefined ? { version: tv } : {}) }, titleContext(api.world)), author: authorLine(authors), authors });
222
+ }
223
+ /** The outline of the document of view `view` at the build `version` names (ExportSpec decision
224
+ * 18; left out, the view's own): its sections, declarations and notes in the document's order,
225
+ * without their text, from the board as its page draws it (as `document` reads it). What the
226
+ * page's linear form draws (GET /api/export/outline); a view too large to print has one too. */
227
+ export function exportOutline(api, view, version) {
228
+ const rec = view ? api.world.views?.book.get(view) : undefined;
229
+ if (!rec)
230
+ return fail(404, `There is no view ${view.slice(0, 200)}.`, "GET /api/agent/views lists them.");
231
+ const at = exportAt(api, rec, version);
232
+ if (at !== null && typeof at === "object")
233
+ return at;
234
+ const v = api.graph();
235
+ if (!(v instanceof View))
236
+ return v;
237
+ const notes = api.world.views?.book.notes ?? [];
238
+ const memory = api.world.views?.book.memoryOf(rec.id, rec.clustering) ?? null;
239
+ const whole = v.meta.layouts?.[rec.clustering];
240
+ let g = v.g;
241
+ let review = api.world.review.data;
242
+ let past;
243
+ if (at !== null) {
244
+ const b = api.pasts.get(at, v.g, v.version, (m) => v.modules.get(m)?.file ?? null);
245
+ if (!b)
246
+ return fail(404, `There is no snapshot ${at}.`, "GET /api/agent/history lists them.");
247
+ past = { snapshot: at, nowName: b.past.nowName, now: v.g, nowReview: review };
248
+ g = b.past.graph;
249
+ review = reviewThen(review, b.past.nowName);
250
+ }
251
+ const set = evaluate(rec.scope, { g, review });
252
+ const plan = planDoc(g, set, rec.clustering, rec.hidden[rec.clustering] ?? [], outsideKeys(g, review));
253
+ const board = boardSpots({ g, review, rec, memory, whole, notes, ...(past ? { past } : {}) });
254
+ return ok({ view: rec.id, ...(at !== null ? { version: at } : {}), outline: outlineOf(plan, g, board) });
255
+ }
256
+ /** The exported document's model (ExportSpec decision 6) of view `view` with `settings` at the
257
+ * build `version` names (decision 16; left out, the view's own), as a request sends them: what
258
+ * the page's Export and an agent typeset (POST /api/export, POST /api/agent/export), and what
259
+ * agents read as JSON (GET /api/agent/export). `retired`: the rest of the request, where what is
260
+ * no longer taken is looked for. */
261
+ export async function document(api, view, settings, retired = {}, version) {
262
+ const r = await docInput(api, view, settings, retired, version);
263
+ if (!("input" in r))
264
+ return r;
265
+ try {
266
+ const doc = buildDoc(r.input);
267
+ // what the document does not say of how it was made (decision 8), and of its order and figures
268
+ const { board, files } = r.input;
269
+ const notes = [...docNotes(doc), ...(board?.fresh ? [FRESH_BOARD] : []), ...(files ? figureNotes(board?.notes ?? [], r.input.review, files) : [])];
270
+ return { doc, notes };
271
+ }
272
+ catch (e) {
273
+ // a view of nothing of the project, or of more than a document prints
274
+ if (e instanceof DocInputError)
275
+ return fail(400, `${e.message}.`, VIEW_HINT);
276
+ throw e;
277
+ }
278
+ }
279
+ /** Typeset a document (ExportSpec decisions 6 and 11): the job that does it, at once — 202 while
280
+ * it runs, 200 once done (the same document asked again, or one the cache holds). For the page's
281
+ * POST /api/export and the agents' POST /api/agent/export alike; an agent (`agent`, the caller)
282
+ * has one job running at most, and is answered 429 while it has, with that job. */
283
+ export async function exportStart(api, body, agent) {
284
+ const ex = api.exporter;
285
+ if (!ex)
286
+ return fail(404, "This server does not export documents.", "GET /api/agent/export gives the document's model as JSON.");
287
+ if (!ex.available())
288
+ return fail(503, "XeLaTeX is not installed on the server, so documents cannot be typeset here.", "GET /api/agent/export gives the document's model as JSON.");
289
+ const owner = agent ? jobOwner(agent) : null;
290
+ const was = owner ? api.exportJobs.get(owner) : undefined;
291
+ const busy = was ? ex.job(was) : null;
292
+ if (busy?.state === "running")
293
+ return fail(429, "You have a document being typeset already: one at a time.", `Wait for it (GET /api/agent/export/job?id=${busy.id}), then ask again.`, { job: busy }, { "retry-after": "5" });
294
+ const b = body && typeof body === "object" && !Array.isArray(body) ? body : {};
295
+ const d = await document(api, b.view, b.settings, b, b.version);
296
+ if (!("doc" in d))
297
+ return d;
298
+ // another request of the same agent may have started one while this was being built
299
+ const raced = owner ? api.exportJobs.get(owner) : undefined;
300
+ const running = raced && raced !== was ? ex.job(raced) : null;
301
+ if (running?.state === "running")
302
+ return fail(429, "You have a document being typeset already: one at a time.", `Wait for it (GET /api/agent/export/job?id=${running.id}), then ask again.`, { job: running }, { "retry-after": "5" });
303
+ const job = ex.compile(renderLatex(d.doc), d.notes, figureFiles(d.doc, api.world.library));
304
+ if (owner && job.state === "running")
305
+ api.exportJobs.set(owner, job.id);
306
+ return { status: job.state === "running" ? 202 : 200, body: { job, ...(agent ? jobLinks(job) : {}) } };
307
+ }
308
+ /** How a typesetting job is doing, by its id; for agents with what to ask next. */
309
+ export function exportJob(api, id, agent) {
310
+ const job = api.exporter?.job(id) ?? null;
311
+ if (!job)
312
+ return fail(404, "There is no such document: it was never asked for, or has left the cache.", "POST /api/agent/export starts one; the same request again finds it while it is kept.");
313
+ return ok({ job, ...(agent ? jobLinks(job) : {}) });
314
+ }
315
+ /** A file of a typeset document: the PDF, the .tex, the style file, or the sources' zip. 409
316
+ * while it is still being typeset (with Retry-After) or where it failed, 404 where it is unknown
317
+ * or has left the cache. */
318
+ export function exportFile(api, id, what) {
319
+ const w = what ?? "pdf";
320
+ if (w !== "pdf" && w !== "tex" && w !== "sty" && w !== "zip")
321
+ return fail(400, "what is pdf, tex, sty or zip.", "pdf (the default): the document; tex and sty: its LaTeX and the style file; zip: everything needed to typeset it again.");
322
+ const ex = api.exporter;
323
+ const job = ex?.job(id) ?? null;
324
+ if (!ex || !job)
325
+ return fail(404, "There is no such document: it was never asked for, or has left the cache.", "POST /api/agent/export starts one; the same request again finds it while it is kept.");
326
+ if (job.state === "running")
327
+ return fail(409, "That document is still being typeset.", `Ask again in a few seconds, or wait for GET /api/agent/export/job?id=${job.id} to say done.`, { job }, { "retry-after": "2" });
328
+ if (job.state === "failed")
329
+ return fail(409, `That document could not be typeset: ${(job.error ?? "XeLaTeX failed").replace(/\.$/, "")}.`, "Its job has the end of XeLaTeX's log (GET /api/agent/export/job).", { job });
330
+ const f = ex.file(id, w);
331
+ if (!f)
332
+ return fail(404, "That document has left the cache.", "Ask for it again: POST /api/agent/export.");
333
+ return { status: 200, body: null, file: f };
334
+ }
335
+ export async function exportGet(api, a) {
336
+ const raw = a.query.get("settings");
337
+ let settings;
338
+ if (raw) {
339
+ try {
340
+ settings = JSON.parse(raw);
341
+ }
342
+ catch {
343
+ return fail(400, "settings is not JSON.", 'Send settings as a JSON object, URL-encoded, e.g. {"paper":"letter"}.');
344
+ }
345
+ }
346
+ const r = await document(api, a.query.get("view") ?? undefined, settings, Object.fromEntries(a.query), a.query.get("version") ?? undefined);
347
+ return "doc" in r ? ok(r.doc) : r;
348
+ }
349
+ export function exportPost(api, a) {
350
+ const no = needAgent(a.caller);
351
+ if (no)
352
+ return no;
353
+ return exportStart(api, a.body, a.caller);
354
+ }
355
+ export function exportFileGet(api, a) {
356
+ // an MCP server from before it saved files (0.3.0) relays `saveTo` as a parameter and would hand the
357
+ // model a PDF as text: it is told to update instead
358
+ const what = a.query.get("what") ?? "pdf";
359
+ if (a.query.has("saveTo") && (what === "pdf" || what === "zip"))
360
+ return fail(400, "Your MCP server cannot save files yet.", "Download it again (GET /api/agent/mcp, as GET /api/agent/mcp/install says), restart your client, then save it again (the export tool, action file).");
361
+ return exportFile(api, a.query.get("id") ?? "", what);
362
+ }
363
+ /** A link to a picture of the board (ExportSpec decision 20, drafted 2026-10-15): a recipe
364
+ * (shared/artrecipe.ts) checked, and resolved against the board of the view it names — the
365
+ * Project's layout in the view's clustering — so that a name, a target or a cluster the board has
366
+ * not is refused here rather than drawn as a picture unlike the one meant; the selection it gives
367
+ * goes in the address, the recipe after it. The page that opens the link resolves it again
368
+ * against the board it opens on, opens the artwork mode, and saves the files asked for. Nothing
369
+ * changes here, and the link holds no key. */
370
+ export async function artwork(api, a) {
371
+ const no = needAgent(a.caller);
372
+ if (no)
373
+ return no;
374
+ const b = body(a);
375
+ const read = readRecipe(b.recipe);
376
+ if ("error" in read)
377
+ return fail(400, read.error, read.hint);
378
+ const r = read.recipe;
379
+ const save = b.save === undefined || b.save === null ? [] : typeof b.save === "string" ? b.save.split(",").map((k) => k.trim()) : null;
380
+ if (!save || save.some((k) => k !== "png" && k !== "svg"))
381
+ return fail(400, "save is png, svg or png,svg.", "The files the page saves once the board is ready; left out, none.");
382
+ const v = api.graph();
383
+ if (!(v instanceof View))
384
+ return v;
385
+ let sel = null;
386
+ if (r.selection) {
387
+ const i = api.find(v, r.selection.name, "selection.name");
388
+ if (typeof i !== "number")
389
+ return i;
390
+ sel = v.g.nodes[i].name;
391
+ }
392
+ const rec = r.view && r.view !== PROJECT ? api.world.views?.book.get(r.view) : undefined;
393
+ if (r.view && r.view !== PROJECT && !rec)
394
+ return fail(404, `There is no view ${r.view}.`, "GET /api/agent/views lists them; left out, the Project.");
395
+ const L = v.meta.layouts[rec?.clustering ?? "namespace"];
396
+ const res = resolveRecipe(r, {
397
+ clusters: L.clusters,
398
+ clusterOf: (name) => {
399
+ const i = v.g.byName.get(name);
400
+ return i === undefined ? undefined : L.cluster[i];
401
+ },
402
+ targets: Object.keys(api.world.review.data.targets),
403
+ projectCount: v.meta.projectCount,
404
+ });
405
+ if (res.problems.length)
406
+ return fail(404, `The recipe names what the board has not: ${res.problems.join("; ")}.`, "Clusters by key (GET /api/agent/views/view lists a view's), declarations and targets by full name (GET /api/agent/search; the targets: GET /api/agent/targets). A target of the review the graph no longer has is left out unsaid where the recipe does not name it.", { problems: res.problems });
407
+ const address = addressOf({ view: rec ? rec.id : null, scope: null, mode: r.selection?.mode ?? "tcb", selection: null, sel });
408
+ const link = `${a.base ?? ""}/#${address}&${RECIPE_PARAM}=${encodeRecipe(r)}${save.length ? `&${SAVE_PARAM}=${[...new Set(save)].join(",")}` : ""}`;
409
+ const look = res.look;
410
+ return ok({
411
+ ok: true,
412
+ link,
413
+ length: link.length,
414
+ size: [look.w, look.h],
415
+ names: look.labels === "chosen" ? res.named : look.labels,
416
+ targets: look.targets === "chosen" ? look.shownTargets : look.targets,
417
+ selection: sel ? { name: sel, mode: r.selection.mode ?? "tcb" } : null,
418
+ // names and targets beyond what the artwork carries, left out: said, not refused
419
+ left: res.left,
420
+ note: "It holds no key: it opens for whoever is let in already, or for a script that enters with the key (scripts/artwork-batch.mjs). The page that opens it resolves the recipe again against its board, opens the artwork mode fitted to the whole board, and saves the files asked for on that machine; nothing comes back here.",
421
+ });
422
+ }
423
+ /** The parameters of the export endpoints, as a GET takes them. */
424
+ export const EXPORT_PARAMS = {
425
+ view: "the view's id (GET /api/agent/views lists them; project for the Project; POST /api/agent/views/open {scope} gives one for a query, e.g. key(T)). A view kept at a past build makes that build's document",
426
+ settings: `optional, a JSON object: ${Object.entries(SETTINGS_HELP).map(([k, h]) => `${k} — ${h}`).join("; ")}`,
427
+ version: "optional: the build to print the view at, a snapshot's id (GET /api/agent/history), as the Time Machine shows a view at another build than its own; null or 0 for the latest. Left out: the view's own build",
428
+ };
429
+ /** What an export's notes say where no page had laid the view's board out for what it holds now
430
+ * (server/boardspots.ts): the order is the board the server laid out. */
431
+ const FRESH_BOARD = "No page had laid out this view's board for what it holds now: the document follows the board as the server laid it out from the view's memory, by the rules a page follows, which is the board a page will show when it next opens the view.";
432
+ /** What a request is told of a view to export. */
433
+ const VIEW_HINT = "Export a view, by its id: {view, settings}. What the view holds is what the document prints. A target's key document is its Key view: POST /api/agent/views/open {\"scope\": \"key(<target>)\"}, then export that view; the full review set is a view of its scope, tcb(<target>) except trusted or (uses(<target>) and kind(axiom) and nonstandard), opened the same way; any other view is a curated set.";
434
+ /** Whose typesetting job a request starts: an agent's own token, else its name. */
435
+ function jobOwner(c) {
436
+ return c.token ? `token:${c.token.id}` : `name:${c.name ?? ""}`;
437
+ }
438
+ /** What an agent asks next about a job: how it is doing while it runs, its files once it is done. */
439
+ function jobLinks(job) {
440
+ const at = (what) => `/api/agent/export/file?id=${job.id}&what=${what}`;
441
+ if (job.state === "running")
442
+ return { next: `GET /api/agent/export/job?id=${job.id}` };
443
+ if (job.state === "done")
444
+ return { files: { pdf: at("pdf"), tex: at("tex"), sty: at("sty"), zip: at("zip") } };
445
+ return {};
446
+ }
447
+ /** The project's commit, where it is a git repository: `git rev-parse`, which only reads (and is
448
+ * told to take no lock), asked at most once every ten seconds. Null where git is not there or the
449
+ * project is not a repository. */
450
+ /** The commit a document of the graph on show is of: a branch's build's, else what git says now. */
451
+ function shownOr(shown, root) {
452
+ return shown === undefined ? commitOf(root) : shown;
453
+ }
454
+ export function commitOf(root) {
455
+ const now = Date.now();
456
+ const was = commits.get(root);
457
+ if (was && now - was.at < 10_000)
458
+ return was.commit;
459
+ const git = (...args) => {
460
+ const r = spawnSync("git", ["-C", root, ...args], { encoding: "utf8", timeout: 5000, env: childEnv({ GIT_OPTIONAL_LOCKS: "0" }), stdio: ["ignore", "pipe", "ignore"] });
461
+ return r.status === 0 ? r.stdout.trim() : null;
462
+ };
463
+ const hash = git("rev-parse", "HEAD");
464
+ const branch = hash ? git("rev-parse", "--abbrev-ref", "HEAD") : null;
465
+ const commit = hash && /^[0-9a-f]{7,64}$/.test(hash) ? { hash, branch: branch && branch !== "HEAD" ? branch : null } : null;
466
+ commits.set(root, { at: now, commit });
467
+ return commit;
468
+ }
469
+ const commits = new Map();