@senad-d/drawme 0.1.4 → 0.1.6

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.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Deterministic canvas fit for `.drawio` files: per page, resize
3
+ * pageWidth/pageHeight to the visible content plus a margin and shift content
4
+ * so it starts exactly at that margin. Grows cramped pages and tightens
5
+ * oversized ones without touching element sizes or relative positions. No
6
+ * draw.io CLI involved.
7
+ */
8
+ import { readFile, writeFile } from "node:fs/promises";
9
+ import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
10
+ import { type DomEl, attr, childrenByTag, directText, firstByTag } from "./dom";
11
+ import { type ById, collectCellsWithIds, contentBounds, geometryIsRelative, pyFloat } from "./geometry";
12
+
13
+ export const DEFAULT_FIT_MARGIN = 40;
14
+
15
+ export interface FitPageResult {
16
+ page: string;
17
+ status: "fitted" | "unchanged" | "skipped";
18
+ /** Why the page was skipped. */
19
+ reason?: string;
20
+ before?: { width?: number; height?: number };
21
+ after?: { width: number; height: number };
22
+ shift?: { dx: number; dy: number };
23
+ }
24
+
25
+ export interface FitCanvasOptions {
26
+ input: string;
27
+ /** Outer margin between content and page edge, in model px (default 40). */
28
+ margin?: number;
29
+ /** Destination path; defaults to overwriting the input. */
30
+ output?: string;
31
+ }
32
+
33
+ export interface FitCanvasResult {
34
+ input: string;
35
+ output: string;
36
+ margin: number;
37
+ /** True when at least one page was resized or shifted. */
38
+ changed: boolean;
39
+ pages: FitPageResult[];
40
+ }
41
+
42
+ function fmt(value: number): string {
43
+ return String(Math.round(value * 1000) / 1000);
44
+ }
45
+
46
+ function shiftAttr(el: DomEl, name: "x" | "y", delta: number): void {
47
+ const current = pyFloat(attr(el, name) ?? "0");
48
+ if (current === undefined || !Number.isFinite(current)) return;
49
+ el.setAttribute(name, fmt(current + delta));
50
+ }
51
+
52
+ /** Shift one top-level cell: absolute vertex origin, or edge points/waypoints. */
53
+ function shiftCell(cell: DomEl, dx: number, dy: number): void {
54
+ const geometry = firstByTag(cell, "mxGeometry");
55
+ if (!geometry) return;
56
+ if (cell.getAttribute("vertex") === "1" && !geometryIsRelative(cell)) {
57
+ shiftAttr(geometry, "x", dx);
58
+ shiftAttr(geometry, "y", dy);
59
+ return;
60
+ }
61
+ if (cell.getAttribute("edge") === "1") {
62
+ for (const point of childrenByTag(geometry, "mxPoint")) {
63
+ const as = attr(point, "as");
64
+ if (as === "sourcePoint" || as === "targetPoint") {
65
+ shiftAttr(point, "x", dx);
66
+ shiftAttr(point, "y", dy);
67
+ }
68
+ }
69
+ const waypoints = firstByTag(geometry, "Array");
70
+ for (const point of waypoints ? childrenByTag(waypoints, "mxPoint") : []) {
71
+ shiftAttr(point, "x", dx);
72
+ shiftAttr(point, "y", dy);
73
+ }
74
+ }
75
+ }
76
+
77
+ /** Ids of layer cells (direct children of the root cell `0`). */
78
+ function layerIds(ids: ById): Set<string> {
79
+ const layers = new Set<string>();
80
+ for (const [id, cell] of ids) {
81
+ if (attr(cell, "parent") === "0") layers.add(id);
82
+ }
83
+ return layers;
84
+ }
85
+
86
+ function pageScale(model: DomEl): number {
87
+ const raw = attr(model, "pageScale");
88
+ const parsed = raw === null ? 1 : pyFloat(raw);
89
+ return parsed !== undefined && Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
90
+ }
91
+
92
+ function currentDimension(model: DomEl, name: "pageWidth" | "pageHeight"): number | undefined {
93
+ const raw = attr(model, name);
94
+ if (raw === null) return undefined;
95
+ const value = pyFloat(raw);
96
+ return value !== undefined && Number.isFinite(value) && value > 0 ? value : undefined;
97
+ }
98
+
99
+ /** Fit a single page's model in place; returns what happened. */
100
+ function fitModel(name: string, model: DomEl, margin: number): FitPageResult {
101
+ if (attr(model, "page") === "0") {
102
+ return { page: name, status: "skipped", reason: "page canvas disabled (infinite canvas)" };
103
+ }
104
+ const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
105
+ const bounds = contentBounds(cells, ids);
106
+ if (!bounds) return { page: name, status: "skipped", reason: "no measurable content" };
107
+
108
+ const scale = pageScale(model);
109
+ const rawDx = margin - bounds.minX;
110
+ const rawDy = margin - bounds.minY;
111
+ const dx = Math.abs(rawDx) < 0.005 ? 0 : Math.round(rawDx * 1000) / 1000;
112
+ const dy = Math.abs(rawDy) < 0.005 ? 0 : Math.round(rawDy * 1000) / 1000;
113
+ const width = Math.ceil((bounds.maxX - bounds.minX + 2 * margin) / scale);
114
+ const height = Math.ceil((bounds.maxY - bounds.minY + 2 * margin) / scale);
115
+ const before = { width: currentDimension(model, "pageWidth"), height: currentDimension(model, "pageHeight") };
116
+
117
+ if (dx === 0 && dy === 0 && before.width === width && before.height === height) {
118
+ return { page: name, status: "unchanged", before, after: { width, height } };
119
+ }
120
+
121
+ if (dx !== 0 || dy !== 0) {
122
+ const layers = layerIds(ids);
123
+ for (const cell of cells) {
124
+ const parent = attr(cell, "parent");
125
+ if (parent !== null && layers.has(parent)) shiftCell(cell, dx, dy);
126
+ }
127
+ }
128
+ model.setAttribute("pageWidth", String(width));
129
+ model.setAttribute("pageHeight", String(height));
130
+ return { page: name, status: "fitted", before, after: { width, height }, shift: { dx, dy } };
131
+ }
132
+
133
+ function fitPage(diagram: DomEl, margin: number): FitPageResult {
134
+ const name = attr(diagram, "name") ?? "?";
135
+ const model = firstByTag(diagram, "mxGraphModel");
136
+ if (!model) {
137
+ const reason = directText(diagram).trim() ? "compressed page (cannot fit)" : "no <mxGraphModel>";
138
+ return { page: name, status: "skipped", reason };
139
+ }
140
+ return fitModel(name, model, margin);
141
+ }
142
+
143
+ /** Fit every page of a `.drawio` file. Throws on read/parse failure or invalid margin. */
144
+ export async function fitCanvasFile(options: FitCanvasOptions): Promise<FitCanvasResult> {
145
+ const margin = options.margin ?? DEFAULT_FIT_MARGIN;
146
+ if (!Number.isFinite(margin) || margin < 0) throw new Error(`invalid margin ${String(options.margin)}`);
147
+ const output = options.output ?? options.input;
148
+ const xml = await readFile(options.input, "utf8");
149
+ const doc = new DOMParser().parseFromString(xml, "text/xml");
150
+ const root = doc.documentElement as unknown as DomEl | null;
151
+ if (!root) throw new Error("no root element (malformed XML)");
152
+
153
+ const diagrams = childrenByTag(root, "diagram");
154
+ let pages: FitPageResult[];
155
+ if (diagrams.length > 0) {
156
+ pages = diagrams.map((diagram) => fitPage(diagram, margin));
157
+ } else if (root.tagName === "mxGraphModel") {
158
+ pages = [fitModel("?", root, margin)];
159
+ } else {
160
+ pages = [{ page: "?", status: "skipped", reason: "no <diagram> pages and root is not <mxGraphModel>" }];
161
+ }
162
+
163
+ const changed = pages.some((page) => page.status === "fitted");
164
+ if (changed || output !== options.input) {
165
+ let serialized = new XMLSerializer().serializeToString(doc as never);
166
+ const declaration = /^<\?xml[^>]*\?>/.exec(xml)?.[0];
167
+ if (declaration && !serialized.startsWith("<?xml")) serialized = `${declaration}\n${serialized}`;
168
+ if (xml.endsWith("\n") && !serialized.endsWith("\n")) serialized += "\n";
169
+ await writeFile(output, serialized, "utf8");
170
+ }
171
+ return { input: options.input, output, margin, changed, pages };
172
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Shared `.drawio` geometry: cell collection, absolute rectangles, explicit
3
+ * edge routes, and visible content bounds. Used by the structural validator
4
+ * and the canvas-fit tool so both agree on what "content" means.
5
+ */
6
+ import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
7
+
8
+ /** [x, y, width, height]. width/height may be NaN when the source omits them. */
9
+ export type Rect = [number, number, number, number];
10
+ export type Point = [number, number];
11
+ export type ById = Map<string, DomEl>;
12
+
13
+ export interface ContentBounds {
14
+ minX: number;
15
+ minY: number;
16
+ maxX: number;
17
+ maxY: number;
18
+ }
19
+
20
+ /** Python `float()` semantics: accepts nan/inf, strict-numeric otherwise; else undefined (≈ ValueError). */
21
+ export function pyFloat(s: string): number | undefined {
22
+ const t = s.trim().toLowerCase();
23
+ if (t === "nan" || t === "+nan" || t === "-nan") return Number.NaN;
24
+ if (t === "inf" || t === "+inf" || t === "infinity" || t === "+infinity") return Infinity;
25
+ if (t === "-inf" || t === "-infinity") return -Infinity;
26
+ if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(t)) return undefined;
27
+ const n = Number(t);
28
+ return Number.isNaN(n) ? undefined : n;
29
+ }
30
+
31
+ export function hasInvalidNumber(values: number[]): boolean {
32
+ return values.some((value) => !Number.isFinite(value));
33
+ }
34
+
35
+ export function rect(cell: DomEl): Rect | null {
36
+ const gy = firstByTag(cell, "mxGeometry");
37
+ if (!gy) return null;
38
+ const x = pyFloat(attr(gy, "x") ?? "0");
39
+ const y = pyFloat(attr(gy, "y") ?? "0");
40
+ const w = pyFloat(attr(gy, "width") ?? "nan");
41
+ const h = pyFloat(attr(gy, "height") ?? "nan");
42
+ if (x === undefined || y === undefined || w === undefined || h === undefined) return null;
43
+ return [x, y, w, h];
44
+ }
45
+
46
+ export function geometryIsRelative(cell: DomEl): boolean {
47
+ return firstByTag(cell, "mxGeometry")?.getAttribute("relative") === "1";
48
+ }
49
+
50
+ /** True for separate edge-label vertices. */
51
+ export function isEdgeLabel(cell: DomEl): boolean {
52
+ return (attr(cell, "style") ?? "").includes("edgeLabel");
53
+ }
54
+
55
+ export function isVisible(cell: DomEl, byId: ById): boolean {
56
+ let current: DomEl | undefined = cell;
57
+ const seen = new Set<string>();
58
+ while (current) {
59
+ if (attr(current, "visible") === "0") return false;
60
+ const parent = attr(current, "parent");
61
+ if (!parent || seen.has(parent)) break;
62
+ seen.add(parent);
63
+ current = byId.get(parent);
64
+ }
65
+ return true;
66
+ }
67
+
68
+ export function styleNum(style: string | null, key: string): number | undefined {
69
+ for (const part of (style ?? "").split(";")) {
70
+ if (part.startsWith(key + "=")) return pyFloat(part.split("=").slice(1).join("="));
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ /** Absolute (x, y, w, h) of a non-relative vertex, summing parent-container offsets. */
76
+ export function absRect(cell: DomEl, byId: ById): Rect | null {
77
+ const r = rect(cell);
78
+ if (r === null || hasInvalidNumber(r)) return null;
79
+ let [x, y] = r;
80
+ const [, , w, h] = r;
81
+ let parent = attr(cell, "parent");
82
+ const seen = new Set<string>();
83
+ while (parent && byId.has(parent) && !seen.has(parent)) {
84
+ seen.add(parent);
85
+ const p = byId.get(parent)!;
86
+ if (p.getAttribute("vertex") === "1" && !geometryIsRelative(p)) {
87
+ const pr = rect(p);
88
+ if (pr && !hasInvalidNumber(pr)) {
89
+ x += pr[0];
90
+ y += pr[1];
91
+ }
92
+ }
93
+ parent = attr(p, "parent");
94
+ }
95
+ return [x, y, w, h];
96
+ }
97
+
98
+ /** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
99
+ export function endpoint(edge: DomEl, end: "source" | "target", byId: ById): Point | null {
100
+ const vid = attr(edge, end);
101
+ if (!vid || !byId.has(vid)) return null;
102
+ const box = absRect(byId.get(vid)!, byId);
103
+ if (box === null) return null;
104
+ const [x, y, w, h] = box;
105
+ const style = attr(edge, "style") ?? "";
106
+ const fx = styleNum(style, end === "source" ? "exitX" : "entryX");
107
+ const fy = styleNum(style, end === "source" ? "exitY" : "entryY");
108
+ return [x + (fx ?? 0.5) * w, y + (fy ?? 0.5) * h];
109
+ }
110
+
111
+ export function edgeWaypoints(edge: DomEl): Point[] {
112
+ const gy = firstByTag(edge, "mxGeometry");
113
+ if (!gy) return [];
114
+ const arr = firstByTag(gy, "Array");
115
+ if (!arr) return [];
116
+ const points: Point[] = [];
117
+ for (const point of childrenByTag(arr, "mxPoint")) {
118
+ const x = pyFloat(attr(point, "x") ?? "");
119
+ const y = pyFloat(attr(point, "y") ?? "");
120
+ if (x !== undefined && y !== undefined && Number.isFinite(x) && Number.isFinite(y)) points.push([x, y]);
121
+ }
122
+ return points;
123
+ }
124
+
125
+ /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
126
+ export function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
127
+ const waypoints = edgeWaypoints(edge);
128
+ if (waypoints.length === 0) return null;
129
+ const source = endpoint(edge, "source", byId);
130
+ const target = endpoint(edge, "target", byId);
131
+ if (source === null || target === null) return null;
132
+ return [source, ...waypoints, target];
133
+ }
134
+
135
+ export function routeMidpoint(points: Point[]): Point {
136
+ const lengths: number[] = [];
137
+ let total = 0;
138
+ for (let i = 0; i < points.length - 1; i++) {
139
+ const length = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][1] - points[i][1]);
140
+ lengths.push(length);
141
+ total += length;
142
+ }
143
+ let remaining = total / 2;
144
+ for (let i = 0; i < lengths.length; i++) {
145
+ if (remaining <= lengths[i]) {
146
+ const fraction = lengths[i] === 0 ? 0 : remaining / lengths[i];
147
+ return [
148
+ points[i][0] + fraction * (points[i + 1][0] - points[i][0]),
149
+ points[i][1] + fraction * (points[i + 1][1] - points[i][1]),
150
+ ];
151
+ }
152
+ remaining -= lengths[i];
153
+ }
154
+ return points.at(-1) ?? [0, 0];
155
+ }
156
+
157
+ /** Conservative box for a separately sized label on an explicitly routed edge. */
158
+ export function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
159
+ if (!isEdgeLabel(cell)) return null;
160
+ const local = rect(cell);
161
+ const parent = attr(cell, "parent");
162
+ const edge = parent ? byId.get(parent) : undefined;
163
+ if (!local || hasInvalidNumber(local) || edge?.getAttribute("edge") !== "1") return null;
164
+ const route = edgeRoute(edge, byId);
165
+ if (!route) return null;
166
+ const [midX, midY] = routeMidpoint(route);
167
+ const geometry = firstByTag(cell, "mxGeometry");
168
+ const offset = geometry
169
+ ? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === "offset")
170
+ : undefined;
171
+ const offsetX = offset ? pyFloat(attr(offset, "x") ?? "0") : 0;
172
+ const offsetY = offset ? pyFloat(attr(offset, "y") ?? "0") : 0;
173
+ if (offsetX === undefined || offsetY === undefined || !Number.isFinite(offsetX) || !Number.isFinite(offsetY)) {
174
+ return null;
175
+ }
176
+ return [midX + offsetX - local[2] / 2, midY + offsetY - local[3] / 2, local[2], local[3]];
177
+ }
178
+
179
+ /** Fold UserObject/object wrappers into their inner mxCell so wrapper ids resolve. */
180
+ export function collectCells(root: DomEl | null): DomEl[] {
181
+ const cells: DomEl[] = [];
182
+ for (const child of root ? elemChildren(root) : []) {
183
+ if (child.tagName === "mxCell") cells.push(child);
184
+ else if (child.tagName === "UserObject" || child.tagName === "object") {
185
+ const inner = firstByTag(child, "mxCell");
186
+ if (inner) {
187
+ inner.setAttribute("id", attr(child, "id") ?? "");
188
+ cells.push(inner);
189
+ }
190
+ }
191
+ }
192
+ return cells;
193
+ }
194
+
195
+ /**
196
+ * Non-mutating variant of collectCells for callers that serialize the DOM
197
+ * afterwards: wrapper ids resolve through the returned map instead of being
198
+ * written onto the inner mxCell.
199
+ */
200
+ export function collectCellsWithIds(root: DomEl | null): { cells: DomEl[]; ids: ById } {
201
+ const cells: DomEl[] = [];
202
+ const ids: ById = new Map();
203
+ for (const child of root ? elemChildren(root) : []) {
204
+ let cell: DomEl | null = null;
205
+ let id: string | null = null;
206
+ if (child.tagName === "mxCell") {
207
+ cell = child;
208
+ id = attr(child, "id");
209
+ } else if (child.tagName === "UserObject" || child.tagName === "object") {
210
+ const inner = firstByTag(child, "mxCell");
211
+ if (inner) {
212
+ cell = inner;
213
+ id = attr(child, "id");
214
+ }
215
+ }
216
+ if (cell) {
217
+ cells.push(cell);
218
+ ids.set(id ?? "", cell);
219
+ }
220
+ }
221
+ return { cells, ids };
222
+ }
223
+
224
+ export function addRectToBounds(bounds: ContentBounds | null, box: Rect): ContentBounds {
225
+ const [x, y, width, height] = box;
226
+ const next = bounds ?? { minX: x, minY: y, maxX: x + width, maxY: y + height };
227
+ next.minX = Math.min(next.minX, x);
228
+ next.minY = Math.min(next.minY, y);
229
+ next.maxX = Math.max(next.maxX, x + width);
230
+ next.maxY = Math.max(next.maxY, y + height);
231
+ return next;
232
+ }
233
+
234
+ export function addPointToBounds(bounds: ContentBounds | null, point: Point): ContentBounds {
235
+ return addRectToBounds(bounds, [point[0], point[1], 0, 0]);
236
+ }
237
+
238
+ export function contentRect(cell: DomEl, ids: ById): Rect | null {
239
+ if (cell.getAttribute("vertex") !== "1") return null;
240
+ if (isEdgeLabel(cell)) return explicitEdgeLabelRect(cell, ids);
241
+ if (geometryIsRelative(cell)) return null;
242
+ return absRect(cell, ids);
243
+ }
244
+
245
+ export function contentWaypoints(cell: DomEl): Point[] {
246
+ return cell.getAttribute("edge") === "1" ? edgeWaypoints(cell) : [];
247
+ }
248
+
249
+ /** Visible vertices/containers, practical edge-label boxes, and explicit waypoints. */
250
+ export function contentBounds(cells: DomEl[], ids: ById): ContentBounds | null {
251
+ let bounds: ContentBounds | null = null;
252
+ for (const cell of cells) {
253
+ if (!isVisible(cell, ids)) continue;
254
+ const box = contentRect(cell, ids);
255
+ if (box && !hasInvalidNumber(box)) bounds = addRectToBounds(bounds, box);
256
+ for (const point of contentWaypoints(cell)) bounds = addPointToBounds(bounds, point);
257
+ }
258
+ return bounds;
259
+ }
package/src/index.ts CHANGED
@@ -4,11 +4,12 @@
4
4
  * CLI. It exposes the authoring workflow as plain commands and model-callable
5
5
  * tools.
6
6
  *
7
- * Tools: drawio_check · drawio_export · drawio_validate · drawio_from_mermaid
8
- * drawio_layout · drawio_shapesearch · drawio_explain · drawio_open
7
+ * Tools: drawio_check · drawio_export · drawio_validate · drawio_fit_canvas
8
+ * drawio_from_mermaid · drawio_layout · drawio_shapesearch
9
+ * drawio_explain · drawio_open
9
10
  * Commands: /drawme · /drawme-check · /drawme-export
10
11
  */
11
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
13
  import { Type, type Static } from "typebox";
13
14
  import { fileURLToPath } from "node:url";
14
15
  import { dirname, resolve } from "node:path";
@@ -24,13 +25,13 @@ import {
24
25
  type LayoutPreset,
25
26
  } from "./drawio";
26
27
  import { validateFile } from "./validate";
28
+ import { fitCanvasFile } from "./fitcanvas";
27
29
  import { searchShapes } from "./shapesearch";
28
30
  import { explainFile } from "./explain";
29
31
  import { drawmeWorkflow } from "./workflow";
30
32
 
31
33
  const HERE = dirname(fileURLToPath(import.meta.url));
32
34
  const REF_DIR = resolve(HERE, "..", "assets", "references");
33
- const AGENT_REFERENCE_PATH = resolve(HERE, "..", "docs", "agent-guide.md");
34
35
 
35
36
  const FORMAT = Type.Union([Type.Literal("png"), Type.Literal("svg"), Type.Literal("pdf"), Type.Literal("jpg")]);
36
37
  const MODE = Type.Union([Type.Literal("preview"), Type.Literal("final")]);
@@ -54,16 +55,26 @@ export type DrawioExportInput = Static<typeof exportParams>;
54
55
 
55
56
  const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
56
57
 
57
- async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>) {
58
+ /**
59
+ * Whether the active model accepts image blocks. Unknown models fail open
60
+ * (attach the image) like Pi's built-in read tool; the provider layer replaces
61
+ * unsupported images with a text placeholder, so failing open is always safe.
62
+ */
63
+ function modelSupportsImages(ctx: ExtensionContext | undefined): boolean {
64
+ return ctx?.model?.input.includes("image") ?? true;
65
+ }
66
+
67
+ async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>, attachImage: boolean) {
58
68
  const content: (
59
69
  | { type: "text"; text: string }
60
70
  | { type: "image"; data: string; mimeType: "image/png" }
61
71
  )[] = [{ type: "text", text }];
62
- if (result.mode === "preview" && result.format === "png") {
72
+ const imageAttached = result.mode === "preview" && result.format === "png" && attachImage;
73
+ if (imageAttached) {
63
74
  const png = await readFile(result.output);
64
75
  content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
65
76
  }
66
- return { content, details: result };
77
+ return { content, details: { ...result, imageAttached } };
67
78
  }
68
79
 
69
80
  export default function drawme(pi: ExtensionAPI): void {
@@ -95,13 +106,14 @@ export default function drawme(pi: ExtensionAPI): void {
95
106
  name: "drawio_export",
96
107
  label: "draw.io: export",
97
108
  description:
98
- "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, never embedded, and attached to the text/metadata tool result for focused visual review. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview.",
109
+ "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, and never embedded; when the current model can view images it is attached to the tool result for visual review, and the result text always states whether it was attached. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file; a replacement preview asks for a fixed/not-fixed/regressed verdict against the prior image. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview.",
99
110
  promptSnippet:
100
- "Export a .drawio to PNG/SVG/PDF/JPG (each mode:'preview' call attaches the latest review image and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
111
+ "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' attaches the review image when the current model can view images — the result text says so — and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
101
112
  parameters: exportParams,
102
- async execute(_id, params) {
113
+ async execute(_id, params, _signal, _onUpdate, ctx) {
103
114
  try {
104
115
  const r = await exportDiagram(params as ExportOptions);
116
+ const canView = modelSupportsImages(ctx);
105
117
  const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
106
118
  if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
107
119
  if (r.removedPreviews.length > 0) lines.push(`Removed preview artifact(s): ${r.removedPreviews.join(", ")}`);
@@ -110,7 +122,20 @@ export default function drawme(pi: ExtensionAPI): void {
110
122
  }
111
123
  const versionSuffix = r.version ? ` (${r.version})` : "";
112
124
  lines.push(`binary=${r.binary}${versionSuffix}`);
113
- return exportResult(lines.join("\n"), r);
125
+ if (r.mode === "preview" && r.format === "png") {
126
+ if (!canView) {
127
+ lines.push(
128
+ "Preview image NOT attached: the current model cannot view images. Do not describe or judge the render; review structurally with drawio_validate and drawio_explain, and share the exported path so the user can view it.",
129
+ );
130
+ } else if (r.replacedPreview) {
131
+ lines.push(
132
+ "Preview image attached below. It replaces the previous preview, whose image is still visible earlier in this conversation: compare the two at each finding you addressed and record a verdict — fixed, not fixed, or regressed — before editing further.",
133
+ );
134
+ } else {
135
+ lines.push("Preview image attached below. Critique it against the current review pass's checklist before editing the source.");
136
+ }
137
+ }
138
+ return exportResult(lines.join("\n"), r, canView);
114
139
  } catch (e) {
115
140
  return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
116
141
  }
@@ -121,7 +146,7 @@ export default function drawme(pi: ExtensionAPI): void {
121
146
  name: "drawio_validate",
122
147
  label: "draw.io: validate",
123
148
  description:
124
- "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, and explicit routes through shapes or across edges. Reports observations and a readability score. Deterministic and does not launch draw.io. Run after every source edit and before exporting.",
149
+ "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, and explicit routes through shapes or across edges. Reports observations and a readability score. Deterministic and does not launch draw.io. Compressed pages cannot be linted and are reported as skipped. Fix boundary/margin/empty-space warnings (and make room for overlapping elements) by spreading elements and running drawio_fit_canvas — never by shrinking content. Run after every source edit and before exporting.",
125
150
  promptSnippet: "Lint a .drawio after every source edit and before exporting.",
126
151
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
127
152
  async execute(_id, params) {
@@ -140,6 +165,47 @@ export default function drawme(pi: ExtensionAPI): void {
140
165
  },
141
166
  });
142
167
 
168
+ pi.registerTool({
169
+ name: "drawio_fit_canvas",
170
+ label: "draw.io: fit canvas",
171
+ description:
172
+ "Resize each page's canvas to fit its content: sets pageWidth/pageHeight to the content bounding box plus a margin (default 40px) and shifts content so it starts exactly at that margin. Grows cramped pages and tightens oversized ones without changing element sizes or relative positions. Use when validation reports boundary, outer-margin, or empty-space warnings, or when elements need more room — spread elements apart, then fit the canvas; never shrink or cram elements to fit a page. Deterministic, no draw.io CLI. Skips compressed pages and intentional infinite canvases (page=\"0\"). Writes in place unless `output` is given; treat the result as a source edit and validate it.",
173
+ promptSnippet:
174
+ "Fit each page's canvas to its content plus a margin (default 40px) — enlarge the page instead of cramming elements; validate after.",
175
+ parameters: Type.Object({
176
+ input: Type.String({ description: "Path to the .drawio file" }),
177
+ margin: Type.Optional(Type.Number({ description: "Outer margin in px between content and page edge (default 40)" })),
178
+ output: Type.Optional(Type.String({ description: "Output path (default: overwrite the input)" })),
179
+ }),
180
+ async execute(_id, params) {
181
+ try {
182
+ const r = await fitCanvasFile(params);
183
+ const lines = r.pages.map((page) => {
184
+ if (page.status === "skipped") return `page '${page.page}': skipped (${page.reason ?? "unknown"})`;
185
+ const beforeText =
186
+ page.before?.width !== undefined && page.before?.height !== undefined
187
+ ? `${page.before.width}x${page.before.height}`
188
+ : "unset";
189
+ const afterText = `${page.after!.width}x${page.after!.height}`;
190
+ if (page.status === "unchanged") return `page '${page.page}': already fitted (${afterText})`;
191
+ const shiftText =
192
+ page.shift && (page.shift.dx !== 0 || page.shift.dy !== 0)
193
+ ? `, content shifted by (${page.shift.dx}, ${page.shift.dy})`
194
+ : "";
195
+ return `page '${page.page}': ${beforeText} → ${afterText} (margin ${r.margin}px${shiftText})`;
196
+ });
197
+ lines.push(
198
+ r.changed
199
+ ? `Wrote ${r.output}. This is a source edit: run drawio_validate next, then re-export the preview.`
200
+ : "No changes were needed.",
201
+ );
202
+ return textResult(lines.join("\n"), r);
203
+ } catch (e) {
204
+ return textResult(`Fit canvas failed: ${(e as Error).message}`, { error: (e as Error).message });
205
+ }
206
+ },
207
+ });
208
+
143
209
  pi.registerTool({
144
210
  name: "drawio_from_mermaid",
145
211
  label: "draw.io: from Mermaid",
@@ -219,7 +285,7 @@ export default function drawme(pi: ExtensionAPI): void {
219
285
  name: "drawio_explain",
220
286
  label: "draw.io: explain",
221
287
  description:
222
- "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. No draw.io CLI needed.",
288
+ "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. No draw.io CLI needed. Compressed pages cannot be described.",
223
289
  promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
224
290
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
225
291
  async execute(_id, params) {
@@ -257,7 +323,21 @@ export default function drawme(pi: ExtensionAPI): void {
257
323
  ctx.ui.notify("Usage: /drawme <description of the diagram to create>", "info");
258
324
  return;
259
325
  }
260
- pi.sendUserMessage(drawmeWorkflow(desc, REF_DIR, AGENT_REFERENCE_PATH));
326
+ const readReference = async (name: string): Promise<string | null> => {
327
+ try {
328
+ return await readFile(resolve(REF_DIR, name), "utf8");
329
+ } catch {
330
+ return null;
331
+ }
332
+ };
333
+ const cli = await resolveBinary();
334
+ pi.sendUserMessage(
335
+ drawmeWorkflow(desc, REF_DIR, cli, {
336
+ diagramTypes: await readReference("diagram-types.md"),
337
+ xmlAuthoring: await readReference("xml-authoring.md"),
338
+ mermaidAuthoring: cli.supportsMermaid ? await readReference("mermaid-authoring.md") : null,
339
+ }),
340
+ );
261
341
  },
262
342
  });
263
343