@senad-d/drawme 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -13,30 +13,45 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
13
13
  import { Type, type Static } from "typebox";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { dirname, resolve } from "node:path";
16
- import { readFile } from "node:fs/promises";
16
+ import { createHash } from "node:crypto";
17
+ import { constants } from "node:fs";
18
+ import { open, readFile, realpath, stat } from "node:fs/promises";
17
19
  import {
20
+ FEATURE_MIN,
21
+ INDEX_MIN,
22
+ LAYOUT_PRESETS,
23
+ MAX_REVIEW_SIDE,
18
24
  applyLayout,
19
25
  convertMermaid,
20
26
  exportDiagram,
21
27
  openFile,
28
+ rendererUnavailable,
22
29
  resolveBinary,
30
+ type DrawioInfo,
23
31
  type ExportFormat,
24
- type ExportOptions,
25
- type LayoutPreset,
32
+ type ExportMode,
26
33
  } from "./drawio";
34
+ import { sessionPath } from "./diagram-files";
35
+ import { inspectPng } from "./png";
27
36
  import { validateFile } from "./validate";
28
37
  import { fitCanvasFile } from "./fitcanvas";
29
38
  import { searchShapes } from "./shapesearch";
30
39
  import { explainFile } from "./explain";
31
- import { drawmeWorkflow } from "./workflow";
40
+ import { drawmeWorkflow, rendererFeatures } from "./workflow";
32
41
  import { animateDiagram } from "./animate";
33
- import { MOTION_EFFECTS, SLIDE_DIRECTIONS } from "./motion";
42
+ import { DEFAULT_HOLD_MS, MOTION_EFFECTS, SLIDE_DIRECTIONS } from "./motion";
43
+ import { MAX_STORYBOARD_FRAMES } from "./storyboard";
34
44
 
35
45
  const HERE = dirname(fileURLToPath(import.meta.url));
36
46
  const REF_DIR = resolve(HERE, "..", "assets", "references");
37
47
 
38
- const FORMAT = Type.Union([Type.Literal("png"), Type.Literal("svg"), Type.Literal("pdf"), Type.Literal("jpg")]);
39
- const MODE = Type.Union([Type.Literal("preview"), Type.Literal("final")]);
48
+ const FORMATS = ["png", "svg", "pdf", "jpg"] as const satisfies readonly ExportFormat[];
49
+ const MODES = ["preview", "final"] as const satisfies readonly ExportMode[];
50
+ const FORMAT = Type.Union(FORMATS.map((format) => Type.Literal(format)));
51
+ const MODE = Type.Union(MODES.map((mode) => Type.Literal(mode)));
52
+ const NATIVE_ANIMATION_HELP = "animated-svg verifies native page sequences or connector flow. For stored DrawMe motion, use drawio_animate with input and omit steps.";
53
+ const EXPORT_USAGE = `Usage: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]\n${NATIVE_ANIMATION_HELP}`;
54
+ const NO_IMAGE_MODEL = "the current model cannot view images or its image support is unknown";
40
55
 
41
56
  const exportParams = Type.Object({
42
57
  input: Type.String({ description: "Path to the .drawio source file" }),
@@ -44,10 +59,10 @@ const exportParams = Type.Object({
44
59
  mode: Type.Optional(MODE),
45
60
  output: Type.Optional(Type.String({ description: "Output path; defaults next to the input" })),
46
61
  scale: Type.Optional(Type.Number({ description: "Raster scale for a final PNG/JPG (default 2)" })),
47
- width: Type.Optional(Type.Number({ description: "Target width in px; overrides scale. Preview uses 2000" })),
62
+ width: Type.Optional(Type.Integer({ minimum: 1, description: "Target width in pixels; overrides raster scale subject to size limits. SVG padding is added after sizing; PDF uses authored page bounds" })),
48
63
  transparent: Type.Optional(Type.Boolean({ description: "Transparent background (PNG only)" })),
49
64
  border: Type.Optional(Type.Number({ description: "Outer margin in px around the content (default 40, matching drawio_fit_canvas)" })),
50
- pageIndex: Type.Optional(Type.Number({ description: "1-based page to export from a multi-page file" })),
65
+ pageIndex: Type.Optional(Type.Integer({ minimum: 1, description: `1-based page to export (default first page). Explicit selection requires draw.io ${INDEX_MIN} or later` })),
51
66
  embed: Type.Optional(
52
67
  Type.Boolean({ description: "Embed diagram XML for an editable output. Default: on for final PNG/SVG/PDF, off for preview" }),
53
68
  ),
@@ -57,7 +72,6 @@ const exportParams = Type.Object({
57
72
  "Require a verified final animated SVG. Defaults format to SVG; preserves connector flow and compiles portable page fade/visibility/wait sequences.",
58
73
  }),
59
74
  ),
60
- binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
61
75
  });
62
76
  export type DrawioExportInput = Static<typeof exportParams>;
63
77
 
@@ -83,37 +97,95 @@ const animateParams = Type.Object({
83
97
  Type.Array(motionStep, { description: "Motion steps in order. Omit to re-export the motion already stored on the page" }),
84
98
  ),
85
99
  loop: Type.Optional(Type.Boolean({ description: "Repeat the sequence (default true)" })),
86
- hold: Type.Optional(Type.Number({ description: "Pause in ms on the final state before a loop restarts (default 1600)" })),
87
- pageIndex: Type.Optional(Type.Number({ description: "1-based page to animate (default 1)" })),
100
+ hold: Type.Optional(Type.Number({ description: `Pause on the final state in ms (default ${DEFAULT_HOLD_MS})` })),
101
+ pageIndex: Type.Optional(Type.Integer({ minimum: 1, description: `1-based page to animate (default 1). Explicit selection requires draw.io ${INDEX_MIN} or later` })),
88
102
  output: Type.Optional(Type.String({ description: "Animated SVG path (default <name>.animated.svg next to the input)" })),
89
103
  storyboard: Type.Optional(
90
- Type.Boolean({ description: "Render <name>.storyboard.png with one frame per step for review (default true)" }),
104
+ Type.Boolean({ description: `Save a PNG with up to ${MAX_STORYBOARD_FRAMES} sampled visual batch end states (default true)` }),
91
105
  ),
92
- binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
93
106
  });
94
107
 
95
- const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
108
+ const textResult = <T>(text: string, details: T) => ({ content: [{ type: "text" as const, text }], details });
109
+
110
+ type ReviewImage = { type: "image"; data: string; mimeType: "image/png" };
111
+ interface PreviewReceipt {
112
+ source: string;
113
+ pageIndex: number;
114
+ toolCallId: string;
115
+ sha256: string;
116
+ }
117
+
118
+ function reviewResult(lines: string[], details: object, image?: ReviewImage) {
119
+ const { content } = textResult(lines.join("\n"), details);
120
+ return { content: image ? [...content, image] : content, details: { ...details, imageAttached: image !== undefined } };
121
+ }
122
+
123
+ function reviewFailure(operation: string, error: unknown) {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ return reviewResult([`${operation} failed: ${message}`], { error: message });
126
+ }
96
127
 
97
- /**
98
- * Whether the active model accepts image blocks. Unknown models fail open
99
- * (attach the image) like Pi's built-in read tool; the provider layer replaces
100
- * unsupported images with a text placeholder, so failing open is always safe.
101
- */
102
128
  function modelSupportsImages(ctx: ExtensionContext | undefined): boolean {
103
- return ctx?.model?.input.includes("image") ?? true;
129
+ const input = ctx?.model?.input;
130
+ return Array.isArray(input) && input.includes("image");
131
+ }
132
+
133
+ function optionalSessionPath(cwd: string, operand: string | undefined): string | undefined {
134
+ return operand === undefined ? undefined : sessionPath(cwd, operand);
135
+ }
136
+
137
+ function cliNotice(info: DrawioInfo): string {
138
+ return info.available
139
+ ? `draw.io ${info.version ?? "(unknown version)"} — ${info.binary}\n${rendererFeatures(info)}`
140
+ : rendererUnavailable(info);
141
+ }
142
+
143
+ async function readPublishedPng(path: string, expectedDigest: string | undefined) {
144
+ if (!(await stat(path)).isFile()) throw new Error(`published PNG is not a regular file: ${path}`);
145
+ // Recheck the opened descriptor; a replaced path must not make us read a pipe.
146
+ const file = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
147
+ try {
148
+ if (!(await file.stat()).isFile()) throw new Error(`published PNG is not a regular file: ${path}`);
149
+ const bytes = await file.readFile();
150
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
151
+ if (sha256 !== expectedDigest) throw new Error(`published PNG no longer matches the verified export: ${path}`);
152
+ const { width, height, editable } = inspectPng(bytes);
153
+ if (editable) throw new Error(`published review PNG contains editable diagram metadata: ${path}`);
154
+ return { bytes, sha256, width, height, fitsReview: Math.max(width, height) <= MAX_REVIEW_SIDE };
155
+ } finally {
156
+ await file.close();
157
+ }
158
+ }
159
+
160
+ function pngImage(bytes: Buffer): ReviewImage {
161
+ return { type: "image", mimeType: "image/png", data: bytes.toString("base64") };
104
162
  }
105
163
 
106
- async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>, attachImage: boolean) {
107
- const content: (
108
- | { type: "text"; text: string }
109
- | { type: "image"; data: string; mimeType: "image/png" }
110
- )[] = [{ type: "text", text }];
111
- const imageAttached = result.mode === "preview" && result.format === "png" && attachImage;
112
- if (imageAttached) {
113
- const png = await readFile(result.output);
114
- content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
164
+ function hasComparablePreview(ctx: ExtensionContext, current: PreviewReceipt): boolean {
165
+ try {
166
+ const entries = ctx.sessionManager?.buildSessionProjection?.().entries;
167
+ if (!entries) return false;
168
+ for (let i = entries.length - 1; i >= 0; i--) {
169
+ const { sourceEntry, messages } = entries[i];
170
+ if (sourceEntry.type !== "message") continue;
171
+ const stored = sourceEntry.message;
172
+ if (stored.role !== "toolResult" || stored.isError || stored.toolName !== "drawio_export" || stored.toolCallId === current.toolCallId) continue;
173
+ const details = stored.details as { imageAttached?: boolean; previewReceipt?: PreviewReceipt } | undefined;
174
+ const prior = details?.previewReceipt;
175
+ if (details?.imageAttached !== true || !prior || prior.toolCallId !== stored.toolCallId ||
176
+ prior.source !== current.source || prior.pageIndex !== current.pageIndex ||
177
+ typeof prior.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(prior.sha256)) continue;
178
+ // Pi can re-encode tool images before storage. A context replacement can
179
+ // retain the same details/call ID, so compare with the stored image itself.
180
+ const image = stored.content.find((block) => block.type === "image");
181
+ if (image?.data && messages.some((message) => message.role === "toolResult" &&
182
+ message.toolName === stored.toolName && message.toolCallId === prior.toolCallId &&
183
+ message.content.some((block) => block.type === "image" && block.mimeType === image.mimeType && block.data === image.data))) return true;
184
+ }
185
+ } catch {
186
+ // Missing or unavailable session projection is not attachment evidence.
115
187
  }
116
- return { content, details: { ...result, imageAttached } };
188
+ return false;
117
189
  }
118
190
 
119
191
  export default function drawme(pi: ExtensionAPI): void {
@@ -121,23 +193,12 @@ export default function drawme(pi: ExtensionAPI): void {
121
193
  name: "drawio_check",
122
194
  label: "draw.io: check CLI",
123
195
  description:
124
- "Detect the draw.io desktop CLI: returns the binary path, version, and whether it supports Mermaid import / the --layout pass (both need v30+). Call before exporting.",
196
+ `Detect the draw.io desktop CLI: returns the binary path, version, and whether Mermaid import and the --layout pass are supported (require ${FEATURE_MIN} or later). Call before exporting.`,
125
197
  promptSnippet: "Check whether the draw.io CLI is available before exporting a diagram.",
126
- parameters: Type.Object({ binary: Type.Optional(Type.String({ description: "Explicit binary path to test first" })) }),
127
- async execute(_id, params) {
128
- const info = await resolveBinary(params.binary);
129
- if (!info.available) {
130
- return textResult(
131
- "draw.io CLI not found. Install with `brew install --cask drawio` (macOS) or from " +
132
- "https://github.com/jgraph/drawio-desktop/releases. You can still author .drawio XML without it.",
133
- info,
134
- );
135
- }
136
- return textResult(
137
- `draw.io available: ${info.binary}\nversion: ${info.version} (major ${info.major})\n` +
138
- `Mermaid import / --layout: ${info.supportsMermaid ? "supported (v30+)" : "unsupported (needs v30+)"}`,
139
- info,
140
- );
198
+ parameters: Type.Object({}),
199
+ async execute() {
200
+ const info = await resolveBinary();
201
+ return textResult(cliNotice(info), info);
141
202
  },
142
203
  });
143
204
 
@@ -145,14 +206,20 @@ export default function drawme(pi: ExtensionAPI): void {
145
206
  name: "drawio_export",
146
207
  label: "draw.io: export",
147
208
  description:
148
- "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. Set animated:true for a verified final SVG: persistent flowAnimation connectors are preserved and portable page visibility/opacity/fade/wait sequences are compiled into standalone SVG CSS with a reduced-motion fallback. Animated export rejects static output and unsupported sequence effects. 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. SVG output is pinned to the authored colors so it matches PNG/PDF in every viewer, including dark-mode ones.",
209
+ "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. Set animated:true for a verified final SVG: persistent flowAnimation connectors are preserved and native page visibility/opacity/fade/wait sequences are compiled into standalone SVG CSS with a reduced-motion fallback. Animated export rejects static output and unsupported sequence effects. For stored DrawMe motion, use drawio_animate with input and omit steps. " +
210
+ `A mode:'preview' PNG has neither side above ${MAX_REVIEW_SIDE}px and never embeds editable XML. The result states whether a checked image was attached for the current model. A successful preview or final export can retire superseded files still tracked as previews of the same source; compare only when a comparable prior attachment is still in context. ` +
211
+ "mode:'final' creates the deliverable (editable PNG/SVG/PDF by default). SVG output uses the authored colors even in dark-mode viewers.",
149
212
  promptSnippet:
150
213
  "Export a .drawio to PNG/SVG/PDF/JPG; set animated:true for a verified final animated SVG. Preview mode attaches a PNG for visual review when supported.",
151
214
  parameters: exportParams,
152
- async execute(_id, params, _signal, _onUpdate, ctx) {
215
+ async execute(id, params, signal, _onUpdate, ctx) {
153
216
  try {
154
- const r = await exportDiagram(params as ExportOptions);
155
- const canView = modelSupportsImages(ctx);
217
+ const cwd = ctx?.cwd ?? process.cwd();
218
+ const input = sessionPath(cwd, params.input);
219
+ const { format, mode, scale, width, transparent, border, pageIndex, embed, animated } = params;
220
+ // Forward only the public options plus Pi's own abort signal.
221
+ const r = await exportDiagram({ input, output: optionalSessionPath(cwd, params.output),
222
+ format, mode, scale, width, transparent, border, pageIndex, embed, animated, signal });
156
223
  const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed} animated=${r.animated}`];
157
224
  if (r.animation) {
158
225
  lines.push(
@@ -167,22 +234,21 @@ export default function drawme(pi: ExtensionAPI): void {
167
234
  }
168
235
  const versionSuffix = r.version ? ` (${r.version})` : "";
169
236
  lines.push(`binary=${r.binary}${versionSuffix}`);
170
- if (r.mode === "preview" && r.format === "png") {
171
- if (!canView) {
172
- lines.push(
173
- "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.",
174
- );
175
- } else if (r.replacedPreview) {
176
- lines.push(
177
- "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.",
178
- );
179
- } else {
180
- lines.push("Preview image attached below. Critique it against the current review pass's checklist before editing the source.");
181
- }
237
+ if (r.mode !== "preview" || r.format !== "png") return reviewResult(lines, r);
238
+
239
+ const png = await readPublishedPng(r.output, r.artifactSha256);
240
+ if (!png.fitsReview) throw new Error(`published preview exceeds the ${MAX_REVIEW_SIDE}px review limit: ${r.output}`);
241
+ if (!modelSupportsImages(ctx)) {
242
+ lines.push(`Preview image NOT attached: ${NO_IMAGE_MODEL}. 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.`);
243
+ return reviewResult(lines, r);
182
244
  }
183
- return exportResult(lines.join("\n"), r, canView);
245
+ const previewReceipt: PreviewReceipt = { source: await realpath(input), pageIndex: pageIndex ?? 1, toolCallId: id, sha256: png.sha256 };
246
+ lines.push(hasComparablePreview(ctx, previewReceipt)
247
+ ? "Preview image attached below. A prior preview of this page is still visible in the model context: compare with the latest comparable image at each finding you addressed and record a verdict — fixed, not fixed, or regressed — before editing further."
248
+ : "Preview image attached below. Critique it against the current review pass's checklist before editing the source.");
249
+ return reviewResult(lines, { ...r, previewReceipt }, pngImage(png.bytes));
184
250
  } catch (e) {
185
- return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
251
+ return reviewFailure("Export", e);
186
252
  }
187
253
  },
188
254
  });
@@ -191,13 +257,18 @@ export default function drawme(pi: ExtensionAPI): void {
191
257
  name: "drawio_animate",
192
258
  label: "draw.io: animate",
193
259
  description:
194
- "Animate an existing .drawio page and export a verified standalone animated SVG. Pass ordered motion steps (fadeIn, fadeOut, dim, popIn, slideIn, drawIn, highlight, travel, wait) with cell ids, optional duration, stagger, parallel, direction, and color. Cells whose first effect is an entrance start hidden. The steps are validated against the page, stored on the page root cell (a source edit), compiled to CSS keyframes and SMIL connector dots with a reduced-motion fallback, and injected into a draw.io SVG export. Omit steps to re-export the stored motion after layout edits. By default a storyboard PNG shows the end state of each step as a captioned frame grid; when the current model can view images it is attached. The storyboard is static: it proves order and visibility, not easing. Effects play in browsers and SVG image embeds; draw.io itself does not play them. Persistent flowAnimation connectors are kept. highlight and travel default to the page theme's accent, and the SVG keeps the authored theme colors in every viewer.",
260
+ "Animate an existing .drawio page and export a verified standalone animated SVG. Pass ordered motion steps (fadeIn, fadeOut, dim, popIn, slideIn, drawIn, highlight, travel, wait) with cell ids, optional duration, stagger, parallel, direction, and color. Cells whose first effect is an entrance start hidden. The steps are validated against the page, stored on the page root cell (a source edit), compiled to CSS keyframes and SMIL connector dots with a reduced-motion fallback, and injected into a draw.io SVG export. Omit steps to re-export stored motion after layout edits. " +
261
+ `By default a storyboard PNG samples up to ${MAX_STORYBOARD_FRAMES} visual batch ends; parallel steps share a batch and standalone waits add no frame. It is a persistent file even if too large to attach for review. The storyboard checks order and visibility, not easing. ` +
262
+ "Effects play in browsers and SVG image embeds; draw.io itself does not play them. Persistent flowAnimation connectors are kept. highlight and travel default to the page theme's accent, and the SVG keeps the authored theme colors in every viewer.",
195
263
  promptSnippet:
196
264
  "Add motion to a .drawio page (draw-in connectors, pop/slide entrances, highlights, travelling dots, cascades) and export a verified animated SVG with a storyboard.",
197
265
  parameters: animateParams,
198
- async execute(_id, params, _signal, _onUpdate, ctx) {
266
+ async execute(_id, params, signal, _onUpdate, ctx) {
199
267
  try {
200
- const r = await animateDiagram(params);
268
+ const cwd = ctx?.cwd ?? process.cwd();
269
+ const { input, output, steps, loop, hold, pageIndex, storyboard } = params;
270
+ const r = await animateDiagram({ input: sessionPath(cwd, input), output: optionalSessionPath(cwd, output),
271
+ steps, loop, hold, pageIndex, storyboard, signal });
201
272
  const playback = r.loop ? `loop every ${r.durationMs}ms` : "plays once";
202
273
  const lines = [
203
274
  `Animated ${r.output} (page '${r.page}')`,
@@ -206,31 +277,26 @@ export default function drawme(pi: ExtensionAPI): void {
206
277
  ? `Stored the motion on the page root cell of ${r.source}. This is a source edit: run drawio_validate.`
207
278
  : `Re-used the motion stored in ${r.source}.`,
208
279
  ];
209
- const content: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: "image/png" })[] = [];
210
- let imageAttached = false;
280
+ let image: ReviewImage | undefined;
211
281
  if (r.storyboard) {
212
- const sampled =
213
- r.storyboardFramesTotal !== r.storyboardFrames ? ` (sampled from ${r.storyboardFramesTotal} steps)` : "";
282
+ const sampled = r.storyboardFramesTotal !== undefined && r.storyboardFramesTotal !== r.storyboardFrames
283
+ ? ` (sampled from ${r.storyboardFramesTotal} visual batches)` : "";
214
284
  lines.push(`Storyboard: ${r.storyboard}, ${r.storyboardFrames} frame(s)${sampled}`);
215
- if (modelSupportsImages(ctx)) {
216
- imageAttached = true;
217
- lines.push(
218
- "Storyboard attached below. Check each frame's caption against the intended order: the right cells visible, hidden, dimmed, or accented at each step, and nothing appearing before what it depends on.",
219
- );
285
+ const png = await readPublishedPng(r.storyboard, r.storyboardSha256);
286
+ if (!modelSupportsImages(ctx)) {
287
+ lines.push(`Storyboard NOT attached: ${NO_IMAGE_MODEL}. Check the step order structurally instead.`);
288
+ } else if (!png.fitsReview) {
289
+ lines.push(`Storyboard NOT attached: its ${png.width}×${png.height}px dimensions exceed the ${MAX_REVIEW_SIDE}px per-side review limit. The published file is available at the path above.`);
220
290
  } else {
221
- lines.push("Storyboard NOT attached: the current model cannot view images. Check the step order structurally instead.");
291
+ image = pngImage(png.bytes);
292
+ lines.push("Storyboard attached below. Check each frame's caption against the intended order and visibility; nothing should appear before what it depends on.");
222
293
  }
223
294
  }
224
295
  const versionLabel = r.version ? ` (${r.version})` : "";
225
296
  lines.push(`binary=${r.binary}${versionLabel}`);
226
- content.push({ type: "text", text: lines.join("\n") });
227
- if (imageAttached && r.storyboard) {
228
- const png = await readFile(r.storyboard);
229
- content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
230
- }
231
- return { content, details: { ...r, imageAttached } };
297
+ return reviewResult(lines, r, image);
232
298
  } catch (e) {
233
- return textResult(`Animate failed: ${(e as Error).message}`, { error: (e as Error).message });
299
+ return reviewFailure("Animate", e);
234
300
  }
235
301
  },
236
302
  });
@@ -242,16 +308,17 @@ export default function drawme(pi: ExtensionAPI): void {
242
308
  "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, explicit routes through shapes or across edges, pinned anchors facing away from the next route direction, edge labels likely overlapping shapes, labels sitting on their own line, labels landing on a bend of their own connector or on another routed connector, and auto-routed edges (no waypoints) whose routing cannot be checked. Auto-routed edges whose direct path pierces a shape are called out as preview-review observations. Give every edge facing-side anchors and explicit waypoints so deterministic route checks engage. 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.",
243
309
  promptSnippet: "Lint a .drawio after every source edit and before exporting.",
244
310
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
245
- async execute(_id, params) {
246
- const r = await validateFile(params.input);
311
+ async execute(_id, params, _signal, _onUpdate, ctx) {
312
+ const r = await validateFile(sessionPath(ctx?.cwd ?? process.cwd(), params.input));
247
313
  const lines = [
314
+ ...(!r.complete ? [`Validation incomplete${r.limit ? ` (limit: ${r.limit})` : ""}; do not treat this report as clean.`] : []),
248
315
  `Errors (${r.errors.length}):`,
249
316
  ...(r.errors.length > 0 ? r.errors.map((error) => `- ${error}`) : ["- none"]),
250
317
  `Actionable warnings (${r.warnings.length}):`,
251
318
  ...(r.warnings.length > 0 ? r.warnings.map((warning) => `- ${warning}`) : ["- none"]),
252
319
  `Informational observations (${r.observations.length}):`,
253
320
  ...(r.observations.length > 0 ? r.observations.map((observation) => `- ${observation}`) : ["- none"]),
254
- `Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}, anchors=${r.score.anchors}; lower is better for variants of this graph)`,
321
+ ...(r.complete ? [`Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}, anchors=${r.score.anchors}; lower is better for variants of this graph)`] : []),
255
322
  `${r.errors.length} error(s), ${r.warnings.length} unresolved warning(s)`,
256
323
  ];
257
324
  return textResult(lines.join("\n"), r);
@@ -270,9 +337,11 @@ export default function drawme(pi: ExtensionAPI): void {
270
337
  margin: Type.Optional(Type.Number({ description: "Outer margin in px between content and page edge (default 40)" })),
271
338
  output: Type.Optional(Type.String({ description: "Output path (default: overwrite the input)" })),
272
339
  }),
273
- async execute(_id, params) {
340
+ async execute(_id, params, _signal, _onUpdate, ctx) {
274
341
  try {
275
- const r = await fitCanvasFile(params);
342
+ const cwd = ctx?.cwd ?? process.cwd();
343
+ const r = await fitCanvasFile({ input: sessionPath(cwd, params.input),
344
+ margin: params.margin, output: optionalSessionPath(cwd, params.output) });
276
345
  const lines = r.pages.map((page) => {
277
346
  if (page.status === "skipped") return `page '${page.page}': skipped (${page.reason ?? "unknown"})`;
278
347
  const beforeText =
@@ -288,7 +357,7 @@ export default function drawme(pi: ExtensionAPI): void {
288
357
  return `page '${page.page}': ${beforeText} → ${afterText} (margin ${r.margin}px${shiftText})`;
289
358
  });
290
359
  lines.push(
291
- r.changed
360
+ r.changed || r.output !== r.input
292
361
  ? `Wrote ${r.output}. This is a source edit: run drawio_validate next, then re-export the preview.`
293
362
  : "No changes were needed.",
294
363
  );
@@ -303,17 +372,20 @@ export default function drawme(pi: ExtensionAPI): void {
303
372
  name: "drawio_from_mermaid",
304
373
  label: "draw.io: from Mermaid",
305
374
  description:
306
- "Convert Mermaid text to a native .drawio (structure + automatic layout) via the CLI. Best for standard diagram types (flowchart, sequence, class, state, ER, gantt, mindmap) with no custom styling. Requires draw.io v30+ (check with drawio_check). Provide `mermaid` (inline text) or `input` (a .mmd path).",
307
- promptSnippet: "Convert Mermaid text into a native .drawio with automatic layout (needs draw.io v30+).",
375
+ `Convert Mermaid to a finite, editable .drawio (structure + automatic layout) via the CLI. Best for standard diagram types with no custom styling. Requires draw.io ${FEATURE_MIN} or later (check with drawio_check). Provide exactly one of \`mermaid\` (inline text) and \`input\` (a .mmd path).`,
376
+ promptSnippet: `Convert Mermaid text into a native .drawio with automatic layout (needs draw.io ${FEATURE_MIN} or later).`,
308
377
  parameters: Type.Object({
309
378
  mermaid: Type.Optional(Type.String({ description: "Inline Mermaid diagram text" })),
310
379
  input: Type.Optional(Type.String({ description: "Path to a .mmd file (alternative to `mermaid`)" })),
311
380
  output: Type.Optional(Type.String({ description: "Output .drawio path" })),
312
- binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
313
381
  }),
314
- async execute(_id, params) {
382
+ async execute(_id, params, _signal, _onUpdate, ctx) {
315
383
  try {
316
- const r = await convertMermaid(params);
384
+ const cwd = ctx?.cwd ?? process.cwd();
385
+ // Do not turn a blank file argument into the session directory.
386
+ const input = params.input?.trim() ? sessionPath(cwd, params.input) : undefined;
387
+ const output = optionalSessionPath(cwd, params.output) ?? (input === undefined ? sessionPath(cwd, "diagram.drawio") : undefined);
388
+ const r = await convertMermaid({ input, output, mermaid: params.mermaid });
317
389
  const versionSuffix = r.version ? ` (${r.version})` : "";
318
390
  return textResult(`Converted Mermaid → ${r.output}\nbinary=${r.binary}${versionSuffix}`, r);
319
391
  } catch (e) {
@@ -326,28 +398,20 @@ export default function drawme(pi: ExtensionAPI): void {
326
398
  name: "drawio_layout",
327
399
  label: "draw.io: auto-layout",
328
400
  description:
329
- "Re-place nodes and route edges in a .drawio using an ELK layout preset via the CLI — for large or graph-heavy diagrams you don't want to hand-place. Requires draw.io v30+. Writes a sibling <name>.layout.drawio by default (pass `output` to overwrite the input).",
330
- promptSnippet: "Auto-lay-out a large .drawio with an ELK preset (needs draw.io v30+).",
401
+ `Re-place nodes and route edges on the first page of a .drawio using an ELK layout preset. Preserves authored page settings and other pages. Requires draw.io ${FEATURE_MIN} or later. Writes a sibling <name>.layout.drawio by default (pass \`output\` to overwrite the input).`,
402
+ promptSnippet: `Auto-lay-out a large .drawio with an ELK preset (needs draw.io ${FEATURE_MIN} or later).`,
331
403
  parameters: Type.Object({
332
404
  input: Type.String({ description: "Path to the .drawio file" }),
333
- preset: Type.Union([
334
- Type.Literal("verticalFlow"),
335
- Type.Literal("horizontalFlow"),
336
- Type.Literal("verticalTree"),
337
- Type.Literal("horizontalTree"),
338
- Type.Literal("radialTree"),
339
- Type.Literal("organic"),
340
- ]),
405
+ preset: Type.Union(LAYOUT_PRESETS.map((preset) => Type.Literal(preset))),
341
406
  output: Type.Optional(Type.String({ description: "Output path (default: sibling .layout.drawio)" })),
342
- binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
343
407
  }),
344
- async execute(_id, params) {
408
+ async execute(_id, params, _signal, _onUpdate, ctx) {
345
409
  try {
410
+ const cwd = ctx?.cwd ?? process.cwd();
346
411
  const r = await applyLayout({
347
- input: params.input,
348
- preset: params.preset as LayoutPreset,
349
- output: params.output,
350
- binary: params.binary,
412
+ input: sessionPath(cwd, params.input),
413
+ preset: params.preset,
414
+ output: optionalSessionPath(cwd, params.output),
351
415
  });
352
416
  return textResult(`Laid out (${r.preset}) → ${r.output}`, r);
353
417
  } catch (e) {
@@ -364,13 +428,13 @@ export default function drawme(pi: ExtensionAPI): void {
364
428
  promptSnippet: "Look up the exact official style= string for a draw.io shape by keyword.",
365
429
  parameters: Type.Object({
366
430
  query: Type.String({ description: "Keywords, e.g. 'aws lambda' or 'uml actor'" }),
367
- limit: Type.Optional(Type.Number({ description: "Max results (default 10)" })),
431
+ limit: Type.Optional(Type.Integer({ minimum: 0, description: "Max results (default 10)" })),
368
432
  }),
369
- execute(_id, params) {
370
- const matches = searchShapes(params.query, params.limit ?? 10);
371
- if (matches.length === 0) return Promise.resolve(textResult(`No shapes matched "${params.query}".`, { matches }));
433
+ async execute(_id, params) {
434
+ const matches = searchShapes(params.query, params.limit);
435
+ if (matches.length === 0) return textResult(`No shapes matched "${params.query}".`, { matches });
372
436
  const lines = matches.map((m) => `${m.title} (${m.w}x${m.h})\n ${m.style}`);
373
- return Promise.resolve(textResult(lines.join("\n"), { matches }));
437
+ return textResult(lines.join("\n"), { matches });
374
438
  },
375
439
  });
376
440
 
@@ -381,9 +445,9 @@ export default function drawme(pi: ExtensionAPI): void {
381
445
  "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.",
382
446
  promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
383
447
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
384
- async execute(_id, params) {
448
+ async execute(_id, params, _signal, _onUpdate, ctx) {
385
449
  try {
386
- const md = await explainFile(params.input);
450
+ const md = await explainFile(sessionPath(ctx?.cwd ?? process.cwd(), params.input));
387
451
  return textResult(md, { markdown: md });
388
452
  } catch (e) {
389
453
  return textResult(`Explain failed: ${(e as Error).message}`, { error: (e as Error).message });
@@ -395,13 +459,14 @@ export default function drawme(pi: ExtensionAPI): void {
395
459
  name: "drawio_open",
396
460
  label: "draw.io: open",
397
461
  description:
398
- "Open a .drawio source or an exported file in the OS default application (draw.io desktop for .drawio) so the user can fine-tune it.",
399
- promptSnippet: "Open a .drawio or exported file in the desktop app.",
400
- parameters: Type.Object({ path: Type.String({ description: "File to open" }) }),
401
- async execute(_id, params) {
462
+ "Open a .drawio source or a PNG, SVG, PDF, or JPEG export in the OS default application so the user can review it or fine-tune the source.",
463
+ promptSnippet: "Open a .drawio or supported export in the desktop app.",
464
+ parameters: Type.Object({ path: Type.String({ description: "Path to an existing diagram or supported export" }) }),
465
+ async execute(_id, params, _signal, _onUpdate, ctx) {
402
466
  try {
403
- const r = await openFile(params.path);
404
- return textResult(`Opened ${params.path} (${r.opener})`, r);
467
+ const path = sessionPath(ctx?.cwd ?? process.cwd(), params.path);
468
+ const r = await openFile(path);
469
+ return textResult(`Open request accepted for ${path} (${r.opener})`, r);
405
470
  } catch (e) {
406
471
  return textResult(`Open failed: ${(e as Error).message}`, { error: (e as Error).message });
407
472
  }
@@ -429,40 +494,34 @@ export default function drawme(pi: ExtensionAPI): void {
429
494
  diagramTypes: await readReference("diagram-types.md"),
430
495
  xmlAuthoring: await readReference("xml-authoring.md"),
431
496
  stylePresets: await readReference("style-presets.md"),
432
- mermaidAuthoring: cli.supportsMermaid ? await readReference("mermaid-authoring.md") : null,
497
+ mermaidAuthoring: cli.available && cli.supportsMermaid ? await readReference("mermaid-authoring.md") : null,
433
498
  }),
499
+ { deliverAs: "followUp" },
434
500
  );
435
501
  },
436
502
  });
437
503
 
438
504
  pi.registerCommand("drawme-check", {
439
- description: "Check whether the draw.io CLI is available",
505
+ description: "Check the draw.io CLI version, path, and Mermaid/layout support",
440
506
  handler: async (_args, ctx) => {
441
507
  const info = await resolveBinary();
442
- ctx.ui.notify(
443
- info.available ? `draw.io ${info.version} — ${info.binary}` : "draw.io CLI not found (macOS: brew install --cask drawio)",
444
- info.available ? "info" : "error",
445
- );
508
+ ctx.ui.notify(cliNotice(info), info.available ? "info" : "error");
446
509
  },
447
510
  });
448
511
 
449
512
  pi.registerCommand("drawme-export", {
450
- description: "Export a .drawio file: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]",
513
+ description: `Export a .drawio file: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]. ${NATIVE_ANIMATION_HELP}`,
451
514
  handler: async (args, ctx) => {
452
- const parts = args.trim().split(/\s+/).filter(Boolean);
453
- if (parts.length === 0) {
454
- ctx.ui.notify("Usage: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]", "info");
455
- return;
456
- }
457
- const [input, requestedFormat = "png"] = parts;
515
+ const [operand, requestedFormat = "png"] = args.trim().split(/\s+/).filter(Boolean);
458
516
  const animated = requestedFormat === "animated-svg";
459
- const format = animated ? "svg" : requestedFormat;
460
- if (!["png", "svg", "pdf", "jpg"].includes(format)) {
461
- ctx.ui.notify("Usage: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]", "info");
517
+ const format = animated ? "svg" : FORMATS.find((candidate) => candidate === requestedFormat);
518
+ if (!operand || !format) {
519
+ ctx.ui.notify(EXPORT_USAGE, "info");
462
520
  return;
463
521
  }
464
522
  try {
465
- const r = await exportDiagram({ input, format: format as ExportFormat, mode: "final", animated });
523
+ const input = sessionPath(ctx.cwd ?? process.cwd(), operand);
524
+ const r = await exportDiagram({ input, format, mode: "final", animated });
466
525
  let status = "";
467
526
  if (r.animation) status = " (animation verified)";
468
527
  else if (r.repaired) status = " (repaired PNG)";