@graview/tools 0.1.18 → 0.1.20

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 (63) hide show
  1. package/README.md +47 -0
  2. package/dist/agent/tools.d.ts +37 -0
  3. package/dist/agent/tools.d.ts.map +1 -1
  4. package/dist/agent/tools.js +87 -15
  5. package/dist/agent/tools.js.map +1 -1
  6. package/dist/ai.d.ts +64 -0
  7. package/dist/ai.d.ts.map +1 -0
  8. package/dist/ai.js +11 -0
  9. package/dist/ai.js.map +1 -0
  10. package/dist/capital.d.ts +3 -0
  11. package/dist/capital.d.ts.map +1 -0
  12. package/dist/capital.js +3 -0
  13. package/dist/capital.js.map +1 -0
  14. package/dist/conversation.d.ts +36 -12
  15. package/dist/conversation.d.ts.map +1 -1
  16. package/dist/conversation.js +95 -31
  17. package/dist/conversation.js.map +1 -1
  18. package/dist/dev-ai.d.ts +27 -0
  19. package/dist/dev-ai.d.ts.map +1 -0
  20. package/dist/dev-ai.js +48 -0
  21. package/dist/dev-ai.js.map +1 -0
  22. package/dist/draft.d.ts +194 -0
  23. package/dist/draft.d.ts.map +1 -0
  24. package/dist/draft.js +1083 -0
  25. package/dist/draft.js.map +1 -0
  26. package/dist/frame.d.ts +6 -6
  27. package/dist/frame.d.ts.map +1 -1
  28. package/dist/frame.js +5 -5
  29. package/dist/frame.js.map +1 -1
  30. package/dist/go.d.ts +177 -0
  31. package/dist/go.d.ts.map +1 -0
  32. package/dist/go.js +839 -0
  33. package/dist/go.js.map +1 -0
  34. package/dist/index.d.ts +7 -3
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +4 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/intelligence.d.ts.map +1 -1
  39. package/dist/intelligence.js +2 -2
  40. package/dist/intelligence.js.map +1 -1
  41. package/dist/keep.d.ts +45 -0
  42. package/dist/keep.d.ts.map +1 -0
  43. package/dist/keep.js +86 -0
  44. package/dist/keep.js.map +1 -0
  45. package/dist/local.d.ts +50 -42
  46. package/dist/local.d.ts.map +1 -1
  47. package/dist/local.js +104 -146
  48. package/dist/local.js.map +1 -1
  49. package/dist/providers/schema.d.ts.map +1 -1
  50. package/dist/providers/schema.js +7 -7
  51. package/dist/providers/schema.js.map +1 -1
  52. package/dist/providers/structure.d.ts.map +1 -1
  53. package/dist/providers/structure.js +2 -2
  54. package/dist/providers/structure.js.map +1 -1
  55. package/dist/suggest.d.ts +102 -0
  56. package/dist/suggest.d.ts.map +1 -0
  57. package/dist/suggest.js +234 -0
  58. package/dist/suggest.js.map +1 -0
  59. package/package.json +19 -3
  60. package/dist/rungs.d.ts +0 -73
  61. package/dist/rungs.d.ts.map +0 -1
  62. package/dist/rungs.js +0 -60
  63. package/dist/rungs.js.map +0 -1
package/dist/draft.js ADDED
@@ -0,0 +1,1083 @@
1
+ import { actingAs, declaredLenses, isShippedLens, isSystem, placesOf, SHIPPED_LENSES, SHIPPED_LENS_NAMES, } from "@graview/core";
2
+ import { fieldSpecOf, parseExpr } from "@graview/core/document";
3
+ import { firstJsonObject } from "./intelligence.js";
4
+ import { capitalize } from "./capital.js";
5
+ export const isDraftFailure = (result) => "failed" in result;
6
+ // ── sight ───────────────────────────────────────────────────────────────────
7
+ /**
8
+ * THE KINDS A SEAT MAY SEE, as a draft reads them: every kind when the
9
+ * policy says nothing of sight, or for the system; otherwise the kinds a
10
+ * sight grants one of the principal's roles (an agent, the person it acts
11
+ * for). `own` sights still reach the kind — which records is the store's
12
+ * question, asked as the draft is drawn.
13
+ */
14
+ export function draftSight(app, principal) {
15
+ const all = app.schema.kinds;
16
+ const sees = app.policy?.sees;
17
+ if (!sees?.length || isSystem(principal))
18
+ return { kinds: all };
19
+ const roles = actingAs(principal).roles ?? [];
20
+ const granted = new Set(sees.filter((sight) => sight.roles === "*" || roles.some((role) => sight.roles.includes(role))).flatMap((sight) => sight.kinds));
21
+ return { kinds: all.filter((kind) => granted.has(kind)) };
22
+ }
23
+ /** The schema as a seat sees it: only the kinds it may see, and only relations between them. */
24
+ function seenSchema(schema, sight) {
25
+ if (!sight)
26
+ return schema;
27
+ const kinds = new Set(sight.kinds.filter((kind) => schema.tryDefinition(kind) !== undefined));
28
+ if (kinds.size === schema.kinds.length)
29
+ return schema;
30
+ const narrowed = new Map();
31
+ const definitionOf = (kind) => {
32
+ if (!kinds.has(kind))
33
+ return undefined;
34
+ if (!narrowed.has(kind)) {
35
+ const definition = schema.tryDefinition(kind);
36
+ const edges = Object.fromEntries(Object.entries(definition?.edges ?? {}).flatMap(([name, edge]) => {
37
+ if (edge.to === "*")
38
+ return [[name, edge]];
39
+ const to = edge.to.filter((target) => kinds.has(target));
40
+ return to.length > 0 ? [[name, { ...edge, to }]] : [];
41
+ }));
42
+ narrowed.set(kind, { ...definition, edges });
43
+ }
44
+ return narrowed.get(kind);
45
+ };
46
+ return {
47
+ ...schema,
48
+ definitions: schema.definitions.filter((definition) => kinds.has(definition.kind)),
49
+ kinds: schema.kinds.filter((kind) => kinds.has(kind)),
50
+ tryDefinition: definitionOf,
51
+ definition: (kind) => {
52
+ const found = definitionOf(kind);
53
+ if (!found)
54
+ throw new Error(`Unknown node kind "${kind}"`);
55
+ return found;
56
+ },
57
+ };
58
+ }
59
+ const kebab = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
60
+ const wordsOf = (name) => kebab(name).replace(/[-_]+/g, " ").trim();
61
+ function readApp(schema) {
62
+ const kinds = [];
63
+ for (const kind of schema.kinds) {
64
+ const definition = schema.tryDefinition(kind);
65
+ if (!definition)
66
+ continue;
67
+ const labels = definition.display?.labels ?? {};
68
+ const fields = Object.entries(definition.fields?.shape ?? {})
69
+ .filter(([name]) => name !== "id" && name !== "kind")
70
+ .map(([name, field]) => {
71
+ const spec = fieldSpecOf(field);
72
+ return { name, type: spec?.type, ...(spec?.options ? { options: spec.options } : {}), words: (labels[name] ?? wordsOf(name)).toLowerCase() };
73
+ });
74
+ const edges = Object.entries(definition.edges ?? {}).map(([name, edge]) => ({
75
+ name,
76
+ from: kind,
77
+ to: edge.to === "*" ? schema.kinds.filter((other) => other !== kind) : edge.to,
78
+ words: wordsOf(name),
79
+ }));
80
+ const plural = (definition.plural ?? `${wordsOf(kind)}s`).toLowerCase();
81
+ kinds.push({ kind, plural, noun: (definition.noun ?? wordsOf(kind)).toLowerCase(), fields, roles: definition.fieldRoles ?? {}, edges });
82
+ }
83
+ const byKind = new Map(kinds.map((info) => [info.kind, info]));
84
+ return { schema, kinds, info: (kind) => byKind.get(kind) };
85
+ }
86
+ const fieldOf = (info, name) => (name === undefined ? undefined : info.fields.find((field) => field.name === name));
87
+ const isDate = (field) => field?.type === "date" || field?.type === "datetime";
88
+ const isNumber = (field) => field?.type === "number" || field?.type === "integer";
89
+ // ── the ask, read ────────────────────────────────────────────────────────────
90
+ const normal = (ask) => ` ${ask
91
+ .toLowerCase()
92
+ .replace(/[“”"’‘]/g, "'")
93
+ .replace(/[^\p{L}\p{N}' -]+/gu, " ")
94
+ .replace(/\s+/g, " ")
95
+ .trim()} `;
96
+ const says = (text, phrase) => text.includes(` ${phrase} `);
97
+ const singular = (word) => (word.endsWith("ies") ? `${word.slice(0, -3)}y` : word.endsWith("ses") ? word.slice(0, -2) : word.endsWith("s") ? word.slice(0, -1) : word);
98
+ /** The kinds an ask names, by plural, noun or name, in the order the ask names them. */
99
+ function kindsNamed(text, reading) {
100
+ const found = [];
101
+ for (const info of reading.kinds) {
102
+ const names = new Set([info.plural, info.noun, `${info.noun}s`, wordsOf(info.kind), `${wordsOf(info.kind)}s`]);
103
+ let at = -1;
104
+ for (const name of names) {
105
+ const index = text.indexOf(` ${name} `);
106
+ if (index >= 0 && (at < 0 || index < at))
107
+ at = index;
108
+ }
109
+ if (at >= 0)
110
+ found.push({ info, at });
111
+ }
112
+ return found.sort((a, b) => a.at - b.at).map((one) => one.info);
113
+ }
114
+ /** A field of a kind the words name: by its label, its name in words, or a word of either. */
115
+ function fieldNamed(info, words, accept) {
116
+ const wanted = words.trim().toLowerCase();
117
+ if (wanted.length === 0)
118
+ return undefined;
119
+ const candidates = info.fields.filter((field) => !accept || accept(field));
120
+ return (candidates.find((field) => field.words === wanted || wordsOf(field.name) === wanted || field.name.toLowerCase() === wanted) ??
121
+ candidates.find((field) => field.words === singular(wanted) || wordsOf(field.name) === singular(wanted)) ??
122
+ candidates.find((field) => wanted.split(" ").some((word) => word.length > 2 && (field.words.split(" ").includes(word) || field.words.split(" ").includes(singular(word))))));
123
+ }
124
+ /** A relation of a kind the words name. */
125
+ function edgeNamed(info, words, reading) {
126
+ const wanted = words.trim().toLowerCase();
127
+ if (wanted.length === 0)
128
+ return undefined;
129
+ return (info.edges.find((edge) => edge.words === wanted || edge.name.toLowerCase() === wanted) ??
130
+ // "by gardener": the relation that reaches that kind.
131
+ info.edges.find((edge) => edge.to.some((target) => {
132
+ const other = reading.info(target);
133
+ return other !== undefined && (other.noun === singular(wanted) || other.plural === wanted || wordsOf(target) === singular(wanted));
134
+ })) ??
135
+ info.edges.find((edge) => wanted.split(" ").some((word) => word.length > 2 && edge.words.split(" ").includes(word))));
136
+ }
137
+ /** What follows "by" in the ask, up to the next joining word. */
138
+ function byWhat(text) {
139
+ const match = / (?:grouped |group |split |sorted |organi[sz]ed )?by ([\p{L}\p{N}' -]+?)(?= (?:and|with|for|in|on|only|where|from|this|that|as|sorted|grouped) |\s*$)/u.exec(text);
140
+ return match?.[1]?.trim();
141
+ }
142
+ const COVERAGE = /\bwho\b.*\b(covers?|cover|tends?|owns?|handles?|does|works? on|looks? after|is on|is assigned|staffs?|runs?)\b|\bcoverage\b|\bmatrix\b|\bwho covers\b/;
143
+ const CALENDAR = /\bcalendar\b|\bmonth\b|\bagenda\b|\bschedule\b|\bdue\b|\bdeadlines?\b|\bdates?\b|\bwhen\b/;
144
+ const TIMELINE = /\btimeline\b|\bover time\b|\bgantt\b|\bspans?\b|\bweek\b/;
145
+ const COLUMNS = /\bboard\b|\bkanban\b|\bcolumns?\b|\bpipeline\b|\bstages?\b|\bstatus\b/;
146
+ const LAYOUT = /\blaid out\b|\blayout\b|\bseating\b|\bwhere (?:they|it|each) (?:sits?|lies?|stands?)\b|\bfloor\b/;
147
+ const PLAN = /\bplan\b|\bmap\b|\bregions?\b/;
148
+ const LIST = /\blist\b|\btable\b|\bgroup(?:ed)? by\b|\bsort(?:ed)? by\b|\bonly\b|\bjust the\b/;
149
+ function intentsOf(text) {
150
+ const out = [];
151
+ // "a list of decisions grouped by status": the reader named the shape, whatever else the words say.
152
+ if (/\blist\b|\btable\b/.test(text))
153
+ out.push("blocks");
154
+ if (COVERAGE.test(text))
155
+ out.push("coverage");
156
+ if (LAYOUT.test(text))
157
+ out.push("board");
158
+ if (/\bfloor plan\b/.test(text) || PLAN.test(text))
159
+ out.push("plan");
160
+ if (TIMELINE.test(text))
161
+ out.push("timeline");
162
+ if (CALENDAR.test(text))
163
+ out.push("calendar");
164
+ if (COLUMNS.test(text))
165
+ out.push("columns");
166
+ if (LIST.test(text) && !out.includes("blocks"))
167
+ out.push("blocks");
168
+ // "deliverables by status": a choice to put things in columns by, said without the word board.
169
+ if (out.length === 0 && byWhat(text))
170
+ out.push("columns");
171
+ return out;
172
+ }
173
+ const windowOf = (text) => {
174
+ const notDone = (done) => (done ? ` and not ${done}` : "");
175
+ if (/\boverdue\b|\blate\b|\bpast due\b/.test(text))
176
+ return { cond: (f, done) => `days(today(), ${f}) < 0${notDone(done)}`, says: (f) => `overdue by ${f.words}` };
177
+ if (/\btoday\b/.test(text))
178
+ return { range: "day", cond: (f) => `days(today(), ${f}) == 0`, says: (f) => `with ${f.words} today` };
179
+ if (/\bthis week\b|\bnext 7 days\b|\bnext week\b/.test(text))
180
+ return { range: "week", cond: (f) => `days(today(), ${f}) >= 0 and days(today(), ${f}) <= 6`, says: (f) => `with ${f.words} in the next week` };
181
+ if (/\bthis month\b|\bnext 30 days\b|\bnext month\b/.test(text))
182
+ return { range: "month", cond: (f) => `days(today(), ${f}) >= 0 and days(today(), ${f}) <= 30`, says: (f) => `with ${f.words} in the next month` };
183
+ if (/\blast month\b|\bpast month\b/.test(text))
184
+ return { range: "month", cond: (f) => `days(today(), ${f}) >= -30 and days(today(), ${f}) <= 0`, says: (f) => `with ${f.words} in the last month` };
185
+ if (/\bthis year\b/.test(text))
186
+ return { range: "year", cond: (f) => `days(today(), ${f}) >= 0 and days(today(), ${f}) <= 365`, says: (f) => `with ${f.words} in the next year` };
187
+ if (/\bquarter\b/.test(text))
188
+ return { range: "quarter", cond: (f) => `days(today(), ${f}) >= 0 and days(today(), ${f}) <= 91`, says: (f) => `with ${f.words} in the next quarter` };
189
+ return undefined;
190
+ };
191
+ const rangeOf = (text) => {
192
+ if (/\bagenda\b|\bin order\b/.test(text))
193
+ return "agenda";
194
+ if (/\btoday\b|\bday\b/.test(text))
195
+ return "day";
196
+ if (/\bweek\b/.test(text))
197
+ return "week";
198
+ if (/\bquarter\b/.test(text))
199
+ return "quarter";
200
+ if (/\byears\b/.test(text))
201
+ return "years";
202
+ if (/\byear\b/.test(text))
203
+ return "year";
204
+ if (/\bmonth\b/.test(text))
205
+ return "month";
206
+ return undefined;
207
+ };
208
+ // ── templates: one per shipped lens ──────────────────────────────────────────
209
+ const PEOPLE = /^(user|person|people|member|staff|gardener|volunteer|owner|agent|employee|worker|team|player|customer|client|contact|party|attendee|guest)s?$/;
210
+ /** Why a template could not draw, said about the kind: "no date field on deliverables". */
211
+ class Cannot extends Error {
212
+ }
213
+ const cannot = (why) => {
214
+ throw new Cannot(why);
215
+ };
216
+ function chooseColumn(info, by) {
217
+ const choices = info.fields.filter((field) => field.type === "enum");
218
+ if (by) {
219
+ const named = fieldNamed(info, by);
220
+ if (named && named.type === "enum")
221
+ return named;
222
+ if (named)
223
+ cannot(`${info.plural}' ${named.words} is not a choice, so it has no columns`);
224
+ }
225
+ const byRole = fieldOf(info, info.roles["status"] ?? info.roles["column"]);
226
+ if (byRole?.type === "enum")
227
+ return byRole;
228
+ const status = choices.find((field) => /^(status|stage|state|phase)$/.test(field.name));
229
+ if (status)
230
+ return status;
231
+ if (choices[0])
232
+ return choices[0];
233
+ return cannot(`${info.plural} have no choice field to put in columns`);
234
+ }
235
+ function chooseDates(info, text) {
236
+ const dates = info.fields.filter(isDate);
237
+ const role = (name) => {
238
+ const field = fieldOf(info, info.roles[name]);
239
+ return isDate(field) ? field : undefined;
240
+ };
241
+ const mentioned = dates.find((field) => says(text, field.words) || says(text, wordsOf(field.name)));
242
+ const start = mentioned ?? role("start") ?? dates.find((field) => /^(due|date|on|at|start|starts|begins|from|sown|when)/i.test(field.name)) ?? dates[0];
243
+ if (!start)
244
+ return cannot(`no date field on ${info.plural}`);
245
+ const end = role("end") ?? dates.find((field) => field !== start && /^(end|ends|until|to|finish|finished|harvested|due|closes|through)/i.test(field.name));
246
+ const done = info.fields.find((field) => field.type === "boolean" && /^(done|finished|complete|completed|closed)$/.test(field.name));
247
+ return { start, ...(end && end !== start ? { end } : {}), ...(done ? { done } : {}) };
248
+ }
249
+ function timelineRoles(info) {
250
+ const start = fieldOf(info, info.roles["start"]);
251
+ const end = fieldOf(info, info.roles["end"]);
252
+ const column = fieldOf(info, info.roles["column"] ?? info.roles["day"] ?? info.roles["columns"]);
253
+ if (isNumber(start) && isNumber(end) && column?.type === "enum")
254
+ return { start: start, end: end, column };
255
+ return undefined;
256
+ }
257
+ function coverageOf(reading, named, text, by) {
258
+ const candidates = [];
259
+ for (const rows of reading.kinds) {
260
+ for (const link of rows.edges) {
261
+ for (const target of link.to) {
262
+ const across = reading.info(target);
263
+ if (!across || across.kind === rows.kind)
264
+ continue;
265
+ let score = 0;
266
+ if (named.includes(rows))
267
+ score += 4;
268
+ if (named.includes(across))
269
+ score += 4;
270
+ if (PEOPLE.test(across.kind) || PEOPLE.test(across.noun))
271
+ score += 3;
272
+ if (by && (link.words.includes(by) || across.noun === singular(by)))
273
+ score += 5;
274
+ if (link.words.split(" ").some((word) => word.length > 2 && text.includes(` ${word}`)))
275
+ score += 2;
276
+ candidates.push({ rows, across, link, score });
277
+ }
278
+ }
279
+ }
280
+ const best = candidates.sort((a, b) => b.score - a.score)[0];
281
+ if (!best)
282
+ return cannot(named[0] ? `${named[0].plural} are joined to nothing else, so there is no who-covers-what to draw` : "nothing here is joined to anything else, so there is no who-covers-what to draw");
283
+ return best;
284
+ }
285
+ /** A recipe from an ask, for one lens over one kind. */
286
+ function recipeFor(intent, info, reading, text, named) {
287
+ const by = byWhat(text);
288
+ switch (intent) {
289
+ case "columns": {
290
+ if (by) {
291
+ const field = fieldNamed(info, by);
292
+ // "deliverables by owner", where owner is a relation: who covers what.
293
+ if (!field || field.type !== "enum") {
294
+ const edge = edgeNamed(info, by, reading);
295
+ if (edge) {
296
+ const across = reading.info(edge.to[0]);
297
+ return { lens: "coverage", kind: info.kind, across: across.kind, link: edge.name };
298
+ }
299
+ }
300
+ }
301
+ return { lens: "columns", kind: info.kind, column: chooseColumn(info, by).name };
302
+ }
303
+ case "calendar": {
304
+ const dates = chooseDates(info, text);
305
+ const range = rangeOf(text);
306
+ return { lens: "calendar", kind: info.kind, start: dates.start.name, ...(dates.end ? { end: dates.end.name } : {}), ...(dates.done ? { done: dates.done.name } : {}), ...(range ? { range } : {}) };
307
+ }
308
+ case "timeline": {
309
+ const roles = timelineRoles(info);
310
+ // A timeline is minutes of a day in columns; asked of dates, the honest timeline of dates is a calendar over a longer range.
311
+ if (roles && !/\bdates?\b|\bdue\b|\bdeadlines?\b|\bmonths?\b|\byears?\b/.test(text))
312
+ return { lens: "timeline", kind: info.kind, start: roles.start.name, end: roles.end.name, column: roles.column.name };
313
+ const dates = chooseDates(info, text);
314
+ return { lens: "calendar", kind: info.kind, start: dates.start.name, ...(dates.end ? { end: dates.end.name } : {}), ...(dates.done ? { done: dates.done.name } : {}), range: rangeOf(text) ?? "quarter" };
315
+ }
316
+ case "coverage": {
317
+ const found = coverageOf(reading, named, text, by);
318
+ return { lens: "coverage", kind: found.rows.kind, across: found.across.kind, link: found.link.name };
319
+ }
320
+ case "board": {
321
+ const x = fieldOf(info, info.roles["x"]) ?? info.fields.find((field) => field.name === "x");
322
+ const y = fieldOf(info, info.roles["y"]) ?? info.fields.find((field) => field.name === "y");
323
+ if (!isNumber(x) || !isNumber(y))
324
+ return cannot(`${info.plural} have no x and y to be laid out by`);
325
+ const inward = reading.kinds.flatMap((other) => other.edges.filter((edge) => edge.to.includes(info.kind) && other.kind !== info.kind));
326
+ const fill = inward[0] ?? info.edges[0];
327
+ if (!fill)
328
+ return cannot(`nothing is joined to ${info.plural} to fill them`);
329
+ return { lens: "board", kind: info.kind, x: x.name, y: y.name, fill: fill.name, ...(fill.from !== info.kind ? { fillFrom: "occupant" } : {}) };
330
+ }
331
+ case "plan": {
332
+ const outline = fieldOf(info, info.roles["outline"]) ?? info.fields.find((field) => field.name === "outline");
333
+ if (!outline)
334
+ return cannot(`${info.plural} have no outline to draw a plan from`);
335
+ return { lens: "plan", kind: info.kind, outline: outline.name };
336
+ }
337
+ case "blocks": {
338
+ const recipe = { lens: "blocks", kind: info.kind, as: /\bcards?\b/.test(text) ? "card" : "row" };
339
+ const group = / group(?:ed)? by ([\p{L}\p{N} -]+?)(?= (?:and|only|sorted|with)|\s*$)/u.exec(text)?.[1] ?? (by && !/ sort(?:ed)? by /.test(text) ? by : undefined);
340
+ if (group) {
341
+ const field = fieldNamed(info, group);
342
+ if (!field || field.type !== "enum")
343
+ return cannot(field ? `${info.plural}' ${field.words} is not a choice, so they cannot be grouped by it` : `${info.plural} have nothing called ${group} to group by`);
344
+ recipe.group = field.name;
345
+ }
346
+ const sort = / sort(?:ed)? by ([\p{L}\p{N} -]+?)(?= (?:and|only|grouped|with)|\s*$)/u.exec(text)?.[1];
347
+ if (sort) {
348
+ const field = fieldNamed(info, sort);
349
+ if (!field)
350
+ return cannot(`${info.plural} have nothing called ${sort} to sort by`);
351
+ recipe.sort = { by: field.name, ...(/\b(newest|latest|desc|descending|most)\b/.test(text) ? { direction: "desc" } : {}) };
352
+ }
353
+ const where = filtersFrom(info, text);
354
+ if (where.length > 0)
355
+ recipe.where = where;
356
+ return recipe;
357
+ }
358
+ }
359
+ }
360
+ /** "only open ones", "only this month", "overdue": the conditions an ask keeps a list to. */
361
+ function filtersFrom(info, text) {
362
+ const out = [];
363
+ const window = windowOf(text);
364
+ if (window) {
365
+ const dates = info.fields.filter(isDate);
366
+ const role = fieldOf(info, info.roles["start"]);
367
+ const field = dates.find((one) => says(text, one.words)) ?? (isDate(role) ? role : undefined) ?? dates[0];
368
+ if (!field || !isDate(field))
369
+ cannot(`no date field on ${info.plural}`);
370
+ const done = info.fields.find((one) => one.type === "boolean" && /^(done|finished|complete|completed|closed)$/.test(one.name));
371
+ out.push({ expr: window.cond(field.name, /\boverdue\b|\blate\b|\bpast due\b/.test(text) ? done?.name : undefined), says: window.says(field) });
372
+ }
373
+ // "only open", "just the agreed ones": a choice's value.
374
+ if (/\bonly\b|\bjust\b|\bthat are\b|\bwhich are\b/.test(text)) {
375
+ for (const field of info.fields) {
376
+ if (field.type !== "enum")
377
+ continue;
378
+ const value = field.options?.find((option) => says(text, option.toLowerCase()) || says(text, wordsOf(option)));
379
+ if (value)
380
+ out.push({ expr: `${field.name} == '${value.replace(/'/g, "")}'`, says: `that are ${wordsOf(value)}` });
381
+ }
382
+ if (/\bnot done\b|\bundone\b|\bunfinished\b|\bopen ones\b|\bstill to do\b/.test(text)) {
383
+ const done = info.fields.find((one) => one.type === "boolean" && /^(done|finished|complete|completed)$/.test(one.name));
384
+ if (done)
385
+ out.push({ expr: `not ${done.name}`, says: `not ${done.words}` });
386
+ }
387
+ }
388
+ return out;
389
+ }
390
+ // ── a recipe, drawn ──────────────────────────────────────────────────────────
391
+ const LENS_WORDS = { columns: "A board", calendar: "A calendar", timeline: "A timeline", coverage: "A grid", board: "A layout", plan: "A plan", blocks: "A list", reach: "A picture" };
392
+ function titled(recipe, reading) {
393
+ const info = reading.info(recipe.kind);
394
+ const words = (name) => (name ? (fieldOf(info, name)?.words ?? wordsOf(name)) : "");
395
+ switch (recipe.lens) {
396
+ case "columns":
397
+ return { title: `${capitalize(info.plural)} by ${words(recipe.column)}`, detail: `of ${info.plural} by ${words(recipe.column)}` };
398
+ case "calendar": {
399
+ const range = recipe.range ?? "month";
400
+ if (range === "agenda")
401
+ return { title: `${capitalize(info.plural)} in date order`, detail: `of ${info.plural} in order of ${words(recipe.start)}` };
402
+ const span = range === "years" ? "year" : range;
403
+ return { title: `${capitalize(info.plural)} by ${span}`, detail: `of ${info.plural} by ${words(recipe.start)}, a ${span} at a time` };
404
+ }
405
+ case "timeline":
406
+ return { title: `${capitalize(info.plural)} over the ${words(recipe.column)}`, detail: `of ${info.plural} from ${words(recipe.start)} to ${words(recipe.end)}, by ${words(recipe.column)}` };
407
+ case "coverage": {
408
+ const across = reading.info(recipe.across);
409
+ return { title: `${capitalize(info.plural)} by ${across.noun}`, detail: `of which ${across.noun} covers which ${info.noun}` };
410
+ }
411
+ case "board":
412
+ return { title: `${capitalize(info.plural)} where they stand`, detail: `of ${info.plural} where they stand` };
413
+ case "plan":
414
+ return { title: `${capitalize(info.plural)} on a plan`, detail: `of ${info.plural}` };
415
+ default: {
416
+ const parts = [recipe.where?.map((one) => one.says).join(" and "), recipe.group ? `by ${words(recipe.group)}` : undefined, recipe.sort ? `in order of ${words(recipe.sort.by)}` : undefined].filter((part) => !!part);
417
+ return { title: [capitalize(info.plural), ...parts].join(" "), detail: [`of ${info.plural}`, ...parts].join(" ") };
418
+ }
419
+ }
420
+ }
421
+ function lensOf(recipe, title) {
422
+ const base = { title, on: recipe.kind };
423
+ switch (recipe.lens) {
424
+ case "columns":
425
+ return { name: "columns", ...base, bindings: { [recipe.kind]: { column: recipe.column } } };
426
+ case "calendar":
427
+ return {
428
+ name: "calendar",
429
+ ...base,
430
+ bindings: { [recipe.kind]: { start: recipe.start, ...(recipe.end ? { end: recipe.end } : {}), ...(recipe.done ? { done: recipe.done } : {}) } },
431
+ ...(recipe.range ? { options: { range: recipe.range } } : {}),
432
+ };
433
+ case "timeline":
434
+ return { name: "timeline", ...base, bindings: { [recipe.kind]: { start: recipe.start, end: recipe.end, column: recipe.column } } };
435
+ case "coverage":
436
+ return { name: "coverage", ...base, bindings: { rows: { kind: recipe.kind }, columns: { kind: recipe.across }, link: { edge: recipe.link } } };
437
+ case "board":
438
+ return {
439
+ name: "board",
440
+ ...base,
441
+ bindings: { slots: { kind: recipe.kind }, x: { field: recipe.x, on: "slots" }, y: { field: recipe.y, on: "slots" }, fill: { edge: recipe.fill } },
442
+ ...(recipe.fillFrom ? { options: { fillFrom: recipe.fillFrom } } : {}),
443
+ };
444
+ case "plan":
445
+ return { name: "plan", ...base, bindings: { regions: { kind: recipe.kind }, outline: { field: recipe.outline, on: "regions" } } };
446
+ default: {
447
+ const where = recipe.where?.length ? ` where ${recipe.where.map((one) => (recipe.where.length > 1 ? `(${one.expr})` : one.expr)).join(" and ")}` : "";
448
+ const list = { list: `all('${recipe.kind}')${where}`, as: recipe.as ?? "row" };
449
+ if (recipe.group)
450
+ list["group"] = recipe.group;
451
+ if (recipe.sort)
452
+ list["sort"] = recipe.sort.direction ? { by: recipe.sort.by, direction: recipe.sort.direction } : recipe.sort.by;
453
+ list["empty"] = "Nothing here yet.";
454
+ return { name: "blocks", ...base, options: { blocks: [list] } };
455
+ }
456
+ }
457
+ }
458
+ /** A title no place of the app already has: the draft's own, or numbered after it. */
459
+ function freeTitle(title, app) {
460
+ const slug = (text) => text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
461
+ const taken = new Set(["home", "overview", ...placesOf(app).map((place) => place.slug), ...(app.lenses ?? []).flatMap((lens) => (lens.title ? [slug(lens.title)] : []))]);
462
+ if (!taken.has(slug(title)))
463
+ return title;
464
+ for (let n = 2;; n++)
465
+ if (!taken.has(slug(`${title} ${n}`)))
466
+ return `${title} ${n}`;
467
+ }
468
+ // ── judging a lens, however it was written ──────────────────────────────────
469
+ /** What each block may say besides the key that names it, for a place about no one record. */
470
+ const PLACE_BLOCKS = {
471
+ title: [],
472
+ headline: [],
473
+ text: ["tone"],
474
+ figure: ["as", "currency", "label"],
475
+ list: ["sort", "limit", "group", "empty", "as"],
476
+ progress: ["label"],
477
+ group: ["direction"],
478
+ when: ["show"],
479
+ divider: [],
480
+ };
481
+ /**
482
+ * WHAT IS WRONG WITH A LENS'S BLOCKS, if anything, in one sentence: each
483
+ * block one the vocabulary has, each expression one the rule language
484
+ * parses, and every kind, field and choice it names one the seat may see.
485
+ * Read with the parser a page already runs, so drafting loads no checker.
486
+ */
487
+ function blocksProblem(reading, blocks) {
488
+ if (!Array.isArray(blocks) || blocks.length === 0)
489
+ return "it has no blocks to draw";
490
+ if (blocks.length > 40)
491
+ return "it has more blocks than a place draws";
492
+ const parsed = (source, what) => {
493
+ if (typeof source !== "string" || source.trim() === "")
494
+ return `its ${what} says nothing`;
495
+ try {
496
+ return parseExpr(source);
497
+ }
498
+ catch (error) {
499
+ return `its ${what} does not read: ${error instanceof Error ? error.message.replace(/ \(at character.*$/, "") : String(error)}`;
500
+ }
501
+ };
502
+ /** The kind of record an expression's set holds, where it says: all('k'), and that filtered. */
503
+ const kindOf = (e) => {
504
+ if (e.t === "where")
505
+ return kindOf(e.set);
506
+ if (e.t === "call" && e.fn === "all") {
507
+ const word = e.args[0];
508
+ return word?.t === "lit" && typeof word.value === "string" ? (reading.info(word.value) ?? null) : undefined;
509
+ }
510
+ return undefined;
511
+ };
512
+ /** The first name an expression reads that the kinds it stands on do not have. */
513
+ const stray = (e, over) => {
514
+ switch (e.t) {
515
+ case "lit":
516
+ return undefined;
517
+ case "ident":
518
+ return over && !over.fields.some((field) => field.name === e.name) && !over.edges.some((edge) => edge.name === e.name) ? `${over.plural} have nothing called ${e.name}` : undefined;
519
+ case "member":
520
+ return stray(e.object, over);
521
+ case "list":
522
+ return e.items.map((item) => stray(item, over)).find(Boolean);
523
+ case "unary":
524
+ return stray(e.operand, over);
525
+ case "binary":
526
+ return stray(e.left, over) ?? stray(e.right, over);
527
+ case "where": {
528
+ const kind = kindOf(e.set);
529
+ if (kind === null)
530
+ return "Nothing by that name here";
531
+ return stray(e.set, over) ?? stray(e.filter, kind ?? undefined);
532
+ }
533
+ case "call": {
534
+ if (e.fn === "all")
535
+ return kindOf(e) === null ? "Nothing by that name here" : undefined;
536
+ return e.args.map((arg) => stray(arg, over)).find(Boolean);
537
+ }
538
+ }
539
+ };
540
+ const judge = (list, depth) => {
541
+ if (depth > 4)
542
+ return "its blocks nest deeper than a place draws";
543
+ for (const block of list) {
544
+ if (!isRecord(block))
545
+ return "a block is not an object";
546
+ const type = Object.keys(PLACE_BLOCKS).find((key) => key in block);
547
+ if (!type)
548
+ return `"${Object.keys(block)[0] ?? ""}" is not a block a place draws`;
549
+ const extra = Object.keys(block).find((key) => key !== type && !PLACE_BLOCKS[type].includes(key));
550
+ if (extra)
551
+ return `a ${type} block takes no "${extra}"`;
552
+ const value = block[type];
553
+ if (type === "list" || type === "figure" || type === "when") {
554
+ if (type === "figure" && value === true)
555
+ continue;
556
+ const e = parsed(value, type);
557
+ if (typeof e === "string")
558
+ return e;
559
+ const wrong = stray(e, undefined);
560
+ if (wrong)
561
+ return wrong;
562
+ if (type === "list") {
563
+ const kind = kindOf(e);
564
+ if (kind === null || kind === undefined)
565
+ return kind === null ? "Nothing by that name here" : "its list does not say which records it lists, like all('task')";
566
+ for (const key of ["group", "sort"]) {
567
+ const said = block[key];
568
+ const name = typeof said === "string" ? said : isRecord(said) && typeof said["by"] === "string" ? said["by"] : undefined;
569
+ if (said === undefined)
570
+ continue;
571
+ const field = name ? kind.fields.find((one) => one.name === name) : undefined;
572
+ if (!field)
573
+ return `${kind.plural} have nothing called ${String(name ?? said)} to ${key} by`;
574
+ if (key === "group" && field.type !== "enum")
575
+ return `${kind.plural}' ${field.words} is not a choice, so they cannot be grouped by it`;
576
+ }
577
+ }
578
+ if (type === "when") {
579
+ const show = block["show"];
580
+ if (!Array.isArray(show))
581
+ return "a when block shows a list of blocks";
582
+ const inner = judge(show, depth + 1);
583
+ if (inner)
584
+ return inner;
585
+ }
586
+ }
587
+ else if (type === "group") {
588
+ if (!Array.isArray(value))
589
+ return "a group block holds a list of blocks";
590
+ const inner = judge(value, depth + 1);
591
+ if (inner)
592
+ return inner;
593
+ }
594
+ else if (type !== "divider" && typeof value !== "string")
595
+ return `a ${type} block says words`;
596
+ else if (typeof value === "string") {
597
+ // A template's braces read like any expression, up to a formatter's bar.
598
+ for (const brace of value.matchAll(/\{([^{}]*)\}/g)) {
599
+ const inner = brace[1].split(/\|(?![|])/)[0];
600
+ const e = parsed(inner, `${type}'s braces`);
601
+ if (typeof e === "string")
602
+ return e;
603
+ const wrong = stray(e, undefined);
604
+ if (wrong)
605
+ return wrong;
606
+ }
607
+ }
608
+ }
609
+ return undefined;
610
+ };
611
+ return judge(blocks, 1);
612
+ }
613
+ /**
614
+ * WHETHER A LENS DRAWS, judged as a declared one is, against what the seat
615
+ * may see: the shipped lens's own sorting (`declaredLenses`, the table
616
+ * `graview check` and `placesOf` read), its bindings against the seen
617
+ * kinds' fields, and the blocks it is drawn from (their expressions parsed,
618
+ * the kinds, fields and choices they name read against what the seat sees).
619
+ * The first thing wrong, in one sentence; or what the primitives draw it
620
+ * with. A kept lens is judged in full again where it is kept (`keepLens`).
621
+ *
622
+ * Judged with what a hosted page already runs and nothing more: the edit
623
+ * vocabulary and the checker (`keepLens`, `@graview/tools/keep`) stay
624
+ * with the host that writes the declaration, so drafting adds nothing to
625
+ * what a page loads before it is asked to draw.
626
+ */
627
+ export function judgeLens(app, lens, sight) {
628
+ const schema = seenSchema(app.schema, sight);
629
+ const fail = (why) => ({ ok: false, failed: `Couldn't draw that: ${why.replace(/\.$/, "")}.` });
630
+ if (!isShippedLens(lens.name) || lens.name === "reach")
631
+ return fail(`"${String(lens.name)}" is not a picture the seat can draw; it draws ${SHIPPED_LENS_NAMES.filter((name) => name !== "reach").join(", ")}`);
632
+ if (typeof lens.title !== "string" || lens.title.trim().length === 0 || lens.title.length > 80)
633
+ return fail("it needs a title of a few words");
634
+ if (typeof lens.on !== "string" || !schema.tryDefinition(lens.on))
635
+ return fail("Nothing by that name here");
636
+ // Every kind a binding names is one the seat may see.
637
+ const shipped = SHIPPED_LENSES[lens.name];
638
+ const bindings = (lens.bindings ?? {});
639
+ if (shipped.binds === "fields") {
640
+ for (const [kind, roles] of Object.entries(bindings)) {
641
+ if (!schema.tryDefinition(kind))
642
+ return fail("Nothing by that name here");
643
+ const fields = Object.keys(schema.tryDefinition(kind).fields?.shape ?? {});
644
+ for (const [role, field] of Object.entries((roles ?? {}))) {
645
+ if (typeof field !== "string" || !fields.includes(field))
646
+ return fail(`${wordsOf(kind)} has no field "${String(field)}" for its ${role}`);
647
+ }
648
+ for (const role of shipped.requiredRoles)
649
+ if (!(role in (roles ?? {})))
650
+ return fail(`a ${lens.name} needs ${wordsOf(kind)}'s ${role}`);
651
+ }
652
+ }
653
+ else if (shipped.binds === "entities") {
654
+ for (const role of shipped.requiredRoles) {
655
+ const binding = bindings[role];
656
+ if (!binding)
657
+ return fail(`a ${lens.name} needs its ${role}`);
658
+ if (typeof binding["kind"] === "string" && !schema.tryDefinition(binding["kind"]))
659
+ return fail("Nothing by that name here");
660
+ }
661
+ }
662
+ const extended = { ...app, schema, lenses: [...(app.lenses ?? []), lens] };
663
+ const index = extended.lenses.length - 1;
664
+ const sorted = declaredLenses(extended);
665
+ const at = `lenses.${index}`;
666
+ const finding = sorted.findings.find((one) => one.path === at || one.path.startsWith(`${at}.`));
667
+ if (finding)
668
+ return fail(finding.message.replace(/^"[^"]*" /, "it "));
669
+ const undrawn = sorted.undrawn.find((one) => one.index === index);
670
+ if (undrawn)
671
+ return fail(undrawn.why);
672
+ const drawn = sorted.drawn.find((one) => one.index === index);
673
+ if (!drawn)
674
+ return fail("its bindings name something the app does not have");
675
+ // The scene keeps its own address whatever a place is called (FR-132).
676
+ if (drawn.as === "overview")
677
+ return fail(`"${lens.title}" is the scene's own address; give it another title`);
678
+ if (lens.name === "blocks") {
679
+ const wrong = blocksProblem(readApp(schema), lens.options?.["blocks"]);
680
+ if (wrong)
681
+ return fail(wrong);
682
+ }
683
+ return { ok: true, drawn };
684
+ }
685
+ /** The edit that keeps a lens. */
686
+ export function lensEditOf(lens) {
687
+ return { op: "add-lens", title: lens.title, lens: lens.name, on: lens.on, ...(lens.bindings ? { bindings: lens.bindings } : {}), ...(lens.options ? { options: lens.options } : {}) };
688
+ }
689
+ /** The edit that takes a kept lens back. */
690
+ export function takeBackEditOf(edit) {
691
+ return { op: "remove-lens", title: edit.title, on: edit.on };
692
+ }
693
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
694
+ /** A lens as a model or a tool caller writes it — `lens` or `name` for which — read as a draft's lens, to be judged. */
695
+ export function lensFromSpec(value) {
696
+ const spec = isRecord(value) ? value : {};
697
+ const name = String(spec["lens"] ?? spec["name"] ?? "");
698
+ const bindings = spec["bindings"];
699
+ const on = typeof spec["on"] === "string" ? spec["on"] : isRecord(bindings) && SHIPPED_LENSES[name]?.binds === "fields" ? (Object.keys(bindings)[0] ?? "") : "";
700
+ return { name, title: typeof spec["title"] === "string" ? spec["title"].trim() : "", on, ...(isRecord(bindings) ? { bindings } : {}), ...(isRecord(spec["options"]) ? { options: spec["options"] } : {}) };
701
+ }
702
+ /** What a template would have made a lens from, read back from the lens, so asking again works on a lens a model wrote. */
703
+ export function recipeOfLens(lens) {
704
+ const roles = (kind) => (isRecord(lens.bindings?.[kind]) ? lens.bindings[kind] : {});
705
+ const text = (value) => (typeof value === "string" ? value : undefined);
706
+ const own = roles(lens.on);
707
+ switch (lens.name) {
708
+ case "columns":
709
+ return text(own["column"]) ? { lens: "columns", kind: lens.on, column: own["column"] } : undefined;
710
+ case "calendar": {
711
+ const range = text(lens.options?.["range"]);
712
+ return text(own["start"]) ? { lens: "calendar", kind: lens.on, start: own["start"], ...(text(own["end"]) ? { end: own["end"] } : {}), ...(text(own["done"]) ? { done: own["done"] } : {}), ...(range ? { range } : {}) } : undefined;
713
+ }
714
+ case "timeline":
715
+ return text(own["start"]) && text(own["end"]) && text(own["column"]) ? { lens: "timeline", kind: lens.on, start: own["start"], end: own["end"], column: own["column"] } : undefined;
716
+ case "coverage": {
717
+ const across = isRecord(lens.bindings?.["columns"]) ? text(lens.bindings["columns"]["kind"]) : undefined;
718
+ const link = isRecord(lens.bindings?.["link"]) ? text(lens.bindings["link"]["edge"]) : undefined;
719
+ return across && link ? { lens: "coverage", kind: lens.on, across, link } : undefined;
720
+ }
721
+ case "blocks": {
722
+ const blocks = lens.options?.["blocks"];
723
+ // A single list of one kind's records, as a template writes one: anything richer is the model's to change.
724
+ if (!Array.isArray(blocks) || blocks.length !== 1 || !isRecord(blocks[0]))
725
+ return undefined;
726
+ const list = blocks[0];
727
+ const whole = new RegExp(`^all\\('${lens.on}'\\)(?: where (.+))?$`).exec(String(list["list"] ?? ""));
728
+ if (!whole)
729
+ return undefined;
730
+ const sort = list["sort"];
731
+ return {
732
+ lens: "blocks",
733
+ kind: lens.on,
734
+ as: list["as"] === "card" ? "card" : "row",
735
+ ...(typeof list["group"] === "string" ? { group: list["group"] } : {}),
736
+ ...(typeof sort === "string" ? { sort: { by: sort } } : isRecord(sort) && typeof sort["by"] === "string" ? { sort: { by: sort["by"], ...(sort["direction"] === "desc" ? { direction: "desc" } : {}) } } : {}),
737
+ ...(whole[1] ? { where: [{ expr: whole[1], says: "as asked" }] } : {}),
738
+ };
739
+ }
740
+ default:
741
+ return undefined;
742
+ }
743
+ }
744
+ /** A lens already judged, as a draft: what a tool caller's lens or the one on screen becomes before it is changed. */
745
+ export function draftFromLens(app, lens, drawn, sight, by) {
746
+ const info = readApp(seenSchema(app.schema, sight)).info(lens.on);
747
+ const recipe = recipeOfLens(lens);
748
+ return { title: lens.title, said: `${LENS_WORDS[lens.name] ?? "A picture"} of ${info?.plural ?? wordsOf(lens.on)}.`, kind: lens.on, lens, drawn, edit: lensEditOf(lens), by, asks: [], ...(recipe ? { recipe } : {}) };
749
+ }
750
+ /** A draft as a tool answers with it: plain JSON a model can hand back to keep_lens. */
751
+ export function draftAnswer(draft) {
752
+ return {
753
+ title: draft.title,
754
+ said: draft.said,
755
+ lens: { title: draft.lens.title, lens: draft.lens.name, on: draft.lens.on, ...(draft.lens.bindings ? { bindings: draft.lens.bindings } : {}), ...(draft.lens.options ? { options: draft.lens.options } : {}) },
756
+ edit: draft.edit,
757
+ by: draft.by,
758
+ check: "It draws, and graview check would take it.",
759
+ };
760
+ }
761
+ function fromRecipe(recipe, reading, options, asks, keepTitle) {
762
+ const named = titled(recipe, reading);
763
+ const title = recipe.title ?? keepTitle ?? freeTitle(named.title, options.app);
764
+ const lens = lensOf(recipe, title);
765
+ const judged = judgeLens(options.app, lens, options.sight);
766
+ if (!judged.ok)
767
+ return { failed: judged.failed, ...(options.lastGood ? { lastGood: options.lastGood } : {}) };
768
+ return { title, said: `${LENS_WORDS[recipe.lens]} ${named.detail}.`, kind: recipe.kind, lens, drawn: judged.drawn, edit: lensEditOf(lens), by: "template", asks, recipe };
769
+ }
770
+ // ── drafting ────────────────────────────────────────────────────────────────
771
+ /** The kinds an intent can be drawn over, best first. */
772
+ function kindsFor(intent, reading, named, text) {
773
+ if (named.length > 0)
774
+ return named;
775
+ const fits = (info) => {
776
+ switch (intent) {
777
+ case "columns":
778
+ return info.fields.some((field) => field.type === "enum");
779
+ case "calendar":
780
+ return info.fields.some(isDate);
781
+ case "timeline":
782
+ return timelineRoles(info) !== undefined || info.fields.some(isDate);
783
+ case "coverage":
784
+ return info.edges.some((edge) => edge.to.some((target) => target !== info.kind));
785
+ case "board":
786
+ return info.fields.some((field) => field.name === "x") && info.fields.some((field) => field.name === "y");
787
+ case "plan":
788
+ return info.fields.some((field) => field.name === "outline") || info.roles["outline"] !== undefined;
789
+ default:
790
+ return true;
791
+ }
792
+ };
793
+ const fitting = reading.kinds.filter(fits);
794
+ // "timeline of dates": a kind whose date is mentioned first.
795
+ return [...fitting].sort((a, b) => Number(b.fields.some((field) => says(text, field.words))) - Number(a.fields.some((field) => says(text, field.words))));
796
+ }
797
+ /**
798
+ * A DRAFT FROM AN ASK, BY TEMPLATE ALONE: no model, no key. The ask's
799
+ * words pick the lens and the kind; the declaration's roles and field types
800
+ * fill the bindings. Undefined when the ask names no way of seeing a
801
+ * template knows (a model may still read it); a failure when it does and
802
+ * the app cannot draw it ("no date field on deliverables").
803
+ */
804
+ export function templateDraft(ask, options) {
805
+ const reading = readApp(seenSchema(options.app.schema, options.sight));
806
+ const text = normal(ask);
807
+ const intents = intentsOf(text);
808
+ if (intents.length === 0)
809
+ return undefined;
810
+ const named = kindsNamed(text, reading);
811
+ let why;
812
+ for (const intent of intents) {
813
+ const kinds = intent === "coverage" ? [named[0] ?? reading.kinds[0]].filter((one) => !!one) : kindsFor(intent, reading, named, text);
814
+ for (const info of kinds) {
815
+ try {
816
+ const recipe = recipeFor(intent, info, reading, text, named);
817
+ const drafted = fromRecipe(recipe, reading, options, [ask]);
818
+ if (!isDraftFailure(drafted))
819
+ return drafted;
820
+ why ??= drafted.failed;
821
+ }
822
+ catch (error) {
823
+ if (!(error instanceof Cannot))
824
+ throw error;
825
+ why ??= `Couldn't draw that: ${error.message}.`;
826
+ }
827
+ }
828
+ if (kinds.length === 0 && named.length === 0)
829
+ why ??= `Couldn't draw that: nothing here has what ${LENS_WORDS[intent].toLowerCase()} needs.`;
830
+ }
831
+ return { failed: why ?? "Couldn't draw that: Nothing by that name here.", ...(options.lastGood ? { lastGood: options.lastGood } : {}) };
832
+ }
833
+ /**
834
+ * A DRAFT FROM AN ASK. A template first — it is instant and needs no key;
835
+ * then, for an ask no template reads, the app's model, whose answer is
836
+ * judged exactly as a declared lens is before it is drawn. A draft that
837
+ * cannot be drawn says why in one line and keeps the last good one.
838
+ */
839
+ export async function draftView(ask, options) {
840
+ const keep = options.lastGood ? { lastGood: options.lastGood } : {};
841
+ if (ask.trim().length === 0)
842
+ return { failed: "Say what you would like to see, like “a board of tasks by status”.", ...keep };
843
+ const templated = templateDraft(ask, options);
844
+ if (templated && !isDraftFailure(templated))
845
+ return templated;
846
+ if (!options.complete)
847
+ return templated ?? { failed: "Couldn't draw that: drawing freely needs AI, which isn't on here. Ask for a board, a calendar, a timeline, a list or who covers what.", ...keep };
848
+ const modeled = await modelDraft(ask, options, undefined);
849
+ // The template's reason is the better sentence when the model could not do better.
850
+ if (isDraftFailure(modeled) && templated)
851
+ return templated;
852
+ return modeled;
853
+ }
854
+ // ── refining ────────────────────────────────────────────────────────────────
855
+ /**
856
+ * ASKING AGAIN: the draft on screen, with one thing changed — "group by
857
+ * owner", "only this month", "as a calendar", "call it The pipeline". Each
858
+ * turn replaces the draft; a turn that cannot be drawn says why and hands
859
+ * the draft back as the last good one.
860
+ */
861
+ export async function refineDraft(draft, ask, options) {
862
+ const keep = { lastGood: draft };
863
+ const opts = { ...options, lastGood: draft };
864
+ const reading = readApp(seenSchema(options.app.schema, options.sight));
865
+ const text = normal(ask);
866
+ const info = reading.info(draft.kind);
867
+ const asks = [...draft.asks, ask];
868
+ if (!info)
869
+ return { failed: "Couldn't change that: Nothing by that name here.", ...keep };
870
+ const recipe = draft.recipe;
871
+ const retitled = /^ (?:call|name|title) (?:it|this)? ?(.+?) $/.exec(text) ?? / (?:call|name) it (.+?) $/.exec(text);
872
+ try {
873
+ if (retitled) {
874
+ const said = ask.replace(/^.*?\b(?:call|name|title)\b\s*(?:it|this)?\s*/i, "").replace(/^["“']|["”']$/g, "").trim();
875
+ if (said.length === 0)
876
+ return { failed: "Couldn't change that: say what to call it.", ...keep };
877
+ const lens = { ...draft.lens, title: freeTitle(said, options.app) };
878
+ const judged = judgeLens(options.app, lens, options.sight);
879
+ if (!judged.ok)
880
+ return { failed: judged.failed, ...keep };
881
+ return { ...draft, title: lens.title, lens, drawn: judged.drawn, edit: lensEditOf(lens), asks, ...(recipe ? { recipe: { ...recipe, title: lens.title } } : {}) };
882
+ }
883
+ // "as a calendar", "show it as a list": the same kind, another lens.
884
+ const as = / as (?:a |an )?(board|kanban|calendar|timeline|list|table|cards|rows|grid|plan|layout)\b/.exec(text);
885
+ if (as) {
886
+ const wanted = as[1] === "board" || as[1] === "kanban" ? "columns" : as[1] === "calendar" ? "calendar" : as[1] === "timeline" ? "timeline" : as[1] === "grid" ? "coverage" : as[1] === "plan" ? "plan" : as[1] === "layout" ? "board" : "blocks";
887
+ const next = recipeFor(wanted, info, reading, text, [info]);
888
+ const blocksAs = as[1] === "cards" ? "card" : as[1] === "rows" ? "row" : undefined;
889
+ const carried = wanted === "blocks" && recipe?.lens === "blocks" ? { ...recipe, ...(blocksAs ? { as: blocksAs } : {}) } : wanted === "blocks" && recipe?.lens === "columns" ? { ...next, group: recipe.column, ...(blocksAs ? { as: blocksAs } : {}) } : next;
890
+ return fromRecipe(withoutTitle(carried), reading, opts, asks);
891
+ }
892
+ if (recipe) {
893
+ const changed = refineRecipe(recipe, info, reading, text);
894
+ if (changed)
895
+ return fromRecipe(changed, reading, opts, asks);
896
+ }
897
+ }
898
+ catch (error) {
899
+ if (!(error instanceof Cannot))
900
+ throw error;
901
+ return { failed: `Couldn't change that: ${error.message}.`, ...keep };
902
+ }
903
+ if (!options.complete)
904
+ return { failed: "Couldn't change that: changing it freely needs AI, which isn't on here. Try “group by status”, “only this month” or “as a calendar”.", ...keep };
905
+ const modeled = await modelDraft(ask, opts, draft);
906
+ return isDraftFailure(modeled) ? modeled : { ...modeled, asks };
907
+ }
908
+ const withoutTitle = (recipe) => {
909
+ const { title: _title, ...rest } = recipe;
910
+ void _title;
911
+ return rest;
912
+ };
913
+ /** One change to a recipe, read from the ask; undefined when the ask says none a template knows. */
914
+ function refineRecipe(recipe, info, reading, text) {
915
+ const by = / (?:group(?:ed)?|split|organi[sz]ed?|put them|columns) by ([\p{L}\p{N} -]+?)(?= (?:and|only|with)|\s*$)/u.exec(text)?.[1] ?? (/^ by /.test(text) ? byWhat(text) : undefined);
916
+ if (by) {
917
+ const field = fieldNamed(info, by);
918
+ if (field?.type === "enum")
919
+ return recipe.lens === "blocks" ? { ...withoutTitle(recipe), group: field.name } : { lens: "columns", kind: recipe.kind, column: field.name };
920
+ const edge = edgeNamed(info, by, reading);
921
+ if (edge)
922
+ return { lens: "coverage", kind: recipe.kind, across: edge.to[0], link: edge.name };
923
+ return cannot(field ? `${info.plural}' ${field.words} is not a choice, so they cannot be grouped by it` : `${info.plural} have nothing called ${by} to group by`);
924
+ }
925
+ const sort = / (?:sort(?:ed)?|order(?:ed)?) by ([\p{L}\p{N} -]+?)(?= (?:and|only|with)|\s*$)/u.exec(text)?.[1];
926
+ if (sort) {
927
+ const field = fieldNamed(info, sort);
928
+ if (!field)
929
+ return cannot(`${info.plural} have nothing called ${sort} to sort by`);
930
+ const base = recipe.lens === "blocks" ? withoutTitle(recipe) : { lens: "blocks", kind: recipe.kind, as: "row", ...(recipe.lens === "columns" ? { group: recipe.column } : {}) };
931
+ return { ...base, sort: { by: field.name, ...(/\b(newest|latest|desc|descending|most)\b/.test(text) ? { direction: "desc" } : {}) } };
932
+ }
933
+ if (/\b(?:all of them|everything|show all|clear the filter|no filter|without the filter)\b/.test(text)) {
934
+ if (recipe.lens !== "blocks" || !recipe.where)
935
+ return cannot("it already shows all of them");
936
+ const { where: _where, ...rest } = withoutTitle(recipe);
937
+ void _where;
938
+ return rest;
939
+ }
940
+ const window = windowOf(text);
941
+ if (window && recipe.lens === "calendar" && window.range)
942
+ return { ...withoutTitle(recipe), range: window.range };
943
+ if (window && recipe.lens === "calendar" && !window.range) {
944
+ // "overdue" on a calendar: a list of what is past, in date order.
945
+ return { lens: "blocks", kind: recipe.kind, as: "row", sort: { by: recipe.start }, where: filtersFrom(info, text) };
946
+ }
947
+ const where = filtersFrom(info, text);
948
+ if (where.length > 0) {
949
+ const base = recipe.lens === "blocks" ? withoutTitle(recipe) : { lens: "blocks", kind: recipe.kind, as: "row", ...(recipe.lens === "columns" ? { group: recipe.column } : {}) };
950
+ return { ...base, where: [...(base.where ?? []), ...where] };
951
+ }
952
+ const range = recipe.lens === "calendar" ? rangeOf(text) : undefined;
953
+ if (range)
954
+ return { ...withoutTitle(recipe), range };
955
+ return undefined;
956
+ }
957
+ // ── a model's draft, judged ─────────────────────────────────────────────────
958
+ /** What a model is told the app is: the kinds the seat may see, their fields and relations. */
959
+ function appInWords(reading) {
960
+ return reading.kinds
961
+ .map((info) => {
962
+ const fields = info.fields.map((field) => `${field.name} (${field.type ?? "value"}${field.options ? `: ${field.options.join(" | ")}` : ""})`).join(", ");
963
+ const edges = info.edges.map((edge) => `${edge.name} → ${edge.to.join(" | ")}`).join(", ");
964
+ const roles = Object.entries(info.roles).map(([role, field]) => `${role}=${field}`).join(", ");
965
+ return `- ${info.kind} ("${info.plural}"): ${fields}${edges ? `; relations: ${edges}` : ""}${roles ? `; roles: ${roles}` : ""}`;
966
+ })
967
+ .join("\n");
968
+ }
969
+ const LENS_GUIDE = [
970
+ 'columns — a board, records in columns by one choice field: {"lens": "columns", "on": K, "bindings": {K: {"column": "<enum field>"}}}',
971
+ 'calendar — records on a calendar by a date: {"lens": "calendar", "on": K, "bindings": {K: {"start": "<date field>", "end"?: "<date field>", "done"?: "<boolean field>"}}, "options": {"range"?: "day" | "week" | "month" | "quarter" | "year" | "agenda"}}',
972
+ 'timeline — minutes of a day in columns: {"lens": "timeline", "on": K, "bindings": {K: {"start": "<number field>", "end": "<number field>", "column": "<enum field>"}}}',
973
+ 'coverage — who covers what, a grid of two kinds joined by a relation: {"lens": "coverage", "on": K, "bindings": {"rows": {"kind": K}, "columns": {"kind": J}, "link": {"edge": "<relation of K to J>"}}}',
974
+ 'blocks — anything else, as blocks: {"lens": "blocks", "on": K, "options": {"blocks": [{"headline": "words"}, {"list": "all(\'K\') where <condition>", "group"?: "<enum field>", "sort"?: "<field>" | {"by": "<field>", "direction": "desc"}, "as"?: "row" | "card", "empty"?: "words"}, {"figure": "count(all(\'K\'))", "label": "words"}]}}. Conditions read a record\'s own fields: status == \'open\', not done, days(today(), due) <= 7.',
975
+ ].join("\n");
976
+ function promptFor(ask, reading, current) {
977
+ return [
978
+ "You draw a view of an app's data as JSON — never code. The app's kinds, their fields (with types) and relations:",
979
+ appInWords(reading),
980
+ "",
981
+ "The lenses you may use (prefer the first four; use blocks only when none of them fits):",
982
+ LENS_GUIDE,
983
+ "",
984
+ current ? `The view on screen now:\n${JSON.stringify(current.lens)}\nChange it as asked, and keep everything not asked about.` : "",
985
+ `Asked: ${JSON.stringify(ask)}`,
986
+ 'Answer with ONE JSON object: {"title": "<a few words, like Deliverables by status>", "lens": …, "on": …, "bindings"?: …, "options"?: …}. Name only the kinds, fields and relations listed above. If it cannot be drawn from them, answer {"failed": "<one sentence saying why>"}.',
987
+ ]
988
+ .filter((line) => line !== "")
989
+ .join("\n");
990
+ }
991
+ async function modelDraft(ask, options, current) {
992
+ const keep = options.lastGood ? { lastGood: options.lastGood } : {};
993
+ const reading = readApp(seenSchema(options.app.schema, options.sight));
994
+ let answer;
995
+ try {
996
+ answer = await options.complete(promptFor(ask, reading, current));
997
+ }
998
+ catch {
999
+ return { failed: "Couldn't draw that: the model did not answer.", ...keep };
1000
+ }
1001
+ const parsed = firstJsonObject(answer);
1002
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
1003
+ return { failed: "Couldn't draw that: the model's answer was not a view.", ...keep };
1004
+ const said = parsed;
1005
+ if (typeof said["failed"] === "string")
1006
+ return { failed: `Couldn't draw that: ${said["failed"].replace(/^Couldn't draw that:\s*/i, "").replace(/\.$/, "")}.`, ...keep };
1007
+ const written = lensFromSpec(said);
1008
+ if (!isShippedLens(written.name))
1009
+ return { failed: `Couldn't draw that: "${written.name}" is not a picture the seat can draw.`, ...keep };
1010
+ const title = written.title ? written.title.slice(0, 80) : (current?.title ?? capitalize(ask.trim()).slice(0, 80));
1011
+ const lens = { ...written, title: current && current.title === title ? title : freeTitle(title, options.app) };
1012
+ const judged = judgeLens(options.app, lens, options.sight);
1013
+ if (!judged.ok)
1014
+ return { failed: judged.failed, ...keep };
1015
+ const drafted = draftFromLens(options.app, lens, judged.drawn, options.sight, "model");
1016
+ return { ...drafted, asks: [ask] };
1017
+ }
1018
+ /**
1019
+ * THE LENSES A READER KEPT FOR THEMSELVES, beside the app's own: a
1020
+ * declaration's lenses with each kept lens that still draws appended, so a
1021
+ * code-declared app shows "Your lenses" in its place list without its
1022
+ * declaration changing. A kept lens that no longer draws is passed over.
1023
+ */
1024
+ export function withReaderLenses(app, kept, sight) {
1025
+ let lenses = [...(app.lenses ?? [])];
1026
+ for (const edit of kept) {
1027
+ const lens = { name: edit.lens, title: edit.title, on: edit.on, ...(edit.bindings ? { bindings: edit.bindings } : {}), ...(edit.options ? { options: edit.options } : {}) };
1028
+ if (lenses.some((one) => one.title === lens.title))
1029
+ continue;
1030
+ const judged = judgeLens({ ...app, lenses }, lens, sight);
1031
+ if (judged.ok)
1032
+ lenses = [...lenses, lens];
1033
+ }
1034
+ return lenses.length === (app.lenses ?? []).length ? app : { ...app, lenses };
1035
+ }
1036
+ /**
1037
+ * THE TWO TOOLS a connector's chat draws and keeps views with, as the tool
1038
+ * runtime calls them: `draft_view` (an ask, a lens to check, or the lens on
1039
+ * screen to change) and `keep_lens` (the lens, checked again, handed to the
1040
+ * host's write). Here rather than in the runtime, so a seat that never asks
1041
+ * carries none of it.
1042
+ */
1043
+ export async function runDraftTool(name, args, context) {
1044
+ const { app, drafts } = context;
1045
+ const sight = draftSight(app, context.principal);
1046
+ const judged = (value) => {
1047
+ const lens = lensFromSpec(value);
1048
+ return { lens, verdict: judgeLens(app, lens, sight) };
1049
+ };
1050
+ if (name === "keep_lens") {
1051
+ const { lens, verdict } = judged(args);
1052
+ if (!verdict.ok)
1053
+ return { ok: false, error: verdict.failed, reason: "invalid" };
1054
+ if (!drafts?.keep)
1055
+ return { ok: false, error: "This app's declaration cannot be written from here." };
1056
+ const edit = lensEditOf(lens);
1057
+ const kept = await drafts.keep(edit);
1058
+ if (!kept.ok)
1059
+ return { ok: false, error: kept.error };
1060
+ return { ok: true, data: { kept: edit, said: kept.said ?? `Adds “${edit.title}” to the places.`, undo: takeBackEditOf(edit) } };
1061
+ }
1062
+ if (args["lens"] !== undefined) {
1063
+ const { lens, verdict } = judged(args["lens"]);
1064
+ if (!verdict.ok)
1065
+ return { ok: false, error: verdict.failed, reason: "invalid" };
1066
+ return { ok: true, data: draftAnswer(draftFromLens(app, lens, verdict.drawn, sight, "model")) };
1067
+ }
1068
+ const options = { app, sight, ...(drafts?.complete ? { complete: drafts.complete } : {}) };
1069
+ const ask = String(args["ask"] ?? "");
1070
+ let result;
1071
+ if (args["current"] !== undefined) {
1072
+ const { lens, verdict } = judged(args["current"]);
1073
+ if (!verdict.ok)
1074
+ return { ok: false, error: verdict.failed, reason: "invalid" };
1075
+ result = await refineDraft(draftFromLens(app, lens, verdict.drawn, sight, "model"), ask, options);
1076
+ }
1077
+ else
1078
+ result = await draftView(ask, options);
1079
+ if (isDraftFailure(result))
1080
+ return { ok: false, error: result.failed, reason: "invalid" };
1081
+ return { ok: true, data: draftAnswer(result) };
1082
+ }
1083
+ //# sourceMappingURL=draft.js.map