@perkyzz/emvb 0.5.0 → 0.6.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 (86) hide show
  1. package/README.md +4 -0
  2. package/THIRD_PARTY_NOTICES.md +23 -1
  3. package/licenses/exif-js.LICENSE +21 -0
  4. package/licenses/fflate.LICENSE +21 -0
  5. package/licenses/glfx.js.LICENSE +19 -0
  6. package/licenses/mini-photo-editor.LICENSE +21 -0
  7. package/licenses/photocn.LICENSE +21 -0
  8. package/package.json +2 -1
  9. package/src/admin/editor/Editor.tsx +6 -0
  10. package/src/admin/editor/collection-previews.ts +6 -1
  11. package/src/admin/editor/editor-chrome.tsx +49 -0
  12. package/src/admin/editor/editor-commands.ts +13 -0
  13. package/src/admin/editor/editor-css.ts +3 -0
  14. package/src/admin/editor/panels/ColorControl.tsx +5 -4
  15. package/src/admin/editor/panels/LayersPanel.tsx +13 -3
  16. package/src/admin/editor/panels/VariableSection.tsx +5 -3
  17. package/src/admin/editor/panels/settings/FieldControl.tsx +18 -7
  18. package/src/admin/editor/panels/settings/MediaPicker.tsx +154 -4
  19. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
  20. package/src/admin/editor/panels/variable-values.ts +14 -0
  21. package/src/admin/editor/store.ts +7 -3
  22. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  23. package/src/admin/image-editor/Canvas.tsx +261 -0
  24. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  25. package/src/admin/image-editor/CurvesPanel.tsx +394 -0
  26. package/src/admin/image-editor/ExportDialog.tsx +354 -0
  27. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  28. package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
  29. package/src/admin/image-editor/MetadataPanel.tsx +183 -0
  30. package/src/admin/image-editor/announce.tsx +65 -0
  31. package/src/admin/image-editor/crop-geometry.ts +161 -0
  32. package/src/admin/image-editor/curve-math.ts +177 -0
  33. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  34. package/src/admin/image-editor/engine.ts +55 -0
  35. package/src/admin/image-editor/exif.ts +82 -0
  36. package/src/admin/image-editor/flatten.ts +54 -0
  37. package/src/admin/image-editor/gpu-fit.ts +81 -0
  38. package/src/admin/image-editor/image-editor-css.ts +398 -0
  39. package/src/admin/image-editor/load.ts +109 -0
  40. package/src/admin/image-editor/panels.tsx +287 -0
  41. package/src/admin/image-editor/parts.tsx +565 -0
  42. package/src/admin/image-editor/save.ts +125 -0
  43. package/src/admin/image-editor/tone-panels.tsx +338 -0
  44. package/src/admin/image-editor/tools.ts +59 -0
  45. package/src/admin/image-editor/worker.ts +111 -0
  46. package/src/admin/media-api.ts +113 -3
  47. package/src/admin/ui.ts +5 -0
  48. package/src/astro/EmVBPage.astro +11 -2
  49. package/src/astro/render.ts +3 -0
  50. package/src/astro/resolve-theme.ts +15 -4
  51. package/src/astro/visitor.ts +4 -3
  52. package/src/constants.ts +1 -1
  53. package/src/core/arrange.ts +2 -0
  54. package/src/core/data/bindings.ts +12 -6
  55. package/src/core/design/classes.ts +5 -3
  56. package/src/core/design/diff.ts +3 -1
  57. package/src/core/design/merge.ts +3 -1
  58. package/src/core/design/transfer.ts +13 -2
  59. package/src/core/design/variables.ts +2 -1
  60. package/src/core/elements/dynamic-elements.ts +9 -1
  61. package/src/core/elements/form-elements.ts +16 -17
  62. package/src/core/elements/plain-text.ts +2 -2
  63. package/src/core/forms/binding.ts +148 -1
  64. package/src/core/history/diff.ts +32 -4
  65. package/src/core/image-edit/schema.ts +145 -0
  66. package/src/core/image-edit/summary.ts +58 -0
  67. package/src/core/index.ts +14 -0
  68. package/src/core/limits.ts +10 -0
  69. package/src/core/migrate/index.ts +3 -1
  70. package/src/core/perf/meter.ts +9 -1
  71. package/src/core/render/dynamic-post.ts +2 -1
  72. package/src/core/render/form.ts +24 -6
  73. package/src/core/render/index.ts +26 -5
  74. package/src/core/schema/layout.ts +11 -1
  75. package/src/core/share/link.ts +5 -2
  76. package/src/core/stable-json.ts +15 -0
  77. package/src/core/theme/dynamic.ts +21 -18
  78. package/src/core/theme/pagination.ts +30 -3
  79. package/src/core/theme/popup-rules.ts +10 -5
  80. package/src/mcp/ports.ts +8 -1
  81. package/src/mcp/read.ts +68 -1
  82. package/src/mcp/tools.ts +1 -1
  83. package/src/mcp/write.ts +100 -18
  84. package/src/server/agent-settings.ts +28 -3
  85. package/src/server/icon-routes.ts +8 -5
  86. package/src/server/mcp-routes.ts +68 -10
@@ -18,13 +18,18 @@ export type PopupDevice = (typeof POPUP_DEVICES)[number];
18
18
  */
19
19
  export const DEVICE_PREVIEW_PX = { desktop: 1280, tablet: 768, mobile: 390 } as const;
20
20
 
21
- /** Public CSS queries. Bounds match `deviceForWidth`: 767 mobile, 1024 tablet, 1025 desktop. */
21
+ /**
22
+ * Public CSS queries. Bounds match `deviceForWidth`: below 768 mobile, below 1025 tablet.
23
+ * W-506: zoom and display scaling give fractional viewport widths; with whole-pixel bounds a
24
+ * width such as 1024.5 matched neither the tablet nor the desktop "hide" query, so an element
25
+ * hidden on both showed. The max bounds sit just under the next device's min (as Bootstrap does).
26
+ */
22
27
  export const DEVICE_MEDIA = {
23
- tablet: "(max-width: 1024px)",
24
- mobile: "(max-width: 767px)",
28
+ tablet: "(max-width: 1024.98px)",
29
+ mobile: "(max-width: 767.98px)",
25
30
  hideDesktop: "(min-width: 1025px)",
26
- hideTablet: "(min-width: 768px) and (max-width: 1024px)",
27
- hideMobile: "(max-width: 767px)",
31
+ hideTablet: "(min-width: 768px) and (max-width: 1024.98px)",
32
+ hideMobile: "(max-width: 767.98px)",
28
33
  } as const;
29
34
 
30
35
  /** A scroll percent as a number from 0 to 100; anything unreadable is 0. */
package/src/mcp/ports.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { AgentSettings } from "./settings.ts";
2
2
  import type { RateClass } from "./rate-limit.ts";
3
- import type { DesignSystem, Layout } from "../core/index.ts";
3
+ import type { DesignSystem, Layout, RequiredFieldInfo } from "../core/index.ts";
4
4
 
5
5
  /** A page as the tool core sees it: the current draft (or published) data and its revision. */
6
6
  export type PageRecord = {
@@ -75,4 +75,11 @@ export interface EmvbPorts {
75
75
  publishPage(id: string, expectedRev: string): Promise<{ rev: string }>;
76
76
  /** Publishes the style draft when the published revision is still `expectedPublishedRevision`. */
77
77
  publishDesign(expectedPublishedRevision: string | null): Promise<{ revision: string }>;
78
+ /**
79
+ * W-511: each form's fields as the forms plugin defines them, for describe_page's required-field
80
+ * warnings. Forms it can't read are left out; without this port there are no such warnings.
81
+ */
82
+ formFields?(
83
+ formIds: readonly string[],
84
+ ): Promise<ReadonlyMap<string, readonly RequiredFieldInfo[]>>;
78
85
  }
package/src/mcp/read.ts CHANGED
@@ -18,7 +18,9 @@ import {
18
18
  } from "../core/index.ts";
19
19
  import { parentChildRefusal } from "../core/arrange.ts";
20
20
  import { KNOWN_NODE_SCHEMAS } from "../core/schema/layout.ts";
21
- import { nodeChildren } from "../core/tree-ops.ts";
21
+ import { requiredFieldIssues, requiredFieldIssueText } from "../core/forms/binding.ts";
22
+ import { isFormNode } from "../core/schema/layout.ts";
23
+ import { forEachNode, nodeChildren } from "../core/tree-ops.ts";
22
24
  import { McpToolError } from "./errors.ts";
23
25
  import type { EmvbPorts, PageRecord } from "./ports.ts";
24
26
 
@@ -282,6 +284,8 @@ export const DescribePageOutput = z.object({
282
284
  }),
283
285
  ),
284
286
  headingOutline: z.array(z.string()),
287
+ /** W-500: things that make content vanish without an error, such as hidden on every device. */
288
+ warnings: z.array(z.object({ nodeId: z.string(), message: z.string() })).optional(),
285
289
  wordCount: z.number(),
286
290
  images: z
287
291
  .array(z.object({ id: z.string(), alt: z.string(), src: z.string(), decorative: z.boolean() }))
@@ -307,6 +311,64 @@ function imagesOf(root: LayoutNode) {
307
311
  return found;
308
312
  }
309
313
 
314
+ /** W-500: elements hidden on desktop, tablet and mobile never show; the agent should know. */
315
+ function hiddenEverywhere(root: LayoutNode) {
316
+ const warnings: { nodeId: string; message: string }[] = [];
317
+ const walk = (node: LayoutNode) => {
318
+ const hidden = new Set((node as { hiddenOn?: string[] }).hiddenOn ?? []);
319
+ if (hidden.has("desktop") && hidden.has("tablet") && hidden.has("mobile")) {
320
+ warnings.push({
321
+ nodeId: node.id,
322
+ message:
323
+ node.id === root.id
324
+ ? "The whole page is hidden on every device, so visitors see an empty page. Unset hiddenOn on the root."
325
+ : `${node.label ?? node.type} ${node.id} is hidden on every device, so it and everything inside it never show. Unset hiddenOn, or remove it.`,
326
+ });
327
+ return;
328
+ }
329
+ for (const child of nodeChildren(node)) walk(child);
330
+ };
331
+ walk(root);
332
+ return warnings.slice(0, 50);
333
+ }
334
+
335
+ /**
336
+ * W-511: required form fields visitors can't fill (missing from the form, or hidden on a device),
337
+ * so the form can't be sent there. Needs the forms plugin's definitions; none without them.
338
+ */
339
+ async function requiredFieldWarnings(ports: EmvbPorts, root: LayoutNode) {
340
+ const forms: LayoutNode[] = [];
341
+ forEachNode(root, (node) => {
342
+ if (isFormNode(node) && node.props.formId.trim() && forms.length < 20) forms.push(node);
343
+ });
344
+ if (forms.length === 0 || !ports.formFields) return [];
345
+ let fields: ReadonlyMap<string, readonly { name: string; label: string; required: boolean }[]>;
346
+ try {
347
+ fields = await ports.formFields([
348
+ ...new Set(forms.map((form) => (form.props as { formId: string }).formId.trim())),
349
+ ]);
350
+ } catch {
351
+ return [];
352
+ }
353
+ const warnings: { nodeId: string; message: string }[] = [];
354
+ for (const form of forms) {
355
+ const defined = fields.get((form.props as { formId: string }).formId.trim());
356
+ if (!defined) continue;
357
+ for (const issue of requiredFieldIssues(form, defined)) {
358
+ warnings.push({
359
+ nodeId: issue.kind === "missing" ? issue.formNodeId : issue.nodeId,
360
+ message:
361
+ issue.kind === "hidden"
362
+ ? `${requiredFieldIssueText(issue)} (Unset hiddenOn on ${issue.nodeId} or the box around it.)`
363
+ : issue.kind === "audience"
364
+ ? `${requiredFieldIssueText(issue)} (Unset audience or variant on ${issue.nodeId} or the box around it.)`
365
+ : `${requiredFieldIssueText(issue)} (Form ${issue.formNodeId}, field name ${issue.field}.)`,
366
+ });
367
+ }
368
+ }
369
+ return warnings;
370
+ }
371
+
310
372
  const clip = (text: string, max: number) =>
311
373
  text.length > max ? `${text.slice(0, max - 1)}…` : text;
312
374
 
@@ -336,6 +398,10 @@ export async function describePage(ports: EmvbPorts, input: z.infer<typeof Descr
336
398
  return section;
337
399
  });
338
400
  const wordCount = all.text.join(" ").split(/\s+/).filter(Boolean).length;
401
+ const warnings = [
402
+ ...hiddenEverywhere(layout.root),
403
+ ...(await requiredFieldWarnings(ports, layout.root)),
404
+ ].slice(0, 50);
339
405
  const summary = clip(
340
406
  `"${page.title}" (/${page.slug}, ${page.status}${page.hasDraft ? ", unpublished changes" : ""}): ` +
341
407
  `${sections.length} top-level section${sections.length === 1 ? "" : "s"}, ` +
@@ -351,6 +417,7 @@ export async function describePage(ports: EmvbPorts, input: z.infer<typeof Descr
351
417
  headingOutline: all.headings,
352
418
  wordCount,
353
419
  images: imagesOf(layout.root),
420
+ ...(warnings.length ? { warnings } : {}),
354
421
  };
355
422
  }
356
423
 
package/src/mcp/tools.ts CHANGED
@@ -50,7 +50,7 @@ const READ_TOOLS: ToolDef[] = [
50
50
  name: "get_layout",
51
51
  title: "Get a page layout",
52
52
  description:
53
- "Returns a page's layout (schema 15) and its revision `rev`. Use format \"outline\" first for a cheap tree of ids, types and labels; pass nodeId for one element's subtree.",
53
+ "Returns a page's layout (schema 16) and its revision `rev`. Use format \"outline\" first for a cheap tree of ids, types and labels; pass nodeId for one element's subtree.",
54
54
  input: read.GetLayoutInput,
55
55
  output: read.GetLayoutOutput,
56
56
  readOnly: true,
package/src/mcp/write.ts CHANGED
@@ -17,7 +17,8 @@ import {
17
17
  } from "../core/index.ts";
18
18
  import { addNode, moveNode, withFreshIds } from "../core/arrange.ts";
19
19
  import { ELEMENT_DESCRIPTORS } from "../core/elements/index.ts";
20
- import { removeNode, slugify, starterLayout, updateNode } from "../core/tree-ops.ts";
20
+ import { nodeChildren, removeNode, slugify, starterLayout, updateNode } from "../core/tree-ops.ts";
21
+ import { sanitizeMediaUrl } from "../core/sanitize/media-url.ts";
21
22
  import { McpToolError } from "./errors.ts";
22
23
  import type { EmvbPorts } from "./ports.ts";
23
24
  import { queued } from "./queue.ts";
@@ -109,6 +110,7 @@ async function mutatePage(
109
110
  );
110
111
  }
111
112
  const next = apply(current.layout);
113
+ refuseUnsafeImageSources(current.layout, next.layout);
112
114
  const layout = checkLayout(next.layout);
113
115
  try {
114
116
  const saved = await ports.savePage(pageId, { layout }, page.rev);
@@ -133,6 +135,44 @@ const refused = (reason: string): never => {
133
135
  throw new McpToolError("REFUSED", reason);
134
136
  };
135
137
 
138
+ /** Image sources (src and srcset widths) on a node, keyed for comparison. */
139
+ function imageSources(root: LayoutNode): Map<string, string[]> {
140
+ const found = new Map<string, string[]>();
141
+ const walk = (node: LayoutNode) => {
142
+ if (node.type === "image") {
143
+ const props = node.props as { src?: unknown; sources?: unknown };
144
+ const list = typeof props.src === "string" ? [props.src] : [];
145
+ if (Array.isArray(props.sources)) {
146
+ for (const source of props.sources as { src?: unknown }[]) {
147
+ if (typeof source?.src === "string") list.push(source.src);
148
+ }
149
+ }
150
+ found.set(node.id, list);
151
+ }
152
+ for (const child of nodeChildren(node)) walk(child);
153
+ };
154
+ walk(root);
155
+ return found;
156
+ }
157
+
158
+ /**
159
+ * W-499: a `javascript:` or `data:` image source passed validation and published as a blank
160
+ * placeholder (the renderer drops it), with nothing telling the agent why. Sources the write
161
+ * adds or changes must be http(s) or a same-site path; ones already stored are left alone.
162
+ */
163
+ function refuseUnsafeImageSources(before: Layout, after: Layout) {
164
+ const old = imageSources(before.root);
165
+ for (const [id, list] of imageSources(after.root)) {
166
+ const kept = new Set(old.get(id) ?? []);
167
+ for (const src of list) {
168
+ if (src.trim() === "" || kept.has(src) || sanitizeMediaUrl(src)) continue;
169
+ refused(
170
+ `Image ${id} has the source ${JSON.stringify(src.slice(0, 80))}, which pages can't show. Use an https:// URL or a path on this site such as /_emdash/api/media/file/photo.jpg (upload in the EmDash media library first).`,
171
+ );
172
+ }
173
+ }
174
+ }
175
+
136
176
  const KNOWN_TYPES = new Set(ELEMENT_DESCRIPTORS.map((d) => d.type));
137
177
 
138
178
  /** An element from the agent: its type's defaults, the given props and fields, fresh ids. */
@@ -323,6 +363,29 @@ export const UpdateElementInput = z.strictObject({
323
363
  const isRecord = (v: unknown): v is Record<string, unknown> =>
324
364
  typeof v === "object" && v !== null && !Array.isArray(v);
325
365
 
366
+ /**
367
+ * W-510: a new `src` merged into an image's props kept the old picture's extra sizes (the
368
+ * browser went on showing the old picture from srcset), its image-editor record and its media
369
+ * id and size. As the editor's picker does (W-422, W-425, W-482), they go unless the same
370
+ * write sets them.
371
+ */
372
+ function dropOldPictureProps(
373
+ before: Record<string, unknown>,
374
+ setProps: Record<string, unknown>,
375
+ copy: Record<string, unknown>,
376
+ ) {
377
+ if (typeof setProps.src !== "string" || setProps.src === before.src) return;
378
+ const props = copy.props;
379
+ if (!isRecord(props)) return;
380
+ for (const key of ["sources", "edit", "mediaId"]) {
381
+ if (!(key in setProps)) delete props[key];
382
+ }
383
+ if (before.mediaId !== undefined && !("mediaId" in setProps)) {
384
+ if (!("width" in setProps)) delete props.width;
385
+ if (!("height" in setProps)) delete props.height;
386
+ }
387
+ }
388
+
326
389
  export async function updateElement(ports: EmvbPorts, input: z.infer<typeof UpdateElementInput>) {
327
390
  const set = resolveDesignRefs(input.set ?? {}, (await ports.getDesign()).design);
328
391
  return mutatePage(ports, "update_element", input.pageId, input.expectedRev, (layout) => {
@@ -335,6 +398,9 @@ export async function updateElement(ports: EmvbPorts, input: z.infer<typeof Upda
335
398
  // Objects merge one level deep, like the editor's panels; anything else replaces.
336
399
  copy[key] = isRecord(value) && isRecord(copy[key]) ? { ...copy[key], ...value } : value;
337
400
  }
401
+ if (node.type === "image" && isRecord(set.props)) {
402
+ dropOldPictureProps(node.props as Record<string, unknown>, set.props, copy);
403
+ }
338
404
  for (const path of input.unset ?? []) {
339
405
  const [top, sub] = path.split(".") as [string, string | undefined];
340
406
  if (top === "id" || top === "type" || top === "children") continue;
@@ -447,7 +513,7 @@ export const UpdateSiteStylesInput = z.strictObject({
447
513
  removeClasses: z.array(z.string().min(1).max(64)).max(100).optional(),
448
514
  defaults: z.record(z.string(), z.unknown()).optional(),
449
515
  direction: z.enum(["ltr", "rtl", "auto"]).optional(),
450
- /** Remove variables even when pages or classes still use them (their references fall back). */
516
+ /** Remove variables or classes even when pages or classes still use them (references fall back). */
451
517
  force: z.boolean().optional(),
452
518
  expectedRevision: z.string().max(256).nullable().optional(),
453
519
  });
@@ -460,14 +526,8 @@ const KIND_OF: Record<(typeof VARIABLE_KINDS)[number], VariableKind> = {
460
526
  spacings: "spacing",
461
527
  };
462
528
 
463
- /** Where a variable is still used: class ids and page titles (W-458 in-use guard). */
464
- async function variableUses(
465
- ports: EmvbPorts,
466
- design: DesignSystem,
467
- id: string,
468
- kind: VariableKind,
469
- ): Promise<string[]> {
470
- const where = findVariableUsagesInDesign(design, id, kind).map((u) => `class ${u.classId}`);
529
+ /** Every EmVB page's title and layout, for the in-use guards (at most 1000 pages). */
530
+ async function allLayouts(ports: EmvbPorts): Promise<{ title: string; layout: Layout }[]> {
471
531
  const pages: { id: string; title: string }[] = [];
472
532
  let cursor: string | undefined;
473
533
  for (let i = 0; i < 20; i++) {
@@ -478,15 +538,35 @@ async function variableUses(
478
538
  cursor = batch.nextCursor;
479
539
  }
480
540
  const records = await Promise.all(pages.map((page) => ports.getPage(page.id)));
541
+ const out: { title: string; layout: Layout }[] = [];
481
542
  records.forEach((record, i) => {
482
543
  const layout = record ? validateLayout(record.layout) : null;
483
- if (layout?.ok && findVariableUsages(layout.layout, id, kind).length > 0) {
484
- where.push(`page "${pages[i]?.title ?? ""}"`);
485
- }
544
+ if (layout?.ok) out.push({ title: pages[i]?.title ?? "", layout: layout.layout });
486
545
  });
546
+ return out;
547
+ }
548
+
549
+ /** Where a variable is still used: class ids and page titles (W-458 in-use guard). */
550
+ function variableUses(
551
+ layouts: { title: string; layout: Layout }[],
552
+ design: DesignSystem,
553
+ id: string,
554
+ kind: VariableKind,
555
+ ): string[] {
556
+ const where = findVariableUsagesInDesign(design, id, kind).map((u) => `class ${u.classId}`);
557
+ for (const { title, layout } of layouts) {
558
+ if (findVariableUsages(layout, id, kind).length > 0) where.push(`page "${title}"`);
559
+ }
487
560
  return where;
488
561
  }
489
562
 
563
+ /** W-504: pages whose elements still carry a class (removing it silently unstyled them). */
564
+ function classUses(layouts: { title: string; layout: Layout }[], id: string): string[] {
565
+ const uses = (node: LayoutNode): boolean =>
566
+ (node.classes ?? []).includes(id) || nodeChildren(node).some(uses);
567
+ return layouts.filter(({ layout }) => uses(layout.root)).map(({ title }) => `page "${title}"`);
568
+ }
569
+
490
570
  const upsert = (list: Item[] | undefined, items: Item[]): Item[] => {
491
571
  const next = [...(list ?? [])];
492
572
  for (const item of items) {
@@ -523,13 +603,15 @@ export async function updateSiteStyles(
523
603
  changes.push(`${items.length} ${kind}`);
524
604
  }
525
605
  }
526
- if (!input.force) {
527
- const inUse = await Promise.all(
528
- (input.removeVariables ?? []).map(async ({ kind, id }) => ({
606
+ if (!input.force && (input.removeVariables?.length || input.removeClasses?.length)) {
607
+ const layouts = await allLayouts(ports);
608
+ const inUse = [
609
+ ...(input.removeVariables ?? []).map(({ kind, id }) => ({
529
610
  id,
530
- where: await variableUses(ports, state.design, id, KIND_OF[kind]),
611
+ where: variableUses(layouts, state.design, id, KIND_OF[kind]),
531
612
  })),
532
- );
613
+ ...(input.removeClasses ?? []).map((id) => ({ id, where: classUses(layouts, id) })),
614
+ ];
533
615
  const blocked = inUse.filter((u) => u.where.length > 0);
534
616
  if (blocked.length > 0) {
535
617
  throw new McpToolError(
@@ -34,7 +34,34 @@ type LogQuery = {
34
34
  items: { id: string; data: unknown }[];
35
35
  }>;
36
36
  put(id: string, data: unknown): Promise<void>;
37
+ deleteMany?(ids: string[]): Promise<number>;
37
38
  };
39
+
40
+ /** Agent activity is kept this many days (W-522). */
41
+ const AGENT_LOG_DAYS = 90;
42
+
43
+ /**
44
+ * Adds one agent activity entry and drops up to 100 entries older than AGENT_LOG_DAYS. The log
45
+ * had no limit, so a busy agent token (60 changes a minute) grew it without end (W-522).
46
+ */
47
+ export async function appendAgentLog(
48
+ store: LogQuery,
49
+ entry: Record<string, unknown>,
50
+ now: Date = new Date(),
51
+ ): Promise<void> {
52
+ const at = now.toISOString();
53
+ await store.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, { ...entry, at });
54
+ if (!store.deleteMany) return;
55
+ const cutoff = new Date(now.getTime() - AGENT_LOG_DAYS * 86_400_000).toISOString();
56
+ const old = await store.query({
57
+ where: { at: { lt: cutoff } },
58
+ orderBy: { at: "asc" },
59
+ limit: 100,
60
+ });
61
+ const ids = old.items.map((item) => item.id);
62
+ if (ids.length > 0) await store.deleteMany(ids);
63
+ }
64
+
38
65
  const agentLog = (ctx: PluginContext) => ctx.storage["agentlog"] as unknown as LogQuery;
39
66
 
40
67
  /** Agents tab: the settings, the MCP endpoint and the last 50 agent changes. Admins only. */
@@ -97,10 +124,8 @@ export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
97
124
  if (!write.applied) {
98
125
  throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
99
126
  }
100
- const at = new Date().toISOString();
101
127
  const s = ctx.input.settings;
102
- await agentLog(ctx).put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
103
- at,
128
+ await appendAgentLog(agentLog(ctx), {
104
129
  target: "settings",
105
130
  tool: "settings",
106
131
  userId: ctx.user?.id ?? null,
@@ -1,3 +1,4 @@
1
+ import { clipText } from "../core/limits.ts";
1
2
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
3
  import { z } from "zod";
3
4
  import {
@@ -33,11 +34,13 @@ const UPLOAD_LIST_LIMIT = 100;
33
34
 
34
35
  /** A file name without its folder or extension, as the icon's label. */
35
36
  export const uploadName = (name: string) =>
36
- name
37
- .replace(/^.*[\\/]/, "")
38
- .replace(/\.svg$/i, "")
39
- .trim()
40
- .slice(0, 80) || "Uploaded icon";
37
+ clipText(
38
+ name
39
+ .replace(/^.*[\\/]/, "")
40
+ .replace(/\.svg$/i, "")
41
+ .trim(),
42
+ 80,
43
+ ).trim() || "Uploaded icon";
41
44
 
42
45
  /**
43
46
  * One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
@@ -1,11 +1,12 @@
1
1
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
2
  import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
3
3
  import { McpToolError } from "../mcp/errors.ts";
4
+ import type { RequiredFieldInfo } from "../core/index.ts";
4
5
  import type { EmvbPorts, PageRecord, PageSummary } from "../mcp/ports.ts";
5
6
  import { callerKey, hitRateLimit, type RateStore } from "../mcp/rate-limit.ts";
6
7
  import { runTool, type ToolDef } from "../mcp/tools.ts";
7
8
  import { publishDesignDraft, readDesign, writeDesignDraft } from "./design-routes.ts";
8
- import { readAgentSettings } from "./agent-settings.ts";
9
+ import { appendAgentLog, readAgentSettings } from "./agent-settings.ts";
9
10
 
10
11
  type Item = {
11
12
  id: string;
@@ -43,8 +44,6 @@ type Content = {
43
44
  publish?(c: string, id: string, o: { _rev: string }): Promise<unknown>;
44
45
  };
45
46
 
46
- type LogStore = { put(id: string, data: unknown): Promise<void> };
47
-
48
47
  const parseJson = (raw: unknown) => {
49
48
  if (typeof raw !== "string") return raw;
50
49
  try {
@@ -63,14 +62,75 @@ const summary = (item: Item): PageSummary => ({
63
62
  updatedAt: item.updatedAt,
64
63
  });
65
64
 
65
+ const FORMS_DEFINITION = "/_emdash/api/plugins/emdash-forms/definition";
66
+
67
+ /**
68
+ * W-511: form fields for describe_page's required-field warnings, from the forms plugin's public
69
+ * definition route on this site. A plugin route has no in-process handle on another plugin, so
70
+ * this is a same-origin request with a short timeout; a form it can't read is left out.
71
+ */
72
+ async function loadFormFieldsFromSite(
73
+ origin: string,
74
+ formIds: readonly string[],
75
+ ): Promise<Map<string, RequiredFieldInfo[]>> {
76
+ const found = new Map<string, RequiredFieldInfo[]>();
77
+ await Promise.all(
78
+ formIds.slice(0, 20).map(async (id) => {
79
+ try {
80
+ const response = await fetch(new URL(FORMS_DEFINITION, origin), {
81
+ method: "POST",
82
+ headers: { "content-type": "application/json" },
83
+ body: JSON.stringify({ id }),
84
+ signal: AbortSignal.timeout(3000),
85
+ });
86
+ if (!response.ok) return;
87
+ const body = (await response.json()) as { data?: unknown };
88
+ const data = (body?.data ?? body) as { pages?: unknown };
89
+ if (!Array.isArray(data?.pages)) return;
90
+ const fields: RequiredFieldInfo[] = [];
91
+ for (const page of data.pages as { fields?: unknown }[]) {
92
+ if (!Array.isArray(page?.fields)) continue;
93
+ for (const raw of page.fields as Record<string, unknown>[]) {
94
+ if (typeof raw?.name !== "string") continue;
95
+ fields.push({
96
+ name: raw.name,
97
+ label: typeof raw.label === "string" ? raw.label : raw.name,
98
+ required: raw.required === true,
99
+ });
100
+ }
101
+ }
102
+ found.set(id, fields);
103
+ } catch {
104
+ // The forms plugin is missing, the form is unknown, or the site can't reach itself.
105
+ }
106
+ }),
107
+ );
108
+ return found;
109
+ }
110
+
66
111
  /** The tool core's ports on a plugin route (D-053, R1 save path). */
67
112
  function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
68
113
  const content = ctx.content as unknown as Content | undefined;
69
114
  if (!content) throw new McpToolError("FORBIDDEN", "EmVB has no content access on this site.");
70
- const versioned = (id: string) =>
71
- content.getVersioned ? content.getVersioned(PAGES_COLLECTION, id) : Promise.resolve(null);
115
+ /**
116
+ * W-497: before "Set up EmVB", EmDash reads a page of the missing collection as "not found", so
117
+ * get_layout said "No EmVB page". A miss checks the collection once and says NOT_SET_UP instead.
118
+ */
119
+ const versioned = async (id: string) => {
120
+ const found = content.getVersioned ? await content.getVersioned(PAGES_COLLECTION, id) : null;
121
+ if (!found) {
122
+ try {
123
+ await content.list(PAGES_COLLECTION, { limit: 1 });
124
+ } catch (error) {
125
+ if (isNotSetUp(error)) throw new McpToolError("NOT_SET_UP", NOT_SET_UP_MESSAGE);
126
+ throw error;
127
+ }
128
+ }
129
+ return found;
130
+ };
72
131
  return {
73
132
  caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
133
+ formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
74
134
  async rateLimit(cls) {
75
135
  await hitRateLimit(
76
136
  ctx.kv as unknown as RateStore,
@@ -98,7 +158,7 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
98
158
  };
99
159
  },
100
160
  async getPage(id): Promise<PageRecord | null> {
101
- const found = content.getVersioned ? await content.getVersioned(PAGES_COLLECTION, id) : null;
161
+ const found = await versioned(id);
102
162
  if (!found) return null;
103
163
  return {
104
164
  ...summary(found.item),
@@ -148,11 +208,9 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
148
208
  return { revision: written };
149
209
  },
150
210
  async log(entry) {
151
- const at = new Date().toISOString();
152
- const store = ctx.storage["agentlog"] as unknown as LogStore;
153
- await store.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
211
+ const store = ctx.storage["agentlog"] as unknown as Parameters<typeof appendAgentLog>[0];
212
+ await appendAgentLog(store, {
154
213
  ...entry,
155
- at,
156
214
  userId: ctx.user?.id ?? null,
157
215
  client: (ctx.request.headers.get("user-agent") ?? "").slice(0, 120),
158
216
  });