visualproof 0.6.0 → 0.8.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 (96) 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-export.webp +0 -0
  9. package/dist/assets/tips/tour-keys.webp +0 -0
  10. package/dist/assets/tips/tour-library.webp +0 -0
  11. package/dist/assets/tips/tour-project.webp +0 -0
  12. package/dist/assets/tips/tour-review.webp +0 -0
  13. package/dist/assets/tips/tour-share.webp +0 -0
  14. package/dist/assets/tips/tour-source.webp +0 -0
  15. package/dist/assets/tips/tour-target.webp +0 -0
  16. package/dist/assets/tips/tour-view.webp +0 -0
  17. package/dist/assets/tips/tour.json +90 -90
  18. package/dist/assets/tips/tour.webp +0 -0
  19. package/dist/extractor/Extract.lean +13 -3
  20. package/dist/server/agent.js +104 -2881
  21. package/dist/server/agentactivity.js +72 -0
  22. package/dist/server/agentadvice.js +128 -0
  23. package/dist/server/agentdocs.js +1 -1
  24. package/dist/server/agententry.js +180 -0
  25. package/dist/server/agentexport.js +469 -0
  26. package/dist/server/agentfollow.js +412 -0
  27. package/dist/server/agentgraph.js +128 -0
  28. package/dist/server/agentlean.js +144 -0
  29. package/dist/server/agentlibrary.js +1 -1
  30. package/dist/server/agentplaces.js +242 -0
  31. package/dist/server/agentread.js +569 -0
  32. package/dist/server/agenttalk.js +282 -0
  33. package/dist/server/agenttcb.js +378 -0
  34. package/dist/server/agentviews.js +3 -3
  35. package/dist/server/app.js +379 -0
  36. package/dist/server/appaccess.js +127 -0
  37. package/dist/server/appagent.js +110 -0
  38. package/dist/server/appgraph.js +176 -0
  39. package/dist/server/appshare.js +179 -0
  40. package/dist/server/appsite.js +120 -0
  41. package/dist/server/apptalk.js +195 -0
  42. package/dist/server/artcmd.js +1 -1
  43. package/dist/server/events.js +1 -1
  44. package/dist/server/history.js +51 -3
  45. package/dist/server/historyapi.js +34 -2
  46. package/dist/server/hover.js +11 -7
  47. package/dist/server/identity.js +1 -1
  48. package/dist/server/libraryroute.js +3 -3
  49. package/dist/server/live.js +162 -12
  50. package/dist/server/main.js +17 -1746
  51. package/dist/server/mcptools.js +1 -1
  52. package/dist/server/options.js +350 -0
  53. package/dist/server/outside.js +311 -0
  54. package/dist/server/pastdoc.js +22 -3
  55. package/dist/server/presence.js +25 -8
  56. package/dist/server/project.js +28 -4
  57. package/dist/server/readonlygate.js +4 -0
  58. package/dist/server/reviewapi.js +10 -3
  59. package/dist/server/send.js +259 -0
  60. package/dist/server/talk.js +13 -7
  61. package/dist/server/tokens.js +3 -3
  62. package/dist/server/view.js +3 -1
  63. package/dist/server/views.js +1 -1
  64. package/dist/shared/artrecipe.js +3 -3
  65. package/dist/shared/board.js +9 -8
  66. package/dist/shared/collab.js +54 -7
  67. package/dist/shared/comment.js +1 -1
  68. package/dist/shared/doc/build.js +30 -14
  69. package/dist/shared/doc/latex.js +7 -2
  70. package/dist/shared/doc/model.js +4 -2
  71. package/dist/shared/doc/sections.js +21 -4
  72. package/dist/shared/outside.js +16 -0
  73. package/dist/shared/pastgraph.js +11 -2
  74. package/dist/shared/pointer.js +152 -0
  75. package/dist/shared/query.js +36 -5
  76. package/dist/shared/review.js +34 -2
  77. package/dist/shared/scope.js +1 -1
  78. package/dist/shared/sharesnap.js +15 -0
  79. package/dist/shared/titles.js +4 -0
  80. package/dist/web/bundle/app.js +51061 -49518
  81. package/dist/web/index.html +4 -0
  82. package/dist/web/src/canvas.js +16 -14
  83. package/dist/web/src/highlight.js +8 -3
  84. package/dist/web/src/reviewqueue.js +52 -10
  85. package/dist/web/src/selection.js +1 -1
  86. package/dist/web/src/status.js +65 -1
  87. package/dist/web/src/theme.js +1 -1
  88. package/dist/web/src/visitors.js +1 -1
  89. package/dist/web/style.css +121 -7
  90. package/docs/agent-api/advice.md +4 -1
  91. package/docs/agent-api/export.md +8 -5
  92. package/docs/agent-api/following.md +9 -3
  93. package/docs/agent-api/history.md +3 -1
  94. package/docs/agent-api/reading.md +8 -2
  95. package/docs/agent-api/views.md +3 -1
  96. package/package.json +1 -1
@@ -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;
@@ -14,7 +14,7 @@ import { MIME, MAX_FILE } from "../shared/library.js";
14
14
  import { fail } from "./agent.js";
15
15
  import { graphOf } from "./agentviews.js";
16
16
  import { libraryApiOf } from "./library.js";
17
- /** Where an agent uploads a file's bytes: main.ts reads the body of this one as bytes, not JSON. */
17
+ /** Where an agent uploads a file's bytes: appagent.ts reads the body of this one as bytes, not JSON. */
18
18
  export const UPLOAD_PATH = "/api/agent/library/upload";
19
19
  /** The library's operations for the agents' API: the same object as the page's routes use. */
20
20
  export function libraryFor(world) {
@@ -0,0 +1,242 @@
1
+ // The Project view's places and pins (docs/agent-api/views.md; AgentSpec decision 4), the endpoints of
2
+ // server/agent.ts: where a declaration or a cluster is, as laid out and as pinned, and what is near
3
+ // it; pins dropped and let go of as one batch, recorded with what each replaced; and a batch undone,
4
+ // by an agent or from a page's Activity. A place is brought inside its parent as a drag would bring
5
+ // it. Other views are arranged through server/agentviews.ts.
6
+ import { CLUSTER_MODES, invalidOps } from "../shared/places.js";
7
+ import { PROJECT } from "../shared/views.js";
8
+ import { View } from "./agentgraph.js";
9
+ import { body, clampInt, fail, needAgent, ok, str } from "./agent.js";
10
+ export function place(api, a) {
11
+ const v = api.graph();
12
+ if (!(v instanceof View))
13
+ return v;
14
+ const mode = (a.query.get("mode") ?? "namespace");
15
+ if (!CLUSTER_MODES.includes(mode))
16
+ return fail(400, `mode ${mode} is neither namespace nor module.`, "Leave it out for namespace, the page's default.");
17
+ const hidden = projectHidden(api, mode);
18
+ const L = v.projectLayout(mode, hidden);
19
+ const near = a.query.get("near");
20
+ const point = near === null ? null : near.split(",").map(Number);
21
+ if (point && (point.length !== 2 || !point.every(Number.isFinite)))
22
+ return fail(400, "near is x,y: two numbers in the parent's coordinates.", "e.g. near=12.5,-40: the siblings nearest that place come first.");
23
+ const cluster = a.query.get("cluster");
24
+ let me;
25
+ if (cluster !== null) {
26
+ const c = L.clusters.findIndex((x) => x.key === cluster);
27
+ if (c < 0)
28
+ return fail(404, `There is no cluster ${cluster} by ${mode}.`, "Clusters are named by their full path, e.g. a namespace; GET /api/agent/place?name=<declaration> names its cluster.");
29
+ const cl = L.clusters[c];
30
+ me = { kind: "cluster", index: c, key: cl.key, parent: cl.parent, r: cl.r, laidOut: [cl.lx, cl.ly] };
31
+ }
32
+ else {
33
+ const i = api.find(v, a.query.get("name"));
34
+ if (typeof i !== "number")
35
+ return i;
36
+ me = { kind: "node", index: i, key: v.g.nodes[i].name, parent: L.cluster[i], r: LEAF_R, laidOut: [L.lx[i], L.ly[i]] };
37
+ }
38
+ const pin = pinOf(api, mode, me.kind, me.key);
39
+ // what else is in the parent, each where it is drawn: its pin, or where the layout put it
40
+ const inside = v.inside(mode, hidden, me.parent);
41
+ const sibs = [
42
+ ...inside.nodes.filter((j) => me.kind !== "node" || j !== me.index).map((j) => ({ kind: "node", key: v.g.nodes[j].name, of: v.g.nodes[j].kind, r: LEAF_R, laidOut: [L.lx[j], L.ly[j]] })),
43
+ ...inside.clusters.filter((k) => me.kind !== "cluster" || k !== me.index).map((k) => ({ kind: "cluster", key: L.clusters[k].key, of: null, r: L.clusters[k].r, laidOut: [L.clusters[k].lx, L.clusters[k].ly] })),
44
+ ].map((x) => {
45
+ const p = pinOf(api, mode, x.kind, x.key);
46
+ return { ...x, pin: p, at: p.at ?? x.laidOut };
47
+ });
48
+ const from = point ?? pin.at ?? me.laidOut;
49
+ // nearest first: what a pin there would crowd. The gap is the free space between the two
50
+ // circles, were this one at `from`; below zero they overlap
51
+ const gap = (x) => Math.hypot(x.at[0] - from[0], x.at[1] - from[1]) - x.r - me.r;
52
+ sibs.sort((x, y) => gap(x) - gap(y));
53
+ const limit = clampInt(a.query.get("limit"), 100, 0, 2000);
54
+ const room = roomIn(L, me.parent, me.r);
55
+ return ok({
56
+ mode,
57
+ kind: me.kind,
58
+ key: me.key,
59
+ parent: { ...parentOf(api, L, me.parent), room: shown(roomIn(L, me.parent, 0)) },
60
+ r: me.r,
61
+ room: shown(room),
62
+ laidOut: me.laidOut,
63
+ pinned: pin.at,
64
+ ...(pin.at ? { pinnedBy: pin.by } : {}),
65
+ siblings: {
66
+ total: sibs.length,
67
+ pinned: sibs.filter((x) => x.pin.at).length,
68
+ nearestTo: from,
69
+ more: Math.max(0, sibs.length - limit),
70
+ list: sibs.slice(0, limit).map((x) => ({
71
+ kind: x.kind,
72
+ key: x.key,
73
+ ...(x.of ? { declKind: x.of } : {}),
74
+ r: x.r,
75
+ at: x.at,
76
+ gap: Math.round(gap(x) * 10) / 10,
77
+ pinned: !!x.pin.at,
78
+ ...(x.pin.at ? { pinnedBy: x.pin.by, laidOut: x.laidOut } : {}),
79
+ })),
80
+ },
81
+ });
82
+ }
83
+ function parentOf(api, L, c) {
84
+ return c >= 0 ? { cluster: L.clusters[c].key, r: L.clusters[c].r } : { cluster: null, r: null };
85
+ }
86
+ /** A pin, and who dropped it as far as the server knows (null: not recorded — it was dropped
87
+ * before the server kept who). */
88
+ /** The levels the Project view hides by `mode` (ViewSpec decision 24); none where the world has
89
+ * no views. */
90
+ function projectHidden(api, mode) {
91
+ return api.world.views?.book.get(PROJECT)?.hidden[mode] ?? [];
92
+ }
93
+ function pinOf(api, mode, kind, key) {
94
+ const P = api.world.places.data.layouts[mode];
95
+ const set = kind === "node" ? P.nodes : P.clusters;
96
+ if (!Object.hasOwn(set, key))
97
+ return { at: null, by: null };
98
+ const who = api.world.places.authorOf(mode, kind, key);
99
+ return { at: set[key], by: who ? { name: who.by, agent: !!who.agent, at: who.at } : null };
100
+ }
101
+ export function pins(api, a) {
102
+ const no = needAgent(a.caller) ?? api.refuse(a.caller, "full");
103
+ if (no)
104
+ return no;
105
+ const v = api.graph();
106
+ if (!(v instanceof View))
107
+ return v;
108
+ const b = body(a);
109
+ const mode = (b.mode ?? "namespace");
110
+ if (!CLUSTER_MODES.includes(mode))
111
+ return fail(400, "mode is namespace or module.", "Leave it out for namespace, the page's default.");
112
+ if (!Array.isArray(b.pins) || !b.pins.length || b.pins.length > MAX_PINS)
113
+ return fail(400, `pins is a list of 1 to ${MAX_PINS} {name or cluster, at: [x, y] or null}.`, "at is in the parent cluster's coordinates (GET /api/agent/place); null lets go of the pin.");
114
+ const L = v.projectLayout(mode, projectHidden(api, mode));
115
+ const keys = new Map(L.clusters.map((c, k) => [c.key, k]));
116
+ const ops = [];
117
+ for (const p of b.pins) {
118
+ if (!p || typeof p !== "object")
119
+ return fail(400, "Each pin is {name or cluster, at}.", "e.g. {\"name\": \"A.b\", \"at\": [12, -40]}.");
120
+ let kind, key, room;
121
+ if (typeof p.cluster === "string") {
122
+ const c = keys.get(p.cluster);
123
+ if (c === undefined)
124
+ return fail(404, `There is no cluster ${p.cluster} by ${mode}.`, "GET /api/agent/place?name=<declaration> names the cluster it is in.");
125
+ kind = "cluster";
126
+ key = p.cluster;
127
+ room = roomIn(L, L.clusters[c].parent, L.clusters[c].r);
128
+ }
129
+ else {
130
+ const i = api.find(v, str(p.name));
131
+ if (typeof i !== "number")
132
+ return i;
133
+ kind = "node";
134
+ key = v.g.nodes[i].name;
135
+ room = roomIn(L, L.cluster[i], LEAF_R);
136
+ }
137
+ if (p.at === null)
138
+ ops.push({ op: "unpin", mode, kind, key });
139
+ else
140
+ ops.push({ op: "pin", mode, kind, key, at: inside(p.at, room) });
141
+ }
142
+ const why = invalidOps(ops);
143
+ if (why)
144
+ return fail(400, `The pins are not right (${why}).`, "at is [x, y], two finite numbers in the parent cluster's coordinates.");
145
+ const done = layout(api, a.caller.name, true, ops);
146
+ // where each one went: a place beyond the parent's room is brought in, as a drag would be
147
+ return ok({ ...done, placed: ops.map((o) => (o.op === "pin" ? { key: o.key, at: o.at } : o.op === "unpin" ? { key: o.key, at: null } : null)).filter(Boolean) });
148
+ }
149
+ /** Drop and let go of pins as one batch (AgentSpec decision 4): applied as a page's drop is, and
150
+ * recorded in the timeline with what each pin was before, so that it can be undone at once. */
151
+ function layout(api, by, agent, ops) {
152
+ const P = api.world.places.data.layouts;
153
+ const id = (o) => `${o.mode}\u0000${o.kind}\u0000${o.key}`;
154
+ const pinOf = (o) => (o.kind === "node" ? P[o.mode].nodes : P[o.mode].clusters)[o.key] ?? null;
155
+ const moves = ops.filter((o) => o.op !== "clear");
156
+ const before = new Map();
157
+ for (const o of moves)
158
+ if (!before.has(id(o)))
159
+ before.set(id(o), { o, at: pinOf(o) });
160
+ if (!api.world.places.apply(moves, { by, agent }))
161
+ return { ok: true, id: null, count: 0 };
162
+ api.world.placesChanged(moves, null, by);
163
+ const as = (o, at) => at ? { op: "pin", mode: o.mode, kind: o.kind, key: o.key, at } : { op: "unpin", mode: o.mode, kind: o.kind, key: o.key };
164
+ // what the batch left (each pin once, where it ended), and what puts back what was there
165
+ const after = [...before.values()].map(({ o }) => as(o, pinOf(o)));
166
+ const undo = [...before.values()].map(({ o, at }) => as(o, at));
167
+ const e = api.world.timeline.add({ kind: "layout", by, ...(agent ? { agent: true } : {}), count: before.size, ops: after, undo });
168
+ return { ok: true, id: e.id, count: before.size };
169
+ }
170
+ /** Undo a layout batch: every pin it set goes back to what it was, except where someone moved it
171
+ * since — that one is left, and the answer (and the timeline) says so. `by` is null for a private
172
+ * reader's undo (CollabSpec decision 8), recorded without a name. */
173
+ export function undo(api, by, agent, id) {
174
+ if (typeof id !== "number" || !Number.isInteger(id))
175
+ return fail(400, "id is the layout batch's number.", "POST /api/agent/pins answers with it; GET /api/agent/activity lists layout events.");
176
+ const events = api.world.timeline.events;
177
+ const e = events.find((x) => x.id === id);
178
+ if (!e || e.kind !== "layout")
179
+ return fail(404, `There is no layout batch #${id}.`, "GET /api/agent/activity lists layout events, each with its id.");
180
+ const done = events.find((x) => x.kind === "undo" && x.of === id);
181
+ if (done)
182
+ return fail(409, `Layout batch #${id} was undone already, by ${done.by ?? "someone"}.`, "Nothing to do.");
183
+ const P = api.world.places.data.layouts;
184
+ const restore = [];
185
+ const kept = [];
186
+ e.ops.forEach((o, k) => {
187
+ if (o.op === "clear")
188
+ return;
189
+ const now = (o.kind === "node" ? P[o.mode].nodes : P[o.mode].clusters)[o.key] ?? null;
190
+ const left = o.op === "pin" ? o.at : null;
191
+ const same = now === left || (!!now && !!left && now[0] === left[0] && now[1] === left[1]);
192
+ if (same)
193
+ restore.push(e.undo[k]);
194
+ else
195
+ kept.push(o.key);
196
+ });
197
+ if (restore.length && api.world.places.apply(restore, { by, agent }))
198
+ api.world.placesChanged(restore, null, by);
199
+ const u = api.world.timeline.add({ kind: "undo", by, ...(agent ? { agent: true } : {}), of: id, restored: restore.length, kept });
200
+ return ok({
201
+ ok: true,
202
+ id: u.id,
203
+ restored: restore.length,
204
+ kept,
205
+ ...(kept.length ? { note: `${kept.length} left where they are: someone moved them since.` } : {}),
206
+ });
207
+ }
208
+ export function undoPost(api, a) {
209
+ const no = needAgent(a.caller) ?? api.refuse(a.caller, "full");
210
+ if (no)
211
+ return no;
212
+ return undo(api, a.caller.name, true, body(a).id);
213
+ }
214
+ export const MAX_PINS = 500;
215
+ /** a declaration's radius as the layout packs it (web/src/scene.ts, LEAF_R) */
216
+ const LEAF_R = 5;
217
+ /** How far from its parent's centre something of radius `r` may be placed, as the page keeps a
218
+ * drop inside its parent's circle (web/src/scene.ts, `inside`): the circle less the room left for
219
+ * its label. Where the page folded the thing, it is smaller and may go further; this is the
220
+ * bound for every page. Infinity at the top, where nothing holds it. */
221
+ function roomIn(L, parent, r) {
222
+ if (parent < 0)
223
+ return Infinity;
224
+ const P = L.clusters[parent];
225
+ return Math.max(0, P.r - (10 + Math.min(14, Math.sqrt(P.count))) - r);
226
+ }
227
+ /** A room as the API says it: to a tenth, never beyond it; null at the top, where nothing holds it. */
228
+ function shown(room) {
229
+ return Number.isFinite(room) ? Math.floor(room * 10) / 10 : null;
230
+ }
231
+ /** A place brought within `room` of the centre, a hair inside so that rounding keeps it there, as
232
+ * every page would bring it. Anything not a place is left for invalidOps to refuse. */
233
+ function inside(at, room) {
234
+ if (!Array.isArray(at) || at.length !== 2 || !at.every((x) => typeof x === "number" && Number.isFinite(x)))
235
+ return at;
236
+ const [x, y] = at;
237
+ const d = Math.hypot(x, y);
238
+ if (d <= room)
239
+ return [x, y];
240
+ const k = Math.max(0, room - 0.1) / d;
241
+ return [Math.round(x * k * 10) / 10, Math.round(y * k * 10) / 10];
242
+ }