@enhance-eng/enhance 0.1.168 → 0.1.171

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.
@@ -445,14 +445,14 @@ const completeObjectPictureWorkInputSchema = z.object({
445
445
  //#region ../../packages/contract/src/canvas/canvas-outline.schema.ts
446
446
  /** The most top layers one report may hold; a browser with more sends the rest in later reports. */
447
447
  const CANVAS_OUTLINE_REPORT_LIMIT = 200;
448
- const coordinate$1 = z.number();
449
- const extent = z.number().nonnegative();
448
+ const coordinate$2 = z.number();
449
+ const extent$1 = z.number().nonnegative();
450
450
  /** A box in page coordinates. */
451
451
  const canvasOutlineBoxSchema = z.strictObject({
452
- x: coordinate$1,
453
- y: coordinate$1,
454
- width: extent,
455
- height: extent
452
+ x: coordinate$2,
453
+ y: coordinate$2,
454
+ width: extent$1,
455
+ height: extent$1
456
456
  });
457
457
  /** What a browser measured of one top layer: its own box, and how far its descendants paint. */
458
458
  const canvasOutlineMeasurementSchema = z.strictObject({
@@ -720,6 +720,36 @@ const markCanvasViewedOutputSchema = z.object({ lastViewedAt: z.iso.datetime().n
720
720
  const restoreCanvasInputSchema = z.object({ canvasId: z.uuid() });
721
721
  const restoreCanvasOutputSchema = z.object({ canvasId: z.uuid() });
722
722
 
723
+ //#endregion
724
+ //#region ../../packages/contract/src/canvas/canvas-activity-end.schema.ts
725
+ /** The most layers one agent activity names, as its start allows. */
726
+ const MAX_ACTIVITY_TARGETS$1 = 100;
727
+ /**
728
+ * Without an id, the call ends the calling token's activity on the canvas. With layer ids, it
729
+ * takes those layers out of the mark, and ends the activity when none remain.
730
+ */
731
+ const endCanvasActivityInputSchema = z.object({
732
+ canvasId: z.uuid(),
733
+ activityId: z.uuid().optional(),
734
+ nodeIds: z.array(z.string().min(1)).max(MAX_ACTIVITY_TARGETS$1).default([])
735
+ });
736
+ /**
737
+ * What finishing did: ended the mark, took the named layers out of it, or found nothing live,
738
+ * which is a success: the agent has finished either way.
739
+ */
740
+ const endCanvasActivityOutputSchema = z.discriminatedUnion("outcome", [
741
+ z.object({
742
+ outcome: z.literal("ended"),
743
+ activityId: z.uuid()
744
+ }),
745
+ z.object({
746
+ outcome: z.literal("narrowed"),
747
+ activityId: z.uuid(),
748
+ remainingNodeIds: z.array(z.string().min(1)).min(1)
749
+ }),
750
+ z.object({ outcome: z.literal("nothing-live") })
751
+ ]);
752
+
723
753
  //#endregion
724
754
  //#region ../../packages/contract/src/canvas/canvas-css-value.schema.ts
725
755
  const unsafeStyleValue = /javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu;
@@ -1456,365 +1486,106 @@ const canvasAdditionalStylePatchSchema = z.object({
1456
1486
  }).strict().refine((patch) => patch.set?.every((item) => patch.clear?.includes(item.id) !== true) ?? true, "a declaration cannot be set and cleared in the same patch");
1457
1487
 
1458
1488
  //#endregion
1459
- //#region ../../packages/contract/src/canvas/canvas-text-links.lib.ts
1460
- const FORBIDDEN_DOMAIN_CHARACTERS = /* @__PURE__ */ new Set([
1461
- "#",
1462
- "%",
1463
- "/",
1464
- ":",
1465
- "<",
1466
- ">",
1467
- "?",
1468
- "@",
1469
- "[",
1470
- "\\",
1471
- "]",
1472
- "^",
1473
- "|"
1489
+ //#region ../../packages/contract/src/canvas/canvas-geometry.schema.ts
1490
+ const coordinate$1 = z.number();
1491
+ const dimension$1 = coordinate$1.nonnegative();
1492
+ const MAX_ID_LENGTH = 200;
1493
+ const MIN_POLYGON_POINTS = 3;
1494
+ const identity$1 = z.string().min(1).max(MAX_ID_LENGTH);
1495
+ const path = z.string().regex(/^[MmLlHhVvCcSsQqTtAaZzEe\d\s.,+-]*$/u);
1496
+ const canvasGeometryBoundsSchema = z.strictObject({
1497
+ x: coordinate$1,
1498
+ y: coordinate$1,
1499
+ width: dimension$1,
1500
+ height: dimension$1
1501
+ });
1502
+ const canvasPathGeometrySchema = z.strictObject({
1503
+ kind: z.literal("path"),
1504
+ path: path.min(1),
1505
+ fillRule: z.enum(["nonzero", "evenodd"]),
1506
+ viewBox: canvasGeometryBoundsSchema.extend({
1507
+ width: dimension$1.positive(),
1508
+ height: dimension$1.positive()
1509
+ })
1510
+ });
1511
+ const canvasPolygonGeometrySchema = z.strictObject({
1512
+ kind: z.literal("polygon"),
1513
+ count: z.number().int().min(MIN_POLYGON_POINTS),
1514
+ innerRatio: z.number().min(0).max(1).optional(),
1515
+ cornerRadius: dimension$1,
1516
+ cornerSmoothing: z.number().min(0).max(1)
1517
+ });
1518
+ const canvasBooleanOperationSchema = z.enum([
1519
+ "union",
1520
+ "subtract",
1521
+ "intersect",
1522
+ "exclude"
1474
1523
  ]);
1475
- const ASCII_SPACE = 32;
1476
- const ASCII_DELETE = 127;
1477
- /** Check the decoded host because browser URL parsing can retain host spaces as percent escapes. */
1478
- const isHttpHostname = (url) => {
1479
- if (url.hostname.startsWith("[")) return true;
1480
- const hostname = decodeURIComponent(url.hostname);
1481
- for (const character of hostname) {
1482
- const point = character.codePointAt(0) ?? 0;
1483
- if (point === ASCII_DELETE || point <= ASCII_SPACE || FORBIDDEN_DOMAIN_CHARACTERS.has(character)) return false;
1484
- }
1485
- return hostname !== "";
1486
- };
1487
- const SAFE_HREF_PROTOCOLS = /* @__PURE__ */ new Set([
1488
- "http:",
1489
- "https:",
1490
- "mailto:",
1491
- "tel:"
1524
+ const canvasBooleanGeometrySchema = z.strictObject({
1525
+ kind: z.literal("boolean"),
1526
+ operation: canvasBooleanOperationSchema,
1527
+ operandIds: z.array(identity$1).min(1).refine((ids) => new Set(ids).size === ids.length),
1528
+ result: z.strictObject({
1529
+ path,
1530
+ fillRule: z.literal("nonzero"),
1531
+ isEmpty: z.boolean(),
1532
+ bounds: canvasGeometryBoundsSchema,
1533
+ inputKey: z.string().regex(/^[a-f0-9]{16}$/u)
1534
+ }).refine((result) => result.isEmpty === (result.path === ""))
1535
+ });
1536
+ const canvasGeometrySchema = z.discriminatedUnion("kind", [
1537
+ canvasPathGeometrySchema,
1538
+ canvasPolygonGeometrySchema,
1539
+ z.strictObject({
1540
+ kind: z.literal("mask"),
1541
+ maskId: identity$1,
1542
+ /** Absent paints as alpha. An outline mask clips to the source's shape only. */
1543
+ mode: z.enum([
1544
+ "alpha",
1545
+ "luminance",
1546
+ "outline"
1547
+ ]).optional()
1548
+ }),
1549
+ canvasBooleanGeometrySchema
1492
1550
  ]);
1493
- const isCanvasRichTextHref = (value) => {
1494
- const href = value.trim();
1495
- if (href === "") return false;
1496
- try {
1497
- const url = new URL(href, "https://enhance.invalid/");
1498
- return SAFE_HREF_PROTOCOLS.has(url.protocol) && (!["http:", "https:"].includes(url.protocol) || isHttpHostname(url));
1499
- } catch {
1500
- return false;
1501
- }
1502
- };
1503
1551
 
1504
1552
  //#endregion
1505
- //#region ../../packages/contract/src/canvas/canvas-rich-text.consts.ts
1506
- const CANVAS_RICH_TEXT_STYLE_PROPERTIES = /* @__PURE__ */ new Set([
1507
- "alignItems",
1508
- "backgroundColor",
1509
- "borderBottom",
1510
- "borderBottomLeftRadius",
1511
- "borderBottomRightRadius",
1512
- "borderLeft",
1513
- "borderRight",
1514
- "borderTop",
1515
- "borderTopLeftRadius",
1516
- "borderTopRightRadius",
1517
- "boxShadow",
1518
- "boxSizing",
1519
- "color",
1520
- "columnGap",
1521
- "direction",
1522
- "display",
1523
- "flexDirection",
1524
- "fontFamily",
1525
- "fontFeatureSettings",
1526
- "fontOpticalSizing",
1527
- "fontSize",
1528
- "fontStretch",
1529
- "fontStyle",
1530
- "fontVariant",
1531
- "fontVariantCaps",
1532
- "fontVariantLigatures",
1533
- "fontVariantNumeric",
1534
- "fontVariantPosition",
1535
- "fontKerning",
1536
- "fontVariationSettings",
1537
- "fontWeight",
1538
- "hyphenateCharacter",
1539
- "hyphens",
1540
- "justifyContent",
1541
- "letterSpacing",
1542
- "lineBreak",
1543
- "lineHeight",
1544
- "marginBottom",
1545
- "marginLeft",
1546
- "marginRight",
1547
- "marginTop",
1548
- "opacity",
1549
- "overflowWrap",
1550
- "paddingBottom",
1551
- "paddingLeft",
1552
- "paddingRight",
1553
- "paddingTop",
1554
- "rowGap",
1555
- "tabSize",
1556
- "textDecorationColor",
1557
- "textDecorationLine",
1558
- "textDecorationSkipInk",
1559
- "textDecorationStyle",
1560
- "textDecorationThickness",
1561
- "textRendering",
1562
- "textShadow",
1563
- "textTransform",
1564
- "textUnderlineOffset",
1565
- "unicodeBidi",
1566
- "verticalAlign",
1567
- "whiteSpace",
1568
- "wordBreak",
1569
- "wordSpacing",
1570
- "WebkitFontSmoothing",
1571
- "WebkitLocale",
1572
- "WebkitTextFillColor",
1573
- "WebkitTextStrokeColor",
1574
- "WebkitTextStrokeWidth",
1575
- "--canvas-text-stroke-alignment"
1576
- ]);
1553
+ //#region ../../packages/contract/src/canvas/canvas-property-section.schema.ts
1554
+ const CANVAS_PROPERTY_SECTIONS = [
1555
+ "position",
1556
+ "layout",
1557
+ "clip",
1558
+ "cornerRadius",
1559
+ "blending",
1560
+ "typography",
1561
+ "nativeControl",
1562
+ "textDecoration",
1563
+ "fill",
1564
+ "outline",
1565
+ "textStroke",
1566
+ "border",
1567
+ "outerShadow",
1568
+ "innerShadow",
1569
+ "filters",
1570
+ "additionalStyles",
1571
+ "vector",
1572
+ "export",
1573
+ "source"
1574
+ ];
1575
+ const canvasPropertySectionSchema = z.enum(CANVAS_PROPERTY_SECTIONS);
1577
1576
 
1578
1577
  //#endregion
1579
- //#region ../../packages/contract/src/canvas/canvas-text-style.schema.ts
1580
- const MAX_DESCRIPTION$1 = 2e3;
1581
- const MAX_OVERRIDE_VALUE = 1e3;
1582
- const canvasTextStyleTypographySchema = canvasTypographySchema.pick({
1583
- family: true,
1584
- fallbackFamilies: true,
1585
- size: true,
1586
- weight: true,
1587
- style: true,
1588
- variations: true,
1589
- opticalSize: true,
1590
- features: true,
1591
- lineHeight: true,
1592
- letterSpacing: true,
1593
- transform: true,
1594
- decoration: true,
1595
- paragraphSpacing: true,
1596
- paragraphIndent: true,
1597
- listSpacing: true,
1598
- hangingList: true,
1599
- hangingPunctuation: true,
1600
- verticalTrim: true,
1601
- wrapStyle: true
1602
- }).extend({ decoration: canvasTypographySchema.shape.decoration.omit({ blendMode: true }) }).strict();
1603
- const CANVAS_TEXT_STYLE_PROPERTIES = canvasTextStyleTypographySchema.keyof().options;
1604
- const canvasTextStyleSchema = z.object({
1605
- id: z.string().min(1),
1606
- name: z.string().trim().min(1),
1607
- description: z.string().max(MAX_DESCRIPTION$1),
1608
- sortKey: z.string().min(1).optional(),
1609
- sourceStyleId: z.string().min(1).optional(),
1610
- sourceCanvasId: z.uuid().optional(),
1611
- sourceRevision: z.number().int().positive().optional(),
1612
- typography: canvasTextStyleTypographySchema.extend({ listStyle: canvasTypographySchema.shape.listStyle }).transform((typography) => {
1613
- Reflect.deleteProperty(typography, "listStyle");
1614
- return typography;
1615
- })
1616
- }).strict().refine((style) => style.sourceCanvasId === void 0 || style.sourceStyleId !== void 0, {
1617
- message: "A source canvas belongs to a reference snapshot.",
1618
- path: ["sourceCanvasId"]
1619
- }).refine((style) => style.sourceRevision === void 0 || style.sourceCanvasId !== void 0 && style.sourceStyleId !== void 0, {
1620
- message: "A published revision belongs to a source style and canvas.",
1621
- path: ["sourceRevision"]
1578
+ //#region ../../packages/contract/src/canvas/canvas-export-settings.schema.ts
1579
+ const format = z.enum(["png", "jpeg"]);
1580
+ const scale = z.number().positive();
1581
+ const canvasExportSettingsSchema = z.strictObject({
1582
+ format: format.optional(),
1583
+ scale: scale.optional()
1622
1584
  });
1623
- const canvasTextStyleBindingSchema = z.object({
1624
- id: canvasTextStyleSchema.shape.id,
1625
- position: z.enum([
1626
- "normal",
1627
- "subscript",
1628
- "superscript"
1629
- ]).optional(),
1630
- overrides: z.partialRecord(z.enum([
1631
- "fontWeight",
1632
- "fontStyle",
1633
- "fontVariationSettings",
1634
- "fontOpticalSizing",
1635
- "textDecorationLine",
1636
- "textDecorationStyle",
1637
- "textDecorationColor",
1638
- "textDecorationThickness",
1639
- "textUnderlineOffset",
1640
- "textDecorationSkipInk"
1641
- ]), z.union([z.string().max(MAX_OVERRIDE_VALUE), z.number()])).optional()
1642
- }).strict();
1643
-
1644
- //#endregion
1645
- //#region ../../packages/contract/src/canvas/canvas-rich-text.lib.ts
1646
- const fillsSchema = canvasPaintSchema.array().optional();
1647
- /** What one rich text run stores besides its text, which the owner list of paint blends reads. */
1648
- const canvasRichTextRunPaintSchema = z.object({ fills: fillsSchema });
1649
- const characterFormattingSchema = canvasTextParagraphSchema.pick({
1650
- paragraphSpacing: true,
1651
- paragraphIndent: true,
1652
- listSpacing: true,
1653
- wrapStyle: true
1654
- }).extend({
1655
- hangingPunctuation: canvasTypographySchema.shape.hangingPunctuation,
1656
- verticalTrim: canvasTypographySchema.shape.verticalTrim,
1657
- stroke: canvasTypographySchema.shape.stroke.nullable(),
1658
- decorationBlendMode: canvasTypographySchema.shape.decoration.shape.blendMode,
1659
- backgroundBlendMode: canvasBlendModeSchema.optional()
1660
- }).strip();
1661
- const safeHref = (value) => typeof value === "string" && isCanvasRichTextHref(value) ? value : void 0;
1662
- const richStylesOf = (value) => {
1663
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
1664
- const entries = Object.entries(value);
1665
- if (entries.some(([property, styleValue]) => !CANVAS_RICH_TEXT_STYLE_PROPERTIES.has(property) || typeof styleValue !== "string" && typeof styleValue !== "number")) return null;
1666
- return Object.fromEntries(entries);
1667
- };
1668
- const richMetadataOf = (value) => {
1669
- const sourcePath = Reflect.get(value, "sourcePath");
1670
- return {
1671
- ...Object.fromEntries(Object.entries(value).filter(([key]) => ![
1672
- "text",
1673
- "href",
1674
- "sourcePath",
1675
- "styles",
1676
- "fills",
1677
- "stroke",
1678
- "decorationBlendMode",
1679
- "backgroundBlendMode",
1680
- "paragraph",
1681
- "paragraphSpacing",
1682
- "paragraphIndent",
1683
- "listSpacing",
1684
- "hangingPunctuation",
1685
- "verticalTrim",
1686
- "wrapStyle",
1687
- "soft",
1688
- "textStyle"
1689
- ].includes(key))),
1690
- ...typeof sourcePath === "string" && { sourcePath }
1691
- };
1692
- };
1693
- const richChildrenOf = (values) => {
1694
- const result = [];
1695
- const pending = values.toReversed().map((value) => ({
1696
- value,
1697
- target: result
1698
- }));
1699
- const ancestors = /* @__PURE__ */ new Set();
1700
- while (pending.length > 0) {
1701
- const task = pending.pop();
1702
- if (task === void 0) continue;
1703
- if ("done" in task) {
1704
- ancestors.delete(task.done);
1705
- continue;
1706
- }
1707
- const children = [];
1708
- const node = richNodeOf(task.value, children);
1709
- if (node === null) return null;
1710
- task.target.push(node);
1711
- if (node.kind !== "span") continue;
1712
- const value = task.value;
1713
- if (typeof value !== "object" || value === null || ancestors.has(value)) return null;
1714
- ancestors.add(value);
1715
- pending.push({ done: value });
1716
- const nested = Reflect.get(value, "children");
1717
- if (!Array.isArray(nested)) return null;
1718
- const candidates = nested;
1719
- for (const child of candidates.toReversed()) pending.push({
1720
- value: child,
1721
- target: children
1722
- });
1723
- }
1724
- return result;
1725
- };
1726
- const richBreakOf = (value) => {
1727
- const soft = Reflect.get(value, "soft");
1728
- if (soft !== void 0 && soft !== true) return null;
1729
- return {
1730
- ...richMetadataOf(value),
1731
- kind: "break",
1732
- ...soft === true && { soft }
1733
- };
1734
- };
1735
- const richNodeOf = (value, children) => {
1736
- if (typeof value !== "object" || value === null) return null;
1737
- const kind = Reflect.get(value, "kind");
1738
- const metadata = richMetadataOf(value);
1739
- if (kind === "break") return richBreakOf(value);
1740
- if (kind === "text") {
1741
- const text = Reflect.get(value, "text");
1742
- return typeof text === "string" ? {
1743
- ...metadata,
1744
- kind,
1745
- text
1746
- } : null;
1747
- }
1748
- if (kind !== "span") return null;
1749
- const values = Reflect.get(value, "children");
1750
- const styles = richStylesOf(Reflect.get(value, "styles"));
1751
- const fills = fillsSchema.safeParse(Reflect.get(value, "fills"));
1752
- const paragraph = canvasTextParagraphSchema.optional().safeParse(Reflect.get(value, "paragraph"));
1753
- const formatting = characterFormattingSchema.safeParse(value);
1754
- const textStyle = canvasTextStyleBindingSchema.optional().safeParse(Reflect.get(value, "textStyle"));
1755
- if (styles === null || !fills.success || !paragraph.success || !formatting.success || !textStyle.success || !Array.isArray(values)) return null;
1756
- const href = safeHref(Reflect.get(value, "href"));
1757
- return {
1758
- ...metadata,
1759
- kind,
1760
- styles,
1761
- children,
1762
- ...textStyle.data !== void 0 && { textStyle: textStyle.data },
1763
- ...fills.data !== void 0 && { fills: fills.data },
1764
- ...paragraph.data !== void 0 && { paragraph: paragraph.data },
1765
- ...Object.fromEntries(Object.entries(formatting.data).filter(([, entry]) => entry !== void 0)),
1766
- ...href !== void 0 && { href }
1767
- };
1768
- };
1769
- const richTextLeafValue = (node) => node.kind === "text" ? node.text : node.soft === true ? "\u2028" : "\n";
1770
- const canvasRichTextValueOf = (nodes) => {
1771
- const pending = nodes.toReversed();
1772
- const text = [];
1773
- while (pending.length > 0) {
1774
- const node = pending.pop();
1775
- if (node === void 0) break;
1776
- if (node.kind === "span") for (const child of node.children.toReversed()) pending.push(child);
1777
- else text.push(richTextLeafValue(node));
1778
- }
1779
- return text.join("");
1780
- };
1781
- const canvasRichTextOf = (node) => {
1782
- const props = node.props;
1783
- if (props === void 0 || !Array.isArray(props["richText"])) return [];
1784
- const rich = richChildrenOf(props["richText"]);
1785
- if (rich === null) return [];
1786
- const text = props["text"];
1787
- return canvasRichTextValueOf(rich) === text ? rich : [];
1788
- };
1789
- const hasCanvasRichTextPaints = (node) => {
1790
- const pending = [...canvasRichTextOf(node)];
1791
- while (pending.length > 0) {
1792
- const run = pending.pop();
1793
- if (run?.kind !== "span") continue;
1794
- if (run.fills !== void 0) return true;
1795
- for (const child of run.children) pending.push(child);
1796
- }
1797
- return false;
1798
- };
1799
- /** Existing-link edits retain authored formatting, including nested descendants. */
1800
- const canvasRichTextLinkOf = (runs) => {
1801
- const destinations = /* @__PURE__ */ new Set();
1802
- const visit = (nodes, inherited) => {
1803
- for (const node of nodes) if (node.kind === "span") visit(node.children, node.href ?? inherited);
1804
- else destinations.add(inherited);
1805
- };
1806
- visit(runs);
1807
- return destinations.size === 1 ? [...destinations][0] ?? null : null;
1808
- };
1809
- /**
1810
- * The style text a run edit clears: the properties it sets, and for a stroke edit the style text
1811
- * that copies a stroke, since the stroke value owns it.
1812
- */
1813
- const canvasRunStylesClearedBy = (command) => [...Object.keys(command.styles), ...command.stroke === void 0 ? [] : [
1814
- "WebkitTextStrokeWidth",
1815
- "WebkitTextStrokeColor",
1816
- "--canvas-text-stroke-alignment"
1817
- ]];
1585
+ const canvasExportSettingsPatchSchema = z.strictObject({
1586
+ format: format.nullable().optional(),
1587
+ scale: scale.nullable().optional()
1588
+ }).refine((patch) => patch.format !== void 0 || patch.scale !== void 0);
1818
1589
 
1819
1590
  //#endregion
1820
1591
  //#region ../../packages/contract/src/shared/blob.schema.ts
@@ -1871,1183 +1642,790 @@ const canvasImageAssetIdentityFromPath = (path) => {
1871
1642
  };
1872
1643
 
1873
1644
  //#endregion
1874
- //#region ../../packages/contract/src/canvas/canvas-font-asset.schema.ts
1875
- const FONT_PATH_SEGMENT_LIMIT = 4;
1876
- const CANVAS_FONT_CONTENT_TYPES = [
1877
- "font/ttf",
1878
- "font/otf",
1879
- "font/woff",
1880
- "font/woff2",
1881
- "font/collection"
1882
- ];
1883
- const canvasFontAssetIdentitySchema = z.object({
1884
- canvasId: z.uuid(),
1885
- sha256: z.string().regex(/^[a-f0-9]{64}$/u)
1886
- });
1887
- const completeCanvasFontInputSchema = canvasFontAssetIdentitySchema.extend({ bytes: z.number().int().positive() });
1888
- const reserveCanvasFontInputSchema = completeCanvasFontInputSchema.extend({ contentType: z.enum(CANVAS_FONT_CONTENT_TYPES) });
1889
- const completeCanvasFontOutputSchema = z.object({ path: z.string().startsWith("/v1/canvas-assets/") });
1890
- const reserveCanvasFontOutputSchema = completeCanvasFontOutputSchema.extend({ upload: signedUploadSchema });
1891
- const canvasFontAssetPath = (canvasId, sha256) => `${CANVAS_ASSET_PATH_PREFIX}${encodeURIComponent(canvasId)}/fonts/${encodeURIComponent(sha256)}`;
1892
- const copyCanvasFontsInputSchema = z.object({
1893
- canvasId: z.uuid(),
1894
- sources: z.array(canvasFontAssetIdentitySchema).min(1)
1645
+ //#region ../../packages/contract/src/canvas/canvas-scene.schema.ts
1646
+ const CANVAS_COMPOSITING_RETIRED = "Update Enhance: compositing is no longer supported. Use the isolation style or a mask group.";
1647
+ const CANVAS_FORMAT_UPDATE_REQUIRED = "This change needs a newer version of Enhance. Refresh the editor, or update the Enhance plugin or command-line tool, then try again.";
1648
+ const CANVAS_FORMAT_SERVER_UPDATING = "Enhance is being updated. Try again in a minute.";
1649
+ /** Marks an issue whose message was written for whoever sent the request, so the API keeps it. */
1650
+ const FOR_CALLER = { forCaller: true };
1651
+ /**
1652
+ * The format a writer was built for, as a plain whole number so tool schemas can describe it. Which
1653
+ * writes that format may make is `refuseUnsafeWriterFormat`'s call.
1654
+ */
1655
+ const canvasDocumentFormatSchema = z.number({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).int({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).positive({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).meta({
1656
+ description: `The document format this client writes. The current format is ${String(15)}.`,
1657
+ examples: [15]
1895
1658
  });
1896
- const copyCanvasFontsOutputSchema = z.object({ resources: z.array(z.object({
1897
- source: canvasFontAssetIdentitySchema,
1898
- path: z.string()
1899
- })) });
1900
- const canvasFontAssetIdentityFromPath = (path) => {
1901
- if (!path.startsWith("/v1/canvas-assets/")) return null;
1902
- const [canvasId, kind, sha256, extra] = path.slice(CANVAS_ASSET_PATH_PREFIX.length).split("/", FONT_PATH_SEGMENT_LIMIT);
1903
- if (kind !== "fonts" || extra !== void 0) return null;
1904
- return canvasFontAssetIdentitySchema.safeParse({
1905
- canvasId,
1906
- sha256
1907
- }).data ?? null;
1908
- };
1909
-
1910
- //#endregion
1911
- //#region ../../packages/contract/src/canvas/canvas-asset-upload.schema.ts
1912
- const MAX_FONT_WEIGHT = 1e3;
1913
- const FONT_CONTENT_TYPES = new Set(CANVAS_FONT_CONTENT_TYPES);
1914
- const isStoredContentType = (kind, contentType) => kind === "image" ? canvasStoredImageContentTypeSchema.safeParse(contentType).success : FONT_CONTENT_TYPES.has(contentType);
1915
- const canvasAssetUploadIdentitySchema = z.strictObject({
1659
+ /**
1660
+ * Refuses a write its client's format could get wrong. A client whose format differs from the
1661
+ * current one only in its number may still name changes, but a whole value it sends may lack
1662
+ * fields added since, so that needs the current format.
1663
+ */
1664
+ const refuseUnsafeWriterFormat = (documentFormatVersion, writes, context) => {
1665
+ const writer = canvasWriterFormat(documentFormatVersion);
1666
+ if (writer === "current" || writer === "number-only" && writes === "names") return;
1667
+ context.addIssue({
1668
+ code: "custom",
1669
+ path: ["documentFormatVersion"],
1670
+ message: writer === "ahead" ? CANVAS_FORMAT_SERVER_UPDATING : CANVAS_FORMAT_UPDATE_REQUIRED,
1671
+ params: FOR_CALLER,
1672
+ input: documentFormatVersion
1673
+ });
1674
+ };
1675
+ const canvasPreservedFontAppearanceSchema = z.object({
1676
+ signature: z.string().regex(/^[a-f0-9]{16}$/u),
1677
+ /** The captured picture of the page's text, inline as written or as its canvas image store path. */
1678
+ image: z.string().refine((image) => image.startsWith("data:image/jpeg;base64,") || canvasImageAssetIdentityFromPath(image) !== null),
1679
+ families: z.array(z.string().min(1)).min(1)
1680
+ });
1681
+ const canvasSceneBoxSchema = z.object({
1682
+ x: z.number(),
1683
+ y: z.number(),
1684
+ width: z.number().nonnegative(),
1685
+ height: z.number().nonnegative()
1686
+ });
1687
+ const canvasConstraintSchema = z.enum([
1688
+ "start",
1689
+ "center",
1690
+ "end",
1691
+ "stretch",
1692
+ "scale"
1693
+ ]);
1694
+ const canvasNodeConstraintsSchema = z.object({
1695
+ x: canvasConstraintSchema,
1696
+ y: canvasConstraintSchema
1697
+ });
1698
+ const canvasNodeLabelOriginSchema = z.enum([
1699
+ "source",
1700
+ "generated",
1701
+ "content",
1702
+ "user"
1703
+ ]);
1704
+ const canvasSceneNodeSchema = z.looseObject({
1705
+ id: z.string().min(1),
1706
+ label: z.string(),
1707
+ component: z.string().min(1),
1708
+ labelOrigin: canvasNodeLabelOriginSchema.optional(),
1709
+ visible: z.boolean().optional(),
1710
+ locked: z.boolean().optional(),
1711
+ constraints: canvasNodeConstraintsSchema.optional(),
1712
+ styles: z.record(z.string(), z.union([z.string(), z.number()])),
1713
+ layout: canvasNodeLayoutSchema.optional(),
1714
+ responsive: z.never().optional(),
1715
+ appearance: canvasAppearanceValuesSchema.optional(),
1716
+ exportSettings: canvasExportSettingsSchema.optional(),
1717
+ typography: canvasAuthoredTypographySchema.optional(),
1718
+ additionalStyles: canvasAdditionalStylesSchema.optional(),
1719
+ geometry: canvasGeometrySchema.optional(),
1720
+ compositing: z.never({ error: CANVAS_COMPOSITING_RETIRED }).optional(),
1721
+ props: z.record(z.string(), z.unknown()).optional(),
1722
+ box: canvasSceneBoxSchema.optional()
1723
+ });
1724
+ const canvasSceneRelationshipSchema = z.object({
1725
+ parentId: z.string().min(1),
1726
+ sortKey: z.string().min(1)
1727
+ });
1728
+ const canvasSceneDocumentSchema = z.object({
1729
+ version: z.literal(15),
1730
+ nodes: z.record(z.string(), canvasSceneNodeSchema),
1731
+ relationships: z.record(z.string(), canvasSceneRelationshipSchema),
1732
+ tombstones: z.record(z.string(), z.literal(true)).default({})
1733
+ });
1734
+ const legacyRecordSchema = z.record(z.string(), z.unknown());
1735
+ /** Known old scenes are adapted in memory; only an explicit mutation persists the new format. */
1736
+ const canvasReadableSceneDocumentSchema = z.preprocess((value) => {
1737
+ const blob = legacyRecordSchema.safeParse(value).data;
1738
+ if (blob === void 0) return value;
1739
+ if (Object.keys(blob).length === 0) return emptyCanvasSceneDocument();
1740
+ return adaptCanvasDocumentFormat(blob);
1741
+ }, canvasSceneDocumentSchema);
1742
+ /** A document's version, or the read result that refuses it before anything else is read. */
1743
+ const refusedVersionOf = (blob) => {
1744
+ const version = blob["version"];
1745
+ if (version !== void 0 && (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1)) return { status: "invalid" };
1746
+ if (version !== void 0 && version > 15) return {
1747
+ status: "unsupported",
1748
+ formatVersion: version
1749
+ };
1750
+ return null;
1751
+ };
1752
+ const readCanvasSceneDocument = (blob) => {
1753
+ if (blob === void 0) return { status: "missing" };
1754
+ const refused = refusedVersionOf(blob);
1755
+ if (refused !== null) return refused;
1756
+ const parsed = canvasReadableSceneDocumentSchema.safeParse(blob);
1757
+ return parsed.success ? {
1758
+ status: "current",
1759
+ document: parsed.data
1760
+ } : { status: "invalid" };
1761
+ };
1762
+ const emptyCanvasSceneDocument = () => ({
1763
+ version: 15,
1764
+ nodes: { root: {
1765
+ id: "root",
1766
+ label: "Canvas",
1767
+ component: "root",
1768
+ labelOrigin: "generated",
1769
+ visible: true,
1770
+ locked: false,
1771
+ styles: {}
1772
+ } },
1773
+ relationships: {},
1774
+ tombstones: {}
1775
+ });
1776
+ const shellSchema = canvasSceneDocumentSchema.extend({
1777
+ nodes: z.record(z.string(), z.unknown()),
1778
+ relationships: z.record(z.string(), z.unknown())
1779
+ });
1780
+
1781
+ //#endregion
1782
+ //#region ../../packages/contract/src/canvas/canvas-inspection.schema.ts
1783
+ const MAX_RENDER_MESSAGE_LENGTH$1 = 500;
1784
+ const MAX_RENDER_KIND_LENGTH = 100;
1785
+ /**
1786
+ * What a layer's box is: `placed` where the canvas draws the layer, `placed-before-transform` where
1787
+ * it draws the layer before the layer's own transform, `recorded` a size kept from when the layer
1788
+ * was made, for a layer the browser lays out.
1789
+ */
1790
+ const canvasBoxSourceSchema = z.enum([
1791
+ "placed",
1792
+ "placed-before-transform",
1793
+ "recorded"
1794
+ ]);
1795
+ /** Present only on a read that holds a `recorded` box. */
1796
+ const boxNoteSchema = z.string().min(1).optional();
1797
+ const canvasInspectNodeSummarySchema = z.object({
1798
+ id: z.string().min(1),
1799
+ label: z.string().max(MAX_RENDER_MESSAGE_LENGTH$1),
1800
+ kind: z.string().min(1).max(MAX_RENDER_KIND_LENGTH),
1801
+ parentId: z.string().min(1).nullable(),
1802
+ childCount: z.number().int().min(0),
1803
+ box: canvasSceneBoxSchema.nullable(),
1804
+ boxSource: canvasBoxSourceSchema.optional(),
1805
+ propertySections: z.array(canvasPropertySectionSchema)
1806
+ });
1807
+ const inspectCanvasInputSchema = z.object({ canvasId: z.uuid() });
1808
+ const inspectCanvasOutputSchema = z.object({
1916
1809
  canvasId: z.uuid(),
1917
- clientToken: z.uuid()
1810
+ openUrl: z.url(),
1811
+ title: z.string().min(1),
1812
+ version: z.number().int().positive(),
1813
+ nodeCount: z.number().int().min(0),
1814
+ rootChildCount: z.number().int().min(0),
1815
+ bounds: canvasSceneBoxSchema.nullable(),
1816
+ kinds: z.record(z.string(), z.number().int().min(0)),
1817
+ boxNote: boxNoteSchema,
1818
+ next: z.array(z.string().min(1))
1918
1819
  });
1919
- const reserveCanvasAssetInputSchema = z.discriminatedUnion("kind", [canvasAssetUploadIdentitySchema.extend({
1920
- kind: z.literal("image"),
1921
- contentType: z.enum(CANVAS_IMAGE_CONTENT_TYPES),
1922
- bytes: z.number().int().positive(),
1923
- sha256: z.string().regex(/^[a-f0-9]{64}$/u)
1924
- }), canvasAssetUploadIdentitySchema.extend({
1925
- kind: z.literal("font"),
1926
- contentType: z.enum(CANVAS_FONT_CONTENT_TYPES),
1927
- bytes: z.number().int().positive(),
1928
- sha256: z.string().regex(/^[a-f0-9]{64}$/u)
1929
- })]);
1930
- const canvasAssetMetadataSchema = z.discriminatedUnion("kind", [z.strictObject({
1931
- kind: z.literal("image"),
1932
- width: z.number().int().positive(),
1933
- height: z.number().int().positive()
1934
- }), z.strictObject({
1935
- kind: z.literal("font"),
1936
- family: z.string().min(1),
1937
- subfamily: z.string(),
1938
- style: z.enum([
1939
- "normal",
1940
- "italic",
1941
- "oblique"
1942
- ]),
1943
- minimumWeight: z.number().min(1).max(MAX_FONT_WEIGHT),
1944
- maximumWeight: z.number().min(1).max(MAX_FONT_WEIGHT)
1945
- }).refine((font) => font.minimumWeight <= font.maximumWeight, "Font weight bounds must be ordered.")]);
1946
- const canvasAssetUploadOutputSchema = z.strictObject({
1820
+ const inspectCanvasTreeInputSchema = z.object({ canvasId: z.uuid() });
1821
+ const inspectCanvasTreeOutputSchema = z.object({
1947
1822
  canvasId: z.uuid(),
1948
- clientToken: z.uuid(),
1949
- assetId: z.uuid(),
1950
- kind: z.enum(["image", "font"]),
1951
- contentType: z.string(),
1952
- bytes: z.number().int().positive(),
1953
- sha256: z.string().regex(/^[a-f0-9]{64}$/u),
1954
- path: z.string().startsWith("/v1/canvas-assets/"),
1955
- state: z.enum(["awaiting_upload", "ready"]),
1956
- metadata: canvasAssetMetadataSchema.nullable()
1957
- }).refine((asset) => asset.state === "ready" === (asset.metadata !== null), "Readiness must match verified metadata.").refine((asset) => asset.metadata === null || asset.metadata.kind === asset.kind, "Metadata must describe the reserved asset kind.").refine((asset) => isStoredContentType(asset.kind, asset.contentType), "Content type must match the asset kind.").refine((asset) => asset.path === (asset.kind === "image" ? canvasImageAssetPath(asset.canvasId, asset.assetId) : canvasFontAssetPath(asset.canvasId, asset.sha256)), "The resource path must match its native identity.");
1958
- const reserveCanvasAssetOutputSchema = canvasAssetUploadOutputSchema.safeExtend({ upload: signedUploadSchema.nullable() }).refine((asset) => asset.state === "awaiting_upload" === (asset.upload !== null), "Only pending uploads receive upload access.");
1823
+ version: z.number().int().positive(),
1824
+ nodes: z.array(canvasInspectNodeSummarySchema),
1825
+ boxNote: boxNoteSchema
1826
+ });
1827
+ const inspectCanvasNodeInputSchema = z.object({
1828
+ canvasId: z.uuid(),
1829
+ nodeId: z.string().min(1)
1830
+ });
1831
+ const inspectCanvasNodeOutputSchema = z.object({
1832
+ canvasId: z.uuid(),
1833
+ version: z.number().int().positive(),
1834
+ node: canvasInspectNodeSummarySchema.extend({
1835
+ styles: z.record(z.string(), z.union([z.string(), z.number()])),
1836
+ layout: canvasNodeLayoutSchema.optional(),
1837
+ appearance: canvasAppearanceValuesSchema.optional(),
1838
+ geometry: canvasGeometrySchema.optional(),
1839
+ typography: canvasAuthoredTypographySchema.optional(),
1840
+ additionalStyles: canvasAdditionalStylesSchema.optional(),
1841
+ props: z.record(z.string(), z.unknown()),
1842
+ children: z.array(z.string().min(1))
1843
+ }),
1844
+ boxNote: boxNoteSchema,
1845
+ next: z.array(z.string().min(1))
1846
+ });
1959
1847
 
1960
1848
  //#endregion
1961
- //#region ../../packages/contract/src/canvas/canvas-css-values.lib.ts
1962
- const UNITLESS_PROPERTIES = /* @__PURE__ */ new Set([
1963
- "aspect-ratio",
1964
- "-webkit-line-clamp",
1965
- "line-clamp",
1966
- "flex-grow",
1967
- "flex-shrink",
1968
- "font-weight",
1969
- "opacity",
1970
- "order",
1971
- "z-index",
1972
- "grid-area",
1973
- "grid-row",
1974
- "grid-column",
1975
- "grid-row-start",
1976
- "grid-row-end",
1977
- "grid-column-start",
1978
- "grid-column-end"
1979
- ]);
1980
- const canvasCssValue = (property, value) => typeof value === "number" && !UNITLESS_PROPERTIES.has(property.toLowerCase()) ? `${String(value)}px` : String(value);
1981
- const SIDES$2 = [
1982
- "top",
1983
- "right",
1984
- "bottom",
1985
- "left"
1986
- ];
1987
- const LEFT_SIDE_INDEX = 3;
1988
- const GRID_TEMPLATE_PROPERTIES = [
1989
- "grid-template-rows",
1990
- "grid-template-columns",
1991
- "grid-template-areas"
1849
+ //#region ../../packages/contract/src/canvas/canvas-placement.schema.ts
1850
+ const coordinate = z.number();
1851
+ const extent = z.number().positive();
1852
+ const placedBox = z.strictObject({
1853
+ x: coordinate,
1854
+ y: coordinate,
1855
+ width: extent,
1856
+ height: extent
1857
+ });
1858
+ /** Where the person who started the request was looking; a preference, never a camera command. */
1859
+ const canvasInitiatingViewHintSchema = z.strictObject({
1860
+ pageId: z.string().min(1),
1861
+ bounds: placedBox
1862
+ });
1863
+ /** How a new top-level screen or copied set is placed on its page. Omitted, positions stay as authored. */
1864
+ const canvasPlacementIntentSchema = z.discriminatedUnion("kind", [
1865
+ z.strictObject({
1866
+ kind: z.literal("auto"),
1867
+ view: canvasInitiatingViewHintSchema.optional()
1868
+ }),
1869
+ z.strictObject({
1870
+ kind: z.literal("near"),
1871
+ anchorNodeId: z.string().min(1),
1872
+ side: z.enum(["right", "below"])
1873
+ }),
1874
+ z.strictObject({
1875
+ kind: z.literal("explicit"),
1876
+ x: coordinate,
1877
+ y: coordinate
1878
+ })
1879
+ ]);
1880
+ /** Where a committed change put its roots, as saved at its own revision. */
1881
+ const canvasPlacementResultSchema = z.strictObject({
1882
+ pageId: z.string().min(1),
1883
+ bounds: placedBox,
1884
+ roots: z.array(z.strictObject({
1885
+ nodeId: z.string().min(1),
1886
+ box: placedBox
1887
+ })).min(1)
1888
+ });
1889
+
1890
+ //#endregion
1891
+ //#region ../../packages/contract/src/canvas/canvas-conversion-draft.schema.ts
1892
+ const temporaryIdSchema = z.string().min(1);
1893
+ const canvasConversionIssueSchema = z.object({
1894
+ code: z.enum([
1895
+ "asset-unavailable",
1896
+ "content-omitted",
1897
+ "cross-origin-frame",
1898
+ "nodes-truncated",
1899
+ "responsive-behavior-not-editable",
1900
+ "style-degraded",
1901
+ "unsupported-surface",
1902
+ "vertical-writing-unsupported"
1903
+ ]),
1904
+ message: z.string().min(1),
1905
+ temporaryId: temporaryIdSchema.optional()
1906
+ });
1907
+ /** Source features that CSS cannot draw; a conversion writes the closest CSS and counts each. */
1908
+ const CANVAS_UNSUPPORTED_FEATURES = [
1909
+ "text-stroke-inside",
1910
+ "text-stroke-outside-translucent",
1911
+ "text-stroke-paints",
1912
+ "text-inner-shadow",
1913
+ "text-shadow-spread",
1914
+ "text-shadow-blend",
1915
+ "text-background-blur",
1916
+ "progressive-layer-blur",
1917
+ "progressive-background-blur",
1918
+ "blend-plus-darker",
1919
+ "blend-linear-burn",
1920
+ "image-exposure",
1921
+ "image-contrast",
1922
+ "image-saturation",
1923
+ "image-temperature",
1924
+ "image-tint",
1925
+ "image-highlights",
1926
+ "image-shadows",
1927
+ "effect-noise",
1928
+ "effect-texture",
1929
+ "effect-glass",
1930
+ "mask-source"
1992
1931
  ];
1993
- const SHORTHANDS = {
1994
- gap: ["row-gap", "column-gap"],
1995
- "text-wrap": ["text-wrap-mode", "text-wrap-style"],
1996
- padding: SIDES$2.map((side) => `padding-${side}`),
1997
- margin: SIDES$2.map((side) => `margin-${side}`),
1998
- flex: [
1999
- "flex-grow",
2000
- "flex-shrink",
2001
- "flex-basis"
2002
- ],
2003
- "flex-flow": ["flex-direction", "flex-wrap"],
2004
- "place-content": ["align-content", "justify-content"],
2005
- "place-items": ["align-items", "justify-items"],
2006
- "place-self": ["align-self", "justify-self"],
2007
- "grid-template": GRID_TEMPLATE_PROPERTIES,
2008
- grid: [
2009
- ...GRID_TEMPLATE_PROPERTIES,
2010
- "grid-auto-rows",
2011
- "grid-auto-columns",
2012
- "grid-auto-flow"
2013
- ],
2014
- "grid-row": ["grid-row-start", "grid-row-end"],
2015
- "grid-column": ["grid-column-start", "grid-column-end"],
2016
- "grid-area": [
2017
- "grid-row-start",
2018
- "grid-column-start",
2019
- "grid-row-end",
2020
- "grid-column-end"
2021
- ]
2022
- };
2023
- /** Related declarations stay authored; a longhand edit must not discard the rest of a shorthand. */
2024
- const canvasCssPropertyScope = (property) => SHORTHANDS[property.toLowerCase()] ?? [property.toLowerCase()];
2025
- const componentStateAfter = (state, character) => {
2026
- if (state.isEscaped) return {
2027
- ...state,
2028
- isEscaped: false
2029
- };
2030
- if (character === "\\") return {
2031
- ...state,
2032
- isEscaped: true
2033
- };
2034
- if (state.quote !== "") return {
2035
- ...state,
2036
- quote: state.quote === character ? "" : state.quote
2037
- };
2038
- if (["\"", "'"].includes(character)) return {
2039
- ...state,
2040
- quote: character
2041
- };
2042
- const delta = [
2043
- "(",
2044
- "[",
2045
- "{"
2046
- ].includes(character) ? 1 : [
2047
- ")",
2048
- "]",
2049
- "}"
2050
- ].includes(character) ? -1 : 0;
2051
- return {
2052
- ...state,
2053
- depth: state.depth + delta
2054
- };
1932
+ const canvasUnsupportedFeatureSchema = z.enum(CANVAS_UNSUPPORTED_FEATURES);
1933
+ const canvasConversionReportSchema = z.object({
1934
+ nodeCount: z.number().int().positive(),
1935
+ unsupportedFeatures: z.array(z.object({
1936
+ feature: canvasUnsupportedFeatureSchema,
1937
+ count: z.number().int().positive()
1938
+ })).optional(),
1939
+ sourceNodeCount: z.number().int().positive().optional(),
1940
+ collapsedNodeCount: z.number().int().nonnegative().optional(),
1941
+ collapsedWrapperNodeCount: z.number().int().nonnegative().optional(),
1942
+ collapsedNeutralWrapperNodeCount: z.number().int().nonnegative().optional(),
1943
+ collapsedTransferredWrapperNodeCount: z.number().int().nonnegative().optional(),
1944
+ layoutContainerCount: z.number().int().nonnegative().optional(),
1945
+ removedLeafNodeCount: z.number().int().nonnegative().optional(),
1946
+ retainedSemanticOwnerNodeCount: z.number().int().nonnegative().optional(),
1947
+ truncatedNodeCount: z.number().int().nonnegative().optional(),
1948
+ addedLayoutNodeCount: z.number().int().nonnegative().optional(),
1949
+ issues: z.array(canvasConversionIssueSchema)
1950
+ });
1951
+ const canvasSubtreeDraftNodeSchema = canvasSceneNodeSchema.omit({ id: true }).extend({ temporaryId: temporaryIdSchema });
1952
+ const canvasSubtreeDraftRelationshipSchema = z.object({
1953
+ temporaryId: temporaryIdSchema,
1954
+ parentTemporaryId: temporaryIdSchema,
1955
+ sortKey: z.string().min(1)
1956
+ });
1957
+ /**
1958
+ * A report that cannot be read says so, rather than reading as "nothing left out". The kind is an
1959
+ * existing one, because installed clients check kinds strictly and would refuse the whole answer.
1960
+ */
1961
+ const UNREADABLE_REPORT = {
1962
+ nodeCount: 0,
1963
+ issues: [{
1964
+ code: "content-omitted",
1965
+ message: "The converter's report could not be read, so what it left out of this insert is unknown."
1966
+ }]
2055
1967
  };
2056
- /** Split only at CSS component boundaries, keeping functions, line names and strings intact. */
2057
- const canvasCssTokens = (value, separator = "space") => {
2058
- const tokens = [];
2059
- let token = "";
2060
- let state = {
2061
- depth: 0,
2062
- quote: "",
2063
- isEscaped: false
2064
- };
2065
- for (const character of value) {
2066
- const canSplit = state.depth === 0 && state.quote === "" && !state.isEscaped;
2067
- state = componentStateAfter(state, character);
2068
- if (canSplit && (separator === "space" ? /\s/u.test(character) : character === separator)) {
2069
- if (separator !== "space" || token !== "") tokens.push(token.trim());
2070
- token = "";
2071
- } else token += character;
1968
+ const canvasSubtreeDraftSchema = z.object({
1969
+ version: z.literal(1),
1970
+ rootTemporaryId: temporaryIdSchema,
1971
+ nodes: z.array(canvasSubtreeDraftNodeSchema).min(1),
1972
+ relationships: z.array(canvasSubtreeDraftRelationshipSchema),
1973
+ report: canvasConversionReportSchema.catch(UNREADABLE_REPORT)
1974
+ }).transform((draft) => ({
1975
+ ...draft,
1976
+ report: {
1977
+ ...draft.report,
1978
+ nodeCount: draft.nodes.length
2072
1979
  }
2073
- if (separator !== "space" || token !== "") tokens.push(token.trim());
2074
- return tokens;
2075
- };
2076
- const omittedGridLine = (value) => /^(?:--|-?[_a-z\u{80}-\u{FFFF}])[-\w\u{80}-\u{FFFF}]*$/iu.test(value) && !/^(?:auto|span|initial|unset)$/iu.test(value) ? value : "auto";
2077
- const gridPlacementValue = (property, value, index) => {
2078
- const parts = canvasCssTokens(value, "/");
2079
- const first = parts[0] ?? value;
2080
- if (property !== "grid-area") return parts[index] ?? omittedGridLine(first);
2081
- const column = parts[1] ?? omittedGridLine(first);
2082
- return [
2083
- first,
2084
- column,
2085
- parts[2] ?? omittedGridLine(first),
2086
- parts[3] ?? omittedGridLine(column)
2087
- ][index] ?? value;
2088
- };
2089
- const implicitGridValues = (row, column, hasAutoRows) => {
2090
- const tokens = canvasCssTokens(hasAutoRows ? row : column);
2091
- const size = tokens.filter((token) => !/^(?:auto-flow|dense)$/iu.test(token)).join(" ");
2092
- const flow = `${hasAutoRows ? "row" : "column"}${tokens.some((token) => /^dense$/iu.test(token)) ? " dense" : ""}`;
2093
- return [
2094
- hasAutoRows ? "none" : row,
2095
- hasAutoRows ? column : "none",
2096
- "none",
2097
- hasAutoRows && size !== "" ? size : "auto",
2098
- !hasAutoRows && size !== "" ? size : "auto",
2099
- flow
2100
- ];
2101
- };
2102
- const gridTemplateValue = (property, value, index) => {
2103
- if (/^(?:none|initial|unset)$/iu.test(value)) return [
2104
- "none",
2105
- "none",
2106
- "none",
2107
- "auto",
2108
- "auto",
2109
- "row"
2110
- ][index] ?? value;
2111
- const parts = canvasCssTokens(value, "/");
2112
- const row = parts[0] ?? value;
2113
- const column = parts[1];
2114
- if (row === "" || column === "" || parts.length > 2) return value;
2115
- const hasAutoRows = canvasCssTokens(row).some((token) => token.toLowerCase() === "auto-flow");
2116
- const hasAutoColumns = column !== void 0 && canvasCssTokens(column).some((token) => token.toLowerCase() === "auto-flow");
2117
- if (property === "grid" && column !== void 0 && hasAutoRows !== hasAutoColumns) return implicitGridValues(row, column, hasAutoRows)[index] ?? value;
2118
- if (hasAutoRows || hasAutoColumns) return value;
2119
- const hasAreas = /["']/u.test(row);
2120
- if (column === void 0 && !hasAreas) return value;
2121
- return [
2122
- hasAreas ? value : row,
2123
- column ?? "none",
2124
- hasAreas ? row : "none",
2125
- "auto",
2126
- "auto",
2127
- "row"
2128
- ][index] ?? value;
2129
- };
2130
- const flexValues = (tokens) => {
2131
- const numbers = [];
2132
- let basis = "0%";
2133
- for (const token of tokens) if (/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(token) && numbers.length < 2) numbers.push(token);
2134
- else basis = token;
2135
- return [
2136
- numbers[0] ?? "1",
2137
- numbers[1] ?? "1",
2138
- basis
2139
- ];
2140
- };
2141
- const canvasCssShorthandValue = (property, value, index) => {
2142
- if (/(?:var|env)\(|^(?:inherit|revert(?:-layer)?)$/iu.test(value)) return value;
2143
- if (/^grid-(?:area|row|column)$/u.test(property)) return gridPlacementValue(property, value, index);
2144
- if (property === "grid-template" || property === "grid") return gridTemplateValue(property, value, index);
2145
- const tokens = canvasCssTokens(value);
2146
- if (property === "text-wrap") return index === 0 ? tokens.find((token) => /^(?:wrap|nowrap)$/u.test(token)) ?? "wrap" : tokens.find((token) => /^(?:auto|balance|pretty|stable)$/u.test(token)) ?? "auto";
2147
- if (property === "flex-flow") return index === 0 ? tokens.find((token) => /^(?:row|column)(?:-reverse)?$/u.test(token)) ?? "row" : tokens.find((token) => /^(?:nowrap|wrap|wrap-reverse)$/u.test(token)) ?? "nowrap";
2148
- if (property === "flex") {
2149
- if (value === "none") return [
2150
- "0",
2151
- "0",
2152
- "auto"
2153
- ][index] ?? value;
2154
- if (value === "initial") return [
2155
- "0",
2156
- "1",
2157
- "auto"
2158
- ][index] ?? value;
2159
- return flexValues(tokens)[index] ?? value;
2160
- }
2161
- return tokens[index] ?? (index === LEFT_SIDE_INDEX ? tokens[1] : void 0) ?? tokens[0] ?? value;
2162
- };
2163
-
2164
- //#endregion
2165
- //#region ../../packages/contract/src/canvas/canvas-authored-css.lib.ts
2166
- const canvasAdditionalStyleDeclarations = (node) => {
2167
- if (node.additionalStyles === void 0) return {};
2168
- return Object.fromEntries(node.additionalStyles.declarations.filter((declaration) => declaration.enabled).map((declaration) => [declaration.property, declaration.value]));
2169
- };
2170
- /** Additional-style controls exclusively own every property they expose, including when off. */
2171
- const canvasAuthoredStyleDeclarations = (node) => {
2172
- const controlledProperties = new Set(node.additionalStyles?.declarations.map((declaration) => declaration.property.toLowerCase()));
2173
- return {
2174
- ...Object.fromEntries(Object.entries(node.styles).filter(([property]) => !controlledProperties.has(property.toLowerCase()))),
2175
- ...canvasAdditionalStyleDeclarations(node)
2176
- };
2177
- };
2178
- const hasCanvasCssPriority = (value) => /!important\s*$/iu.test(String(value));
2179
- const cssValue = (value, shouldPreserveCase) => {
2180
- const source = String(value).replace(/\s*!important\s*$/iu, "").trim();
2181
- return shouldPreserveCase || source.includes("(") ? source : source.toLowerCase();
2182
- };
2183
- const authoredLayoutValue = (node, property) => {
2184
- let result = null;
2185
- let isImportant = false;
2186
- const declarations = Object.entries(canvasAuthoredStyleDeclarations(node));
2187
- for (const [key, raw] of declarations) {
2188
- const scope = canvasCssPropertyScope(key);
2189
- const index = scope.indexOf(property);
2190
- if (index === -1) continue;
2191
- const isPriority = hasCanvasCssPriority(raw);
2192
- if (isImportant && !isPriority) continue;
2193
- const value = cssValue(raw, /^grid(?:-|$)/iu.test(key));
2194
- result = scope.length === 1 ? value : canvasCssShorthandValue(key.toLowerCase(), value, index);
2195
- isImportant = isPriority;
2196
- }
2197
- return result ?? void 0;
2198
- };
2199
- /**
2200
- * Edits replace a node's style objects rather than changing them, so their identity keys the values
2201
- * already read. Rendering a large document reads each property of each node many times.
2202
- */
2203
- const readAuthoredValues = /* @__PURE__ */ new WeakMap();
2204
- /** Read supported authored longhands without measuring or rewriting unresolved CSS expressions. */
2205
- const canvasAuthoredLayoutValueOf = (node, property) => {
2206
- const known = readAuthoredValues.get(node.styles);
2207
- const read = known !== void 0 && known.additionalStyles === node.additionalStyles ? known : {
2208
- additionalStyles: node.additionalStyles,
2209
- values: /* @__PURE__ */ new Map()
2210
- };
2211
- if (read !== known) readAuthoredValues.set(node.styles, read);
2212
- if (read.values.has(property)) return read.values.get(property);
2213
- const value = authoredLayoutValue(node, property);
2214
- read.values.set(property, value);
2215
- return value;
2216
- };
2217
- const canvasCssPixelValue = (value) => {
2218
- if (value === void 0) return;
2219
- return /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:px)?$/u.test(value) ? Number(value.replace("px", "")) : void 0;
2220
- };
2221
- /** Named controls override only their own longhand, even beside an important shorthand. */
2222
- const canvasLayoutPriorityDeclarations = (node, declarations) => {
2223
- const important = new Set(Object.entries(canvasAuthoredStyleDeclarations(node)).filter(([, value]) => hasCanvasCssPriority(value)).flatMap(([property]) => canvasCssPropertyScope(property)));
2224
- return Object.fromEntries(Object.entries(declarations).map(([property, value]) => [property, canvasCssPropertyScope(property).some((owned) => important.has(owned)) && !hasCanvasCssPriority(value) ? `${canvasCssValue(property, value)} !important` : value]));
2225
- };
2226
- const canvasWritingModeOf = (node, document) => {
2227
- const visited = /* @__PURE__ */ new Set();
2228
- let current = node;
2229
- while (current !== void 0 && !visited.has(current.id)) {
2230
- visited.add(current.id);
2231
- const value = canvasAuthoredLayoutValueOf(current, "writing-mode");
2232
- if (value !== void 0 && value !== "inherit" && value !== "unset") return value;
2233
- if (document === void 0) break;
2234
- const parentId = document.relationships[current.id]?.parentId;
2235
- if (parentId === void 0) break;
2236
- current = document.nodes[parentId];
2237
- }
2238
- return "horizontal-tb";
2239
- };
2240
- const canvasAxisStyleProperties = (node, axis, document) => {
2241
- const isVerticalWriting = /^(?:vertical|sideways)-/u.test(canvasWritingModeOf(node, document));
2242
- return [axis === "horizontal" ? "width" : "height", axis === "vertical" === isVerticalWriting ? "inline-size" : "block-size"];
2243
- };
2244
- const canvasLayoutPositionOf = (node) => {
2245
- const position = canvasAuthoredLayoutValueOf(node, "position");
2246
- return node.layout?.position ?? (position === "absolute" || position === "fixed" || position === void 0 && node.box !== void 0 ? "absolute" : "flow");
2247
- };
2248
- /** Authored display wins over legacy presets; Grid has no Flex main axis. */
2249
- const canvasLayoutFlowOf = (node) => {
2250
- if (node === void 0) return "freeform";
2251
- const display = canvasAuthoredLayoutValueOf(node, "display");
2252
- if (display !== void 0) {
2253
- if (/^(?:(?:inline|block)\s+|inline-)?grid$/u.test(display)) return "grid";
2254
- if (/^(?:(?:inline|block)\s+|inline-)?flex$/u.test(display)) return "flex";
2255
- return "freeform";
2256
- }
2257
- const container = node.layout?.container;
2258
- if (container === void 0) return "freeform";
2259
- return container.gridColumns !== void 0 || container.gridAutoRepeat !== void 0 ? "grid" : "flex";
2260
- };
2261
- /** Read a Flex main axis in its inherited writing mode without persisting a preset. */
2262
- const canvasLayoutMainAxisOf = (node, document) => {
2263
- if (node === void 0) return void 0;
2264
- if (canvasLayoutFlowOf(node) !== "flex") return void 0;
2265
- const container = node.layout?.container;
2266
- const css = (property) => canvasAuthoredLayoutValueOf(node, property);
2267
- const direction = container?.direction ?? css("flex-direction") ?? "row";
2268
- if (!/^(?:row|column)(?:-reverse)?$/u.test(direction)) return void 0;
2269
- const isVerticalWriting = /^(?:vertical|sideways)-/u.test(canvasWritingModeOf(node, document));
2270
- return direction.startsWith("column") === isVerticalWriting ? "horizontal" : "vertical";
1980
+ }));
1981
+ /** A capture that lands as a new editable frame on a page, with no screen layer. */
1982
+ const editableFrameCaptureSchema = z.object({
1983
+ screenId: z.string().min(1),
1984
+ pageId: z.string().min(1),
1985
+ pictureNodeId: z.string().min(1).optional().describe("The capture's picture, which the frame replaces in place and whose id it keeps. Refused as capture-already-landed once the picture is a frame.")
1986
+ });
1987
+ const editableFrameInputBase = {
1988
+ canvasId: z.uuid(),
1989
+ documentFormatVersion: canvasDocumentFormatSchema,
1990
+ mutationId: z.uuid(),
1991
+ baseVersion: z.number().int().positive(),
1992
+ draft: canvasSubtreeDraftSchema
2271
1993
  };
1994
+ /** An editable frame comes from exactly one screen layer or one capture, never both. */
1995
+ const createEditableFrameInputSchema = z.union([z.strictObject({
1996
+ ...editableFrameInputBase,
1997
+ screenNodeId: z.string().min(1).describe("The screen layer to convert beside itself."),
1998
+ position: z.strictObject({
1999
+ x: z.number(),
2000
+ y: z.number()
2001
+ }).optional().describe("Where the editor measured room for the frame below its screen.")
2002
+ }), z.strictObject({
2003
+ ...editableFrameInputBase,
2004
+ capture: editableFrameCaptureSchema.describe("The stored page a new capture lands from, and the page its frame goes on.")
2005
+ })]).superRefine((input, context) => {
2006
+ refuseUnsafeWriterFormat(input.documentFormatVersion, "whole", context);
2007
+ });
2008
+ const createEditableFrameResultSchema = z.object({
2009
+ canvasId: z.uuid(),
2010
+ mutationId: z.uuid(),
2011
+ previousVersion: z.number().int().positive(),
2012
+ version: z.number().int().positive(),
2013
+ rootNodeId: z.string().min(1),
2014
+ idMap: z.record(temporaryIdSchema, z.string().min(1)),
2015
+ insertedNodeIds: z.array(z.string().min(1)),
2016
+ removedNodeIds: z.array(z.string().min(1)),
2017
+ boxes: z.record(z.string().min(1), canvasSceneBoxSchema),
2018
+ affectedBounds: canvasSceneBoxSchema,
2019
+ /** Where requested placement saved the root; absent when the request asked for none. */
2020
+ placement: canvasPlacementResultSchema.optional()
2021
+ });
2272
2022
 
2273
2023
  //#endregion
2274
- //#region ../../packages/contract/src/canvas/canvas-box-source.lib.ts
2275
- const INSETS = [
2276
- "left",
2277
- "right",
2278
- "top",
2279
- "bottom",
2280
- "inset",
2281
- "inset-inline",
2282
- "inset-inline-start",
2283
- "inset-inline-end",
2284
- "inset-block",
2285
- "inset-block-start",
2286
- "inset-block-end"
2024
+ //#region ../../packages/contract/src/canvas/canvas-render.consts.ts
2025
+ const RENDER_PHASES = [
2026
+ "queued",
2027
+ "claimed",
2028
+ "grant",
2029
+ "navigate",
2030
+ "document",
2031
+ "sources",
2032
+ "fonts",
2033
+ "layout",
2034
+ "target",
2035
+ "capture",
2036
+ "serialize",
2037
+ "compile",
2038
+ "commit",
2039
+ "upload",
2040
+ "complete"
2287
2041
  ];
2288
- const TRANSFORMS = [
2289
- "transform",
2290
- "translate",
2291
- "rotate",
2292
- "scale"
2042
+ const RENDER_STATES = [
2043
+ "queued",
2044
+ "running",
2045
+ "succeeded",
2046
+ "failed",
2047
+ "cancelled",
2048
+ "expired"
2049
+ ];
2050
+ const RENDER_FAILURE_REASONS = [
2051
+ "VERSION_CHANGED",
2052
+ "TARGET_NOT_FOUND",
2053
+ "TARGET_INVALID",
2054
+ "OUTPUT_TOO_LARGE",
2055
+ "READINESS_TIMEOUT",
2056
+ "SOURCE_FAILED",
2057
+ "BROWSER_CRASH",
2058
+ "CAPTURE_FAILED",
2059
+ "CONVERSION_FAILED",
2060
+ "PREPARATION_FAILED",
2061
+ "UPLOAD_FAILED",
2062
+ "WORKER_UNAVAILABLE",
2063
+ "CANCELLED",
2064
+ "EXPIRED",
2065
+ "INTERNAL"
2066
+ ];
2067
+ const RENDER_WARNING_CODES = [
2068
+ "ASSET_UNAVAILABLE",
2069
+ "FONT_FALLBACK",
2070
+ "LOCAL_FONT_FALLBACK",
2071
+ "SOURCE_FALLBACK",
2072
+ "SCALE_REDUCED",
2073
+ "LAYOUT_FALLBACK",
2074
+ "DRAWN_APPROXIMATELY"
2293
2075
  ];
2294
- const GROUP_TRANSFORM = "--enhance-group-affine-residual";
2295
- const CANVAS_RECORDED_BOX_NOTE = "A box whose boxSource is \"recorded\" is a size kept from when the layer was made: the browser lays that layer out, so the box is not where it is drawn. `enhance canvas render` shows what is on screen.";
2296
- const isSet = (value) => value !== void 0 && value !== "" && value !== "none";
2297
- const hasOwnTransform = (node, authored) => TRANSFORMS.some((property) => isSet(authored[property])) || (node.layout?.rotation ?? 0) !== 0 || node.layout?.flipHorizontal === true || node.layout?.flipVertical === true || Object.keys(authored).some((property) => property.toLowerCase() === GROUP_TRANSFORM);
2298
- /**
2299
- * The canvas draws a layer at its box only when it positions the layer absolutely and the layer
2300
- * names no inset of its own; an inset on either axis takes that axis from the box. This is the
2301
- * test the style projection makes before it writes `left` and `top` from the box, and a layer
2302
- * with no box has no source.
2303
- */
2304
- const canvasBoxSourceOf = (node) => {
2305
- if (node.box === void 0) return void 0;
2306
- const authored = canvasAuthoredStyleDeclarations(node);
2307
- if (!(canvasLayoutPositionOf(node) === "absolute" && INSETS.every((property) => authored[property] === void 0))) return "recorded";
2308
- return hasOwnTransform(node, authored) ? "placed-before-transform" : "placed";
2309
- };
2310
- /** One line for a whole read, however many of its boxes are recorded. */
2311
- const canvasRecordedBoxNoteFor = (boxes) => boxes.some((box) => box.boxSource === "recorded") ? { boxNote: CANVAS_RECORDED_BOX_NOTE } : {};
2312
2076
 
2313
2077
  //#endregion
2314
- //#region ../../packages/contract/src/canvas/canvas-export-settings.schema.ts
2315
- const format = z.enum(["png", "jpeg"]);
2316
- const scale = z.number().positive();
2317
- const canvasExportSettingsSchema = z.strictObject({
2318
- format: format.optional(),
2319
- scale: scale.optional()
2320
- });
2321
- const canvasExportSettingsPatchSchema = z.strictObject({
2322
- format: format.nullable().optional(),
2323
- scale: scale.nullable().optional()
2324
- }).refine((patch) => patch.format !== void 0 || patch.scale !== void 0);
2325
-
2326
- //#endregion
2327
- //#region ../../packages/contract/src/canvas/canvas-geometry.schema.ts
2328
- const coordinate = z.number();
2329
- const dimension$1 = coordinate.nonnegative();
2330
- const MAX_ID_LENGTH = 200;
2331
- const MIN_POLYGON_POINTS = 3;
2332
- const identity$1 = z.string().min(1).max(MAX_ID_LENGTH);
2333
- const path = z.string().regex(/^[MmLlHhVvCcSsQqTtAaZzEe\d\s.,+-]*$/u);
2334
- const canvasGeometryBoundsSchema = z.strictObject({
2335
- x: coordinate,
2336
- y: coordinate,
2337
- width: dimension$1,
2338
- height: dimension$1
2078
+ //#region ../../packages/contract/src/canvas/canvas-render.schema.ts
2079
+ const MAX_RENDER_MESSAGE_LENGTH = 500;
2080
+ const canvasRenderPixelLimitSchema = z.number().int().positive();
2081
+ const canvasWorldBoundsSchema = z.object({
2082
+ x: z.number(),
2083
+ y: z.number(),
2084
+ width: z.number().positive(),
2085
+ height: z.number().positive()
2339
2086
  });
2340
- const canvasPathGeometrySchema = z.strictObject({
2341
- kind: z.literal("path"),
2342
- path: path.min(1),
2343
- fillRule: z.enum(["nonzero", "evenodd"]),
2344
- viewBox: canvasGeometryBoundsSchema.extend({
2345
- width: dimension$1.positive(),
2346
- height: dimension$1.positive()
2087
+ const canvasRenderTargetSchema = z.discriminatedUnion("kind", [
2088
+ z.object({ kind: z.literal("content") }),
2089
+ z.object({
2090
+ kind: z.literal("page"),
2091
+ pageId: z.string().min(1)
2092
+ }),
2093
+ z.object({
2094
+ kind: z.literal("node"),
2095
+ nodeId: z.string().min(1)
2096
+ }),
2097
+ z.object({
2098
+ kind: z.literal("bounds"),
2099
+ bounds: canvasWorldBoundsSchema
2347
2100
  })
2348
- });
2349
- const canvasPolygonGeometrySchema = z.strictObject({
2350
- kind: z.literal("polygon"),
2351
- count: z.number().int().min(MIN_POLYGON_POINTS),
2352
- innerRatio: z.number().min(0).max(1).optional(),
2353
- cornerRadius: dimension$1,
2354
- cornerSmoothing: z.number().min(0).max(1)
2355
- });
2356
- const canvasBooleanOperationSchema = z.enum([
2357
- "union",
2358
- "subtract",
2359
- "intersect",
2360
- "exclude"
2361
2101
  ]);
2362
- const canvasBooleanGeometrySchema = z.strictObject({
2363
- kind: z.literal("boolean"),
2364
- operation: canvasBooleanOperationSchema,
2365
- operandIds: z.array(identity$1).min(1).refine((ids) => new Set(ids).size === ids.length),
2366
- result: z.strictObject({
2367
- path,
2368
- fillRule: z.literal("nonzero"),
2369
- isEmpty: z.boolean(),
2370
- bounds: canvasGeometryBoundsSchema,
2371
- inputKey: z.string().regex(/^[a-f0-9]{16}$/u)
2372
- }).refine((result) => result.isEmpty === (result.path === ""))
2102
+ const canvasRenderSourceStateSchema = z.object({
2103
+ kind: z.literal("recording"),
2104
+ recordingId: z.uuid(),
2105
+ atMs: z.number().int().nonnegative()
2373
2106
  });
2374
- const canvasGeometrySchema = z.discriminatedUnion("kind", [
2375
- canvasPathGeometrySchema,
2376
- canvasPolygonGeometrySchema,
2377
- z.strictObject({
2378
- kind: z.literal("mask"),
2379
- maskId: identity$1,
2380
- /** Absent paints as alpha. An outline mask clips to the source's shape only. */
2381
- mode: z.enum([
2382
- "alpha",
2383
- "luminance",
2384
- "outline"
2385
- ]).optional()
2386
- }),
2387
- canvasBooleanGeometrySchema
2388
- ]);
2389
-
2390
- //#endregion
2391
- //#region ../../packages/contract/src/canvas/canvas-scene.schema.ts
2392
- const CANVAS_COMPOSITING_RETIRED = "Update Enhance: compositing is no longer supported. Use the isolation style or a mask group.";
2393
- const CANVAS_FORMAT_UPDATE_REQUIRED = "This change needs a newer version of Enhance. Refresh the editor, or update the Enhance plugin or command-line tool, then try again.";
2394
- const CANVAS_FORMAT_SERVER_UPDATING = "Enhance is being updated. Try again in a minute.";
2395
- /** Marks an issue whose message was written for whoever sent the request, so the API keeps it. */
2396
- const FOR_CALLER = { forCaller: true };
2397
- /**
2398
- * The format a writer was built for, as a plain whole number so tool schemas can describe it. Which
2399
- * writes that format may make is `refuseUnsafeWriterFormat`'s call.
2400
- */
2401
- const canvasDocumentFormatSchema = z.number({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).int({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).positive({ error: CANVAS_FORMAT_UPDATE_REQUIRED }).meta({
2402
- description: `The document format this client writes. The current format is ${String(15)}.`,
2403
- examples: [15]
2107
+ const canvasRenderSourceStateEvidenceSchema = z.object({
2108
+ kind: z.literal("recording"),
2109
+ recordingId: z.uuid(),
2110
+ requestedAtMs: z.number().int().nonnegative(),
2111
+ settledAtMs: z.number().int().nonnegative()
2404
2112
  });
2405
- /**
2406
- * Refuses a write its client's format could get wrong. A client whose format differs from the
2407
- * current one only in its number may still name changes, but a whole value it sends may lack
2408
- * fields added since, so that needs the current format.
2409
- */
2410
- const refuseUnsafeWriterFormat = (documentFormatVersion, writes, context) => {
2411
- const writer = canvasWriterFormat(documentFormatVersion);
2412
- if (writer === "current" || writer === "number-only" && writes === "names") return;
2413
- context.addIssue({
2414
- code: "custom",
2415
- path: ["documentFormatVersion"],
2416
- message: writer === "ahead" ? CANVAS_FORMAT_SERVER_UPDATING : CANVAS_FORMAT_UPDATE_REQUIRED,
2417
- params: FOR_CALLER,
2418
- input: documentFormatVersion
2419
- });
2420
- };
2421
- const canvasPreservedFontAppearanceSchema = z.object({
2422
- signature: z.string().regex(/^[a-f0-9]{16}$/u),
2423
- /** The captured picture of the page's text, inline as written or as its canvas image store path. */
2424
- image: z.string().refine((image) => image.startsWith("data:image/jpeg;base64,") || canvasImageAssetIdentityFromPath(image) !== null),
2425
- families: z.array(z.string().min(1)).min(1)
2113
+ const canvasRenderSnapshotResultSchema = z.object({
2114
+ recordingId: z.uuid(),
2115
+ atMs: z.number().int().nonnegative(),
2116
+ screenId: z.uuid(),
2117
+ /** Null when the snapshot asked for a place only, so no screen layer was added. */
2118
+ screenNodeId: z.string().min(1).nullable(),
2119
+ /** The page the place is on. */
2120
+ pageId: z.string().min(1).optional(),
2121
+ viewport: z.object({
2122
+ width: z.number().int().positive(),
2123
+ height: z.number().int().positive()
2124
+ }),
2125
+ box: canvasWorldBoundsSchema,
2126
+ version: z.number().int().positive(),
2127
+ alreadyPresent: z.boolean()
2426
2128
  });
2427
- const canvasSceneBoxSchema = z.object({
2428
- x: z.number(),
2429
- y: z.number(),
2430
- width: z.number().nonnegative(),
2431
- height: z.number().nonnegative()
2129
+ const createCanvasRenderInputSchema = z.object({
2130
+ canvasId: z.uuid(),
2131
+ expectedVersion: z.number().int().positive().optional(),
2132
+ scope: z.strictObject({
2133
+ pageId: z.string().min(1).optional(),
2134
+ nodeIds: z.array(z.string().min(1))
2135
+ }).optional(),
2136
+ target: canvasRenderTargetSchema.default({ kind: "content" }),
2137
+ sourceState: canvasRenderSourceStateSchema.optional(),
2138
+ scale: z.number().positive().default(1),
2139
+ maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
2140
+ format: z.literal("png").default("png")
2141
+ }).refine((input) => input.sourceState === void 0 || input.target.kind === "node", {
2142
+ message: "a source state requires a node render target",
2143
+ path: ["sourceState"]
2432
2144
  });
2433
- const canvasConstraintSchema = z.enum([
2434
- "start",
2435
- "center",
2436
- "end",
2437
- "stretch",
2438
- "scale"
2439
- ]);
2440
- const canvasNodeConstraintsSchema = z.object({
2441
- x: canvasConstraintSchema,
2442
- y: canvasConstraintSchema
2145
+ const canvasRenderPhaseSchema = z.enum(RENDER_PHASES);
2146
+ const canvasRenderStateSchema = z.enum(RENDER_STATES);
2147
+ const canvasRenderFailureReasonSchema = z.enum(RENDER_FAILURE_REASONS);
2148
+ const canvasRenderWarningCodeSchema = z.enum(RENDER_WARNING_CODES);
2149
+ const canvasRenderWarningSchema = z.object({
2150
+ code: canvasRenderWarningCodeSchema,
2151
+ message: z.string().min(1).max(MAX_RENDER_MESSAGE_LENGTH),
2152
+ sourceId: z.string().min(1).nullable()
2443
2153
  });
2444
- const canvasNodeLabelOriginSchema = z.enum([
2445
- "source",
2446
- "generated",
2447
- "content",
2448
- "user"
2449
- ]);
2450
- const canvasSceneNodeSchema = z.looseObject({
2451
- id: z.string().min(1),
2452
- label: z.string(),
2453
- component: z.string().min(1),
2454
- labelOrigin: canvasNodeLabelOriginSchema.optional(),
2455
- visible: z.boolean().optional(),
2456
- locked: z.boolean().optional(),
2457
- constraints: canvasNodeConstraintsSchema.optional(),
2458
- styles: z.record(z.string(), z.union([z.string(), z.number()])),
2459
- layout: canvasNodeLayoutSchema.optional(),
2460
- responsive: z.never().optional(),
2461
- appearance: canvasAppearanceValuesSchema.optional(),
2462
- exportSettings: canvasExportSettingsSchema.optional(),
2463
- typography: canvasAuthoredTypographySchema.optional(),
2464
- additionalStyles: canvasAdditionalStylesSchema.optional(),
2465
- geometry: canvasGeometrySchema.optional(),
2466
- compositing: z.never({ error: CANVAS_COMPOSITING_RETIRED }).optional(),
2467
- props: z.record(z.string(), z.unknown()).optional(),
2468
- box: canvasSceneBoxSchema.optional()
2154
+ const canvasRenderFailureSchema = z.object({
2155
+ reason: canvasRenderFailureReasonSchema,
2156
+ phase: canvasRenderPhaseSchema,
2157
+ message: z.string().min(1).max(MAX_RENDER_MESSAGE_LENGTH),
2158
+ retryable: z.boolean(),
2159
+ sourceId: z.string().min(1).nullable()
2469
2160
  });
2470
- const canvasSceneRelationshipSchema = z.object({
2471
- parentId: z.string().min(1),
2472
- sortKey: z.string().min(1)
2161
+ const canvasRenderTimingSchema = z.object({
2162
+ phase: canvasRenderPhaseSchema,
2163
+ durationMs: z.number().int().min(0)
2473
2164
  });
2474
- const canvasSceneDocumentSchema = z.object({
2475
- version: z.literal(15),
2476
- nodes: z.record(z.string(), canvasSceneNodeSchema),
2477
- relationships: z.record(z.string(), canvasSceneRelationshipSchema),
2478
- tombstones: z.record(z.string(), z.literal(true)).default({})
2165
+ const canvasRenderResultSchema = z.object({
2166
+ canvasId: z.uuid(),
2167
+ requestedVersion: z.number().int().positive(),
2168
+ loadedVersion: z.number().int().positive(),
2169
+ target: canvasRenderTargetSchema,
2170
+ sourceState: canvasRenderSourceStateEvidenceSchema.optional(),
2171
+ snapshot: canvasRenderSnapshotResultSchema.optional(),
2172
+ bounds: canvasWorldBoundsSchema,
2173
+ width: z.number().int().positive(),
2174
+ height: z.number().int().positive(),
2175
+ scale: z.number().positive(),
2176
+ contentType: z.literal("image/png"),
2177
+ bytes: z.number().int().positive(),
2178
+ warnings: z.array(canvasRenderWarningSchema),
2179
+ timings: z.array(canvasRenderTimingSchema),
2180
+ expiresAt: z.iso.datetime()
2479
2181
  });
2480
- const legacyRecordSchema = z.record(z.string(), z.unknown());
2481
- /** Known old scenes are adapted in memory; only an explicit mutation persists the new format. */
2482
- const canvasReadableSceneDocumentSchema = z.preprocess((value) => {
2483
- const blob = legacyRecordSchema.safeParse(value).data;
2484
- if (blob === void 0) return value;
2485
- if (Object.keys(blob).length === 0) return emptyCanvasSceneDocument();
2486
- return adaptCanvasDocumentFormat(blob);
2487
- }, canvasSceneDocumentSchema);
2488
- /** A document's version, or the read result that refuses it before anything else is read. */
2489
- const refusedVersionOf = (blob) => {
2490
- const version = blob["version"];
2491
- if (version !== void 0 && (typeof version !== "number" || !Number.isSafeInteger(version) || version < 1)) return { status: "invalid" };
2492
- if (version !== void 0 && version > 15) return {
2493
- status: "unsupported",
2494
- formatVersion: version
2495
- };
2496
- return null;
2497
- };
2498
- const readCanvasSceneDocument = (blob) => {
2499
- if (blob === void 0) return { status: "missing" };
2500
- const refused = refusedVersionOf(blob);
2501
- if (refused !== null) return refused;
2502
- const parsed = canvasReadableSceneDocumentSchema.safeParse(blob);
2503
- return parsed.success ? {
2504
- status: "current",
2505
- document: parsed.data
2506
- } : { status: "invalid" };
2507
- };
2508
- const emptyCanvasSceneDocument = () => ({
2509
- version: 15,
2510
- nodes: { root: {
2511
- id: "root",
2512
- label: "Canvas",
2513
- component: "root",
2514
- labelOrigin: "generated",
2515
- visible: true,
2516
- locked: false,
2517
- styles: {}
2518
- } },
2519
- relationships: {},
2520
- tombstones: {}
2521
- });
2522
- const shellSchema = canvasSceneDocumentSchema.extend({
2523
- nodes: z.record(z.string(), z.unknown()),
2524
- relationships: z.record(z.string(), z.unknown())
2525
- });
2526
-
2527
- //#endregion
2528
- //#region ../../packages/contract/src/canvas/canvas-conversion-draft.schema.ts
2529
- const temporaryIdSchema = z.string().min(1);
2530
- const canvasConversionIssueSchema = z.object({
2531
- code: z.enum([
2532
- "asset-unavailable",
2533
- "content-omitted",
2534
- "cross-origin-frame",
2535
- "nodes-truncated",
2536
- "responsive-behavior-not-editable",
2537
- "style-degraded",
2538
- "unsupported-surface",
2539
- "vertical-writing-unsupported"
2182
+ const canvasRenderJobBaseSchema = z.object({
2183
+ id: z.uuid(),
2184
+ canvasId: z.uuid(),
2185
+ purpose: z.enum([
2186
+ "inspection",
2187
+ "snapshot",
2188
+ "thumbnail",
2189
+ "export"
2540
2190
  ]),
2541
- message: z.string().min(1),
2542
- temporaryId: temporaryIdSchema.optional()
2191
+ phase: canvasRenderPhaseSchema,
2192
+ requestedVersion: z.number().int().positive(),
2193
+ target: canvasRenderTargetSchema,
2194
+ sourceState: canvasRenderSourceStateSchema.optional(),
2195
+ scale: z.number().positive(),
2196
+ maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
2197
+ format: z.literal("png"),
2198
+ attempt: z.number().int().min(0),
2199
+ lastFailure: canvasRenderFailureSchema.optional(),
2200
+ createdAt: z.iso.datetime(),
2201
+ updatedAt: z.iso.datetime()
2543
2202
  });
2544
- /** Source features that CSS cannot draw; a conversion writes the closest CSS and counts each. */
2545
- const CANVAS_UNSUPPORTED_FEATURES = [
2546
- "text-stroke-inside",
2547
- "text-stroke-outside-translucent",
2548
- "text-stroke-paints",
2549
- "text-inner-shadow",
2550
- "text-shadow-spread",
2551
- "text-shadow-blend",
2552
- "text-background-blur",
2553
- "progressive-layer-blur",
2554
- "progressive-background-blur",
2555
- "blend-plus-darker",
2556
- "blend-linear-burn",
2557
- "image-exposure",
2558
- "image-contrast",
2559
- "image-saturation",
2560
- "image-temperature",
2561
- "image-tint",
2562
- "image-highlights",
2563
- "image-shadows",
2564
- "effect-noise",
2565
- "effect-texture",
2566
- "effect-glass",
2567
- "mask-source"
2568
- ];
2569
- const canvasUnsupportedFeatureSchema = z.enum(CANVAS_UNSUPPORTED_FEATURES);
2570
- const canvasConversionReportSchema = z.object({
2571
- nodeCount: z.number().int().positive(),
2572
- unsupportedFeatures: z.array(z.object({
2573
- feature: canvasUnsupportedFeatureSchema,
2574
- count: z.number().int().positive()
2575
- })).optional(),
2576
- sourceNodeCount: z.number().int().positive().optional(),
2577
- collapsedNodeCount: z.number().int().nonnegative().optional(),
2578
- collapsedWrapperNodeCount: z.number().int().nonnegative().optional(),
2579
- collapsedNeutralWrapperNodeCount: z.number().int().nonnegative().optional(),
2580
- collapsedTransferredWrapperNodeCount: z.number().int().nonnegative().optional(),
2581
- layoutContainerCount: z.number().int().nonnegative().optional(),
2582
- removedLeafNodeCount: z.number().int().nonnegative().optional(),
2583
- retainedSemanticOwnerNodeCount: z.number().int().nonnegative().optional(),
2584
- truncatedNodeCount: z.number().int().nonnegative().optional(),
2585
- addedLayoutNodeCount: z.number().int().nonnegative().optional(),
2586
- issues: z.array(canvasConversionIssueSchema)
2203
+ const canvasRenderJobSchema = z.discriminatedUnion("state", [
2204
+ canvasRenderJobBaseSchema.extend({
2205
+ state: z.literal("queued"),
2206
+ result: z.null(),
2207
+ failure: z.null()
2208
+ }),
2209
+ canvasRenderJobBaseSchema.extend({
2210
+ state: z.literal("running"),
2211
+ result: z.null(),
2212
+ failure: z.null()
2213
+ }),
2214
+ canvasRenderJobBaseSchema.extend({
2215
+ state: z.literal("succeeded"),
2216
+ phase: z.literal("complete"),
2217
+ result: canvasRenderResultSchema,
2218
+ failure: z.null()
2219
+ }),
2220
+ canvasRenderJobBaseSchema.extend({
2221
+ state: z.literal("failed"),
2222
+ result: z.null(),
2223
+ failure: canvasRenderFailureSchema
2224
+ }),
2225
+ canvasRenderJobBaseSchema.extend({
2226
+ state: z.literal("cancelled"),
2227
+ result: z.null(),
2228
+ failure: canvasRenderFailureSchema.extend({ reason: z.literal("CANCELLED") })
2229
+ }),
2230
+ canvasRenderJobBaseSchema.extend({
2231
+ state: z.literal("expired"),
2232
+ result: z.null(),
2233
+ failure: canvasRenderFailureSchema.extend({ reason: z.literal("EXPIRED") })
2234
+ })
2235
+ ]);
2236
+ const createCanvasRenderOutputSchema = z.object({
2237
+ job: canvasRenderJobSchema,
2238
+ alreadyExists: z.boolean()
2587
2239
  });
2588
- const canvasSubtreeDraftNodeSchema = canvasSceneNodeSchema.omit({ id: true }).extend({ temporaryId: temporaryIdSchema });
2589
- const canvasSubtreeDraftRelationshipSchema = z.object({
2590
- temporaryId: temporaryIdSchema,
2591
- parentTemporaryId: temporaryIdSchema,
2592
- sortKey: z.string().min(1)
2240
+ const getCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2241
+ /** The longest an export read waits on the server for the job to settle. */
2242
+ const CANVAS_EXPORT_LONGEST_WAIT_MS = 1e4;
2243
+ const getCanvasExportInputSchema = getCanvasRenderInputSchema.extend({ waitMs: z.number().int().min(0).max(CANVAS_EXPORT_LONGEST_WAIT_MS).optional() });
2244
+ const getCanvasRenderOutputSchema = z.object({ job: canvasRenderJobSchema });
2245
+ const cancelCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2246
+ const cancelCanvasRenderOutputSchema = z.object({ job: canvasRenderJobSchema });
2247
+ const canvasRenderSourceSchema = z.discriminatedUnion("status", [z.object({
2248
+ status: z.literal("available"),
2249
+ version: z.number().int().positive(),
2250
+ format: z.literal("enhance-scene-json"),
2251
+ code: z.string(),
2252
+ prototypes: z.array(z.object({
2253
+ nodeId: z.string(),
2254
+ prototypeId: z.uuid(),
2255
+ deploymentId: z.uuid(),
2256
+ capability: z.literal("canvas.read"),
2257
+ canvasPath: z.string(),
2258
+ input: z.object({
2259
+ canvasRef: z.uuid(),
2260
+ view: z.literal("source"),
2261
+ nodeId: z.string()
2262
+ }),
2263
+ guidance: z.string()
2264
+ })),
2265
+ guidance: z.string()
2266
+ }), z.object({
2267
+ status: z.literal("unavailable"),
2268
+ guidance: z.string()
2269
+ })]);
2270
+ /** A person's image export of one layer at the saved revision, drawn by the render worker. */
2271
+ const createCanvasExportInputSchema = z.object({
2272
+ canvasId: z.uuid(),
2273
+ nodeId: z.string().min(1),
2274
+ expectedVersion: z.number().int().positive(),
2275
+ scale: z.number().positive()
2593
2276
  });
2594
- /**
2595
- * A report that cannot be read says so, rather than reading as "nothing left out". The kind is an
2596
- * existing one, because installed clients check kinds strictly and would refuse the whole answer.
2597
- */
2598
- const UNREADABLE_REPORT = {
2599
- nodeCount: 0,
2600
- issues: [{
2601
- code: "content-omitted",
2602
- message: "The converter's report could not be read, so what it left out of this insert is unknown."
2603
- }]
2604
- };
2605
- const canvasSubtreeDraftSchema = z.object({
2606
- version: z.literal(1),
2607
- rootTemporaryId: temporaryIdSchema,
2608
- nodes: z.array(canvasSubtreeDraftNodeSchema).min(1),
2609
- relationships: z.array(canvasSubtreeDraftRelationshipSchema),
2610
- report: canvasConversionReportSchema.catch(UNREADABLE_REPORT)
2611
- }).transform((draft) => ({
2612
- ...draft,
2613
- report: {
2614
- ...draft.report,
2615
- nodeCount: draft.nodes.length
2616
- }
2617
- }));
2618
- /** A capture that lands as a new editable frame on a page, with no screen layer. */
2619
- const editableFrameCaptureSchema = z.object({
2620
- screenId: z.string().min(1),
2621
- pageId: z.string().min(1),
2622
- pictureNodeId: z.string().min(1).optional().describe("The capture's picture, which the frame replaces in place and whose id it keeps. Refused as capture-already-landed once the picture is a frame.")
2277
+ const downloadCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2278
+ const downloadCanvasRenderOutputSchema = z.object({
2279
+ jobId: z.uuid(),
2280
+ download: signedDownloadSchema,
2281
+ source: canvasRenderSourceSchema.optional()
2623
2282
  });
2624
- const editableFrameInputBase = {
2625
- canvasId: z.uuid(),
2626
- documentFormatVersion: canvasDocumentFormatSchema,
2627
- mutationId: z.uuid(),
2628
- baseVersion: z.number().int().positive(),
2629
- draft: canvasSubtreeDraftSchema
2630
- };
2631
- /** An editable frame comes from exactly one screen layer or one capture, never both. */
2632
- const createEditableFrameInputSchema = z.union([z.strictObject({
2633
- ...editableFrameInputBase,
2634
- screenNodeId: z.string().min(1).describe("The screen layer to convert beside itself.")
2635
- }), z.strictObject({
2636
- ...editableFrameInputBase,
2637
- capture: editableFrameCaptureSchema.describe("The stored page a new capture lands from, and the page its frame goes on.")
2638
- })]).superRefine((input, context) => {
2639
- refuseUnsafeWriterFormat(input.documentFormatVersion, "whole", context);
2283
+ const canvasSnapshotRequestSchema = z.strictObject({
2284
+ previewJobId: z.uuid(),
2285
+ scope: z.strictObject({
2286
+ pageId: z.string().min(1).optional(),
2287
+ nodeIds: z.array(z.string().min(1))
2288
+ }),
2289
+ /**
2290
+ * Below the walkthrough: as a screen layer, which installed CLIs ask for, or as a place only,
2291
+ * where the agent's CLI lands an editable frame.
2292
+ */
2293
+ placement: z.strictObject({ kind: z.enum(["below-source", "editable-below-source"]) })
2640
2294
  });
2641
- const createEditableFrameResultSchema = z.object({
2295
+ const createRecordingSnapshotInputSchema = z.object({
2642
2296
  canvasId: z.uuid(),
2643
- mutationId: z.uuid(),
2644
- previousVersion: z.number().int().positive(),
2645
- version: z.number().int().positive(),
2646
- rootNodeId: z.string().min(1),
2647
- idMap: z.record(temporaryIdSchema, z.string().min(1)),
2648
- insertedNodeIds: z.array(z.string().min(1)),
2649
- removedNodeIds: z.array(z.string().min(1)),
2650
- boxes: z.record(z.string().min(1), canvasSceneBoxSchema),
2651
- affectedBounds: canvasSceneBoxSchema
2652
- });
2297
+ recordingId: z.uuid(),
2298
+ atMs: z.number().int().nonnegative(),
2299
+ context: z.strictObject({
2300
+ expectedVersion: z.number().int().positive(),
2301
+ request: canvasSnapshotRequestSchema
2302
+ }).optional()
2303
+ });
2304
+ const createRecordingSnapshotOutputSchema = z.object({
2305
+ job: canvasRenderJobSchema,
2306
+ alreadyExists: z.boolean()
2307
+ });
2653
2308
 
2654
2309
  //#endregion
2655
- //#region ../../packages/contract/src/canvas/canvas-render.consts.ts
2656
- const RENDER_PHASES = [
2657
- "queued",
2658
- "claimed",
2659
- "grant",
2660
- "navigate",
2661
- "document",
2662
- "sources",
2663
- "fonts",
2664
- "layout",
2665
- "target",
2666
- "capture",
2667
- "serialize",
2668
- "compile",
2669
- "commit",
2670
- "upload",
2671
- "complete"
2672
- ];
2673
- const RENDER_STATES = [
2674
- "queued",
2675
- "running",
2676
- "succeeded",
2677
- "failed",
2678
- "cancelled",
2679
- "expired"
2680
- ];
2681
- const RENDER_FAILURE_REASONS = [
2682
- "VERSION_CHANGED",
2683
- "TARGET_NOT_FOUND",
2684
- "TARGET_INVALID",
2685
- "OUTPUT_TOO_LARGE",
2686
- "READINESS_TIMEOUT",
2687
- "SOURCE_FAILED",
2688
- "BROWSER_CRASH",
2689
- "CAPTURE_FAILED",
2690
- "CONVERSION_FAILED",
2691
- "PREPARATION_FAILED",
2692
- "UPLOAD_FAILED",
2693
- "WORKER_UNAVAILABLE",
2694
- "CANCELLED",
2695
- "EXPIRED",
2696
- "INTERNAL"
2697
- ];
2698
- const RENDER_WARNING_CODES = [
2699
- "ASSET_UNAVAILABLE",
2700
- "FONT_FALLBACK",
2701
- "LOCAL_FONT_FALLBACK",
2702
- "SOURCE_FALLBACK",
2703
- "SCALE_REDUCED",
2704
- "LAYOUT_FALLBACK",
2705
- "DRAWN_APPROXIMATELY"
2706
- ];
2310
+ //#region ../../packages/contract/src/canvas/canvas-write-scope.schema.ts
2311
+ const canvasWriteScopeSchema = z.object({ rootIds: z.array(z.string().min(1)) });
2707
2312
 
2708
2313
  //#endregion
2709
- //#region ../../packages/contract/src/canvas/canvas-render.schema.ts
2710
- const MAX_RENDER_MESSAGE_LENGTH$1 = 500;
2711
- const canvasRenderPixelLimitSchema = z.number().int().positive();
2712
- const canvasWorldBoundsSchema = z.object({
2713
- x: z.number(),
2714
- y: z.number(),
2715
- width: z.number().positive(),
2716
- height: z.number().positive()
2717
- });
2718
- const canvasRenderTargetSchema = z.discriminatedUnion("kind", [
2719
- z.object({ kind: z.literal("content") }),
2314
+ //#region ../../packages/contract/src/canvas/canvas-conversion.schema.ts
2315
+ const canvasConversionDestinationSchema = z.discriminatedUnion("kind", [
2720
2316
  z.object({
2721
- kind: z.literal("page"),
2722
- pageId: z.string().min(1)
2317
+ kind: z.literal("adjacent"),
2318
+ /** Where the page was measured to have room for the frame. Absent, stored boxes are searched. */
2319
+ position: z.strictObject({
2320
+ x: z.number(),
2321
+ y: z.number()
2322
+ }).optional()
2723
2323
  }),
2724
2324
  z.object({
2725
- kind: z.literal("node"),
2726
- nodeId: z.string().min(1)
2325
+ kind: z.literal("insert-children"),
2326
+ pageId: z.string().min(1).optional(),
2327
+ targetNodeId: z.string().min(1),
2328
+ /** World placement for a new top-level screen. Absent, the authored position stands. */
2329
+ placement: canvasPlacementIntentSchema.optional()
2727
2330
  }),
2728
2331
  z.object({
2729
- kind: z.literal("bounds"),
2730
- bounds: canvasWorldBoundsSchema
2332
+ kind: z.literal("replace"),
2333
+ targetNodeId: z.string().min(1),
2334
+ /**
2335
+ * A capture's swap: the target must still be the capture's picture. When another browser has
2336
+ * already made it editable, the swap is refused as `capture-already-landed`.
2337
+ */
2338
+ onlyPicture: z.literal(true).optional()
2731
2339
  })
2732
2340
  ]);
2733
- const canvasRenderSourceStateSchema = z.object({
2734
- kind: z.literal("recording"),
2735
- recordingId: z.uuid(),
2736
- atMs: z.number().int().nonnegative()
2737
- });
2738
- const canvasRenderSourceStateEvidenceSchema = z.object({
2739
- kind: z.literal("recording"),
2740
- recordingId: z.uuid(),
2741
- requestedAtMs: z.number().int().nonnegative(),
2742
- settledAtMs: z.number().int().nonnegative()
2743
- });
2744
- const canvasRenderSnapshotResultSchema = z.object({
2745
- recordingId: z.uuid(),
2746
- atMs: z.number().int().nonnegative(),
2747
- screenId: z.uuid(),
2748
- /** Null when the snapshot asked for a place only, so no screen layer was added. */
2749
- screenNodeId: z.string().min(1).nullable(),
2750
- /** The page the place is on. */
2751
- pageId: z.string().min(1).optional(),
2752
- viewport: z.object({
2753
- width: z.number().int().positive(),
2754
- height: z.number().int().positive()
2755
- }),
2756
- box: canvasWorldBoundsSchema,
2757
- version: z.number().int().positive(),
2758
- alreadyPresent: z.boolean()
2759
- });
2760
- const createCanvasRenderInputSchema = z.object({
2761
- canvasId: z.uuid(),
2762
- expectedVersion: z.number().int().positive().optional(),
2763
- scope: z.strictObject({
2764
- pageId: z.string().min(1).optional(),
2765
- nodeIds: z.array(z.string().min(1))
2766
- }).optional(),
2767
- target: canvasRenderTargetSchema.default({ kind: "content" }),
2768
- sourceState: canvasRenderSourceStateSchema.optional(),
2769
- scale: z.number().positive().default(1),
2770
- maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
2771
- format: z.literal("png").default("png")
2772
- }).refine((input) => input.sourceState === void 0 || input.target.kind === "node", {
2773
- message: "a source state requires a node render target",
2774
- path: ["sourceState"]
2775
- });
2776
- const canvasRenderPhaseSchema = z.enum(RENDER_PHASES);
2777
- const canvasRenderStateSchema = z.enum(RENDER_STATES);
2778
- const canvasRenderFailureReasonSchema = z.enum(RENDER_FAILURE_REASONS);
2779
- const canvasRenderWarningCodeSchema = z.enum(RENDER_WARNING_CODES);
2780
- const canvasRenderWarningSchema = z.object({
2781
- code: canvasRenderWarningCodeSchema,
2782
- message: z.string().min(1).max(MAX_RENDER_MESSAGE_LENGTH$1),
2783
- sourceId: z.string().min(1).nullable()
2784
- });
2785
- const canvasRenderFailureSchema = z.object({
2786
- reason: canvasRenderFailureReasonSchema,
2787
- phase: canvasRenderPhaseSchema,
2788
- message: z.string().min(1).max(MAX_RENDER_MESSAGE_LENGTH$1),
2789
- retryable: z.boolean(),
2790
- sourceId: z.string().min(1).nullable()
2791
- });
2792
- const canvasRenderTimingSchema = z.object({
2793
- phase: canvasRenderPhaseSchema,
2794
- durationMs: z.number().int().min(0)
2795
- });
2796
- const canvasRenderResultSchema = z.object({
2797
- canvasId: z.uuid(),
2798
- requestedVersion: z.number().int().positive(),
2799
- loadedVersion: z.number().int().positive(),
2800
- target: canvasRenderTargetSchema,
2801
- sourceState: canvasRenderSourceStateEvidenceSchema.optional(),
2802
- snapshot: canvasRenderSnapshotResultSchema.optional(),
2803
- bounds: canvasWorldBoundsSchema,
2804
- width: z.number().int().positive(),
2805
- height: z.number().int().positive(),
2806
- scale: z.number().positive(),
2807
- contentType: z.literal("image/png"),
2808
- bytes: z.number().int().positive(),
2809
- warnings: z.array(canvasRenderWarningSchema),
2810
- timings: z.array(canvasRenderTimingSchema),
2811
- expiresAt: z.iso.datetime()
2341
+ const canvasConversionSourceSchema = z.discriminatedUnion("kind", [z.object({
2342
+ kind: z.literal("screen"),
2343
+ nodeId: z.string().min(1)
2344
+ }), z.object({
2345
+ kind: z.literal("html"),
2346
+ html: z.string().min(1),
2347
+ label: z.string().min(1),
2348
+ idPrefix: z.string().min(1).regex(/^[\w-]+$/u).optional()
2349
+ })]);
2350
+ const canvasConversionRequestSchema = z.object({
2351
+ source: canvasConversionSourceSchema,
2352
+ destination: canvasConversionDestinationSchema,
2353
+ revisionPolicy: z.enum(["strict", "rebase"]).optional()
2354
+ }).superRefine((request, context) => {
2355
+ if (request.source.kind === "screen" && request.destination.kind !== "adjacent") context.addIssue({
2356
+ code: "custom",
2357
+ message: "stored screens convert beside their source",
2358
+ path: ["destination"]
2359
+ });
2360
+ if (request.source.kind === "html" && request.destination.kind === "adjacent") context.addIssue({
2361
+ code: "custom",
2362
+ message: "authored HTML requires an editable destination",
2363
+ path: ["destination"]
2364
+ });
2812
2365
  });
2813
- const canvasRenderJobBaseSchema = z.object({
2366
+ const canvasConversionSourceSummarySchema = z.discriminatedUnion("kind", [z.object({
2367
+ kind: z.literal("screen"),
2368
+ nodeId: z.string().min(1)
2369
+ }), z.object({
2370
+ kind: z.literal("html"),
2371
+ label: z.string().min(1)
2372
+ })]);
2373
+ const canvasConversionJobBaseSchema = z.object({
2814
2374
  id: z.uuid(),
2815
2375
  canvasId: z.uuid(),
2816
- purpose: z.enum([
2817
- "inspection",
2818
- "snapshot",
2819
- "thumbnail",
2820
- "export"
2821
- ]),
2376
+ source: canvasConversionSourceSummarySchema,
2377
+ destination: canvasConversionDestinationSchema,
2822
2378
  phase: canvasRenderPhaseSchema,
2823
2379
  requestedVersion: z.number().int().positive(),
2824
- target: canvasRenderTargetSchema,
2825
- sourceState: canvasRenderSourceStateSchema.optional(),
2826
- scale: z.number().positive(),
2827
- maxOutputPixels: canvasRenderPixelLimitSchema.optional(),
2828
- format: z.literal("png"),
2829
- attempt: z.number().int().min(0),
2830
- lastFailure: canvasRenderFailureSchema.optional(),
2380
+ attempt: z.number().int().nonnegative(),
2831
2381
  createdAt: z.iso.datetime(),
2832
2382
  updatedAt: z.iso.datetime()
2833
2383
  });
2834
- const canvasRenderJobSchema = z.discriminatedUnion("state", [
2835
- canvasRenderJobBaseSchema.extend({
2384
+ const canvasConversionJobSchema = z.discriminatedUnion("state", [
2385
+ canvasConversionJobBaseSchema.extend({
2836
2386
  state: z.literal("queued"),
2837
2387
  result: z.null(),
2838
2388
  failure: z.null()
2839
2389
  }),
2840
- canvasRenderJobBaseSchema.extend({
2390
+ canvasConversionJobBaseSchema.extend({
2841
2391
  state: z.literal("running"),
2842
2392
  result: z.null(),
2843
2393
  failure: z.null()
2844
2394
  }),
2845
- canvasRenderJobBaseSchema.extend({
2395
+ canvasConversionJobBaseSchema.extend({
2846
2396
  state: z.literal("succeeded"),
2847
2397
  phase: z.literal("complete"),
2848
- result: canvasRenderResultSchema,
2398
+ result: createEditableFrameResultSchema.extend({ report: canvasConversionReportSchema }),
2849
2399
  failure: z.null()
2850
2400
  }),
2851
- canvasRenderJobBaseSchema.extend({
2401
+ canvasConversionJobBaseSchema.extend({
2852
2402
  state: z.literal("failed"),
2853
2403
  result: z.null(),
2854
2404
  failure: canvasRenderFailureSchema
2855
2405
  }),
2856
- canvasRenderJobBaseSchema.extend({
2406
+ canvasConversionJobBaseSchema.extend({
2857
2407
  state: z.literal("cancelled"),
2858
2408
  result: z.null(),
2859
2409
  failure: canvasRenderFailureSchema.extend({ reason: z.literal("CANCELLED") })
2860
2410
  }),
2861
- canvasRenderJobBaseSchema.extend({
2411
+ canvasConversionJobBaseSchema.extend({
2862
2412
  state: z.literal("expired"),
2863
2413
  result: z.null(),
2864
2414
  failure: canvasRenderFailureSchema.extend({ reason: z.literal("EXPIRED") })
2865
2415
  })
2866
2416
  ]);
2867
- const createCanvasRenderOutputSchema = z.object({
2868
- job: canvasRenderJobSchema,
2869
- alreadyExists: z.boolean()
2870
- });
2871
- const getCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2872
- /** The longest an export read waits on the server for the job to settle. */
2873
- const CANVAS_EXPORT_LONGEST_WAIT_MS = 1e4;
2874
- const getCanvasExportInputSchema = getCanvasRenderInputSchema.extend({ waitMs: z.number().int().min(0).max(CANVAS_EXPORT_LONGEST_WAIT_MS).optional() });
2875
- const getCanvasRenderOutputSchema = z.object({ job: canvasRenderJobSchema });
2876
- const cancelCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2877
- const cancelCanvasRenderOutputSchema = z.object({ job: canvasRenderJobSchema });
2878
- const canvasRenderSourceSchema = z.discriminatedUnion("status", [z.object({
2879
- status: z.literal("available"),
2880
- version: z.number().int().positive(),
2881
- format: z.literal("enhance-scene-json"),
2882
- code: z.string(),
2883
- prototypes: z.array(z.object({
2884
- nodeId: z.string(),
2885
- prototypeId: z.uuid(),
2886
- deploymentId: z.uuid(),
2887
- capability: z.literal("canvas.read"),
2888
- canvasPath: z.string(),
2889
- input: z.object({
2890
- canvasRef: z.uuid(),
2891
- view: z.literal("source"),
2892
- nodeId: z.string()
2893
- }),
2894
- guidance: z.string()
2895
- })),
2896
- guidance: z.string()
2897
- }), z.object({
2898
- status: z.literal("unavailable"),
2899
- guidance: z.string()
2900
- })]);
2901
- /** A person's image export of one layer at the saved revision, drawn by the render worker. */
2902
- const createCanvasExportInputSchema = z.object({
2903
- canvasId: z.uuid(),
2904
- nodeId: z.string().min(1),
2905
- expectedVersion: z.number().int().positive(),
2906
- scale: z.number().positive()
2907
- });
2908
- const downloadCanvasRenderInputSchema = z.object({ jobId: z.uuid() });
2909
- const downloadCanvasRenderOutputSchema = z.object({
2910
- jobId: z.uuid(),
2911
- download: signedDownloadSchema,
2912
- source: canvasRenderSourceSchema.optional()
2913
- });
2914
- const canvasSnapshotRequestSchema = z.strictObject({
2915
- previewJobId: z.uuid(),
2916
- scope: z.strictObject({
2917
- pageId: z.string().min(1).optional(),
2918
- nodeIds: z.array(z.string().min(1))
2919
- }),
2920
- /**
2921
- * Below the walkthrough: as a screen layer, which installed CLIs ask for, or as a place only,
2922
- * where the agent's CLI lands an editable frame.
2923
- */
2924
- placement: z.strictObject({ kind: z.enum(["below-source", "editable-below-source"]) })
2925
- });
2926
- const createRecordingSnapshotInputSchema = z.object({
2927
- canvasId: z.uuid(),
2928
- recordingId: z.uuid(),
2929
- atMs: z.number().int().nonnegative(),
2930
- context: z.strictObject({
2931
- expectedVersion: z.number().int().positive(),
2932
- request: canvasSnapshotRequestSchema
2933
- }).optional()
2934
- });
2935
- const createRecordingSnapshotOutputSchema = z.object({
2936
- job: canvasRenderJobSchema,
2937
- alreadyExists: z.boolean()
2938
- });
2939
-
2940
- //#endregion
2941
- //#region ../../packages/contract/src/canvas/canvas-write-scope.schema.ts
2942
- const canvasWriteScopeSchema = z.object({ rootIds: z.array(z.string().min(1)) });
2943
-
2944
- //#endregion
2945
- //#region ../../packages/contract/src/canvas/canvas-conversion.schema.ts
2946
- const canvasConversionDestinationSchema = z.discriminatedUnion("kind", [
2947
- z.object({ kind: z.literal("adjacent") }),
2948
- z.object({
2949
- kind: z.literal("insert-children"),
2950
- pageId: z.string().min(1).optional(),
2951
- targetNodeId: z.string().min(1)
2952
- }),
2953
- z.object({
2954
- kind: z.literal("replace"),
2955
- targetNodeId: z.string().min(1),
2956
- /**
2957
- * A capture's swap: the target must still be the capture's picture. When another browser has
2958
- * already made it editable, the swap is refused as `capture-already-landed`.
2959
- */
2960
- onlyPicture: z.literal(true).optional()
2961
- })
2962
- ]);
2963
- const canvasConversionSourceSchema = z.discriminatedUnion("kind", [z.object({
2964
- kind: z.literal("screen"),
2965
- nodeId: z.string().min(1)
2966
- }), z.object({
2967
- kind: z.literal("html"),
2968
- html: z.string().min(1),
2969
- label: z.string().min(1),
2970
- idPrefix: z.string().min(1).regex(/^[\w-]+$/u).optional()
2971
- })]);
2972
- const canvasConversionRequestSchema = z.object({
2973
- source: canvasConversionSourceSchema,
2974
- destination: canvasConversionDestinationSchema,
2975
- revisionPolicy: z.enum(["strict", "rebase"]).optional()
2976
- }).superRefine((request, context) => {
2977
- if (request.source.kind === "screen" && request.destination.kind !== "adjacent") context.addIssue({
2978
- code: "custom",
2979
- message: "stored screens convert beside their source",
2980
- path: ["destination"]
2981
- });
2982
- if (request.source.kind === "html" && request.destination.kind === "adjacent") context.addIssue({
2983
- code: "custom",
2984
- message: "authored HTML requires an editable destination",
2985
- path: ["destination"]
2986
- });
2987
- });
2988
- const canvasConversionSourceSummarySchema = z.discriminatedUnion("kind", [z.object({
2989
- kind: z.literal("screen"),
2990
- nodeId: z.string().min(1)
2991
- }), z.object({
2992
- kind: z.literal("html"),
2993
- label: z.string().min(1)
2994
- })]);
2995
- const canvasConversionJobBaseSchema = z.object({
2996
- id: z.uuid(),
2997
- canvasId: z.uuid(),
2998
- source: canvasConversionSourceSummarySchema,
2999
- destination: canvasConversionDestinationSchema,
3000
- phase: canvasRenderPhaseSchema,
3001
- requestedVersion: z.number().int().positive(),
3002
- attempt: z.number().int().nonnegative(),
3003
- createdAt: z.iso.datetime(),
3004
- updatedAt: z.iso.datetime()
3005
- });
3006
- const canvasConversionJobSchema = z.discriminatedUnion("state", [
3007
- canvasConversionJobBaseSchema.extend({
3008
- state: z.literal("queued"),
3009
- result: z.null(),
3010
- failure: z.null()
3011
- }),
3012
- canvasConversionJobBaseSchema.extend({
3013
- state: z.literal("running"),
3014
- result: z.null(),
3015
- failure: z.null()
3016
- }),
3017
- canvasConversionJobBaseSchema.extend({
3018
- state: z.literal("succeeded"),
3019
- phase: z.literal("complete"),
3020
- result: createEditableFrameResultSchema.extend({ report: canvasConversionReportSchema }),
3021
- failure: z.null()
3022
- }),
3023
- canvasConversionJobBaseSchema.extend({
3024
- state: z.literal("failed"),
3025
- result: z.null(),
3026
- failure: canvasRenderFailureSchema
3027
- }),
3028
- canvasConversionJobBaseSchema.extend({
3029
- state: z.literal("cancelled"),
3030
- result: z.null(),
3031
- failure: canvasRenderFailureSchema.extend({ reason: z.literal("CANCELLED") })
3032
- }),
3033
- canvasConversionJobBaseSchema.extend({
3034
- state: z.literal("expired"),
3035
- result: z.null(),
3036
- failure: canvasRenderFailureSchema.extend({ reason: z.literal("EXPIRED") })
3037
- })
3038
- ]);
3039
- const createCanvasConversionInputSchema = canvasConversionRequestSchema.and(z.object({
3040
- canvasId: z.uuid(),
3041
- expectedVersion: z.number().int().positive().optional(),
3042
- mutationId: z.uuid().optional(),
3043
- writeScope: canvasWriteScopeSchema.optional(),
3044
- scope: createCanvasRenderInputSchema.shape.scope
3045
- })).refine((input) => input.scope === void 0 && input.revisionPolicy !== "strict" || input.expectedVersion !== void 0, {
3046
- message: "scoped or strict conversion requires an expected version",
3047
- path: ["expectedVersion"]
3048
- });
3049
- const createCanvasConversionOutputSchema = z.object({
3050
- job: canvasConversionJobSchema,
2417
+ const createCanvasConversionInputSchema = canvasConversionRequestSchema.and(z.object({
2418
+ canvasId: z.uuid(),
2419
+ expectedVersion: z.number().int().positive().optional(),
2420
+ mutationId: z.uuid().optional(),
2421
+ writeScope: canvasWriteScopeSchema.optional(),
2422
+ scope: createCanvasRenderInputSchema.shape.scope
2423
+ })).refine((input) => input.scope === void 0 && input.revisionPolicy !== "strict" || input.expectedVersion !== void 0, {
2424
+ message: "scoped or strict conversion requires an expected version",
2425
+ path: ["expectedVersion"]
2426
+ });
2427
+ const createCanvasConversionOutputSchema = z.object({
2428
+ job: canvasConversionJobSchema,
3051
2429
  alreadyExists: z.boolean()
3052
2430
  });
3053
2431
  const getCanvasConversionInputSchema = z.object({ jobId: z.uuid() });
@@ -3063,7 +2441,9 @@ const conversionRouteStateSchema = z.discriminatedUnion("state", [
3063
2441
  state: z.literal("ready"),
3064
2442
  jobId: z.uuid(),
3065
2443
  loadedVersion: z.number().int().positive(),
3066
- draft: canvasSubtreeDraftSchema
2444
+ draft: canvasSubtreeDraftSchema,
2445
+ /** Where measured placement put the draft's root, when the request asked for it. */
2446
+ placement: canvasSceneBoxSchema.optional()
3067
2447
  }),
3068
2448
  z.object({
3069
2449
  state: z.literal("failed"),
@@ -3448,6 +2828,72 @@ const canvasEditTextOperationSchema = z.object({
3448
2828
  source: canvasTextSourceSchema.optional()
3449
2829
  });
3450
2830
 
2831
+ //#endregion
2832
+ //#region ../../packages/contract/src/canvas/canvas-text-style.schema.ts
2833
+ const MAX_DESCRIPTION$1 = 2e3;
2834
+ const MAX_OVERRIDE_VALUE = 1e3;
2835
+ const canvasTextStyleTypographySchema = canvasTypographySchema.pick({
2836
+ family: true,
2837
+ fallbackFamilies: true,
2838
+ size: true,
2839
+ weight: true,
2840
+ style: true,
2841
+ variations: true,
2842
+ opticalSize: true,
2843
+ features: true,
2844
+ lineHeight: true,
2845
+ letterSpacing: true,
2846
+ transform: true,
2847
+ decoration: true,
2848
+ paragraphSpacing: true,
2849
+ paragraphIndent: true,
2850
+ listSpacing: true,
2851
+ hangingList: true,
2852
+ hangingPunctuation: true,
2853
+ verticalTrim: true,
2854
+ wrapStyle: true
2855
+ }).extend({ decoration: canvasTypographySchema.shape.decoration.omit({ blendMode: true }) }).strict();
2856
+ const CANVAS_TEXT_STYLE_PROPERTIES = canvasTextStyleTypographySchema.keyof().options;
2857
+ const canvasTextStyleSchema = z.object({
2858
+ id: z.string().min(1),
2859
+ name: z.string().trim().min(1),
2860
+ description: z.string().max(MAX_DESCRIPTION$1),
2861
+ sortKey: z.string().min(1).optional(),
2862
+ sourceStyleId: z.string().min(1).optional(),
2863
+ sourceCanvasId: z.uuid().optional(),
2864
+ sourceRevision: z.number().int().positive().optional(),
2865
+ typography: canvasTextStyleTypographySchema.extend({ listStyle: canvasTypographySchema.shape.listStyle }).transform((typography) => {
2866
+ Reflect.deleteProperty(typography, "listStyle");
2867
+ return typography;
2868
+ })
2869
+ }).strict().refine((style) => style.sourceCanvasId === void 0 || style.sourceStyleId !== void 0, {
2870
+ message: "A source canvas belongs to a reference snapshot.",
2871
+ path: ["sourceCanvasId"]
2872
+ }).refine((style) => style.sourceRevision === void 0 || style.sourceCanvasId !== void 0 && style.sourceStyleId !== void 0, {
2873
+ message: "A published revision belongs to a source style and canvas.",
2874
+ path: ["sourceRevision"]
2875
+ });
2876
+ const canvasTextStyleBindingSchema = z.object({
2877
+ id: canvasTextStyleSchema.shape.id,
2878
+ position: z.enum([
2879
+ "normal",
2880
+ "subscript",
2881
+ "superscript"
2882
+ ]).optional(),
2883
+ overrides: z.partialRecord(z.enum([
2884
+ "fontWeight",
2885
+ "fontStyle",
2886
+ "fontVariationSettings",
2887
+ "fontOpticalSizing",
2888
+ "textDecorationLine",
2889
+ "textDecorationStyle",
2890
+ "textDecorationColor",
2891
+ "textDecorationThickness",
2892
+ "textUnderlineOffset",
2893
+ "textDecorationSkipInk"
2894
+ ]), z.union([z.string().max(MAX_OVERRIDE_VALUE), z.number()])).optional()
2895
+ }).strict();
2896
+
3451
2897
  //#endregion
3452
2898
  //#region ../../packages/contract/src/canvas/text-style-library.schema.ts
3453
2899
  const MAX_DESCRIPTION = 2e3;
@@ -3717,6 +3163,932 @@ const createEditableFrameOutputSchema = createEditableFrameResultSchema.extend({
3717
3163
  next: z.array(z.string().min(1))
3718
3164
  });
3719
3165
 
3166
+ //#endregion
3167
+ //#region ../../packages/contract/src/canvas/canvas-operation-writes.schema.ts
3168
+ /**
3169
+ * What each operation writes. `names` sets one plain value, places, removes, or merges a patch, so
3170
+ * values its client never knew stay as stored. `whole` brings a whole layer or replaces a whole
3171
+ * group of values, which a client that read the canvas in an older format may have stripped.
3172
+ */
3173
+ const CANVAS_OPERATION_WRITES = {
3174
+ insertConvertedSubtree: "whole",
3175
+ insertNode: "whole",
3176
+ insertText: "names",
3177
+ insertPrototype: "names",
3178
+ setPrototypeDeployment: "names",
3179
+ editText: "names",
3180
+ setText: "names",
3181
+ setBox: "names",
3182
+ setLabel: "names",
3183
+ setContainerKind: "names",
3184
+ setVisibility: "names",
3185
+ setLocked: "names",
3186
+ setConstraints: "names",
3187
+ setStyles: "names",
3188
+ patchExportSettings: "names",
3189
+ setAppearance: "names",
3190
+ setLayout: "whole",
3191
+ patchTypography: "names",
3192
+ setTypography: "whole",
3193
+ patchAdditionalStyles: "names",
3194
+ setAdditionalStyles: "whole",
3195
+ setArtworkColor: "whole",
3196
+ setTextStyleLibrary: "whole",
3197
+ patchFontLibrary: "names",
3198
+ setTextStyle: "whole",
3199
+ setGeometry: "whole",
3200
+ setProps: "whole",
3201
+ setParentage: "names",
3202
+ move: "names",
3203
+ remove: "names"
3204
+ };
3205
+
3206
+ //#endregion
3207
+ //#region ../../packages/contract/src/canvas/canvas-mutation.schema.ts
3208
+ const nodeIdSchema$2 = canvasSceneNodeSchema.shape.id;
3209
+ const writableBoxSchema = canvasSceneBoxSchema.extend({
3210
+ width: z.number().positive(),
3211
+ height: z.number().positive()
3212
+ });
3213
+ const copiedNodeIdsSchema = z.record(nodeIdSchema$2, nodeIdSchema$2);
3214
+ /** A receipt stored before boxes said what they are holds none, so the source stays optional. */
3215
+ const canvasReceiptBoxSchema = canvasSceneBoxSchema.extend({ boxSource: canvasBoxSourceSchema.optional() });
3216
+ const canvasMutationRequestContextSchema = z.strictObject({
3217
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/u),
3218
+ revisionPolicy: z.enum(["strict", "rebase"]),
3219
+ copiedNodeIds: copiedNodeIdsSchema.optional()
3220
+ });
3221
+ /** The request's fields alone, for callers that derive their own input from it. */
3222
+ const applyCanvasOperationsFieldsSchema = z.object({
3223
+ canvasId: z.uuid(),
3224
+ mutationId: z.uuid(),
3225
+ documentFormatVersion: canvasDocumentFormatSchema,
3226
+ baseVersion: z.number().int().positive(),
3227
+ operations: z.array(canvasOperationSchema).min(1),
3228
+ requestContext: canvasMutationRequestContextSchema.optional(),
3229
+ writeScope: canvasWriteScopeSchema.optional()
3230
+ });
3231
+ const applyCanvasOperationsInputSchema = applyCanvasOperationsFieldsSchema.superRefine((input, context) => {
3232
+ refuseUnsafeWriterFormat(input.documentFormatVersion, input.operations.every((operation) => CANVAS_OPERATION_WRITES[operation.op] === "names") ? "names" : "whole", context);
3233
+ });
3234
+ const applyCanvasOperationsOutputSchema = z.object({
3235
+ canvasId: z.uuid(),
3236
+ mutationId: z.uuid(),
3237
+ previousVersion: z.number().int().positive(),
3238
+ version: z.number().int().positive(),
3239
+ operations: z.array(canvasOperationSchema),
3240
+ insertedNodeIds: z.array(nodeIdSchema$2),
3241
+ changedNodeIds: z.array(nodeIdSchema$2),
3242
+ removedNodeIds: z.array(nodeIdSchema$2),
3243
+ boxes: z.record(nodeIdSchema$2, canvasReceiptBoxSchema),
3244
+ affectedBounds: writableBoxSchema.nullable(),
3245
+ copiedNodeIds: copiedNodeIdsSchema.optional(),
3246
+ next: z.array(z.string().min(1))
3247
+ });
3248
+ const getCanvasMutationInputSchema = z.strictObject({
3249
+ canvasId: z.uuid(),
3250
+ mutationId: z.uuid(),
3251
+ fingerprint: canvasMutationRequestContextSchema.shape.fingerprint
3252
+ });
3253
+ const getCanvasMutationOutputSchema = z.discriminatedUnion("state", [z.strictObject({ state: z.literal("not-found") }), z.strictObject({
3254
+ state: z.literal("committed"),
3255
+ /** `url` is the canvas's web address. An API older than the field answers without it. */
3256
+ result: applyCanvasOperationsOutputSchema.extend({ url: z.url().optional() })
3257
+ })]);
3258
+
3259
+ //#endregion
3260
+ //#region ../../packages/contract/src/canvas/canvas-agent-edit.schema.ts
3261
+ const nodeId$6 = z.string().min(1);
3262
+ const nodeIds$2 = z.array(nodeId$6).min(1);
3263
+ /** An agent's small edits, in the order the API plans them. */
3264
+ const canvasAgentEditsSchema = z.array(z.discriminatedUnion("kind", [
3265
+ z.object({
3266
+ kind: z.literal("set_text"),
3267
+ nodeId: nodeId$6,
3268
+ text: z.string()
3269
+ }),
3270
+ z.object({
3271
+ kind: z.literal("set_styles"),
3272
+ nodeIds: nodeIds$2,
3273
+ styles: z.record(z.string(), z.union([
3274
+ z.string(),
3275
+ z.number(),
3276
+ z.null()
3277
+ ]))
3278
+ }),
3279
+ z.object({
3280
+ kind: z.literal("rename"),
3281
+ nodeId: nodeId$6,
3282
+ name: z.string().trim().min(1)
3283
+ }),
3284
+ z.object({
3285
+ kind: z.literal("duplicate"),
3286
+ nodeIds: nodeIds$2,
3287
+ parentId: nodeId$6.optional()
3288
+ }),
3289
+ z.object({
3290
+ kind: z.literal("move"),
3291
+ nodeId: nodeId$6,
3292
+ destination: z.discriminatedUnion("kind", [
3293
+ z.object({
3294
+ kind: z.literal("before"),
3295
+ nodeId: nodeId$6
3296
+ }),
3297
+ z.object({
3298
+ kind: z.literal("after"),
3299
+ nodeId: nodeId$6
3300
+ }),
3301
+ z.object({
3302
+ kind: z.literal("parent"),
3303
+ parentId: nodeId$6,
3304
+ index: z.number().int().nonnegative().optional()
3305
+ })
3306
+ ])
3307
+ })
3308
+ ])).min(1);
3309
+ /** An edit batch the API plans and saves as one version. */
3310
+ const editCanvasInputSchema = z.strictObject({
3311
+ canvasId: z.uuid(),
3312
+ mutationId: z.uuid(),
3313
+ baseVersion: z.number().int().positive(),
3314
+ edits: canvasAgentEditsSchema,
3315
+ /** The prefix of copies' ids; the API makes one from the mutation id when it is left out. */
3316
+ idPrefix: z.string().min(1).optional(),
3317
+ /** A selection link's layers: the batch may change nothing outside them. */
3318
+ scopeNodeIds: z.array(nodeId$6).optional(),
3319
+ /** A selection link's page: the batch may name no layer on another page. */
3320
+ scopePageId: z.string().min(1).optional(),
3321
+ /** Whose words a refusal's next step is written in. */
3322
+ surface: z.enum(["cli", "mcp"]).optional(),
3323
+ fingerprint: canvasMutationRequestContextSchema.shape.fingerprint
3324
+ });
3325
+ const plannedNodeSchema = z.object({
3326
+ sourceId: z.string(),
3327
+ newId: z.string(),
3328
+ name: z.string(),
3329
+ component: z.string(),
3330
+ descendantIdMap: z.record(z.string(), z.string())
3331
+ });
3332
+ const editCanvasOutputSchema = z.discriminatedUnion("outcome", [applyCanvasOperationsOutputSchema.extend({
3333
+ outcome: z.literal("committed"),
3334
+ /** True when the answer is the commit of an earlier identical request. */
3335
+ recovered: z.boolean(),
3336
+ duplicatedNodes: z.array(plannedNodeSchema).optional(),
3337
+ moves: z.array(z.object({
3338
+ nodeId: z.string(),
3339
+ parentId: z.string(),
3340
+ index: z.number().int()
3341
+ })).optional(),
3342
+ affectedParents: z.array(z.object({
3343
+ parentId: z.string(),
3344
+ children: z.array(z.string())
3345
+ })).optional()
3346
+ }), z.object({
3347
+ outcome: z.literal("no_op"),
3348
+ canvasId: z.uuid(),
3349
+ version: z.number().int().positive()
3350
+ })]);
3351
+
3352
+ //#endregion
3353
+ //#region ../../packages/contract/src/canvas/canvas-text-links.lib.ts
3354
+ const FORBIDDEN_DOMAIN_CHARACTERS = /* @__PURE__ */ new Set([
3355
+ "#",
3356
+ "%",
3357
+ "/",
3358
+ ":",
3359
+ "<",
3360
+ ">",
3361
+ "?",
3362
+ "@",
3363
+ "[",
3364
+ "\\",
3365
+ "]",
3366
+ "^",
3367
+ "|"
3368
+ ]);
3369
+ const ASCII_SPACE = 32;
3370
+ const ASCII_DELETE = 127;
3371
+ /** Check the decoded host because browser URL parsing can retain host spaces as percent escapes. */
3372
+ const isHttpHostname = (url) => {
3373
+ if (url.hostname.startsWith("[")) return true;
3374
+ const hostname = decodeURIComponent(url.hostname);
3375
+ for (const character of hostname) {
3376
+ const point = character.codePointAt(0) ?? 0;
3377
+ if (point === ASCII_DELETE || point <= ASCII_SPACE || FORBIDDEN_DOMAIN_CHARACTERS.has(character)) return false;
3378
+ }
3379
+ return hostname !== "";
3380
+ };
3381
+ const SAFE_HREF_PROTOCOLS = /* @__PURE__ */ new Set([
3382
+ "http:",
3383
+ "https:",
3384
+ "mailto:",
3385
+ "tel:"
3386
+ ]);
3387
+ const isCanvasRichTextHref = (value) => {
3388
+ const href = value.trim();
3389
+ if (href === "") return false;
3390
+ try {
3391
+ const url = new URL(href, "https://enhance.invalid/");
3392
+ return SAFE_HREF_PROTOCOLS.has(url.protocol) && (!["http:", "https:"].includes(url.protocol) || isHttpHostname(url));
3393
+ } catch {
3394
+ return false;
3395
+ }
3396
+ };
3397
+
3398
+ //#endregion
3399
+ //#region ../../packages/contract/src/canvas/canvas-rich-text.consts.ts
3400
+ const CANVAS_RICH_TEXT_STYLE_PROPERTIES = /* @__PURE__ */ new Set([
3401
+ "alignItems",
3402
+ "backgroundColor",
3403
+ "borderBottom",
3404
+ "borderBottomLeftRadius",
3405
+ "borderBottomRightRadius",
3406
+ "borderLeft",
3407
+ "borderRight",
3408
+ "borderTop",
3409
+ "borderTopLeftRadius",
3410
+ "borderTopRightRadius",
3411
+ "boxShadow",
3412
+ "boxSizing",
3413
+ "color",
3414
+ "columnGap",
3415
+ "direction",
3416
+ "display",
3417
+ "flexDirection",
3418
+ "fontFamily",
3419
+ "fontFeatureSettings",
3420
+ "fontOpticalSizing",
3421
+ "fontSize",
3422
+ "fontStretch",
3423
+ "fontStyle",
3424
+ "fontVariant",
3425
+ "fontVariantCaps",
3426
+ "fontVariantLigatures",
3427
+ "fontVariantNumeric",
3428
+ "fontVariantPosition",
3429
+ "fontKerning",
3430
+ "fontVariationSettings",
3431
+ "fontWeight",
3432
+ "hyphenateCharacter",
3433
+ "hyphens",
3434
+ "justifyContent",
3435
+ "letterSpacing",
3436
+ "lineBreak",
3437
+ "lineHeight",
3438
+ "marginBottom",
3439
+ "marginLeft",
3440
+ "marginRight",
3441
+ "marginTop",
3442
+ "opacity",
3443
+ "overflowWrap",
3444
+ "paddingBottom",
3445
+ "paddingLeft",
3446
+ "paddingRight",
3447
+ "paddingTop",
3448
+ "rowGap",
3449
+ "tabSize",
3450
+ "textCombineUpright",
3451
+ "textDecorationColor",
3452
+ "textDecorationLine",
3453
+ "textDecorationSkipInk",
3454
+ "textDecorationStyle",
3455
+ "textDecorationThickness",
3456
+ "textEmphasisColor",
3457
+ "textEmphasisPosition",
3458
+ "textEmphasisStyle",
3459
+ "textOrientation",
3460
+ "textRendering",
3461
+ "textShadow",
3462
+ "textTransform",
3463
+ "textUnderlineOffset",
3464
+ "unicodeBidi",
3465
+ "verticalAlign",
3466
+ "whiteSpace",
3467
+ "wordBreak",
3468
+ "wordSpacing",
3469
+ "WebkitFontSmoothing",
3470
+ "WebkitLocale",
3471
+ "WebkitTextFillColor",
3472
+ "WebkitTextStrokeColor",
3473
+ "WebkitTextStrokeWidth",
3474
+ "--canvas-text-stroke-alignment"
3475
+ ]);
3476
+
3477
+ //#endregion
3478
+ //#region ../../packages/contract/src/canvas/canvas-rich-text.lib.ts
3479
+ const fillsSchema = canvasPaintSchema.array().optional();
3480
+ /** What one rich text run stores besides its text, which the owner list of paint blends reads. */
3481
+ const canvasRichTextRunPaintSchema = z.object({ fills: fillsSchema });
3482
+ const characterFormattingSchema = canvasTextParagraphSchema.pick({
3483
+ paragraphSpacing: true,
3484
+ paragraphIndent: true,
3485
+ listSpacing: true,
3486
+ wrapStyle: true
3487
+ }).extend({
3488
+ hangingPunctuation: canvasTypographySchema.shape.hangingPunctuation,
3489
+ verticalTrim: canvasTypographySchema.shape.verticalTrim,
3490
+ stroke: canvasTypographySchema.shape.stroke.nullable(),
3491
+ decorationBlendMode: canvasTypographySchema.shape.decoration.shape.blendMode,
3492
+ backgroundBlendMode: canvasBlendModeSchema.optional()
3493
+ }).strip();
3494
+ const safeHref = (value) => typeof value === "string" && isCanvasRichTextHref(value) ? value : void 0;
3495
+ const richStylesOf = (value) => {
3496
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
3497
+ const entries = Object.entries(value);
3498
+ if (entries.some(([property, styleValue]) => !CANVAS_RICH_TEXT_STYLE_PROPERTIES.has(property) || typeof styleValue !== "string" && typeof styleValue !== "number")) return null;
3499
+ return Object.fromEntries(entries);
3500
+ };
3501
+ const richMetadataOf = (value) => {
3502
+ const sourcePath = Reflect.get(value, "sourcePath");
3503
+ return {
3504
+ ...Object.fromEntries(Object.entries(value).filter(([key]) => ![
3505
+ "text",
3506
+ "href",
3507
+ "sourcePath",
3508
+ "styles",
3509
+ "fills",
3510
+ "stroke",
3511
+ "decorationBlendMode",
3512
+ "backgroundBlendMode",
3513
+ "paragraph",
3514
+ "paragraphSpacing",
3515
+ "paragraphIndent",
3516
+ "listSpacing",
3517
+ "hangingPunctuation",
3518
+ "verticalTrim",
3519
+ "wrapStyle",
3520
+ "soft",
3521
+ "textStyle"
3522
+ ].includes(key))),
3523
+ ...typeof sourcePath === "string" && { sourcePath }
3524
+ };
3525
+ };
3526
+ const richChildrenOf = (values) => {
3527
+ const result = [];
3528
+ const pending = values.toReversed().map((value) => ({
3529
+ value,
3530
+ target: result
3531
+ }));
3532
+ const ancestors = /* @__PURE__ */ new Set();
3533
+ while (pending.length > 0) {
3534
+ const task = pending.pop();
3535
+ if (task === void 0) continue;
3536
+ if ("done" in task) {
3537
+ ancestors.delete(task.done);
3538
+ continue;
3539
+ }
3540
+ const children = [];
3541
+ const node = richNodeOf(task.value, children);
3542
+ if (node === null) return null;
3543
+ task.target.push(node);
3544
+ if (node.kind !== "span") continue;
3545
+ const value = task.value;
3546
+ if (typeof value !== "object" || value === null || ancestors.has(value)) return null;
3547
+ ancestors.add(value);
3548
+ pending.push({ done: value });
3549
+ const nested = Reflect.get(value, "children");
3550
+ if (!Array.isArray(nested)) return null;
3551
+ const candidates = nested;
3552
+ for (const child of candidates.toReversed()) pending.push({
3553
+ value: child,
3554
+ target: children
3555
+ });
3556
+ }
3557
+ return result;
3558
+ };
3559
+ const richBreakOf = (value) => {
3560
+ const soft = Reflect.get(value, "soft");
3561
+ if (soft !== void 0 && soft !== true) return null;
3562
+ return {
3563
+ ...richMetadataOf(value),
3564
+ kind: "break",
3565
+ ...soft === true && { soft }
3566
+ };
3567
+ };
3568
+ const richNodeOf = (value, children) => {
3569
+ if (typeof value !== "object" || value === null) return null;
3570
+ const kind = Reflect.get(value, "kind");
3571
+ const metadata = richMetadataOf(value);
3572
+ if (kind === "break") return richBreakOf(value);
3573
+ if (kind === "text") {
3574
+ const text = Reflect.get(value, "text");
3575
+ return typeof text === "string" ? {
3576
+ ...metadata,
3577
+ kind,
3578
+ text
3579
+ } : null;
3580
+ }
3581
+ if (kind !== "span") return null;
3582
+ const values = Reflect.get(value, "children");
3583
+ const styles = richStylesOf(Reflect.get(value, "styles"));
3584
+ const fills = fillsSchema.safeParse(Reflect.get(value, "fills"));
3585
+ const paragraph = canvasTextParagraphSchema.optional().safeParse(Reflect.get(value, "paragraph"));
3586
+ const formatting = characterFormattingSchema.safeParse(value);
3587
+ const textStyle = canvasTextStyleBindingSchema.optional().safeParse(Reflect.get(value, "textStyle"));
3588
+ if (styles === null || !fills.success || !paragraph.success || !formatting.success || !textStyle.success || !Array.isArray(values)) return null;
3589
+ const href = safeHref(Reflect.get(value, "href"));
3590
+ return {
3591
+ ...metadata,
3592
+ kind,
3593
+ styles,
3594
+ children,
3595
+ ...textStyle.data !== void 0 && { textStyle: textStyle.data },
3596
+ ...fills.data !== void 0 && { fills: fills.data },
3597
+ ...paragraph.data !== void 0 && { paragraph: paragraph.data },
3598
+ ...Object.fromEntries(Object.entries(formatting.data).filter(([, entry]) => entry !== void 0)),
3599
+ ...href !== void 0 && { href }
3600
+ };
3601
+ };
3602
+ const richTextLeafValue = (node) => node.kind === "text" ? node.text : node.soft === true ? "\u2028" : "\n";
3603
+ const canvasRichTextValueOf = (nodes) => {
3604
+ const pending = nodes.toReversed();
3605
+ const text = [];
3606
+ while (pending.length > 0) {
3607
+ const node = pending.pop();
3608
+ if (node === void 0) break;
3609
+ if (node.kind === "span") for (const child of node.children.toReversed()) pending.push(child);
3610
+ else text.push(richTextLeafValue(node));
3611
+ }
3612
+ return text.join("");
3613
+ };
3614
+ const canvasRichTextOf = (node) => {
3615
+ const props = node.props;
3616
+ if (props === void 0 || !Array.isArray(props["richText"])) return [];
3617
+ const rich = richChildrenOf(props["richText"]);
3618
+ if (rich === null) return [];
3619
+ const text = props["text"];
3620
+ return canvasRichTextValueOf(rich) === text ? rich : [];
3621
+ };
3622
+ const hasCanvasRichTextPaints = (node) => {
3623
+ const pending = [...canvasRichTextOf(node)];
3624
+ while (pending.length > 0) {
3625
+ const run = pending.pop();
3626
+ if (run?.kind !== "span") continue;
3627
+ if (run.fills !== void 0) return true;
3628
+ for (const child of run.children) pending.push(child);
3629
+ }
3630
+ return false;
3631
+ };
3632
+ /** Existing-link edits retain authored formatting, including nested descendants. */
3633
+ const canvasRichTextLinkOf = (runs) => {
3634
+ const destinations = /* @__PURE__ */ new Set();
3635
+ const visit = (nodes, inherited) => {
3636
+ for (const node of nodes) if (node.kind === "span") visit(node.children, node.href ?? inherited);
3637
+ else destinations.add(inherited);
3638
+ };
3639
+ visit(runs);
3640
+ return destinations.size === 1 ? [...destinations][0] ?? null : null;
3641
+ };
3642
+ /**
3643
+ * The style text a run edit clears: the properties it sets, and for a stroke edit the style text
3644
+ * that copies a stroke, since the stroke value owns it.
3645
+ */
3646
+ const canvasRunStylesClearedBy = (command) => [...Object.keys(command.styles), ...command.stroke === void 0 ? [] : [
3647
+ "WebkitTextStrokeWidth",
3648
+ "WebkitTextStrokeColor",
3649
+ "--canvas-text-stroke-alignment"
3650
+ ]];
3651
+
3652
+ //#endregion
3653
+ //#region ../../packages/contract/src/canvas/canvas-font-asset.schema.ts
3654
+ const FONT_PATH_SEGMENT_LIMIT = 4;
3655
+ const CANVAS_FONT_CONTENT_TYPES = [
3656
+ "font/ttf",
3657
+ "font/otf",
3658
+ "font/woff",
3659
+ "font/woff2",
3660
+ "font/collection"
3661
+ ];
3662
+ const canvasFontAssetIdentitySchema = z.object({
3663
+ canvasId: z.uuid(),
3664
+ sha256: z.string().regex(/^[a-f0-9]{64}$/u)
3665
+ });
3666
+ const completeCanvasFontInputSchema = canvasFontAssetIdentitySchema.extend({ bytes: z.number().int().positive() });
3667
+ const reserveCanvasFontInputSchema = completeCanvasFontInputSchema.extend({ contentType: z.enum(CANVAS_FONT_CONTENT_TYPES) });
3668
+ const completeCanvasFontOutputSchema = z.object({ path: z.string().startsWith("/v1/canvas-assets/") });
3669
+ const reserveCanvasFontOutputSchema = completeCanvasFontOutputSchema.extend({ upload: signedUploadSchema });
3670
+ const canvasFontAssetPath = (canvasId, sha256) => `${CANVAS_ASSET_PATH_PREFIX}${encodeURIComponent(canvasId)}/fonts/${encodeURIComponent(sha256)}`;
3671
+ const copyCanvasFontsInputSchema = z.object({
3672
+ canvasId: z.uuid(),
3673
+ sources: z.array(canvasFontAssetIdentitySchema).min(1)
3674
+ });
3675
+ const copyCanvasFontsOutputSchema = z.object({ resources: z.array(z.object({
3676
+ source: canvasFontAssetIdentitySchema,
3677
+ path: z.string()
3678
+ })) });
3679
+ const canvasFontAssetIdentityFromPath = (path) => {
3680
+ if (!path.startsWith("/v1/canvas-assets/")) return null;
3681
+ const [canvasId, kind, sha256, extra] = path.slice(CANVAS_ASSET_PATH_PREFIX.length).split("/", FONT_PATH_SEGMENT_LIMIT);
3682
+ if (kind !== "fonts" || extra !== void 0) return null;
3683
+ return canvasFontAssetIdentitySchema.safeParse({
3684
+ canvasId,
3685
+ sha256
3686
+ }).data ?? null;
3687
+ };
3688
+
3689
+ //#endregion
3690
+ //#region ../../packages/contract/src/canvas/canvas-asset-upload.schema.ts
3691
+ const MAX_FONT_WEIGHT = 1e3;
3692
+ const FONT_CONTENT_TYPES = new Set(CANVAS_FONT_CONTENT_TYPES);
3693
+ const isStoredContentType = (kind, contentType) => kind === "image" ? canvasStoredImageContentTypeSchema.safeParse(contentType).success : FONT_CONTENT_TYPES.has(contentType);
3694
+ const canvasAssetUploadIdentitySchema = z.strictObject({
3695
+ canvasId: z.uuid(),
3696
+ clientToken: z.uuid()
3697
+ });
3698
+ const reserveCanvasAssetInputSchema = z.discriminatedUnion("kind", [canvasAssetUploadIdentitySchema.extend({
3699
+ kind: z.literal("image"),
3700
+ contentType: z.enum(CANVAS_IMAGE_CONTENT_TYPES),
3701
+ bytes: z.number().int().positive(),
3702
+ sha256: z.string().regex(/^[a-f0-9]{64}$/u)
3703
+ }), canvasAssetUploadIdentitySchema.extend({
3704
+ kind: z.literal("font"),
3705
+ contentType: z.enum(CANVAS_FONT_CONTENT_TYPES),
3706
+ bytes: z.number().int().positive(),
3707
+ sha256: z.string().regex(/^[a-f0-9]{64}$/u)
3708
+ })]);
3709
+ const canvasAssetMetadataSchema = z.discriminatedUnion("kind", [z.strictObject({
3710
+ kind: z.literal("image"),
3711
+ width: z.number().int().positive(),
3712
+ height: z.number().int().positive()
3713
+ }), z.strictObject({
3714
+ kind: z.literal("font"),
3715
+ family: z.string().min(1),
3716
+ subfamily: z.string(),
3717
+ style: z.enum([
3718
+ "normal",
3719
+ "italic",
3720
+ "oblique"
3721
+ ]),
3722
+ minimumWeight: z.number().min(1).max(MAX_FONT_WEIGHT),
3723
+ maximumWeight: z.number().min(1).max(MAX_FONT_WEIGHT)
3724
+ }).refine((font) => font.minimumWeight <= font.maximumWeight, "Font weight bounds must be ordered.")]);
3725
+ const canvasAssetUploadOutputSchema = z.strictObject({
3726
+ canvasId: z.uuid(),
3727
+ clientToken: z.uuid(),
3728
+ assetId: z.uuid(),
3729
+ kind: z.enum(["image", "font"]),
3730
+ contentType: z.string(),
3731
+ bytes: z.number().int().positive(),
3732
+ sha256: z.string().regex(/^[a-f0-9]{64}$/u),
3733
+ path: z.string().startsWith("/v1/canvas-assets/"),
3734
+ state: z.enum(["awaiting_upload", "ready"]),
3735
+ metadata: canvasAssetMetadataSchema.nullable()
3736
+ }).refine((asset) => asset.state === "ready" === (asset.metadata !== null), "Readiness must match verified metadata.").refine((asset) => asset.metadata === null || asset.metadata.kind === asset.kind, "Metadata must describe the reserved asset kind.").refine((asset) => isStoredContentType(asset.kind, asset.contentType), "Content type must match the asset kind.").refine((asset) => asset.path === (asset.kind === "image" ? canvasImageAssetPath(asset.canvasId, asset.assetId) : canvasFontAssetPath(asset.canvasId, asset.sha256)), "The resource path must match its native identity.");
3737
+ const reserveCanvasAssetOutputSchema = canvasAssetUploadOutputSchema.safeExtend({ upload: signedUploadSchema.nullable() }).refine((asset) => asset.state === "awaiting_upload" === (asset.upload !== null), "Only pending uploads receive upload access.");
3738
+
3739
+ //#endregion
3740
+ //#region ../../packages/contract/src/canvas/canvas-css-values.lib.ts
3741
+ const UNITLESS_PROPERTIES = /* @__PURE__ */ new Set([
3742
+ "aspect-ratio",
3743
+ "-webkit-line-clamp",
3744
+ "line-clamp",
3745
+ "flex-grow",
3746
+ "flex-shrink",
3747
+ "font-weight",
3748
+ "opacity",
3749
+ "order",
3750
+ "z-index",
3751
+ "grid-area",
3752
+ "grid-row",
3753
+ "grid-column",
3754
+ "grid-row-start",
3755
+ "grid-row-end",
3756
+ "grid-column-start",
3757
+ "grid-column-end"
3758
+ ]);
3759
+ const canvasCssValue = (property, value) => typeof value === "number" && !UNITLESS_PROPERTIES.has(property.toLowerCase()) ? `${String(value)}px` : String(value);
3760
+ const SIDES$2 = [
3761
+ "top",
3762
+ "right",
3763
+ "bottom",
3764
+ "left"
3765
+ ];
3766
+ const LEFT_SIDE_INDEX = 3;
3767
+ const GRID_TEMPLATE_PROPERTIES = [
3768
+ "grid-template-rows",
3769
+ "grid-template-columns",
3770
+ "grid-template-areas"
3771
+ ];
3772
+ const SHORTHANDS = {
3773
+ gap: ["row-gap", "column-gap"],
3774
+ "text-wrap": ["text-wrap-mode", "text-wrap-style"],
3775
+ padding: SIDES$2.map((side) => `padding-${side}`),
3776
+ margin: SIDES$2.map((side) => `margin-${side}`),
3777
+ flex: [
3778
+ "flex-grow",
3779
+ "flex-shrink",
3780
+ "flex-basis"
3781
+ ],
3782
+ "flex-flow": ["flex-direction", "flex-wrap"],
3783
+ "place-content": ["align-content", "justify-content"],
3784
+ "place-items": ["align-items", "justify-items"],
3785
+ "place-self": ["align-self", "justify-self"],
3786
+ "grid-template": GRID_TEMPLATE_PROPERTIES,
3787
+ grid: [
3788
+ ...GRID_TEMPLATE_PROPERTIES,
3789
+ "grid-auto-rows",
3790
+ "grid-auto-columns",
3791
+ "grid-auto-flow"
3792
+ ],
3793
+ "grid-row": ["grid-row-start", "grid-row-end"],
3794
+ "grid-column": ["grid-column-start", "grid-column-end"],
3795
+ "grid-area": [
3796
+ "grid-row-start",
3797
+ "grid-column-start",
3798
+ "grid-row-end",
3799
+ "grid-column-end"
3800
+ ]
3801
+ };
3802
+ /** Related declarations stay authored; a longhand edit must not discard the rest of a shorthand. */
3803
+ const canvasCssPropertyScope = (property) => SHORTHANDS[property.toLowerCase()] ?? [property.toLowerCase()];
3804
+ const componentStateAfter = (state, character) => {
3805
+ if (state.isEscaped) return {
3806
+ ...state,
3807
+ isEscaped: false
3808
+ };
3809
+ if (character === "\\") return {
3810
+ ...state,
3811
+ isEscaped: true
3812
+ };
3813
+ if (state.quote !== "") return {
3814
+ ...state,
3815
+ quote: state.quote === character ? "" : state.quote
3816
+ };
3817
+ if (["\"", "'"].includes(character)) return {
3818
+ ...state,
3819
+ quote: character
3820
+ };
3821
+ const delta = [
3822
+ "(",
3823
+ "[",
3824
+ "{"
3825
+ ].includes(character) ? 1 : [
3826
+ ")",
3827
+ "]",
3828
+ "}"
3829
+ ].includes(character) ? -1 : 0;
3830
+ return {
3831
+ ...state,
3832
+ depth: state.depth + delta
3833
+ };
3834
+ };
3835
+ /** Split only at CSS component boundaries, keeping functions, line names and strings intact. */
3836
+ const canvasCssTokens = (value, separator = "space") => {
3837
+ const tokens = [];
3838
+ let token = "";
3839
+ let state = {
3840
+ depth: 0,
3841
+ quote: "",
3842
+ isEscaped: false
3843
+ };
3844
+ for (const character of value) {
3845
+ const canSplit = state.depth === 0 && state.quote === "" && !state.isEscaped;
3846
+ state = componentStateAfter(state, character);
3847
+ if (canSplit && (separator === "space" ? /\s/u.test(character) : character === separator)) {
3848
+ if (separator !== "space" || token !== "") tokens.push(token.trim());
3849
+ token = "";
3850
+ } else token += character;
3851
+ }
3852
+ if (separator !== "space" || token !== "") tokens.push(token.trim());
3853
+ return tokens;
3854
+ };
3855
+ const omittedGridLine = (value) => /^(?:--|-?[_a-z\u{80}-\u{FFFF}])[-\w\u{80}-\u{FFFF}]*$/iu.test(value) && !/^(?:auto|span|initial|unset)$/iu.test(value) ? value : "auto";
3856
+ const gridPlacementValue = (property, value, index) => {
3857
+ const parts = canvasCssTokens(value, "/");
3858
+ const first = parts[0] ?? value;
3859
+ if (property !== "grid-area") return parts[index] ?? omittedGridLine(first);
3860
+ const column = parts[1] ?? omittedGridLine(first);
3861
+ return [
3862
+ first,
3863
+ column,
3864
+ parts[2] ?? omittedGridLine(first),
3865
+ parts[3] ?? omittedGridLine(column)
3866
+ ][index] ?? value;
3867
+ };
3868
+ const implicitGridValues = (row, column, hasAutoRows) => {
3869
+ const tokens = canvasCssTokens(hasAutoRows ? row : column);
3870
+ const size = tokens.filter((token) => !/^(?:auto-flow|dense)$/iu.test(token)).join(" ");
3871
+ const flow = `${hasAutoRows ? "row" : "column"}${tokens.some((token) => /^dense$/iu.test(token)) ? " dense" : ""}`;
3872
+ return [
3873
+ hasAutoRows ? "none" : row,
3874
+ hasAutoRows ? column : "none",
3875
+ "none",
3876
+ hasAutoRows && size !== "" ? size : "auto",
3877
+ !hasAutoRows && size !== "" ? size : "auto",
3878
+ flow
3879
+ ];
3880
+ };
3881
+ const gridTemplateValue = (property, value, index) => {
3882
+ if (/^(?:none|initial|unset)$/iu.test(value)) return [
3883
+ "none",
3884
+ "none",
3885
+ "none",
3886
+ "auto",
3887
+ "auto",
3888
+ "row"
3889
+ ][index] ?? value;
3890
+ const parts = canvasCssTokens(value, "/");
3891
+ const row = parts[0] ?? value;
3892
+ const column = parts[1];
3893
+ if (row === "" || column === "" || parts.length > 2) return value;
3894
+ const hasAutoRows = canvasCssTokens(row).some((token) => token.toLowerCase() === "auto-flow");
3895
+ const hasAutoColumns = column !== void 0 && canvasCssTokens(column).some((token) => token.toLowerCase() === "auto-flow");
3896
+ if (property === "grid" && column !== void 0 && hasAutoRows !== hasAutoColumns) return implicitGridValues(row, column, hasAutoRows)[index] ?? value;
3897
+ if (hasAutoRows || hasAutoColumns) return value;
3898
+ const hasAreas = /["']/u.test(row);
3899
+ if (column === void 0 && !hasAreas) return value;
3900
+ return [
3901
+ hasAreas ? value : row,
3902
+ column ?? "none",
3903
+ hasAreas ? row : "none",
3904
+ "auto",
3905
+ "auto",
3906
+ "row"
3907
+ ][index] ?? value;
3908
+ };
3909
+ const flexValues = (tokens) => {
3910
+ const numbers = [];
3911
+ let basis = "0%";
3912
+ for (const token of tokens) if (/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(token) && numbers.length < 2) numbers.push(token);
3913
+ else basis = token;
3914
+ return [
3915
+ numbers[0] ?? "1",
3916
+ numbers[1] ?? "1",
3917
+ basis
3918
+ ];
3919
+ };
3920
+ const canvasCssShorthandValue = (property, value, index) => {
3921
+ if (/(?:var|env)\(|^(?:inherit|revert(?:-layer)?)$/iu.test(value)) return value;
3922
+ if (/^grid-(?:area|row|column)$/u.test(property)) return gridPlacementValue(property, value, index);
3923
+ if (property === "grid-template" || property === "grid") return gridTemplateValue(property, value, index);
3924
+ const tokens = canvasCssTokens(value);
3925
+ if (property === "text-wrap") return index === 0 ? tokens.find((token) => /^(?:wrap|nowrap)$/u.test(token)) ?? "wrap" : tokens.find((token) => /^(?:auto|balance|pretty|stable)$/u.test(token)) ?? "auto";
3926
+ if (property === "flex-flow") return index === 0 ? tokens.find((token) => /^(?:row|column)(?:-reverse)?$/u.test(token)) ?? "row" : tokens.find((token) => /^(?:nowrap|wrap|wrap-reverse)$/u.test(token)) ?? "nowrap";
3927
+ if (property === "flex") {
3928
+ if (value === "none") return [
3929
+ "0",
3930
+ "0",
3931
+ "auto"
3932
+ ][index] ?? value;
3933
+ if (value === "initial") return [
3934
+ "0",
3935
+ "1",
3936
+ "auto"
3937
+ ][index] ?? value;
3938
+ return flexValues(tokens)[index] ?? value;
3939
+ }
3940
+ return tokens[index] ?? (index === LEFT_SIDE_INDEX ? tokens[1] : void 0) ?? tokens[0] ?? value;
3941
+ };
3942
+
3943
+ //#endregion
3944
+ //#region ../../packages/contract/src/canvas/canvas-authored-css.lib.ts
3945
+ const canvasAdditionalStyleDeclarations = (node) => {
3946
+ if (node.additionalStyles === void 0) return {};
3947
+ return Object.fromEntries(node.additionalStyles.declarations.filter((declaration) => declaration.enabled).map((declaration) => [declaration.property, declaration.value]));
3948
+ };
3949
+ /** Additional-style controls exclusively own every property they expose, including when off. */
3950
+ const canvasAuthoredStyleDeclarations = (node) => {
3951
+ const controlledProperties = new Set(node.additionalStyles?.declarations.map((declaration) => declaration.property.toLowerCase()));
3952
+ return {
3953
+ ...Object.fromEntries(Object.entries(node.styles).filter(([property]) => !controlledProperties.has(property.toLowerCase()))),
3954
+ ...canvasAdditionalStyleDeclarations(node)
3955
+ };
3956
+ };
3957
+ const hasCanvasCssPriority = (value) => /!important\s*$/iu.test(String(value));
3958
+ const cssValue = (value, shouldPreserveCase) => {
3959
+ const source = String(value).replace(/\s*!important\s*$/iu, "").trim();
3960
+ return shouldPreserveCase || source.includes("(") ? source : source.toLowerCase();
3961
+ };
3962
+ const authoredLayoutValue = (node, property) => {
3963
+ let result = null;
3964
+ let isImportant = false;
3965
+ const declarations = Object.entries(canvasAuthoredStyleDeclarations(node));
3966
+ for (const [key, raw] of declarations) {
3967
+ const scope = canvasCssPropertyScope(key);
3968
+ const index = scope.indexOf(property);
3969
+ if (index === -1) continue;
3970
+ const isPriority = hasCanvasCssPriority(raw);
3971
+ if (isImportant && !isPriority) continue;
3972
+ const value = cssValue(raw, /^grid(?:-|$)/iu.test(key));
3973
+ result = scope.length === 1 ? value : canvasCssShorthandValue(key.toLowerCase(), value, index);
3974
+ isImportant = isPriority;
3975
+ }
3976
+ return result ?? void 0;
3977
+ };
3978
+ /**
3979
+ * Edits replace a node's style objects rather than changing them, so their identity keys the values
3980
+ * already read. Rendering a large document reads each property of each node many times.
3981
+ */
3982
+ const readAuthoredValues = /* @__PURE__ */ new WeakMap();
3983
+ /** Read supported authored longhands without measuring or rewriting unresolved CSS expressions. */
3984
+ const canvasAuthoredLayoutValueOf = (node, property) => {
3985
+ const known = readAuthoredValues.get(node.styles);
3986
+ const read = known !== void 0 && known.additionalStyles === node.additionalStyles ? known : {
3987
+ additionalStyles: node.additionalStyles,
3988
+ values: /* @__PURE__ */ new Map()
3989
+ };
3990
+ if (read !== known) readAuthoredValues.set(node.styles, read);
3991
+ if (read.values.has(property)) return read.values.get(property);
3992
+ const value = authoredLayoutValue(node, property);
3993
+ read.values.set(property, value);
3994
+ return value;
3995
+ };
3996
+ const canvasCssPixelValue = (value) => {
3997
+ if (value === void 0) return;
3998
+ return /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:px)?$/u.test(value) ? Number(value.replace("px", "")) : void 0;
3999
+ };
4000
+ /** Named controls override only their own longhand, even beside an important shorthand. */
4001
+ const canvasLayoutPriorityDeclarations = (node, declarations) => {
4002
+ const important = new Set(Object.entries(canvasAuthoredStyleDeclarations(node)).filter(([, value]) => hasCanvasCssPriority(value)).flatMap(([property]) => canvasCssPropertyScope(property)));
4003
+ return Object.fromEntries(Object.entries(declarations).map(([property, value]) => [property, canvasCssPropertyScope(property).some((owned) => important.has(owned)) && !hasCanvasCssPriority(value) ? `${canvasCssValue(property, value)} !important` : value]));
4004
+ };
4005
+ const canvasWritingModeOf = (node, document) => {
4006
+ const visited = /* @__PURE__ */ new Set();
4007
+ let current = node;
4008
+ while (current !== void 0 && !visited.has(current.id)) {
4009
+ visited.add(current.id);
4010
+ const value = canvasAuthoredLayoutValueOf(current, "writing-mode");
4011
+ if (value !== void 0 && value !== "inherit" && value !== "unset") return value;
4012
+ if (document === void 0) break;
4013
+ const parentId = document.relationships[current.id]?.parentId;
4014
+ if (parentId === void 0) break;
4015
+ current = document.nodes[parentId];
4016
+ }
4017
+ return "horizontal-tb";
4018
+ };
4019
+ const canvasAxisStyleProperties = (node, axis, document) => {
4020
+ const isVerticalWriting = /^(?:vertical|sideways)-/u.test(canvasWritingModeOf(node, document));
4021
+ return [axis === "horizontal" ? "width" : "height", axis === "vertical" === isVerticalWriting ? "inline-size" : "block-size"];
4022
+ };
4023
+ const canvasLayoutPositionOf = (node) => {
4024
+ const position = canvasAuthoredLayoutValueOf(node, "position");
4025
+ return node.layout?.position ?? (position === "absolute" || position === "fixed" || position === void 0 && node.box !== void 0 ? "absolute" : "flow");
4026
+ };
4027
+ /** Authored display wins over legacy presets; Grid has no Flex main axis. */
4028
+ const canvasLayoutFlowOf = (node) => {
4029
+ if (node === void 0) return "freeform";
4030
+ const display = canvasAuthoredLayoutValueOf(node, "display");
4031
+ if (display !== void 0) {
4032
+ if (/^(?:(?:inline|block)\s+|inline-)?grid$/u.test(display)) return "grid";
4033
+ if (/^(?:(?:inline|block)\s+|inline-)?flex$/u.test(display)) return "flex";
4034
+ return "freeform";
4035
+ }
4036
+ const container = node.layout?.container;
4037
+ if (container === void 0) return "freeform";
4038
+ return container.gridColumns !== void 0 || container.gridAutoRepeat !== void 0 ? "grid" : "flex";
4039
+ };
4040
+ /** Read a Flex main axis in its inherited writing mode without persisting a preset. */
4041
+ const canvasLayoutMainAxisOf = (node, document) => {
4042
+ if (node === void 0) return void 0;
4043
+ if (canvasLayoutFlowOf(node) !== "flex") return void 0;
4044
+ const container = node.layout?.container;
4045
+ const css = (property) => canvasAuthoredLayoutValueOf(node, property);
4046
+ const direction = container?.direction ?? css("flex-direction") ?? "row";
4047
+ if (!/^(?:row|column)(?:-reverse)?$/u.test(direction)) return void 0;
4048
+ const isVerticalWriting = /^(?:vertical|sideways)-/u.test(canvasWritingModeOf(node, document));
4049
+ return direction.startsWith("column") === isVerticalWriting ? "horizontal" : "vertical";
4050
+ };
4051
+
4052
+ //#endregion
4053
+ //#region ../../packages/contract/src/canvas/canvas-box-source.lib.ts
4054
+ const INSETS = [
4055
+ "left",
4056
+ "right",
4057
+ "top",
4058
+ "bottom",
4059
+ "inset",
4060
+ "inset-inline",
4061
+ "inset-inline-start",
4062
+ "inset-inline-end",
4063
+ "inset-block",
4064
+ "inset-block-start",
4065
+ "inset-block-end"
4066
+ ];
4067
+ const TRANSFORMS = [
4068
+ "transform",
4069
+ "translate",
4070
+ "rotate",
4071
+ "scale"
4072
+ ];
4073
+ const GROUP_TRANSFORM = "--enhance-group-affine-residual";
4074
+ const CANVAS_RECORDED_BOX_NOTE = "A box whose boxSource is \"recorded\" is a size kept from when the layer was made: the browser lays that layer out, so the box is not where it is drawn. `enhance canvas render` shows what is on screen.";
4075
+ const isSet = (value) => value !== void 0 && value !== "" && value !== "none";
4076
+ const hasOwnTransform = (node, authored) => TRANSFORMS.some((property) => isSet(authored[property])) || (node.layout?.rotation ?? 0) !== 0 || node.layout?.flipHorizontal === true || node.layout?.flipVertical === true || Object.keys(authored).some((property) => property.toLowerCase() === GROUP_TRANSFORM);
4077
+ /**
4078
+ * The canvas draws a layer at its box only when it positions the layer absolutely and the layer
4079
+ * names no inset of its own; an inset on either axis takes that axis from the box. This is the
4080
+ * test the style projection makes before it writes `left` and `top` from the box, and a layer
4081
+ * with no box has no source.
4082
+ */
4083
+ const canvasBoxSourceOf = (node) => {
4084
+ if (node.box === void 0) return void 0;
4085
+ const authored = canvasAuthoredStyleDeclarations(node);
4086
+ if (!(canvasLayoutPositionOf(node) === "absolute" && INSETS.every((property) => authored[property] === void 0))) return "recorded";
4087
+ return hasOwnTransform(node, authored) ? "placed-before-transform" : "placed";
4088
+ };
4089
+ /** One line for a whole read, however many of its boxes are recorded. */
4090
+ const canvasRecordedBoxNoteFor = (boxes) => boxes.some((box) => box.boxSource === "recorded") ? { boxNote: CANVAS_RECORDED_BOX_NOTE } : {};
4091
+
3720
4092
  //#endregion
3721
4093
  //#region ../../packages/contract/src/canvas/canvas-document.schema.ts
3722
4094
  /** Reads retain unsupported documents; the write boundary validates the current scene format. */
@@ -3984,98 +4356,6 @@ const textLinksOf = (node) => {
3984
4356
  return nonOverlapping;
3985
4357
  };
3986
4358
 
3987
- //#endregion
3988
- //#region ../../packages/contract/src/canvas/canvas-property-section.schema.ts
3989
- const CANVAS_PROPERTY_SECTIONS = [
3990
- "position",
3991
- "layout",
3992
- "clip",
3993
- "cornerRadius",
3994
- "blending",
3995
- "typography",
3996
- "nativeControl",
3997
- "textDecoration",
3998
- "fill",
3999
- "outline",
4000
- "textStroke",
4001
- "border",
4002
- "outerShadow",
4003
- "innerShadow",
4004
- "filters",
4005
- "additionalStyles",
4006
- "vector",
4007
- "export",
4008
- "source"
4009
- ];
4010
- const canvasPropertySectionSchema = z.enum(CANVAS_PROPERTY_SECTIONS);
4011
-
4012
- //#endregion
4013
- //#region ../../packages/contract/src/canvas/canvas-inspection.schema.ts
4014
- const MAX_RENDER_MESSAGE_LENGTH = 500;
4015
- const MAX_RENDER_KIND_LENGTH = 100;
4016
- /**
4017
- * What a layer's box is: `placed` where the canvas draws the layer, `placed-before-transform` where
4018
- * it draws the layer before the layer's own transform, `recorded` a size kept from when the layer
4019
- * was made, for a layer the browser lays out.
4020
- */
4021
- const canvasBoxSourceSchema = z.enum([
4022
- "placed",
4023
- "placed-before-transform",
4024
- "recorded"
4025
- ]);
4026
- /** Present only on a read that holds a `recorded` box. */
4027
- const boxNoteSchema = z.string().min(1).optional();
4028
- const canvasInspectNodeSummarySchema = z.object({
4029
- id: z.string().min(1),
4030
- label: z.string().max(MAX_RENDER_MESSAGE_LENGTH),
4031
- kind: z.string().min(1).max(MAX_RENDER_KIND_LENGTH),
4032
- parentId: z.string().min(1).nullable(),
4033
- childCount: z.number().int().min(0),
4034
- box: canvasSceneBoxSchema.nullable(),
4035
- boxSource: canvasBoxSourceSchema.optional(),
4036
- propertySections: z.array(canvasPropertySectionSchema)
4037
- });
4038
- const inspectCanvasInputSchema = z.object({ canvasId: z.uuid() });
4039
- const inspectCanvasOutputSchema = z.object({
4040
- canvasId: z.uuid(),
4041
- openUrl: z.url(),
4042
- title: z.string().min(1),
4043
- version: z.number().int().positive(),
4044
- nodeCount: z.number().int().min(0),
4045
- rootChildCount: z.number().int().min(0),
4046
- bounds: canvasSceneBoxSchema.nullable(),
4047
- kinds: z.record(z.string(), z.number().int().min(0)),
4048
- boxNote: boxNoteSchema,
4049
- next: z.array(z.string().min(1))
4050
- });
4051
- const inspectCanvasTreeInputSchema = z.object({ canvasId: z.uuid() });
4052
- const inspectCanvasTreeOutputSchema = z.object({
4053
- canvasId: z.uuid(),
4054
- version: z.number().int().positive(),
4055
- nodes: z.array(canvasInspectNodeSummarySchema),
4056
- boxNote: boxNoteSchema
4057
- });
4058
- const inspectCanvasNodeInputSchema = z.object({
4059
- canvasId: z.uuid(),
4060
- nodeId: z.string().min(1)
4061
- });
4062
- const inspectCanvasNodeOutputSchema = z.object({
4063
- canvasId: z.uuid(),
4064
- version: z.number().int().positive(),
4065
- node: canvasInspectNodeSummarySchema.extend({
4066
- styles: z.record(z.string(), z.union([z.string(), z.number()])),
4067
- layout: canvasNodeLayoutSchema.optional(),
4068
- appearance: canvasAppearanceValuesSchema.optional(),
4069
- geometry: canvasGeometrySchema.optional(),
4070
- typography: canvasAuthoredTypographySchema.optional(),
4071
- additionalStyles: canvasAdditionalStylesSchema.optional(),
4072
- props: z.record(z.string(), z.unknown()),
4073
- children: z.array(z.string().min(1))
4074
- }),
4075
- boxNote: boxNoteSchema,
4076
- next: z.array(z.string().min(1))
4077
- });
4078
-
4079
4359
  //#endregion
4080
4360
  //#region ../../packages/contract/src/canvas/canvas-layout-ownership.lib.ts
4081
4361
  const CANVAS_LAYOUT_CSS_FIELDS = [
@@ -4185,99 +4465,6 @@ const canvasLayoutWithoutCssProperties = (held, changed, axes) => {
4185
4465
  return layout;
4186
4466
  };
4187
4467
 
4188
- //#endregion
4189
- //#region ../../packages/contract/src/canvas/canvas-operation-writes.schema.ts
4190
- /**
4191
- * What each operation writes. `names` sets one plain value, places, removes, or merges a patch, so
4192
- * values its client never knew stay as stored. `whole` brings a whole layer or replaces a whole
4193
- * group of values, which a client that read the canvas in an older format may have stripped.
4194
- */
4195
- const CANVAS_OPERATION_WRITES = {
4196
- insertConvertedSubtree: "whole",
4197
- insertNode: "whole",
4198
- insertText: "names",
4199
- insertPrototype: "names",
4200
- setPrototypeDeployment: "names",
4201
- editText: "names",
4202
- setText: "names",
4203
- setBox: "names",
4204
- setLabel: "names",
4205
- setContainerKind: "names",
4206
- setVisibility: "names",
4207
- setLocked: "names",
4208
- setConstraints: "names",
4209
- setStyles: "names",
4210
- patchExportSettings: "names",
4211
- setAppearance: "names",
4212
- setLayout: "whole",
4213
- patchTypography: "names",
4214
- setTypography: "whole",
4215
- patchAdditionalStyles: "names",
4216
- setAdditionalStyles: "whole",
4217
- setArtworkColor: "whole",
4218
- setTextStyleLibrary: "whole",
4219
- patchFontLibrary: "names",
4220
- setTextStyle: "whole",
4221
- setGeometry: "whole",
4222
- setProps: "whole",
4223
- setParentage: "names",
4224
- move: "names",
4225
- remove: "names"
4226
- };
4227
-
4228
- //#endregion
4229
- //#region ../../packages/contract/src/canvas/canvas-mutation.schema.ts
4230
- const nodeIdSchema$2 = canvasSceneNodeSchema.shape.id;
4231
- const writableBoxSchema = canvasSceneBoxSchema.extend({
4232
- width: z.number().positive(),
4233
- height: z.number().positive()
4234
- });
4235
- const copiedNodeIdsSchema = z.record(nodeIdSchema$2, nodeIdSchema$2);
4236
- /** A receipt stored before boxes said what they are holds none, so the source stays optional. */
4237
- const canvasReceiptBoxSchema = canvasSceneBoxSchema.extend({ boxSource: canvasBoxSourceSchema.optional() });
4238
- const canvasMutationRequestContextSchema = z.strictObject({
4239
- fingerprint: z.string().regex(/^[a-f0-9]{64}$/u),
4240
- revisionPolicy: z.enum(["strict", "rebase"]),
4241
- copiedNodeIds: copiedNodeIdsSchema.optional()
4242
- });
4243
- /** The request's fields alone, for callers that derive their own input from it. */
4244
- const applyCanvasOperationsFieldsSchema = z.object({
4245
- canvasId: z.uuid(),
4246
- mutationId: z.uuid(),
4247
- documentFormatVersion: canvasDocumentFormatSchema,
4248
- baseVersion: z.number().int().positive(),
4249
- operations: z.array(canvasOperationSchema).min(1),
4250
- requestContext: canvasMutationRequestContextSchema.optional(),
4251
- writeScope: canvasWriteScopeSchema.optional()
4252
- });
4253
- const applyCanvasOperationsInputSchema = applyCanvasOperationsFieldsSchema.superRefine((input, context) => {
4254
- refuseUnsafeWriterFormat(input.documentFormatVersion, input.operations.every((operation) => CANVAS_OPERATION_WRITES[operation.op] === "names") ? "names" : "whole", context);
4255
- });
4256
- const applyCanvasOperationsOutputSchema = z.object({
4257
- canvasId: z.uuid(),
4258
- mutationId: z.uuid(),
4259
- previousVersion: z.number().int().positive(),
4260
- version: z.number().int().positive(),
4261
- operations: z.array(canvasOperationSchema),
4262
- insertedNodeIds: z.array(nodeIdSchema$2),
4263
- changedNodeIds: z.array(nodeIdSchema$2),
4264
- removedNodeIds: z.array(nodeIdSchema$2),
4265
- boxes: z.record(nodeIdSchema$2, canvasReceiptBoxSchema),
4266
- affectedBounds: writableBoxSchema.nullable(),
4267
- copiedNodeIds: copiedNodeIdsSchema.optional(),
4268
- next: z.array(z.string().min(1))
4269
- });
4270
- const getCanvasMutationInputSchema = z.strictObject({
4271
- canvasId: z.uuid(),
4272
- mutationId: z.uuid(),
4273
- fingerprint: canvasMutationRequestContextSchema.shape.fingerprint
4274
- });
4275
- const getCanvasMutationOutputSchema = z.discriminatedUnion("state", [z.strictObject({ state: z.literal("not-found") }), z.strictObject({
4276
- state: z.literal("committed"),
4277
- /** `url` is the canvas's web address. An API older than the field answers without it. */
4278
- result: applyCanvasOperationsOutputSchema.extend({ url: z.url().optional() })
4279
- })]);
4280
-
4281
4468
  //#endregion
4282
4469
  //#region ../../packages/contract/src/canvas/canvas-mutation-review.schema.ts
4283
4470
  const LIMITS = {
@@ -4676,7 +4863,9 @@ const canvasDuplicatePreparationSchema = z.strictObject({
4676
4863
  destination: z.discriminatedUnion("kind", [z.strictObject({ kind: z.literal("native") }), z.strictObject({
4677
4864
  kind: z.literal("inside"),
4678
4865
  parentId: nodeId$5
4679
- })])
4866
+ })]),
4867
+ /** World placement for a set of top-level copies. Absent, the native copy offset stands. */
4868
+ placement: canvasPlacementIntentSchema.optional()
4680
4869
  });
4681
4870
  const canvasPreparationRequestSchema = z.discriminatedUnion("kind", [
4682
4871
  z.strictObject({
@@ -4997,14 +5186,11 @@ const beginCanvasActivityInputSchema = z.object({
4997
5186
  const beginCanvasActivityOutputSchema = z.object({
4998
5187
  activityId: z.uuid(),
4999
5188
  expiresAt: z.iso.datetime(),
5000
- renewAfterMs: z.number().int().positive()
5189
+ renewAfterMs: z.number().int().positive(),
5190
+ /** The layers the mark names after this call: a start keeps the ones a live mark had. */
5191
+ nodeIds: z.array(z.string().min(1)).max(MAX_ACTIVITY_TARGETS).optional()
5001
5192
  });
5002
5193
  const renewCanvasActivityInputSchema = beginCanvasActivityInputSchema.extend({ activityId: z.uuid() });
5003
- const endCanvasActivityInputSchema = z.object({
5004
- canvasId: z.uuid(),
5005
- activityId: z.uuid()
5006
- });
5007
- const endCanvasActivityOutputSchema = z.object({ ended: z.literal(true) });
5008
5194
  const serverEnvelopeBase = {
5009
5195
  v: z.literal(1),
5010
5196
  seq: z.number().int().nonnegative()
@@ -5427,6 +5613,10 @@ const claimRenderWorkOutputSchema = z.discriminatedUnion("purpose", [
5427
5613
  outputPrefix: z.string().min(1).max(MAX_STORAGE_KEY_LENGTH)
5428
5614
  })
5429
5615
  ]);
5616
+ const snapshotPlacementSchema = z.object({
5617
+ x: z.number(),
5618
+ y: z.number()
5619
+ });
5430
5620
  const completeRenderWorkInputSchema = z.object({
5431
5621
  jobId: z.uuid(),
5432
5622
  loadedVersion: z.number().int().positive(),
@@ -5447,14 +5637,18 @@ const completeRenderWorkInputSchema = z.object({
5447
5637
  viewport: z.object({
5448
5638
  width: z.number().int().positive(),
5449
5639
  height: z.number().int().positive()
5450
- })
5640
+ }),
5641
+ /** Where the page's search put the captured screen, at `loadedVersion`. */
5642
+ placement: snapshotPlacementSchema.optional()
5451
5643
  }).optional()
5452
5644
  });
5453
5645
  const completeRenderWorkOutputSchema = z.object({ accepted: z.literal(true) });
5454
5646
  const completeConversionWorkInputSchema = z.object({
5455
5647
  jobId: z.uuid(),
5456
5648
  loadedVersion: z.number().int().positive(),
5457
- draft: canvasSubtreeDraftSchema
5649
+ draft: canvasSubtreeDraftSchema,
5650
+ /** The root's measured place at `loadedVersion`, for a request that asked to be placed. */
5651
+ placement: canvasSceneBoxSchema.optional()
5458
5652
  });
5459
5653
  const completeConversionWorkOutputSchema = z.object({ accepted: z.literal(true) });
5460
5654
  const renderRouteSnapshotSchema = z.object({
@@ -5467,7 +5661,9 @@ const renderRouteSnapshotSchema = z.object({
5467
5661
  viewport: z.object({
5468
5662
  width: z.number().int().positive(),
5469
5663
  height: z.number().int().positive()
5470
- })
5664
+ }),
5665
+ /** Where the editor's search for a capture below this recording puts the screen. */
5666
+ placement: snapshotPlacementSchema.optional()
5471
5667
  });
5472
5668
  const failRenderWorkInputSchema = z.object({
5473
5669
  jobId: z.uuid(),
@@ -7594,7 +7790,11 @@ const desktopRequestSchema = z.object({
7594
7790
  const desktopMutationIntentSchema = z.object({
7595
7791
  mutationId: id$2,
7596
7792
  canvasId: id$2,
7597
- procedure: z.enum(["canvas.applyOperations", "canvas.render.importSource"]),
7793
+ procedure: z.enum([
7794
+ "canvas.applyOperations",
7795
+ "canvas.render.importSource",
7796
+ "canvas.applyEdits"
7797
+ ]),
7598
7798
  input: z.record(z.string(), z.unknown()),
7599
7799
  state: z.enum([
7600
7800
  "recorded",
@@ -8246,7 +8446,9 @@ const createAgentTokenOutputSchema = z.object({
8246
8446
  const listAgentTokensInputSchema = z.object({});
8247
8447
  const listAgentTokensOutputSchema = z.object({
8248
8448
  items: z.array(agentTokenSchema),
8249
- isConnected: z.boolean()
8449
+ isConnected: z.boolean(),
8450
+ /** True once any agent credential of this person was ever used, even if all are now revoked. */
8451
+ hasEverConnected: z.boolean()
8250
8452
  });
8251
8453
  const revokeAgentTokenInputSchema = z.object({ tokenId: z.uuid() });
8252
8454
  const revokeAgentTokenOutputSchema = z.object({
@@ -8265,6 +8467,49 @@ const cliAuthConfigurationSchema = z.discriminatedUnion("method", [z.object({ me
8265
8467
  scope: z.literal(CLI_AUTH_SCOPE)
8266
8468
  })]);
8267
8469
 
8470
+ //#endregion
8471
+ //#region ../../packages/contract/src/person/onboarding.schema.ts
8472
+ /** The four contextual canvas hints, in the order the canvas offers them. */
8473
+ const ONBOARDING_STEP_IDS = [
8474
+ "connect_agent",
8475
+ "first_agent_work",
8476
+ "comment",
8477
+ "share_comments"
8478
+ ];
8479
+ const onboardingStepIdSchema = z.enum(ONBOARDING_STEP_IDS);
8480
+ /** One person's preferences for one hint. `isSnoozed` is worked out with the API's clock. */
8481
+ const onboardingStepStateSchema = z.object({
8482
+ isAcknowledged: z.boolean(),
8483
+ maybeLaterCount: z.number().int().min(0),
8484
+ snoozedUntil: z.iso.datetime().nullable(),
8485
+ isSnoozed: z.boolean(),
8486
+ isStopped: z.boolean(),
8487
+ automaticShowCount: z.number().int().min(0),
8488
+ lastPresentationId: z.uuid().nullable()
8489
+ });
8490
+ const onboardingInputSchema = z.strictObject({});
8491
+ const onboardingOutputSchema = z.object({
8492
+ hasCommented: z.boolean(),
8493
+ hasCopiedCanvasLink: z.boolean(),
8494
+ steps: z.object({
8495
+ connect_agent: onboardingStepStateSchema,
8496
+ first_agent_work: onboardingStepStateSchema,
8497
+ comment: onboardingStepStateSchema,
8498
+ share_comments: onboardingStepStateSchema
8499
+ })
8500
+ });
8501
+ const dismissOnboardingStepInputSchema = z.strictObject({
8502
+ stepId: onboardingStepIdSchema,
8503
+ choice: z.enum(["got_it", "maybe_later"])
8504
+ });
8505
+ const presentOnboardingStepInputSchema = z.strictObject({
8506
+ stepId: onboardingStepIdSchema,
8507
+ presentationId: z.uuid()
8508
+ });
8509
+ const presentOnboardingStepOutputSchema = z.object({ automaticShowNumber: z.number().int().min(1) });
8510
+ const recordCanvasLinkCopiedInputSchema = z.strictObject({});
8511
+ const recordCanvasLinkCopiedOutputSchema = z.object({ hasCopiedCanvasLink: z.literal(true) });
8512
+
8268
8513
  //#endregion
8269
8514
  //#region ../../packages/contract/src/person/person.schema.ts
8270
8515
  const personSchema = z.object({
@@ -10520,15 +10765,6 @@ var CliError = class extends Error {
10520
10765
  */
10521
10766
  const isFormatRefusalError = (error) => error instanceof CliError && error.fields?.["documentFormatVersion"] !== void 0;
10522
10767
 
10523
- //#endregion
10524
- //#region src/application/partial-batch.error.ts
10525
- var PartialBatchError = class extends CliError {
10526
- constructor(message, remediation, details) {
10527
- super(details?.code ?? "INTERNAL", message, remediation, details?.fields);
10528
- this.name = "PartialBatchError";
10529
- }
10530
- };
10531
-
10532
10768
  //#endregion
10533
10769
  //#region src/application/skill-texts.use-case.ts
10534
10770
  /** The skills, by the short name each has before a surface names it. */
@@ -10561,17 +10797,100 @@ const wordsOf = (skill, wording) => {
10561
10797
  command: isTool ? wording.command : ""
10562
10798
  };
10563
10799
  };
10800
+ /**
10801
+ * Each design rule that a tool repeats where it applies, one sentence each. The guide, the
10802
+ * start-up list and the tools hold the same sentence, so the surfaces cannot drift apart; no
10803
+ * sentence names a command or a tool, so it reads the same on every surface.
10804
+ */
10805
+ const DESIGN_RULES = {
10806
+ look: "Read the canvas outline first: its screens, their widths, and what the person has selected.",
10807
+ brief: "Before the first write, tell the person your design brief in a few lines: the moods you considered and the one you chose, five or six colours with their roles, the type, and the direction in one line.",
10808
+ fonts: "Use the canvas's fonts or import one; put an @font-face whose src is the path the import returned in each write that uses it, since the family name alone draws a fallback. If you cannot, use the closest, say so, and go on.",
10809
+ units: "Set font sizes and line heights in px, and letter spacing in em.",
10810
+ sizes: "Start a new screen at 1440 by 900 for desktop, 768 by 1024 for tablet or 390 by 844 for mobile, unless the brief or the product says otherwise; the height is only a starting point.",
10811
+ group: "Write one visual group per call, about 15 lines of HTML, so the screen grows in view.",
10812
+ html: "Write inline styles with flex, padding and gap, and a layer-name attribute on each element, since other name attributes are dropped; set the font family on each group, since a group does not take it from the layer it goes into. No margins, grids or tables.",
10813
+ rows: "In repeated rows, give icons, values and trailing actions a fixed width, and keep the slot when a row has nothing in it.",
10814
+ review: "After each section, get a picture of the screen, check it against the review list, and tell the person one line that starts with \"Review:\".",
10815
+ scale: "Use scale 1 for layout; use 2 only to read small text.",
10816
+ fit: "When a frame cuts its content off, set its height to fit its content with the style \"height\": \"hug\"; never guess a new fixed height.",
10817
+ fix: "Fix what a picture shows with small edits, not by rebuilding the screen: starting again throws away work the person has watched, and content that overflows is never a reason to delete a frame.",
10818
+ ids: "Never show layer ids to the person; name screens and layers by what they are.",
10819
+ finish: "When you have finished, call finish, naming the screens or none; if refused, go on.",
10820
+ code: "For code, read exact values from the design, never from a picture."
10821
+ };
10564
10822
  /** The heading over a skill's list: the tool has commands, and the plugin has tools. */
10565
10823
  const listHeading = ({ two }) => two({
10566
10824
  cli: "## Commands",
10567
10825
  mcp: "## Tools"
10568
10826
  });
10569
10827
  /**
10828
+ * The design skill's rules, after its list of commands or tools: how to look first, the brief,
10829
+ * the look of a screen with no product to follow, how to write, review and finish.
10830
+ */
10831
+ const designSections = (words) => `## Start by looking
10832
+
10833
+ ${DESIGN_RULES.look}
10834
+
10835
+ A change to an existing screen keeps that screen's look. A new screen on a canvas that holds a product's screens follows those screens first: their fonts, sizes, colours, spacing and corner radii. The rules for the look below are for a screen with no product to follow.
10836
+
10837
+ ## Tell the person your brief
10838
+
10839
+ ${DESIGN_RULES.brief} Skip it only when the brief or the product already fixes the design.
10840
+
10841
+ - Moods: name three or four mood words, and choose one that is not the first that came to mind. Say in a few words why it fits better.
10842
+ - Colours: picture a scene for that mood, and take each colour from an object in it. Pure white is the usual ground, and one strong colour carries the screen.
10843
+ - Type: a display face and a text face, with their sizes.
10844
+ - Direction: one line on the layout idea.
10845
+
10846
+ ## Decide the look
10847
+
10848
+ - Few elements, each doing work. Make the thing that matters most much bigger than the rest; a page of equal cards has no first read.
10849
+ - Pair heavy display type with light, small labels, as an editorial page does. Use three type sizes, far apart.
10850
+ - Vary the spacing: tight inside a group, generous between groups. Prefer an asymmetric layout to a centred one when the content allows.
10851
+ - Put content straight on the page. Add a card, border or shadow only to show grouping or something clickable, and leave out dated gradients and heavy shadows.
10852
+ - Light mode unless asked. No text under 13px, and text under 16px at 4.5:1 contrast or more.
10853
+ - A product screen should be clear at a glance. Brand and marketing work should impress, and can be playful. When the brief is vague, aim to impress.
10854
+ - Real words and numbers of realistic length. SVG for icons, not emoji.
10855
+ - Asked for several directions, change the layout or the idea, not only the colours, and keep the content the same.
10856
+
10857
+ ## Fonts, units and sizes
10858
+
10859
+ - ${DESIGN_RULES.fonts} ${DESIGN_RULES.units}
10860
+ - ${DESIGN_RULES.sizes}
10861
+ - A mobile screen starts with the status bar of the guide's \`mobile-status-bar\` topic, pasted as its first child; never draw one by hand.
10862
+
10863
+ ## Write a group at a time
10864
+
10865
+ - ${DESIGN_RULES.group}
10866
+ - ${DESIGN_RULES.html}
10867
+ - For repeated rows, write the container together with its first row, then copy that row with ${words.call("canvas.edit")} and change its text, rather than write the same HTML again. Read the copy's layers for their ids; never guess an id.
10868
+ - ${DESIGN_RULES.rows} After three similar rows, look at a picture and check that the slots line up down the page.
10869
+ - To restructure, move layers with ${words.call("canvas.edit")}; never delete a layer and write it again.
10870
+
10871
+ ## Look at what you made
10872
+
10873
+ ${DESIGN_RULES.review} ${DESIGN_RULES.scale} For more detail, get a picture of a smaller layer. The review list, in order:
10874
+
10875
+ 1. Spacing: is it even where it should be even, tight in groups and generous between them?
10876
+ 2. Type: are there few sizes, far apart, and none under 13px?
10877
+ 3. Contrast: can all text be read against its ground, at 4.5:1 or more under 16px?
10878
+ 4. Alignment: do edges and repeated rows line up down the page?
10879
+ 5. Fit: is anything cut off or overflowing its frame?
10880
+ 6. Repetition: do repeated items match one another, with no stray one?
10881
+ 7. Is everything that was asked for there?
10882
+
10883
+ ${DESIGN_RULES.fix} ${DESIGN_RULES.fit} Then look again.
10884
+
10885
+ ## When you have finished
10886
+
10887
+ ${DESIGN_RULES.finish} Then give the canvas link. ${DESIGN_RULES.ids}
10888
+ `;
10889
+ /**
10570
10890
  * Each skill states its goal and names what the surface offers for it; the commands' own help
10571
10891
  * and the tools' own descriptions teach the rest. A line is added only when measured runs are
10572
- * worse without it; `skill-evaluation` holds the cases and what the last runs found. The design
10573
- * skill's small-edit line and its two sections on the look of a screen were added without runs,
10574
- * and the record marks each as not measured.
10892
+ * worse without it; `skill-evaluation` holds the cases and what the last runs found, line group
10893
+ * by line group, for the design skill's rules too.
10575
10894
  */
10576
10895
  const SKILLS = {
10577
10896
  capture: {
@@ -10610,37 +10929,16 @@ ${listHeading(words)}
10610
10929
  cli: `\`${words.command} canvas create --title "<what this is>"\``,
10611
10930
  mcp: `${call("canvas.create")} with a \`title\``
10612
10931
  })} makes a canvas and answers with its id and its link.
10613
- - ${learn("canvas.read", "read what a canvas holds: its outline, or one screen as HTML")}
10614
- - ${learn("canvas.insertHtml", "add a screen as HTML, with an example")} Read it before the first insert.
10615
- - ${learn("canvas.edit", "change text, styles, names and order on layers that are already there, and copy a layer, many in one call")} Use it for any change to existing work.
10616
- - ${learn("canvas.updateHtml", "rebuild the inside of a layer")} Use it only when the structure itself changes.
10617
- - ${learn("canvas.importAsset", "bring in an image or a font")}
10618
- - ${learn("canvas.render", "get a picture of a screen")}
10619
-
10620
- ## Decide the look before the markup
10621
-
10622
- A change to an existing screen keeps that screen's look. A new screen on a canvas that holds a product's screens takes their fonts, sizes, colours, spacing and corner radii. With no product to follow:
10623
-
10624
- - White background, near-black text and one accent colour, used for the main action and little else, unless the brief asks otherwise.
10625
- - Three type sizes, far apart: one large, one body, one small. No text under 13px, and body text at 4.5:1 contrast or more.
10626
- - Make the thing that matters most much bigger than the rest. A page of equal cards has no first read.
10627
- - Put content straight on the page and separate it with space: tight inside a group, generous between groups. Add a card, border or shadow only to show grouping or something clickable.
10628
- - Real words and numbers of realistic length. SVG for icons, not emoji.
10629
- - In repeated rows, give icons, values and trailing actions a fixed width, and keep the slot when a row has nothing in it.
10630
- - Asked for several directions, change the layout or the idea, not only the accent colour, and keep the content the same.
10631
-
10632
- ## Look at what you made
10633
-
10634
- After each screen, and after any change a person would notice, get a picture and check, in this order:
10635
-
10636
- 1. Is everything that was asked for there, and readable?
10637
- 2. Is anything cut off or overflowing its frame? Fix the frame's size or the content's wrapping; do not shrink the text.
10638
- 3. Do repeated rows line up down the page?
10639
- 4. Is the first thing you notice the thing that matters most?
10640
- 5. Is spacing even where it should be even?
10932
+ - ${learn("canvas.read", "read what a canvas holds: its outline, or one screen as HTML")}
10933
+ - ${learn("canvas.insertHtml", "add a screen as HTML, with an example")} Read it before the first insert.
10934
+ - Give a new top-level screen \`"placement": {"kind": "auto"}\` so Enhance puts it in free space, unless the person gave coordinates. Place the next screen of a sequence with \`{"kind": "near", "anchorNodeId": "<the previous screen's id from its answer>", "side": "right"}\`.
10935
+ - ${learn("canvas.edit", "change text, styles, names and order on layers that are already there, and copy a layer, many in one call")} Use it for any change to existing work.
10936
+ - ${learn("canvas.updateHtml", "rebuild the inside of a layer")} Use it only when the structure itself changes.
10937
+ - ${learn("canvas.importAsset", "bring in an image or a font")}
10938
+ - ${learn("canvas.render", "get a picture of a screen")}
10939
+ - ${learn("canvas.finishWorkingOnNodes", "say that you have finished, so your mark leaves the canvas")}
10641
10940
 
10642
- Fix what you see with ${call("canvas.edit")}, not by rebuilding the screen, then look again.
10643
- `;
10941
+ ${designSections(words)}`;
10644
10942
  }
10645
10943
  },
10646
10944
  "publish-prototype": {
@@ -10680,19 +10978,16 @@ ${listHeading(words)}
10680
10978
  "apply-canvas-design": {
10681
10979
  job: "applying a canvas design",
10682
10980
  description: "Implement an approved or edited Enhance canvas design in the owning product source, republish it, and verify source-to-design fidelity. Use for canvas-to-code or canvas-to-prototype handoff.",
10683
- body: (words) => {
10684
- const { learn } = words;
10685
- return `# Apply a canvas design
10981
+ body: (words) => `# Apply a canvas design
10686
10982
 
10687
10983
  Make the product's source match an approved design on an Enhance canvas, then update the prototype on that canvas from the new build.
10688
10984
 
10689
10985
  ${listHeading(words)}
10690
10986
 
10691
- - ${learn("canvas.read", "read the design: the canvas's outline, or one screen as HTML")}
10692
- - ${learn("canvas.render", "get a picture of a screen")}
10693
- - ${learn("prototype.publish", "update the prototype that is already on the canvas")} Read it before publishing.
10694
- `;
10695
- }
10987
+ - ${words.learn("canvas.read", "read the design: the canvas's outline, or one screen as HTML")} ${DESIGN_RULES.code}
10988
+ - ${words.learn("canvas.render", "get a picture of a screen")}
10989
+ - ${words.learn("prototype.publish", "update the prototype that is already on the canvas")} Read it before publishing.
10990
+ `
10696
10991
  }
10697
10992
  };
10698
10993
  /**
@@ -10700,20 +10995,109 @@ ${listHeading(words)}
10700
10995
  * and development tools never overwrite one another's; the plugin's host names them itself.
10701
10996
  */
10702
10997
  const skillTextsFor = (wording) => SKILL_NAMES.map((skill) => {
10703
- const source = SKILLS[skill];
10998
+ const { body: write, description } = SKILLS[skill];
10704
10999
  const name = wording.surface === "cli" ? `${wording.commandName}-${skill}` : skill;
10705
- const body = source.body(wordsOf(skill, wording));
11000
+ const body = write(wordsOf(skill, wording));
10706
11001
  return {
10707
11002
  skill,
10708
11003
  name,
10709
- description: source.description,
11004
+ description,
10710
11005
  body,
10711
- text: `---\nname: ${name}\ndescription: ${source.description}\n---\n\n${body}`
11006
+ text: `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}`
10712
11007
  };
10713
11008
  });
10714
11009
  /** The job each skill is for, in the order of the skills, for a sentence that lists them. */
10715
11010
  const SKILL_JOBS = SKILL_NAMES.map((skill) => SKILLS[skill].job);
10716
11011
 
11012
+ //#endregion
11013
+ //#region src/application/design-guidance.use-case.ts
11014
+ /**
11015
+ * Where an agent meets the design rules besides the guide: the start-up list when it connects,
11016
+ * and the rules each tool and command repeats where it applies. Every sentence is one of the
11017
+ * guide's own, so no surface can teach a rule in other words.
11018
+ */
11019
+ /** The places an agent writes, looks or finishes, each with the rules that apply there. */
11020
+ const POINTS_OF_USE = {
11021
+ create: ["brief"],
11022
+ write: [
11023
+ "brief",
11024
+ "sizes",
11025
+ "group",
11026
+ "html",
11027
+ "rows",
11028
+ "ids"
11029
+ ],
11030
+ import: ["fonts"],
11031
+ update: ["html", "fix"],
11032
+ edit: [
11033
+ "fit",
11034
+ "fix",
11035
+ "ids"
11036
+ ],
11037
+ render: ["review", "scale"],
11038
+ finish: ["finish"]
11039
+ };
11040
+ /** The rules for one point of use, as one paragraph for a tool's description or a command's help. */
11041
+ const pointOfUseText = (use) => POINTS_OF_USE[use].map((rule) => DESIGN_RULES[rule]).join(" ");
11042
+ /** The rules of the start-up list, in order, after the line that says to load the guide. */
11043
+ const START_UP_RULES = [
11044
+ "look",
11045
+ "brief",
11046
+ "fonts",
11047
+ "units",
11048
+ "group",
11049
+ "review",
11050
+ "fit",
11051
+ "rows",
11052
+ "ids",
11053
+ "finish",
11054
+ "code"
11055
+ ];
11056
+ /**
11057
+ * The short list an agent meets when it connects: on an MCP server, its instructions; on the
11058
+ * command line, the top of `canvas --help`. Its first line says how this surface loads the guide.
11059
+ */
11060
+ const startUpListFor = (wording) => [
11061
+ "Designing on an Enhance canvas:",
11062
+ `- ${loadGuideLineFor(wording)}`,
11063
+ ...START_UP_RULES.map((rule) => `- ${DESIGN_RULES[rule]}`)
11064
+ ].join("\n");
11065
+ /**
11066
+ * The start-up list's first line: how this surface loads the guide. The command line's canvas
11067
+ * help has room for this line alone; the guide holds every rule.
11068
+ */
11069
+ const loadGuideLineFor = (wording) => wording.surface === "cli" ? `Load the design guide first: run \`${wording.command} canvas guide\` once in each session, before other commands, and again when a long thread may have lost it.` : "Load the design guide first: call workflow_guide with design-on-canvas once in each session, before other calls, and again when a long thread may have lost it.";
11070
+
11071
+ //#endregion
11072
+ //#region src/application/partial-batch.error.ts
11073
+ var PartialBatchError = class extends CliError {
11074
+ constructor(message, remediation, details) {
11075
+ super(details?.code ?? "INTERNAL", message, remediation, details?.fields);
11076
+ this.name = "PartialBatchError";
11077
+ }
11078
+ };
11079
+
11080
+ //#endregion
11081
+ //#region ../../packages/canvas-document/src/canvas-edit-words.consts.ts
11082
+ /**
11083
+ * The phrases a planned edit's refusal uses, for each way into Enhance: the command-line tool's
11084
+ * commands, and the tools an assistant calls. The tool layer holds the tool names to its own list.
11085
+ */
11086
+ const CANVAS_EDIT_WORDS = {
11087
+ cli: {
11088
+ layerList: "canvas tree",
11089
+ currentIds: (ids = "a current stable node id") => `Run canvas tree and use ${ids}.`,
11090
+ updateHtml: "canvas update-html",
11091
+ arrange: "canvas arrange"
11092
+ },
11093
+ mcp: {
11094
+ layerList: "a new read of the canvas",
11095
+ currentIds: (ids = "a current stable node id") => `Read the canvas again and use ${ids}.`,
11096
+ updateHtml: "canvas_update_html",
11097
+ arrange: "canvas_arrange"
11098
+ }
11099
+ };
11100
+
10717
11101
  //#endregion
10718
11102
  //#region src/infrastructure/mcp-tool-names.consts.ts
10719
11103
  /** The tool a hosted assistant calls for each capability that has one of its own. */
@@ -10727,6 +11111,7 @@ const MCP_TOOL_BY_CAPABILITY = {
10727
11111
  "canvas.duplicateNodes": "canvas_duplicate",
10728
11112
  "canvas.edit": "canvas_edit",
10729
11113
  "canvas.find": "canvas_find",
11114
+ "canvas.finishWorkingOnNodes": "canvas_finish_working",
10730
11115
  "canvas.importAsset": "asset_import",
10731
11116
  "canvas.insertHtml": "canvas_insert_html",
10732
11117
  "canvas.makeEditable": "canvas_make_editable",
@@ -10783,16 +11168,8 @@ const callOf = (capability, given) => inSurfaceWords({
10783
11168
  cli: `enhance ${cliPathOf(capability)} ${given.cli}`,
10784
11169
  mcp: `${toolOf(capability)} with ${JSON.stringify(given.mcp)}`
10785
11170
  });
10786
- /** Where a layer's current id is read: the tool's tree command, or an assistant's own read. */
10787
- const layerListName = () => inSurfaceWords({
10788
- cli: "canvas tree",
10789
- mcp: "a new read of the canvas"
10790
- });
10791
11171
  /** The step that finds layer ids that still exist. */
10792
- const currentNodeIdStep = (ids = "a current stable node id") => inSurfaceWords({
10793
- cli: `Run canvas tree and use ${ids}.`,
10794
- mcp: `Read the canvas again and use ${ids}.`
10795
- });
11172
+ const currentNodeIdStep = (ids = "a current stable node id") => CANVAS_EDIT_WORDS[callingSurface()].currentIds(ids);
10796
11173
 
10797
11174
  //#endregion
10798
11175
  //#region src/application/stored-canvas-scene.use-case.ts
@@ -10810,6 +11187,20 @@ const readStoredCanvasScene = (document) => {
10810
11187
  throw new CliError("INTERNAL", "The stored canvas is not an editable scene.", "Open the canvas in the editor and repair or recreate the invalid document.");
10811
11188
  };
10812
11189
 
11190
+ //#endregion
11191
+ //#region ../../packages/canvas-document/src/canvas-work-tally.lib.ts
11192
+ const counts = /* @__PURE__ */ new Map();
11193
+ const apartCounts = /* @__PURE__ */ new Map();
11194
+ const apart = { depth: 0 };
11195
+ /**
11196
+ * Counts work an editor path did, by kind. The integration count gates read the tally to hold
11197
+ * per-edit work constant as boards grow; the product never reads it.
11198
+ */
11199
+ const tallyCanvasWork = (kind, amount = 1) => {
11200
+ const held = apart.depth > 0 ? apartCounts : counts;
11201
+ held.set(kind, (held.get(kind) ?? 0) + amount);
11202
+ };
11203
+
10813
11204
  //#endregion
10814
11205
  //#region ../../packages/contract/src/capture/capture-comparison.schema.ts
10815
11206
  const COMMIT_LENGTH = 200;
@@ -10930,63 +11321,6 @@ const captureReviewSchema = z.strictObject({
10930
11321
  }))
10931
11322
  });
10932
11323
 
10933
- //#endregion
10934
- //#region src/application/canvas-reference.use-case.ts
10935
- const hasCanvasReferenceScope = (reference) => reference.pageId !== void 0 || reference.nodeIds.length > 0;
10936
- /** The origin a `/c/<id>` path is read against. The path names no host, and none is kept. */
10937
- const PATH_ORIGIN = "https://canvas.invalid";
10938
- /**
10939
- * `canvas find` and `prototype publish` answer with the path `/c/<id>`, which is not an address by
10940
- * itself, so it is read as the address it would be on any host.
10941
- */
10942
- const asAddress = (reference) => {
10943
- const candidate = reference.trim();
10944
- return candidate.startsWith("/c/") ? `${PATH_ORIGIN}${candidate}` : reference;
10945
- };
10946
- const parseCanvasReference = (reference) => {
10947
- const parsed = readCanvasReference(asAddress(reference));
10948
- if (parsed.ok) return parsed.value;
10949
- throw new CliError("BAD_REQUEST", `The canvas link contains an invalid or unsupported ${parsed.reason}.`, "Copy a current canvas, page or selection link. Recording and version links require their dedicated commands; do not discard their scope.");
10950
- };
10951
- const fromCanvasReference = (reference) => {
10952
- const parsed = parseCanvasReference(reference);
10953
- if (hasCanvasReferenceScope(parsed)) throw new CliError("BAD_REQUEST", `This command cannot discard the link ${parsed.nodeIds.length > 0 ? "selection" : "page"}.`, "Use canvas tree, a scoped render or a targeted edit. Use a canvas URL without page or selection only when the request covers the whole canvas.");
10954
- return parsed.canvasId;
10955
- };
10956
- const canvasReferenceNodeIds = (reference, document) => {
10957
- if (!hasCanvasReferenceScope(reference)) return /* @__PURE__ */ new Set();
10958
- const scope = resolveCanvasReference(reference, document);
10959
- if (scope.ok) return scope.nodeIds;
10960
- const reason = scope.reason;
10961
- throw new CliError(reason === "page" || reason === "selection" ? "NOT_FOUND" : "BAD_REQUEST", `The link ${reason} is unavailable or inconsistent: ${reference.nodeIds.join(", ")}${reference.pageId === void 0 ? "" : ` on page ${reference.pageId}`}.`, "Copy a current link. Keep its complete page and selection; do not substitute or broaden the target.");
10962
- };
10963
- const assertCanvasReferenceNodes = (reference, document, nodeIds) => {
10964
- if (!hasCanvasReferenceScope(reference)) return;
10965
- const scope = canvasReferenceNodeIds(reference, document);
10966
- assertNodesInScope(scope, nodeIds);
10967
- };
10968
- const assertNodesInScope = (scope, nodeIds) => {
10969
- const outside = nodeIds.filter((id) => !scope.has(id));
10970
- if (outside.length > 0) throw new CliError("BAD_REQUEST", `These nodes are outside the link selection: ${outside.join(", ")}.`, "Limit the edit to the selected nodes and their descendants. Request a wider selection only when the person wants a wider change.");
10971
- };
10972
- const canvasReferenceRenderTarget = (reference, document, target) => {
10973
- if (!hasCanvasReferenceScope(reference)) return target;
10974
- const scope = canvasReferenceNodeIds(reference, document);
10975
- const nodeId = target.kind === "node" ? target.nodeId : target.kind === "content" && reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0;
10976
- if (nodeId !== void 0) {
10977
- assertNodesInScope(scope, [nodeId]);
10978
- return {
10979
- kind: "node",
10980
- nodeId
10981
- };
10982
- }
10983
- if (reference.nodeIds.length === 0 && reference.pageId !== void 0 && (target.kind === "content" || target.kind === "page" && target.pageId === reference.pageId)) return {
10984
- kind: "page",
10985
- pageId: reference.pageId
10986
- };
10987
- throw new CliError("BAD_REQUEST", "This render target would discard the link page or selection.", "Render the linked page, or choose one node within the selection. Bounds and other pages may include unrelated content.");
10988
- };
10989
-
10990
11324
  //#endregion
10991
11325
  //#region src/application/canvas-resource-read.schema.ts
10992
11326
  const MAX_RESOURCE_PAGE = 100;
@@ -11141,12 +11475,19 @@ const canvasSourceEvidenceSchema = z.discriminatedUnion("kind", [
11141
11475
  })
11142
11476
  ]);
11143
11477
 
11478
+ //#endregion
11479
+ //#region src/application/client-token.schema.ts
11480
+ /**
11481
+ * A write's retry token, as every agent tool takes it: left out, the tool makes one and names it in
11482
+ * its answer, so an agent never invents a value that another request may already have used.
11483
+ */
11484
+ const retryClientTokenSchema = z.uuid().optional().describe("Leave out: the tool makes one and names it in its answer. Repeat that clientToken, with identical arguments, only after an uncertain outcome.");
11485
+
11144
11486
  //#endregion
11145
11487
  //#region src/application/canvas-exchange.schema.ts
11146
11488
  const MAX_PREPARATION_WAIT_MS = 12e4;
11147
11489
  const DEFAULT_PREPARATION_WAIT_MS = 3e4;
11148
11490
  const MAX_TOKEN_LENGTH = 16384;
11149
- const MAX_TARGETS = 1e3;
11150
11491
  const MAX_OUTLINE_PAGE = 100;
11151
11492
  const DEFAULT_OUTLINE_PAGE = 50;
11152
11493
  const MAX_OUTLINE_DEPTH = 64;
@@ -11174,7 +11515,7 @@ const canvasReadInputSchema = z.discriminatedUnion("view", [
11174
11515
  z.strictObject({
11175
11516
  ...sharedRead,
11176
11517
  view: z.literal("outline"),
11177
- rootNodeIds: z.array(nodeId$2).min(1).max(MAX_TARGETS).optional(),
11518
+ rootNodeIds: z.array(nodeId$2).min(1).optional(),
11178
11519
  depth: z.number().int().min(0).max(MAX_OUTLINE_DEPTH).default(2),
11179
11520
  limit: z.number().int().min(1).max(MAX_OUTLINE_PAGE).default(DEFAULT_OUTLINE_PAGE),
11180
11521
  cursor: cursor.optional()
@@ -11185,18 +11526,26 @@ const canvasUpdateHtmlInputSchema = z.strictObject({
11185
11526
  waitMs: z.number().int().min(0).max(MAX_PREPARATION_WAIT_MS).default(DEFAULT_PREPARATION_WAIT_MS).describe("Additional polling for native HTML compilation. Preparation alone never commits."),
11186
11527
  snapshotToken: cursor,
11187
11528
  html: z.string().min(1),
11188
- removeNodeIds: z.array(nodeId$2).max(MAX_TARGETS).default([]),
11189
- clientToken: z.uuid().describe("Caller-generated intent ID. Reuse unchanged after an uncertain outcome.")
11529
+ removeNodeIds: z.array(nodeId$2).default([]),
11530
+ clientToken: retryClientTokenSchema
11190
11531
  });
11191
- const canvasSnapshotBindingSchema = z.strictObject({
11192
- protocol: z.literal("enhance-canvas-editable/1"),
11532
+ const snapshotBinding = {
11193
11533
  canvasId: z.uuid(),
11194
11534
  version,
11195
11535
  rootNodeId: nodeId$2,
11196
- scopeNodeIds: z.array(nodeId$2).max(MAX_TARGETS),
11197
11536
  scopePageId: z.string().nullable(),
11198
11537
  digest: z.string().regex(/^[a-f0-9]{64}$/u)
11199
- });
11538
+ };
11539
+ /** Tokens issued before the scope became a digest list their selected roots; both are read. */
11540
+ const canvasSnapshotBindingSchema = z.discriminatedUnion("protocol", [z.strictObject({
11541
+ ...snapshotBinding,
11542
+ protocol: z.literal("enhance-canvas-editable/1"),
11543
+ scopeNodeIds: z.array(nodeId$2)
11544
+ }), z.strictObject({
11545
+ ...snapshotBinding,
11546
+ protocol: z.literal("enhance-canvas-editable/2"),
11547
+ scopeDigest: z.string().regex(/^[a-f0-9]{64}$/u)
11548
+ })]);
11200
11549
  const canvasOutlineCursorSchema = z.strictObject({
11201
11550
  protocol: z.literal("enhance-canvas-outline/1"),
11202
11551
  canvasId: z.uuid(),
@@ -11275,19 +11624,104 @@ const decodeCanvasExchangeToken = (token, schema) => {
11275
11624
  throw new CliError("BAD_REQUEST", "The canvas snapshot or cursor is invalid or unsupported.", "Repeat the read and use its complete token without changing it.");
11276
11625
  }
11277
11626
  };
11627
+ const byCodeUnit = (left, right) => {
11628
+ if (left === right) return 0;
11629
+ return left < right ? -1 : 1;
11630
+ };
11631
+ /** The selected roots a snapshot is bound to: each once, in an order every machine agrees on. */
11632
+ const canonicalScope = (reference) => {
11633
+ const scope = [...new Set(reference.nodeIds)].toSorted(byCodeUnit);
11634
+ tallyCanvasWork("scope ids sorted", scope.length);
11635
+ return scope;
11636
+ };
11637
+ /** The fixed-length fingerprint of a scope: its size never follows the selection's. */
11638
+ const scopeDigestOf = (scope) => {
11639
+ const encoded = JSON.stringify(scope);
11640
+ tallyCanvasWork("scope bytes hashed", Buffer.byteLength(encoded));
11641
+ return createHash("sha256").update(encoded).digest("hex");
11642
+ };
11278
11643
  const canvasSnapshotToken = (input) => encodeCanvasExchangeToken({
11279
- protocol: "enhance-canvas-editable/1",
11644
+ protocol: "enhance-canvas-editable/2",
11280
11645
  canvasId: input.reference.canvasId,
11281
11646
  version: input.version,
11282
11647
  rootNodeId: input.rootNodeId,
11283
- scopeNodeIds: input.reference.nodeIds.toSorted((left, right) => left.localeCompare(right)),
11648
+ scopeDigest: scopeDigestOf(canonicalScope(input.reference)),
11284
11649
  scopePageId: input.reference.pageId ?? null,
11285
11650
  digest: canvasExchangeDigest(input.html)
11286
11651
  });
11652
+ const hasSameScope = (binding, reference) => {
11653
+ const scope = canonicalScope(reference);
11654
+ if (binding.protocol === "enhance-canvas-editable/2") return binding.scopeDigest === scopeDigestOf(scope);
11655
+ const bound = new Set(binding.scopeNodeIds);
11656
+ return bound.size === scope.length && scope.every((id) => bound.has(id));
11657
+ };
11658
+ /** What a snapshot was taken of, in one shape for every token format still in flight. */
11287
11659
  const resolveCanvasSnapshot = (token, reference) => {
11288
11660
  const binding = decodeCanvasExchangeToken(token, canvasSnapshotBindingSchema);
11289
- if (binding.canvasId !== reference.canvasId || binding.scopePageId !== (reference.pageId ?? null) || JSON.stringify(binding.scopeNodeIds) !== JSON.stringify(reference.nodeIds.toSorted((left, right) => left.localeCompare(right)))) throw new CliError("BAD_REQUEST", "The editable snapshot belongs to a different canvas, page or selection.", "Use the original canvas reference and read a fresh complete subtree if its scope must change.");
11290
- return binding;
11661
+ if (binding.canvasId !== reference.canvasId || binding.scopePageId !== (reference.pageId ?? null) || !hasSameScope(binding, reference)) throw new CliError("BAD_REQUEST", "The editable snapshot belongs to a different canvas, page or selection.", "Use the original canvas reference and read a fresh complete subtree if its scope must change.");
11662
+ return {
11663
+ canvasId: binding.canvasId,
11664
+ version: binding.version,
11665
+ rootNodeId: binding.rootNodeId,
11666
+ digest: binding.digest
11667
+ };
11668
+ };
11669
+
11670
+ //#endregion
11671
+ //#region src/application/canvas-reference.use-case.ts
11672
+ const hasCanvasReferenceScope = (reference) => reference.pageId !== void 0 || reference.nodeIds.length > 0;
11673
+ /** The origin a `/c/<id>` path is read against. The path names no host, and none is kept. */
11674
+ const PATH_ORIGIN = "https://canvas.invalid";
11675
+ /**
11676
+ * `canvas find` and `prototype publish` answer with the path `/c/<id>`, which is not an address by
11677
+ * itself, so it is read as the address it would be on any host.
11678
+ */
11679
+ const asAddress = (reference) => {
11680
+ const candidate = reference.trim();
11681
+ return candidate.startsWith("/c/") ? `${PATH_ORIGIN}${candidate}` : reference;
11682
+ };
11683
+ const parseCanvasReference = (reference) => {
11684
+ const parsed = readCanvasReference(asAddress(reference));
11685
+ if (parsed.ok) return parsed.value;
11686
+ throw new CliError("BAD_REQUEST", `The canvas link contains an invalid or unsupported ${parsed.reason}.`, "Copy a current canvas, page or selection link. Recording and version links require their dedicated commands; do not discard their scope.");
11687
+ };
11688
+ const fromCanvasReference = (reference) => {
11689
+ const parsed = parseCanvasReference(reference);
11690
+ if (hasCanvasReferenceScope(parsed)) throw new CliError("BAD_REQUEST", `This command cannot discard the link ${parsed.nodeIds.length > 0 ? "selection" : "page"}.`, "Use canvas tree, a scoped render or a targeted edit. Use a canvas URL without page or selection only when the request covers the whole canvas.");
11691
+ return parsed.canvasId;
11692
+ };
11693
+ const canvasReferenceNodeIds = (reference, document) => {
11694
+ if (!hasCanvasReferenceScope(reference)) return /* @__PURE__ */ new Set();
11695
+ const scope = resolveCanvasReference(reference, document);
11696
+ if (scope.ok) return scope.nodeIds;
11697
+ const reason = scope.reason;
11698
+ throw new CliError(reason === "page" || reason === "selection" ? "NOT_FOUND" : "BAD_REQUEST", `The link ${reason} is unavailable or inconsistent: ${reference.nodeIds.join(", ")}${reference.pageId === void 0 ? "" : ` on page ${reference.pageId}`}.`, "Copy a current link. Keep its complete page and selection; do not substitute or broaden the target.");
11699
+ };
11700
+ const assertCanvasReferenceNodes = (reference, document, nodeIds) => {
11701
+ if (!hasCanvasReferenceScope(reference)) return;
11702
+ const scope = canvasReferenceNodeIds(reference, document);
11703
+ assertNodesInScope(scope, nodeIds);
11704
+ };
11705
+ const assertNodesInScope = (scope, nodeIds) => {
11706
+ const outside = nodeIds.filter((id) => !scope.has(id));
11707
+ if (outside.length > 0) throw new CliError("BAD_REQUEST", `These nodes are outside the link selection: ${outside.join(", ")}.`, "Limit the edit to the selected nodes and their descendants. Request a wider selection only when the person wants a wider change.");
11708
+ };
11709
+ const canvasReferenceRenderTarget = (reference, document, target) => {
11710
+ if (!hasCanvasReferenceScope(reference)) return target;
11711
+ const scope = canvasReferenceNodeIds(reference, document);
11712
+ const nodeId = target.kind === "node" ? target.nodeId : target.kind === "content" && reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0;
11713
+ if (nodeId !== void 0) {
11714
+ assertNodesInScope(scope, [nodeId]);
11715
+ return {
11716
+ kind: "node",
11717
+ nodeId
11718
+ };
11719
+ }
11720
+ if (reference.nodeIds.length === 0 && reference.pageId !== void 0 && (target.kind === "content" || target.kind === "page" && target.pageId === reference.pageId)) return {
11721
+ kind: "page",
11722
+ pageId: reference.pageId
11723
+ };
11724
+ throw new CliError("BAD_REQUEST", "This render target would discard the link page or selection.", "Render the linked page, or choose one node within the selection. Bounds and other pages may include unrelated content.");
11291
11725
  };
11292
11726
 
11293
11727
  //#endregion
@@ -11573,9 +12007,10 @@ const canvasInsertHtmlInputSchema = z.strictObject({
11573
12007
  canvasRef: z.string().min(1),
11574
12008
  baseVersion: z.number().int().positive(),
11575
12009
  destination: z.strictObject({ parentNodeId: canvasSceneNodeSchema.shape.id.describe("Existing editable container, or root for top-level insertion. Preserve page and selection scope.") }),
11576
- html: z.string().min(1).describe("One populated, safe HTML/CSS visual group. Use authored positioning in the HTML for placement. The canonical compiler assigns fresh IDs."),
12010
+ html: z.string().min(1).describe("One populated, safe HTML/CSS visual group. Without placement, the root lands at its authored position. The canonical compiler assigns fresh IDs."),
12011
+ placement: canvasPlacementIntentSchema.optional().describe("Where a new top-level screen (parentNodeId root) goes. auto: Enhance finds free space on the page and ignores the position authored on the root. near: beside or below an existing screen, the way to lay out a sequence; name the previous screen from its receipt. explicit: exactly these page coordinates, overlap allowed. Omit to keep the authored position. Not accepted for an insertion inside a container. The answer reports where the screen landed in result.placement."),
11577
12012
  waitMs: z.number().int().min(0).max(MAX_WAIT_MS$1).default(DEFAULT_WAIT_MS$1).describe("Additional polling after the initial server call; this does not bound initial compilation time."),
11578
- clientToken: z.uuid()
12013
+ clientToken: retryClientTokenSchema
11579
12014
  });
11580
12015
  const canvasInsertHtmlCapabilityInputSchema = canvasInsertHtmlInputSchema.omit({ clientToken: true });
11581
12016
  const canvasMakeEditableInputSchema = z.strictObject({
@@ -11651,7 +12086,7 @@ const canvasFindCursorSchema = z.strictObject({
11651
12086
  const canvasCreateToolInputSchema = z.strictObject({
11652
12087
  destination: canvasDestinationSchema,
11653
12088
  title: createCanvasInputSchema.shape.title,
11654
- clientToken: z.uuid()
12089
+ clientToken: retryClientTokenSchema
11655
12090
  });
11656
12091
  const canvasCreateToolOutputSchema = z.strictObject({
11657
12092
  canvasRef: z.uuid(),
@@ -11669,7 +12104,7 @@ const canvasRemoveInputSchema = z.strictObject({
11669
12104
  canvasRef: z.string().min(1),
11670
12105
  baseVersion: z.number().int().positive(),
11671
12106
  rootNodeIds: z.array(canvasSceneNodeSchema.shape.id).min(1),
11672
- clientToken: z.uuid()
12107
+ clientToken: retryClientTokenSchema
11673
12108
  });
11674
12109
  const canvasRemoveCapabilityInputSchema = canvasRemoveInputSchema.omit({ clientToken: true });
11675
12110
 
@@ -11721,7 +12156,7 @@ const canvasRenderRequestSchema = z.strictObject({
11721
12156
  canvasRenderTargetSchema.options[3].strict().extend({ bounds: canvasRenderTargetSchema.options[3].shape.bounds.strict() })
11722
12157
  ]),
11723
12158
  sourceState: canvasRenderSourceStateSchema.strict().nullable().default(null),
11724
- scale: z.number().positive().default(1),
12159
+ scale: z.number().positive().default(1).describe(DESIGN_RULES.scale),
11725
12160
  waitMs: z.number().int().min(0).max(MAX_WAIT_MS).default(DEFAULT_WAIT_MS).describe("Additional local polling after the server returns an active job; render creation retains its existing bounded HTTP deadline.")
11726
12161
  });
11727
12162
 
@@ -11791,7 +12226,7 @@ const canvasRenderBatchResultSchema = z.object({
11791
12226
  next: z.array(z.string())
11792
12227
  });
11793
12228
  const canvasRenderScopedInputSchema = z.union([canvasRenderRequestSchema, canvasRenderBatchRequestSchema]).meta({ type: "object" });
11794
- const canvasRenderScopedToolInputSchema = z.union([canvasRenderRequestSchema.extend({ clientToken: z.uuid() }), canvasRenderBatchRequestSchema.safeExtend({ clientToken: z.uuid() })]).meta({ type: "object" });
12229
+ const canvasRenderScopedToolInputSchema = z.union([canvasRenderRequestSchema.extend({ clientToken: retryClientTokenSchema }), canvasRenderBatchRequestSchema.safeExtend({ clientToken: z.uuid().optional() })]).meta({ type: "object" });
11795
12230
 
11796
12231
  //#endregion
11797
12232
  //#region src/application/canvas-asset.schema.ts
@@ -11803,7 +12238,7 @@ const canvasAssetImportCapabilityInputSchema = z.strictObject({
11803
12238
  path: z.string().min(1).describe("Explicit local file path. PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2.")
11804
12239
  })
11805
12240
  });
11806
- const canvasAssetImportInputSchema = canvasAssetImportCapabilityInputSchema.extend({ clientToken: z.uuid() });
12241
+ const canvasAssetImportInputSchema = canvasAssetImportCapabilityInputSchema.extend({ clientToken: retryClientTokenSchema });
11807
12242
  const canvasAssetImportOutputSchema = z.strictObject({
11808
12243
  operation: canvasAssetOperationSchema,
11809
12244
  resource: canvasAssetUploadOutputSchema.safeExtend({
@@ -11857,6 +12292,8 @@ const canvasWriteReceiptSchema = z.discriminatedUnion("outcome", [z.strictObject
11857
12292
  total: z.number().int().nonnegative()
11858
12293
  }).optional(),
11859
12294
  affected: z.strictObject(affectedNodes),
12295
+ /** Where a placed copied set was saved; absent when the request asked for no placement. */
12296
+ placement: canvasPlacementResultSchema.optional(),
11860
12297
  verification: z.strictObject({ rendered: z.literal(false) }),
11861
12298
  warnings: z.array(z.string())
11862
12299
  })]).meta({ type: "object" });
@@ -11877,7 +12314,7 @@ const common = {
11877
12314
  canvasRef: z.string().min(1),
11878
12315
  baseVersion: z.number().int().positive(),
11879
12316
  waitMs: z.number().int().min(0).max(12e4).default(3e4).describe("Additional polling after the initial server call; this does not bound initial native preparation time."),
11880
- clientToken: z.uuid()
12317
+ clientToken: retryClientTokenSchema
11881
12318
  };
11882
12319
  const canvasArrangeInputSchema = z.strictObject({
11883
12320
  ...common,
@@ -11886,7 +12323,8 @@ const canvasArrangeInputSchema = z.strictObject({
11886
12323
  const canvasDuplicateInputSchema = z.strictObject({
11887
12324
  ...common,
11888
12325
  nodeIds: canvasDuplicatePreparationSchema.shape.nodeIds,
11889
- destination: canvasDuplicatePreparationSchema.shape.destination
12326
+ destination: canvasDuplicatePreparationSchema.shape.destination,
12327
+ placement: canvasDuplicatePreparationSchema.shape.placement.describe("Where a set of top-level copies goes: {kind:\"auto\"} for free space on the page, {kind:\"near\",anchorNodeId,side} beside a layer, or {kind:\"explicit\",x,y}. The set moves as one. Omit it for the native copy offset.")
11890
12328
  });
11891
12329
  const canvasArrangeCapabilityInputSchema = canvasArrangeInputSchema.omit({ clientToken: true });
11892
12330
  const canvasDuplicateCapabilityInputSchema = canvasDuplicateInputSchema.omit({ clientToken: true });
@@ -11926,7 +12364,7 @@ const canvasCaptureCapabilityInputSchema = z.strictObject({
11926
12364
  previewJobId: z.uuid().describe("The successful render job whose pixels you inspected at this exact recording time and canvas version."),
11927
12365
  placement: canvasSnapshotRequestSchema.shape.placement.describe("Use editable-below-source. below-source is kept for older clients and lands the same editable frame below the root-level recording on its page.")
11928
12366
  });
11929
- const canvasCaptureInputSchema = canvasCaptureCapabilityInputSchema.extend({ clientToken: z.uuid() });
12367
+ const canvasCaptureInputSchema = canvasCaptureCapabilityInputSchema.extend({ clientToken: retryClientTokenSchema });
11930
12368
  const canvasCaptureOutputSchema = z.strictObject({
11931
12369
  operation: z.discriminatedUnion("kind", [
11932
12370
  z.strictObject({
@@ -12062,6 +12500,7 @@ const canvasConversionStatusSchema = z.strictObject({
12062
12500
  version: z.number().int().positive(),
12063
12501
  rootNodeId: z.string(),
12064
12502
  affectedBounds: canvasSceneBoxSchema,
12503
+ placement: canvasPlacementResultSchema.optional().describe("Where a placed insertion saved its screen, at this version."),
12065
12504
  insertedCount: z.number().int().nonnegative(),
12066
12505
  removedCount: z.number().int().nonnegative(),
12067
12506
  identityCount: z.number().int().nonnegative(),
@@ -12152,7 +12591,7 @@ const canvasPrototypeCapabilityInputSchema = z.strictObject({
12152
12591
  waitMs: canvasRenderRequestSchema.shape.waitMs.describe("Additional ingestion polling, capped at five seconds. This budget does not include packaging or network transfers."),
12153
12592
  source: z.discriminatedUnion("kind", [directorySourceSchema, deploymentSourceSchema])
12154
12593
  });
12155
- const canvasPrototypeInputSchema = canvasPrototypeCapabilityInputSchema.extend({ clientToken: z.uuid() });
12594
+ const canvasPrototypeInputSchema = canvasPrototypeCapabilityInputSchema.extend({ clientToken: retryClientTokenSchema });
12156
12595
  const canvasPrototypeIntentSchema = canvasPrototypeInputSchema.extend({ source: z.discriminatedUnion("kind", [canvasPrototypeBuildSourceSchema, deploymentSourceSchema]) });
12157
12596
  const canvasPrototypeOutputSchema = z.strictObject({
12158
12597
  operation: prototypeOperationSchema,
@@ -12210,7 +12649,7 @@ const canvasCapturePageCapabilityInputSchema = z.strictObject({
12210
12649
  }).optional().describe("Optional: the width and height the snippet answered, for the picture shown while the page converts. Without it that picture is 1280 by 800. The frame always takes the captured page's own size."),
12211
12650
  baseVersion: z.number().int().positive().optional().describe("The canvas version you read; the frame is saved as one change at it.")
12212
12651
  });
12213
- const canvasCapturePageInputSchema = canvasCapturePageCapabilityInputSchema.extend({ clientToken: z.uuid() });
12652
+ const canvasCapturePageInputSchema = canvasCapturePageCapabilityInputSchema.extend({ clientToken: retryClientTokenSchema });
12214
12653
  const canvasCapturePageOutputSchema = z.strictObject({
12215
12654
  step: z.enum([
12216
12655
  "run-snippet",
@@ -12355,6 +12794,7 @@ const PROCEDURE_DESCRIPTIONS = {
12355
12794
  ...CANVAS_VERSION_PROCEDURE_DESCRIPTIONS,
12356
12795
  "canvas.createEditableFrame": "Insert one validated primitive subtree beside its source screen as an atomic canvas edit.",
12357
12796
  "canvas.create": "Create a canvas and return the id required by canvas-scoped commands.",
12797
+ "canvas.applyEdits": "Plan and save an agent's text, style, name, copy and order edits as one canvas version.",
12358
12798
  "canvas.applyOperations": "Atomically apply validated text, geometry, style, ordering, and removal operations to one canvas version.",
12359
12799
  "canvas.realtime.ticket": "Issue a one-use browser ticket for a live canvas room.",
12360
12800
  "canvas.realtime.activity.begin": "Show that this agent has started work on a canvas.",
@@ -12695,6 +13135,16 @@ const PROTOTYPE_LIFECYCLE_POLICY = {
12695
13135
  reason: "Prototype upload lifecycle is wrapped by prototype publish.",
12696
13136
  owner: "product"
12697
13137
  };
13138
+ const ONBOARDING_POLICY = {
13139
+ exposure: "internal",
13140
+ reason: "Onboarding hints and their preferences belong to the person's own web app.",
13141
+ owner: "product"
13142
+ };
13143
+ const CREDENTIAL_LIFECYCLE_POLICY = {
13144
+ exposure: "cli-transport",
13145
+ reason: "Credential lifecycle remains in the interactive CLI auth surface.",
13146
+ owner: "cli"
13147
+ };
12698
13148
  const STAGED_TRANSFER_POLICY = {
12699
13149
  exposure: "internal",
12700
13150
  reason: "Signed transfers are wrapped by prototype publish and asset import.",
@@ -12735,6 +13185,12 @@ const CAPTURE_PIPELINE_POLICY = {
12735
13185
  owner: "product",
12736
13186
  reason: "Capture reservation, publication and baseline promotion belong to explicit SDK pipeline callers."
12737
13187
  };
13188
+ /** A write that agents reach only through the bounded, intention-revealing authoring commands. */
13189
+ const AUTHORING_POLICY = {
13190
+ exposure: "internal",
13191
+ reason: "Wrapped by bounded, intention-revealing authoring capabilities.",
13192
+ owner: "product"
13193
+ };
12738
13194
  const PROCEDURE_CAPABILITY_POLICIES = {
12739
13195
  "captureRun.review": SHARED_CAPABILITY_POLICY,
12740
13196
  "captureRun.decide": {
@@ -12808,11 +13264,8 @@ const PROCEDURE_CAPABILITY_POLICIES = {
12808
13264
  ...CANVAS_RECOVERY_POLICIES,
12809
13265
  "canvas.chats.publish": CHAT_HISTORY_POLICY,
12810
13266
  "canvas.copyFromWork": RECOVERY_COPY_POLICY,
12811
- "canvas.applyOperations": {
12812
- exposure: "internal",
12813
- reason: "Wrapped by bounded, intention-revealing authoring capabilities.",
12814
- owner: "product"
12815
- },
13267
+ "canvas.applyOperations": AUTHORING_POLICY,
13268
+ "canvas.applyEdits": AUTHORING_POLICY,
12816
13269
  "canvas.realtime.ticket": {
12817
13270
  exposure: "internal",
12818
13271
  reason: "Browser WebSocket admission is not an agent capability.",
@@ -12870,21 +13323,13 @@ const PROCEDURE_CAPABILITY_POLICIES = {
12870
13323
  reason: "Restoring historical state is restricted to an interactive person session.",
12871
13324
  owner: "product"
12872
13325
  },
12873
- "person.createAgentToken": {
12874
- exposure: "cli-transport",
12875
- reason: "Credential lifecycle remains in the interactive CLI auth surface.",
12876
- owner: "cli"
12877
- },
12878
- "person.listAgentTokens": {
12879
- exposure: "cli-transport",
12880
- reason: "Credential lifecycle remains in the interactive CLI auth surface.",
12881
- owner: "cli"
12882
- },
12883
- "person.revokeAgentToken": {
12884
- exposure: "cli-transport",
12885
- reason: "Credential lifecycle remains in the interactive CLI auth surface.",
12886
- owner: "cli"
12887
- },
13326
+ "person.createAgentToken": CREDENTIAL_LIFECYCLE_POLICY,
13327
+ "person.listAgentTokens": CREDENTIAL_LIFECYCLE_POLICY,
13328
+ "person.revokeAgentToken": CREDENTIAL_LIFECYCLE_POLICY,
13329
+ "person.onboarding": ONBOARDING_POLICY,
13330
+ "person.dismissOnboardingStep": ONBOARDING_POLICY,
13331
+ "person.presentOnboardingStep": ONBOARDING_POLICY,
13332
+ "person.recordCanvasLinkCopied": ONBOARDING_POLICY,
12888
13333
  "person.signIn": {
12889
13334
  exposure: "internal",
12890
13335
  reason: "Browser sign-in protocol is wrapped by the CLI auth surface.",
@@ -13476,6 +13921,8 @@ const SESSION_EXPIRED_REMEDIATION = `Your Enhance session expired. ${remediation
13476
13921
  const remediationOf = (error, status) => {
13477
13922
  const formatRefusal = error.fields?.["documentFormatVersion"];
13478
13923
  if (formatRefusal !== void 0) return formatRefusal;
13924
+ const given = error.fields?.["remediation"];
13925
+ if (given !== void 0) return given;
13479
13926
  if (status === void 0) return remediationFor(error.code);
13480
13927
  const outcome = requestOutcomeOf({
13481
13928
  kind: "response",
@@ -13485,7 +13932,7 @@ const remediationOf = (error, status) => {
13485
13932
  });
13486
13933
  if (outcome.kind === "sign-in" && outcome.reason === "session-expired") return SESSION_EXPIRED_REMEDIATION;
13487
13934
  if (error.code === "CONFLICT" && outcome.kind === "transient") return "Wait a few seconds, then retry the same command with the same clientToken.";
13488
- if (outcome.kind === "fault" && outcome.detail === "mutation-id-reused") return "Do not reuse a clientToken with different arguments. Send this change with a new clientToken.";
13935
+ if (outcome.kind === "fault" && outcome.detail === "mutation-id-reused") return "Do not reuse a clientToken with different arguments. Send this change without a clientToken; the tool makes a new one.";
13489
13936
  return remediationFor(error.code);
13490
13937
  };
13491
13938
  const trpcErrorSchema = z.object({ data: z.looseObject({
@@ -13496,8 +13943,12 @@ const appErrorFrom = (error) => {
13496
13943
  const parsed = trpcErrorSchema.safeParse(error);
13497
13944
  const appError = appErrorSchema.safeParse(parsed.success ? parsed.data.data.appError : null);
13498
13945
  if (!appError.success) return null;
13946
+ const fields = Object.fromEntries(Object.entries(appError.data.fields ?? {}).filter(([name]) => name !== "remediation"));
13499
13947
  return {
13500
- appError: appError.data,
13948
+ appError: {
13949
+ ...appError.data,
13950
+ ...appError.data.fields !== void 0 && { fields: Object.keys(fields).length === 0 ? void 0 : fields }
13951
+ },
13501
13952
  remediation: remediationOf(appError.data, parsed.data?.data.httpStatus)
13502
13953
  };
13503
13954
  };
@@ -13730,6 +14181,29 @@ const createMcpCapabilityDiscoveryAdapter = (catalog) => ({
13730
14181
  const toPresentedCapabilities = (catalog, exposures) => catalog.filter((capability) => exposures.includes(capability.policy.exposure));
13731
14182
  const toSharedCapabilities = (catalog) => toPresentedCapabilities(catalog, ["shared"]);
13732
14183
 
14184
+ //#endregion
14185
+ //#region src/application/guide-topics.consts.ts
14186
+ /** Texts the design guide answers with by name, beside the skills. */
14187
+ const GUIDE_TOPIC_NAMES = ["mobile-status-bar"];
14188
+ /** A topic names no command and no tool, so every surface hands out the same text. */
14189
+ const GUIDE_TOPICS = { "mobile-status-bar": {
14190
+ description: "Paste-ready markup for the status bar at the top of a 390 px mobile screen: the time, signal and battery.",
14191
+ body: `# Mobile status bar
14192
+
14193
+ A mobile screen starts with a status bar. Paste this as the first child of a 390 px screen, and never draw one by hand. On a dark screen, change each \`#000000\` to \`#ffffff\`.
14194
+
14195
+ \`\`\`html
14196
+ <div layer-name="Status bar" style="display:flex;align-items:center;justify-content:space-between;width:390px;height:47px;padding:0 26px 0 32px;box-sizing:border-box;flex-shrink:0">
14197
+ <span layer-name="Time" style="font-family:Inter;font-size:16px;line-height:20px;font-weight:600;color:#000000">9:41</span>
14198
+ <div layer-name="Indicators" style="display:flex;align-items:center;gap:6px">
14199
+ <svg layer-name="Signal" width="18" height="12" viewBox="0 0 18 12"><rect x="0" y="9" width="3" height="3" rx="1" fill="#000000"/><rect x="5" y="6" width="3" height="6" rx="1" fill="#000000"/><rect x="10" y="3" width="3" height="9" rx="1" fill="#000000"/><rect x="15" y="0" width="3" height="12" rx="1" fill="#000000"/></svg>
14200
+ <svg layer-name="Battery" width="26" height="12" viewBox="0 0 26 12"><rect x="0.5" y="0.5" width="22" height="11" rx="3" fill="none" stroke="#000000" stroke-opacity="0.4"/><rect x="2" y="2" width="19" height="8" rx="2" fill="#000000"/><rect x="24" y="4" width="2" height="4" rx="1" fill="#000000" fill-opacity="0.4"/></svg>
14201
+ </div>
14202
+ </div>
14203
+ \`\`\`
14204
+ `
14205
+ } };
14206
+
13733
14207
  //#endregion
13734
14208
  //#region src/infrastructure/capability-example.mapper.ts
13735
14209
  const jsonRecordSchema$2 = z.record(z.string(), z.unknown());
@@ -13970,14 +14444,7 @@ const CANVAS_CAPABILITY_SPECS = [
13970
14444
  inputSchema: canvasEditCapabilityInputSchema,
13971
14445
  outputSchema: canvasEditOutputSchema,
13972
14446
  summary: "Change selected text, styles, names, duplicates, or positions in one atomic design edit.",
13973
- procedures: [
13974
- "canvas.document.get",
13975
- "canvas.mutation.get",
13976
- "canvas.realtime.activity.begin",
13977
- "canvas.realtime.activity.renew",
13978
- "canvas.realtime.activity.end",
13979
- "canvas.applyOperations"
13980
- ],
14447
+ procedures: ["canvas.edit"],
13981
14448
  inputExample: {
13982
14449
  canvas: CAPABILITY_UUID_EXAMPLE,
13983
14450
  baseVersion: 1,
@@ -15432,7 +15899,10 @@ const toCanvasSceneNodeContract = (node) => canvasSceneNodeSchema.parse({
15432
15899
  * that has no screen layer, onto its page at the box the draft gives.
15433
15900
  */
15434
15901
  const toEditableFrameOrigin = (input) => "screenNodeId" in input ? {
15435
- destination: { kind: "adjacent" },
15902
+ destination: {
15903
+ kind: "adjacent",
15904
+ ...input.position !== void 0 && { position: input.position }
15905
+ },
15436
15906
  source: {
15437
15907
  kind: "screen",
15438
15908
  nodeId: input.screenNodeId
@@ -16741,7 +17211,38 @@ const receiptSchema$1 = applyCanvasOperationsOutputSchema.pick({
16741
17211
  changedNodeIds: true,
16742
17212
  removedNodeIds: true
16743
17213
  }).extend({ review: canvasMutationReviewSchema });
17214
+ /** An agent's edit batch: the API plans it on the layers it touches and saves it as one version. */
17215
+ const edit = (handlers) => canvasEditorProcedure.input(editCanvasInputSchema).output(editCanvasOutputSchema).mutation(async ({ input, ctx }) => {
17216
+ const edited = orThrow(await handlers.edit.execute({
17217
+ ...input,
17218
+ surface: input.surface ?? "cli",
17219
+ personId: ctx.viewer.personId,
17220
+ actor: toCanvasMutationActor(ctx.viewer)
17221
+ }));
17222
+ if (edited.outcome === "no_op") return edited;
17223
+ const { duplicatedNodes, moves, affectedParents, ...applied } = edited;
17224
+ return {
17225
+ ...applied,
17226
+ operations: applied.operations.map((operation) => canvasOperationSchema.parse(operation)),
17227
+ insertedNodeIds: [...applied.insertedNodeIds],
17228
+ changedNodeIds: [...applied.changedNodeIds],
17229
+ removedNodeIds: [...applied.removedNodeIds],
17230
+ boxes: { ...applied.boxes },
17231
+ ...applied.copiedNodeIds !== void 0 && { copiedNodeIds: { ...applied.copiedNodeIds } },
17232
+ ...duplicatedNodes !== void 0 && { duplicatedNodes: duplicatedNodes.map((node) => ({
17233
+ ...node,
17234
+ descendantIdMap: { ...node.descendantIdMap }
17235
+ })) },
17236
+ ...moves !== void 0 && { moves: moves.map((move) => ({ ...move })) },
17237
+ ...affectedParents !== void 0 && { affectedParents: affectedParents.map((parent) => ({
17238
+ parentId: parent.parentId,
17239
+ children: [...parent.children]
17240
+ })) },
17241
+ next: []
17242
+ };
17243
+ });
16744
17244
  const createCanvasMutationRecoveryRouter = (handlers) => trpcRouter({
17245
+ applyEdits: edit(handlers),
16745
17246
  revertMutations: canvasEditorProcedure.input(z.object({
16746
17247
  canvasId: z.uuid(),
16747
17248
  mutationIds: z.array(z.uuid()).min(1),
@@ -16962,7 +17463,8 @@ const createCanvasActivityRouter = (activity) => trpcRouter({
16962
17463
  return {
16963
17464
  activityId: started.activityId,
16964
17465
  expiresAt: started.expiresAt.toISOString(),
16965
- renewAfterMs: CANVAS_ACTIVITY_RENEW_AFTER_MS
17466
+ renewAfterMs: CANVAS_ACTIVITY_RENEW_AFTER_MS,
17467
+ nodeIds: [...started.nodeIds]
16966
17468
  };
16967
17469
  }),
16968
17470
  renew: agentCanvasReaderProcedure.input(renewCanvasActivityInputSchema).output(beginCanvasActivityOutputSchema).mutation(async ({ input, ctx }) => {
@@ -16975,16 +17477,20 @@ const createCanvasActivityRouter = (activity) => trpcRouter({
16975
17477
  return {
16976
17478
  activityId: renewed.activityId,
16977
17479
  expiresAt: renewed.expiresAt.toISOString(),
16978
- renewAfterMs: CANVAS_ACTIVITY_RENEW_AFTER_MS
17480
+ renewAfterMs: CANVAS_ACTIVITY_RENEW_AFTER_MS,
17481
+ nodeIds: [...renewed.nodeIds]
16979
17482
  };
16980
17483
  }),
16981
17484
  end: agentCanvasReaderProcedure.input(endCanvasActivityInputSchema).output(endCanvasActivityOutputSchema).mutation(async ({ input, ctx }) => {
16982
17485
  if (ctx.viewer.kind !== "agent") throw new TypeError("agent identity was not narrowed");
16983
- orThrow(await activity.end({
17486
+ const ended = orThrow(await activity.end({
16984
17487
  ...input,
16985
17488
  tokenId: ctx.viewer.tokenId
16986
17489
  }));
16987
- return { ended: true };
17490
+ return ended.outcome === "narrowed" ? {
17491
+ ...ended,
17492
+ remainingNodeIds: [...ended.remainingNodeIds]
17493
+ } : ended;
16988
17494
  })
16989
17495
  });
16990
17496
  const createCanvasRealtimeRouter = (handlers, endpoint) => trpcRouter({
@@ -17435,13 +17941,17 @@ const wireResult = (job, result) => ({
17435
17941
  ...result.snapshot !== null && result.snapshot !== void 0 && { snapshot: result.snapshot },
17436
17942
  expiresAt: result.expiresAt.toISOString()
17437
17943
  });
17438
- const wireConversionResult = (result) => ({
17944
+ const wireConversionResult = ({ placement, ...result }) => ({
17439
17945
  ...result,
17440
17946
  idMap: { ...result.idMap },
17441
17947
  insertedNodeIds: [...result.insertedNodeIds],
17442
17948
  removedNodeIds: [...result.removedNodeIds],
17443
17949
  boxes: { ...result.boxes },
17444
17950
  affectedBounds: { ...result.affectedBounds },
17951
+ ...placement !== void 0 && { placement: {
17952
+ ...placement,
17953
+ roots: [...placement.roots]
17954
+ } },
17445
17955
  report: {
17446
17956
  ...result.report,
17447
17957
  issues: [...result.report.issues]
@@ -18313,6 +18823,43 @@ const createOrganisationPeopleRouter = (handlers) => trpcRouter({
18313
18823
  transferOwnership: transferOwnership(handlers)
18314
18824
  });
18315
18825
 
18826
+ //#endregion
18827
+ //#region ../api/src/person/infrastructure/onboarding.router.ts
18828
+ const stepOnWire = (step) => ({
18829
+ ...step,
18830
+ snoozedUntil: step.snoozedUntil?.toISOString() ?? null
18831
+ });
18832
+ /** Translates the onboarding calls into the use case. No rules, no persistence. */
18833
+ const onboardingRoutes = (onboarding) => ({
18834
+ onboarding: personProcedure.meta({ description: "Read the onboarding facts and hint preferences for this person." }).input(onboardingInputSchema).output(onboardingOutputSchema).query(async ({ ctx }) => {
18835
+ const view = orThrow(await onboarding.read(ctx.viewer.personId));
18836
+ return {
18837
+ hasCommented: view.hasCommented,
18838
+ hasCopiedCanvasLink: view.hasCopiedCanvasLink,
18839
+ steps: {
18840
+ connect_agent: stepOnWire(view.steps.connect_agent),
18841
+ first_agent_work: stepOnWire(view.steps.first_agent_work),
18842
+ comment: stepOnWire(view.steps.comment),
18843
+ share_comments: stepOnWire(view.steps.share_comments)
18844
+ }
18845
+ };
18846
+ }),
18847
+ dismissOnboardingStep: personProcedure.meta({ description: "Record Got it or Maybe later on one onboarding hint." }).input(dismissOnboardingStepInputSchema).output(onboardingStepStateSchema).mutation(async ({ input, ctx }) => stepOnWire(orThrow(await onboarding.dismiss({
18848
+ personId: ctx.viewer.personId,
18849
+ stepId: input.stepId,
18850
+ choice: input.choice
18851
+ })))),
18852
+ presentOnboardingStep: personProcedure.meta({ description: "Count one automatic showing of an onboarding hint." }).input(presentOnboardingStepInputSchema).output(presentOnboardingStepOutputSchema).mutation(async ({ input, ctx }) => ({ automaticShowNumber: orThrow(await onboarding.present({
18853
+ personId: ctx.viewer.personId,
18854
+ stepId: input.stepId,
18855
+ presentationId: input.presentationId
18856
+ })) })),
18857
+ recordCanvasLinkCopied: personProcedure.meta({ description: "Record that a canvas link was copied successfully." }).input(recordCanvasLinkCopiedInputSchema).output(recordCanvasLinkCopiedOutputSchema).mutation(async ({ ctx }) => {
18858
+ orThrow(await onboarding.recordCanvasLinkCopied(ctx.viewer.personId));
18859
+ return { hasCopiedCanvasLink: true };
18860
+ })
18861
+ });
18862
+
18316
18863
  //#endregion
18317
18864
  //#region ../api/src/person/domain/prepared-canvas-id.domain-service.ts
18318
18865
  const UUID_PART_LIMIT = 5;
@@ -18362,6 +18909,7 @@ const agentTokenRoutes = (handlers) => ({
18362
18909
  }),
18363
18910
  listAgentTokens: personProcedure.meta({ description: "List agent credentials so unused or revoked ones can be identified." }).input(listAgentTokensInputSchema).output(listAgentTokensOutputSchema).query(async ({ ctx }) => ({
18364
18911
  isConnected: orThrow(await handlers.agentTokens.isConnected(ctx.viewer.personId)),
18912
+ hasEverConnected: orThrow(await handlers.agentTokens.hasEverConnected(ctx.viewer.personId)),
18365
18913
  items: orThrow(await handlers.agentTokens.list(ctx.viewer.personId)).map((token) => tokenOnWire(token))
18366
18914
  })),
18367
18915
  revokeAgentToken: personProcedure.meta({ description: "Revoke an agent credential before its next request." }).input(revokeAgentTokenInputSchema).output(revokeAgentTokenOutputSchema).mutation(async ({ input, ctx }) => {
@@ -18490,6 +19038,15 @@ const profilePhotoRoutes = (profile) => ({
18490
19038
  }))) }))
18491
19039
  });
18492
19040
 
19041
+ //#endregion
19042
+ //#region ../api/src/person/person-router.plugin.ts
19043
+ /** The `person` namespace: this context's routers side by side, as a router may not import one. */
19044
+ const personRouterPlugin = (handlers) => ({
19045
+ ...createPersonRouter(handlers)._def.record,
19046
+ ...profilePhotoRoutes(handlers.profile),
19047
+ ...onboardingRoutes(handlers.onboarding)
19048
+ });
19049
+
18493
19050
  //#endregion
18494
19051
  //#region ../api/src/prototype/infrastructure/prototype-completion.mapper.ts
18495
19052
  const toPrototypeCompletionContract = (completed, input) => {
@@ -19405,10 +19962,7 @@ const createAppRouter = (handlers, options = DEFAULT_ROUTER_OPTIONS) => trpcRout
19405
19962
  people: createOrganisationPeopleRouter(handlers.organisation),
19406
19963
  invites: createOrganisationInviteRouter(handlers.organisation)
19407
19964
  }),
19408
- person: trpcRouter({
19409
- ...createPersonRouter(handlers.person)._def.record,
19410
- ...profilePhotoRoutes(handlers.person.profile)
19411
- }),
19965
+ person: trpcRouter(personRouterPlugin(handlers.person)),
19412
19966
  prototype: createPrototypeRouter(handlers.prototype),
19413
19967
  stagedUpload: createStagedUploadRouter(handlers.prototype.stagedUploads),
19414
19968
  recording: trpcRouter({
@@ -19483,6 +20037,7 @@ const handlers = {
19483
20037
  markRead: unavailable.execute
19484
20038
  },
19485
20039
  applyOperations: unavailable,
20040
+ edit: unavailable,
19486
20041
  createEditableFrame: unavailable,
19487
20042
  create: unavailable,
19488
20043
  get: unavailable,
@@ -19588,7 +20143,14 @@ const handlers = {
19588
20143
  list: () => unavailable.execute(),
19589
20144
  find: () => unavailable.execute(),
19590
20145
  isConnected: () => unavailable.execute(),
20146
+ hasEverConnected: () => unavailable.execute(),
19591
20147
  revoke: () => unavailable.execute()
20148
+ },
20149
+ onboarding: {
20150
+ read: () => unavailable.execute(),
20151
+ dismiss: () => unavailable.execute(),
20152
+ present: () => unavailable.execute(),
20153
+ recordCanvasLinkCopied: () => unavailable.execute()
19592
20154
  }
19593
20155
  },
19594
20156
  prototype: {
@@ -20074,4 +20636,4 @@ const withCommandInFailure = (value, commandName) => ({
20074
20636
  });
20075
20637
 
20076
20638
  //#endregion
20077
- export { canvasAssetImportInputSchema as $, applyCanvasTypographyPatch as $n, canvasAxisStyleProperties as $r, inSurfaceWords as $t, recordingSnapshotCapabilityInputSchema as A, createAgentTokenOutputSchema as An, textOf as Ar, canvasSnapshotToken as At, operationStatusImageSchema as B, domLocatorSchema as Bn, canvasRenderTargetSchema as Br, canvasResourcesCursorSchema as Bt, PROCEDURE_DESCRIPTIONS as C, getPrototypePublishStatusOutputSchema as Cn, RECTANGLE_KIND as Cr, ROOT_FIELD as Ct, canvasWriteHtmlCapabilityInputSchema as D, getMeOutputSchema as Dn, applyCanvasOperationsOutputSchema as Dr, objectFieldNames as Dt, canvasRenderCapabilityInputSchema as E, submitPrototypeArtifactOutputSchema as En, applyCanvasOperationsInputSchema as Er, isInputRecord as Et, canvasPrototypeCapabilityInputSchema as F, commentAuthorSchema as Fn, canvasNodeStylePatchSchema as Fr, canvasReadInputSchema as Ft, canvasCaptureOutputSchema as G, replyCommentInputSchema as Gn, getCanvasRenderOutputSchema as Gr, hasCanvasReferenceScope as Gt, operationStatusOutputSchema as H, getCommentOutputSchema as Hn, createCanvasRenderOutputSchema as Hr, canvasReferenceNodeIds as Ht, canvasPrototypeInputSchema as I, commentCanvasContextSchema as In, createCanvasConversionOutputSchema as Ir, canvasReadOutputSchema as It, canvasDuplicateCapabilityInputSchema as J, screenElementCommentTargetSchema as Jn, emptyCanvasSceneDocument as Jr, callOf as Jt, canvasArrangeCapabilityInputSchema as K, replyCommentOutputSchema as Kn, canvasReadableSceneDocumentSchema as Kr, parseCanvasReference as Kt, canvasPrototypeIntentSchema as L, commentMessageSchema as Ln, getCanvasConversionOutputSchema as Lr, canvasUpdateHtmlCapabilityInputSchema as Lt, canvasCapturePageCapabilityInputSchema as M, listOrganisationsOutputSchema as Mn, saveCanvasDocumentOutputSchema as Mr, encodeCanvasExchangeToken as Mt, canvasCapturePageInputSchema as N, emptyFixtureDocument as Nn, wholeCanvasDocumentOutputSchema as Nr, resolveCanvasSnapshot as Nt, commentAttentionCapabilityInputSchema as O, MCP_AUTH_SCOPE as On, getCanvasMutationOutputSchema as Or, quotedValue as Ot, canvasCapturePageOutputSchema as P, withFixtureScreen as Pn, canvasOperationSchema as Pr, canvasOutlineCursorSchema as Pt, canvasAssetImportCapabilityInputSchema as Q, createCapturePassOutputSchema as Qn, canvasAuthoredStyleDeclarations as Qr, diagnosisStep as Qt, canvasPrototypeOutputSchema as R, commentResolverSchema as Rn, canvasRenderSourceStateSchema as Rr, canvasUpdateHtmlInputSchema as Rt, PROTOTYPE_UPDATE_GUIDANCE as S, getPrototypeArtifactCapabilitiesOutputSchema as Sn, PAGE_KIND as Sr, canvasEditsSchema as St, canvasReadCapabilityInputSchema as T, prototypeArtifactPathSchema as Tn, TEXT_KIND as Tr, inputProblemSummary as Tt, canvasCaptureCapabilityInputSchema as U, listCommentsInputSchema as Un, createRecordingSnapshotOutputSchema as Ur, canvasReferenceRenderTarget as Ut, operationStatusInputSchema as V, elementAnchorSchema as Vn, canvasWorldBoundsSchema as Vr, assertCanvasReferenceNodes as Vt, canvasCaptureInputSchema as W, listCommentsOutputSchema as Wn, downloadCanvasRenderOutputSchema as Wr, fromCanvasReference as Wt, canvasPreparationOutputSchema as X, screenTextCommentTargetSchema as Xn, canvasRecordedBoxNoteFor as Xr, commandName as Xt, canvasDuplicateInputSchema as Y, screenElementsCommentTargetSchema as Yn, canvasBoxSourceOf as Yr, cliPathOf as Yt, canvasWriteReceiptSchema as Z, startCommentInputSchema as Zn, canvasAuthoredLayoutValueOf as Zr, currentNodeIdStep as Zt, CANVAS_UPDATE_HTML_INPUT_EXAMPLE as _, CANVAS_BLEND_MODES as _i, startRecordingOutputSchema as _n, createCanvasPreparationOutputSchema as _r, canvasInsertHtmlCapabilityInputSchema as _t, createRouterShapeAdapter as a, canvasCssValue as ai, SKILL_NAMES as an, canvasCaptureSchema as ar, canvasRenderScopedToolInputSchema as at, ProcessExitError as b, canvasSchema as bi, createPrototypeArtifactOutputSchema as bn, GROUP_KIND as br, canvasMakeEditableInputSchema as bt, toKebabCase as c, reserveCanvasAssetOutputSchema as ci, CliError as cn, canvasRecordingPropsSchema as cr, canvasRemoveCapabilityInputSchema as ct, createMcpCapabilityDiscoveryAdapter as d, signedDownloadSchema as di, appErrorSchema as dn, canvasReferencePageOf as dr, canvasCreateToolOutputSchema as dt, canvasCssPixelValue as ei, inputName as en, canvasCssTypographyOwners as er, canvasAssetImportOutputSchema as et, toExitCode as f, canvasRichTextOf as fi, completeScreenOutputSchema as fn, resolveCanvasReference as fr, canvasFindCursorSchema as ft, toRemoteError as g, canvasAdditionalStyleSchema as gi, getRecordingOutputSchema as gn, agentClientMetadata as gr, listedCanvasesAnswerSchema as gt, toPublishedExitTable as h, CANVAS_RICH_TEXT_STYLE_PROPERTIES as hi, completeRecordingOutputSchema as hn, AGENT_CLIENT_HEADER as hr, createdCanvasAnswerSchema as ht, createLazyCapabilityCatalogAdapter as i, canvasCssTokens as ii, SKILL_JOBS as in, CAPTURE_LANDING_CONVERTING as ir, canvasRenderScopedInputSchema as it, transcriptReadCapabilityInputSchema as j, createOrganisationOutputSchema as jn, mapCanvasFontSources as jr, decodeCanvasExchangeToken as jt, prototypePublishCapabilityInputSchema as k, cliAuthConfigurationSchema as kn, canvasLayoutWithoutCssProperties as kr, canvasExchangeDigest as kt, toPresentedCapabilities as l, canvasFontAssetIdentityFromPath as li, isFormatRefusalError as ln, captureLandingSchema as lr, canvasRemoveInputSchema as lt, toMcpFailurePayload as m, hasCanvasRichTextPaints as mi, appendRecordingChunkOutputSchema as mn, canvasAgentActivityPhaseSchema as mr, canvasFindOutputSchema as mt, withCommandName as n, canvasLayoutPositionOf as ni, onSurface as nn, canvasTextPropsWithContent as nr, canvasRenderBatchResultSchema as nt, CAPTURE_PAGE_CALLS as o, canvasAssetUploadOutputSchema as oi, skillTextsFor as on, canvasConversionMetadataSchema as or, canvasRenderRequestSchema as ot, toFailurePayload as p, canvasRichTextValueOf as pi, createScreenOutputSchema as pn, beginCanvasActivityOutputSchema as pr, canvasFindInputSchema as pt, canvasArrangeInputSchema as q, screenAreaCommentTargetSchema as qn, canvasSceneDocumentSchema as qr, readStoredCanvasScene as qt, toCanvasAuthoringResult as r, canvasLayoutPriorityDeclarations as ri, MCP_TOOL_BY_CAPABILITY as rn, canvasTextRunsOf as rr, canvasRenderPendingSchema as rt, toCapabilityDefinition as s, reserveCanvasAssetInputSchema as si, PartialBatchError as sn, canvasPrototypePropsSchema as sr, canvasRenderFileSchema as st, withCommandInFailure as t, canvasLayoutMainAxisOf as ti, layerListName as tn, canvasTextChangeBetween as tr, canvasRenderBatchRequestSchema as tt, toSharedCapabilities as u, canvasImageAssetIdentityFromPath as ui, transcriptOutputSchema as un, DEFAULT_CANVAS_REFERENCE_PAGE_ID as ur, canvasCreateToolInputSchema as ut, CAPABILITY_UUID_EXAMPLE as v, canvasBlendModeSchema as vi, PROTOTYPE_ARTIFACT_MANIFEST_PATH as vn, getCanvasPreparationOutputSchema as vr, canvasInsertHtmlInputSchema as vt, canvasApplyCapabilityInputSchema as w, prototypeArtifactManifestSchema as wn, SCREEN_KIND as wr, inputProblemFields as wt, OPTION_DESCRIPTIONS as x, foldPrototypeArtifactPath as xn, IMAGE_KIND as xr, canvasEditCapabilityInputSchema as xt, createCapabilityPolicyAdapter as y, canvasPaintSchema as yi, attachPrototypeArtifactOutputSchema as yn, FRAME_KIND as yr, canvasMakeEditableCapabilityInputSchema as yt, canvasConversionStatusSchema as z, commentThreadSchema as zn, canvasRenderStateSchema as zr, canvasTranscriptCursorSchema as zt };
20639
+ export { canvasWriteReceiptSchema as $, listCommentsOutputSchema as $n, reserveCanvasAssetOutputSchema as $r, callingSurface as $t, commentAttentionCapabilityInputSchema as A, endCanvasActivityOutputSchema as Ai, foldPrototypeArtifactPath as An, IMAGE_KIND as Ar, quotedValue as At, canvasPrototypeOutputSchema as B, createOrganisationOutputSchema as Bn, canvasBoxSourceOf as Br, encodeCanvasExchangeToken as Bt, OPTION_DESCRIPTIONS as C, emptyCanvasSceneDocument as Ci, appendRecordingChunkOutputSchema as Cn, canvasAgentActivityPhaseSchema as Cr, canvasEditCapabilityInputSchema as Ct, canvasReadCapabilityInputSchema as D, CANVAS_BLEND_MODES as Di, PROTOTYPE_ARTIFACT_MANIFEST_PATH as Dn, getCanvasPreparationOutputSchema as Dr, inputProblemSummary as Dt, canvasApplyCapabilityInputSchema as E, canvasAdditionalStyleSchema as Ei, startRecordingOutputSchema as En, createCanvasPreparationOutputSchema as Er, inputProblemFields as Et, canvasCapturePageInputSchema as F, submitPrototypeArtifactOutputSchema as Fn, canvasLayoutWithoutCssProperties as Fr, hasCanvasReferenceScope as Ft, canvasCaptureCapabilityInputSchema as G, commentCanvasContextSchema as Gn, canvasCssPixelValue as Gr, canvasUpdateHtmlCapabilityInputSchema as Gt, operationStatusImageSchema as H, emptyFixtureDocument as Hn, canvasAuthoredLayoutValueOf as Hr, canvasOutlineCursorSchema as Ht, canvasCapturePageOutputSchema as I, getMeOutputSchema as In, textOf as Ir, parseCanvasReference as It, canvasArrangeCapabilityInputSchema as J, commentThreadSchema as Jn, canvasLayoutPriorityDeclarations as Jr, canvasTranscriptCursorSchema as Jt, canvasCaptureInputSchema as K, commentMessageSchema as Kn, canvasLayoutMainAxisOf as Kr, canvasUpdateHtmlInputSchema as Kt, canvasPrototypeCapabilityInputSchema as L, MCP_AUTH_SCOPE as Ln, mapCanvasFontSources as Lr, canvasExchangeDigest as Lt, recordingSnapshotCapabilityInputSchema as M, getPrototypePublishStatusOutputSchema as Mn, RECTANGLE_KIND as Mr, canvasReferenceNodeIds as Mt, transcriptReadCapabilityInputSchema as N, prototypeArtifactManifestSchema as Nn, SCREEN_KIND as Nr, canvasReferenceRenderTarget as Nt, canvasRenderCapabilityInputSchema as O, canvasBlendModeSchema as Oi, attachPrototypeArtifactOutputSchema as On, FRAME_KIND as Or, isInputRecord as Ot, canvasCapturePageCapabilityInputSchema as P, prototypeArtifactPathSchema as Pn, TEXT_KIND as Pr, fromCanvasReference as Pt, canvasPreparationOutputSchema as Q, listCommentsInputSchema as Qn, reserveCanvasAssetInputSchema as Qr, callOf as Qt, canvasPrototypeInputSchema as R, cliAuthConfigurationSchema as Rn, saveCanvasDocumentOutputSchema as Rr, canvasSnapshotToken as Rt, ProcessExitError as S, canvasSceneDocumentSchema as Si, createScreenOutputSchema as Sn, beginCanvasActivityOutputSchema as Sr, canvasMakeEditableInputSchema as St, PROCEDURE_DESCRIPTIONS as T, signedDownloadSchema as Ti, getRecordingOutputSchema as Tn, agentClientMetadata as Tr, ROOT_FIELD as Tt, operationStatusInputSchema as U, withFixtureScreen as Un, canvasAuthoredStyleDeclarations as Ur, canvasReadInputSchema as Ut, canvasConversionStatusSchema as V, listOrganisationsOutputSchema as Vn, canvasRecordedBoxNoteFor as Vr, resolveCanvasSnapshot as Vt, operationStatusOutputSchema as W, commentAuthorSchema as Wn, canvasAxisStyleProperties as Wr, canvasReadOutputSchema as Wt, canvasDuplicateCapabilityInputSchema as X, elementAnchorSchema as Xn, canvasCssValue as Xr, tallyCanvasWork as Xt, canvasArrangeInputSchema as Y, domLocatorSchema as Yn, canvasCssTokens as Yr, canvasResourcesCursorSchema as Yt, canvasDuplicateInputSchema as Z, getCommentOutputSchema as Zn, canvasAssetUploadOutputSchema as Zr, readStoredCanvasScene as Zt, toPublishedExitTable as _, createCanvasRenderOutputSchema as _i, CliError as _n, canvasRecordingPropsSchema as _r, createdCanvasAnswerSchema as _t, createRouterShapeAdapter as a, editCanvasOutputSchema as ai, inputName as an, screenTextCommentTargetSchema as ar, canvasRenderPendingSchema as at, CAPABILITY_UUID_EXAMPLE as b, getCanvasRenderOutputSchema as bi, appErrorSchema as bn, canvasReferencePageOf as br, canvasInsertHtmlInputSchema as bt, toKebabCase as c, getCanvasMutationOutputSchema as ci, CANVAS_EDIT_WORDS as cn, applyCanvasTypographyPatch as cr, canvasRenderRequestSchema as ct, toPresentedCapabilities as d, createCanvasConversionOutputSchema as di, pointOfUseText as dn, canvasTextPropsWithContent as dr, canvasRemoveInputSchema as dt, canvasFontAssetIdentityFromPath as ei, cliPathOf as en, replyCommentInputSchema as er, canvasAssetImportCapabilityInputSchema as et, toSharedCapabilities as f, getCanvasConversionOutputSchema as fi, startUpListFor as fn, canvasTextRunsOf as fr, canvasCreateToolInputSchema as ft, toMcpFailurePayload as g, canvasWorldBoundsSchema as gi, skillTextsFor as gn, canvasPrototypePropsSchema as gr, canvasFindOutputSchema as gt, toFailurePayload as h, canvasRenderTargetSchema as hi, SKILL_NAMES as hn, canvasConversionMetadataSchema as hr, canvasFindInputSchema as ht, createLazyCapabilityCatalogAdapter as i, CANVAS_RICH_TEXT_STYLE_PROPERTIES as ii, inSurfaceWords as in, screenElementsCommentTargetSchema as ir, canvasRenderBatchResultSchema as it, prototypePublishCapabilityInputSchema as j, canvasSchema as ji, getPrototypeArtifactCapabilitiesOutputSchema as jn, PAGE_KIND as jr, assertCanvasReferenceNodes as jt, canvasWriteHtmlCapabilityInputSchema as k, canvasPaintSchema as ki, createPrototypeArtifactOutputSchema as kn, GROUP_KIND as kr, objectFieldNames as kt, GUIDE_TOPICS as l, canvasOperationSchema as li, PartialBatchError as ln, canvasCssTypographyOwners as lr, canvasRenderFileSchema as lt, toExitCode as m, canvasRenderStateSchema as mi, SKILL_JOBS as mn, canvasCaptureSchema as mr, canvasFindCursorSchema as mt, withCommandName as n, canvasRichTextValueOf as ni, currentNodeIdStep as nn, screenAreaCommentTargetSchema as nr, canvasAssetImportOutputSchema as nt, CAPTURE_PAGE_CALLS as o, applyCanvasOperationsInputSchema as oi, onSurface as on, startCommentInputSchema as or, canvasRenderScopedInputSchema as ot, createMcpCapabilityDiscoveryAdapter as p, canvasRenderSourceStateSchema as pi, DESIGN_RULES as pn, CAPTURE_LANDING_CONVERTING as pr, canvasCreateToolOutputSchema as pt, canvasCaptureOutputSchema as q, commentResolverSchema as qn, canvasLayoutPositionOf as qr, retryClientTokenSchema as qt, toCanvasAuthoringResult as r, hasCanvasRichTextPaints as ri, diagnosisStep as rn, screenElementCommentTargetSchema as rr, canvasRenderBatchRequestSchema as rt, toCapabilityDefinition as s, applyCanvasOperationsOutputSchema as si, MCP_TOOL_BY_CAPABILITY as sn, createCapturePassOutputSchema as sr, canvasRenderScopedToolInputSchema as st, withCommandInFailure as t, canvasRichTextOf as ti, commandName as tn, replyCommentOutputSchema as tr, canvasAssetImportInputSchema as tt, GUIDE_TOPIC_NAMES as u, canvasNodeStylePatchSchema as ui, loadGuideLineFor as un, canvasTextChangeBetween as ur, canvasRemoveCapabilityInputSchema as ut, toRemoteError as v, createRecordingSnapshotOutputSchema as vi, isFormatRefusalError as vn, captureLandingSchema as vr, listedCanvasesAnswerSchema as vt, PROTOTYPE_UPDATE_GUIDANCE as w, canvasImageAssetIdentityFromPath as wi, completeRecordingOutputSchema as wn, AGENT_CLIENT_HEADER as wr, canvasEditsSchema as wt, createCapabilityPolicyAdapter as x, canvasReadableSceneDocumentSchema as xi, completeScreenOutputSchema as xn, resolveCanvasReference as xr, canvasMakeEditableCapabilityInputSchema as xt, CANVAS_UPDATE_HTML_INPUT_EXAMPLE as y, downloadCanvasRenderOutputSchema as yi, transcriptOutputSchema as yn, DEFAULT_CANVAS_REFERENCE_PAGE_ID as yr, canvasInsertHtmlCapabilityInputSchema as yt, canvasPrototypeIntentSchema as z, createAgentTokenOutputSchema as zn, wholeCanvasDocumentOutputSchema as zr, decodeCanvasExchangeToken as zt };