@canvakit/tool 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 AGENTIK SAS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @canvakit/tool
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ canvakit render as an **agentproto primitive**. A deck template + a content
4
+ source + a swappable brand theme in, a PDF out — exposed as an AIP-14 tool
5
+ contract (`render_deck`) plus an AIP-30 builtin driver, wrapping
6
+ [`@canvakit/export`](../export)'s programmatic render.
7
+
8
+ The standalone `decks/*/render.mjs` is JS glue: it string-swaps a theme path in a
9
+ template's frontmatter, writes a temp file, and shells out to the `canvakit` CLI.
10
+ This package is the in-process, typed equivalent — no temp file, no subprocess —
11
+ and projects the same body to any driver transport (builtin / cli / http / mcp /
12
+ sdk) or host adapter (`toMastraTool`, `toAiSdkTool`) without a rewrite.
13
+
14
+ ## Use
15
+
16
+ ### As a plain function
17
+
18
+ ```ts
19
+ import { renderDeck } from "@canvakit/tool"
20
+
21
+ const { path, bytes } = await renderDeck({
22
+ template: "decks/acme/deck.canvakit.html",
23
+ theme: "acme", // → themes/acme.theme.json next to the template
24
+ out: "decks/acme/deck.pdf", // default: deck-<brand>.pdf next to the template
25
+ })
26
+ ```
27
+
28
+ ### Through the agentproto tool path
29
+
30
+ ```ts
31
+ import { runTool } from "@agentproto/driver"
32
+ import { render_deck, renderDeckDriver } from "@canvakit/tool"
33
+
34
+ const result = await runTool({
35
+ tool: render_deck,
36
+ candidates: [renderDeckDriver],
37
+ input: { template, theme: "acme", out },
38
+ })
39
+ // input is validated against the contract's zod schema before dispatch
40
+ ```
41
+
42
+ ## Contract
43
+
44
+ `render_deck` (AIP-14):
45
+
46
+ | field | value |
47
+ | ---------- | ------------------------------------------- |
48
+ | input | `{ template, theme?, data?, out? }` |
49
+ | output | `{ path, bytes, format: "pdf" }` |
50
+ | mutates | `["file:out"]` (writes a PDF) |
51
+ | idempotent | `true` |
52
+
53
+ A **theme** is a bare brand name — resolved to `themes/<name>.theme.json` next to
54
+ the template — or an explicit theme path. Optional **data** overrides the
55
+ template's default content source. Vendor-neutral: no brand names live in this
56
+ package; a template's structure + content stay agnostic and the theme file
57
+ carries the brand tokens (colors, fonts, logo, mascot). Swap the theme to reskin
58
+ the same deck.
59
+
60
+ ## Exports
61
+
62
+ - `renderDeck(opts)` — the plain async render primitive.
63
+ - `render_deck` — the AIP-14 `defineTool` contract handle.
64
+ - `renderDeckDriver` — the AIP-30 builtin `defineDriver` binding, dispatched via
65
+ `runTool`.
66
+
67
+ ## License
68
+
69
+ [FSL-1.1-ALv2](./LICENSE), the Functional Source License with an Apache 2.0 future
70
+ license: free for any use except offering a competing product or service, and
71
+ each version becomes Apache-2.0 two years after its release. Copyright AGENTIK SAS.
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.mjs ADDED
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'util';
3
+ import { promises } from 'fs';
4
+ import * as nodePath from 'path';
5
+ import { z } from 'zod';
6
+ import { exportCanvas, cdpChromeRenderer } from '@canvakit/export';
7
+ import { designkitExtension } from '@canvakit/designkit';
8
+ import { defineTool } from '@agentproto/tool';
9
+ import { implementTool, defineDriver } from '@agentproto/driver';
10
+
11
+ /**
12
+ * @canvakit/tool v0.1.0
13
+ * canvakit render as an agentproto primitive (render_deck).
14
+ */
15
+
16
+ function nodeFilesystem(baseDir) {
17
+ const abs = nodePath.resolve(baseDir);
18
+ const resolve2 = (p) => nodePath.resolve(abs, p.replace(/^\/+/, ""));
19
+ return {
20
+ async readFile(p) {
21
+ return promises.readFile(resolve2(p));
22
+ },
23
+ async writeFile(p, contents) {
24
+ const full = resolve2(p);
25
+ await promises.mkdir(nodePath.dirname(full), { recursive: true });
26
+ await promises.writeFile(full, contents);
27
+ },
28
+ async exists(p) {
29
+ try {
30
+ await promises.access(resolve2(p));
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ },
36
+ async readdir(p) {
37
+ try {
38
+ const found = await promises.readdir(resolve2(p), { withFileTypes: true });
39
+ return found.map((e) => ({
40
+ name: e.name,
41
+ type: e.isDirectory() ? "directory" : "file"
42
+ }));
43
+ } catch {
44
+ return [];
45
+ }
46
+ }
47
+ };
48
+ }
49
+ function looksLikePath(theme) {
50
+ return theme.includes("/") || theme.toLowerCase().endsWith(".json");
51
+ }
52
+ function resolveThemePath(theme, templateDir, cwd) {
53
+ if (!looksLikePath(theme)) return `themes/${theme}.theme.json`;
54
+ const abs = nodePath.resolve(cwd, theme);
55
+ const rel = nodePath.relative(templateDir, abs);
56
+ if (rel.startsWith("..") || nodePath.isAbsolute(rel)) {
57
+ throw new Error(
58
+ `renderDeck: theme path "${theme}" resolves outside the template directory (${templateDir}); themes must live under the template so canvakit can resolve them.`
59
+ );
60
+ }
61
+ return rel.split(nodePath.sep).join("/");
62
+ }
63
+ function resolveDataPath(data, templateDir, cwd) {
64
+ const abs = nodePath.resolve(cwd, data);
65
+ const rel = nodePath.relative(templateDir, abs);
66
+ if (rel.startsWith("..") || nodePath.isAbsolute(rel)) {
67
+ throw new Error(
68
+ `renderDeck: data path "${data}" resolves outside the template directory (${templateDir}); data must live under the template so canvakit can resolve it.`
69
+ );
70
+ }
71
+ return rel.split(nodePath.sep).join("/");
72
+ }
73
+ function swapSourcePath(templateRaw, sourceKey, newPath) {
74
+ const re = new RegExp(
75
+ `(\\n[ \\t]*${sourceKey}:[ \\t]*\\n(?:[ \\t]+[^\\n]*\\n)*?[ \\t]+path:[ \\t]*)(["']?)[^"'\\n]+\\2`
76
+ );
77
+ if (!re.test(templateRaw)) {
78
+ throw new Error(
79
+ `renderDeck: no \`${sourceKey}\` file source with a \`path:\` found in the template frontmatter`
80
+ );
81
+ }
82
+ return templateRaw.replace(re, (_m, prefix, quote) => {
83
+ const q = quote || '"';
84
+ return `${prefix}${q}${newPath}${q}`;
85
+ });
86
+ }
87
+ async function renderDeck(opts) {
88
+ const cwd = opts.cwd ?? process.cwd();
89
+ const absTemplate = nodePath.resolve(cwd, opts.template);
90
+ const templateDir = nodePath.dirname(absTemplate);
91
+ let templateRaw;
92
+ try {
93
+ templateRaw = await promises.readFile(absTemplate, "utf-8");
94
+ } catch (err) {
95
+ throw new Error(
96
+ `renderDeck: cannot read template ${absTemplate}: ${err instanceof Error ? err.message : String(err)}`
97
+ );
98
+ }
99
+ if (opts.data) {
100
+ templateRaw = swapSourcePath(
101
+ templateRaw,
102
+ "d",
103
+ resolveDataPath(opts.data, templateDir, cwd)
104
+ );
105
+ }
106
+ if (opts.theme) {
107
+ const themePath = resolveThemePath(opts.theme, templateDir, cwd);
108
+ if (!await exists(nodePath.join(templateDir, themePath))) {
109
+ throw new Error(
110
+ `renderDeck: no theme at ${nodePath.join(templateDir, themePath)}`
111
+ );
112
+ }
113
+ templateRaw = swapSourcePath(templateRaw, "t", themePath);
114
+ }
115
+ const filesystem = nodeFilesystem(templateDir);
116
+ const extensions = [designkitExtension({ fonts: opts.fonts ?? "embed" })];
117
+ const res = await exportCanvas(
118
+ {
119
+ // `templatePath` is the basename so `file` sources resolve from
120
+ // `templateDir` (dirname("") === "" → the filesystem's own base).
121
+ template: templateRaw,
122
+ templatePath: nodePath.basename(absTemplate),
123
+ filesystem,
124
+ extensions
125
+ },
126
+ { format: "pdf" }
127
+ );
128
+ const errored = Object.values(res.statuses ?? {}).find(
129
+ (s) => s.status === "error"
130
+ );
131
+ if (errored) {
132
+ throw new Error(
133
+ `renderDeck: source error [${errored.status}]: ${errored.reason}`
134
+ );
135
+ }
136
+ const outPath = nodePath.resolve(cwd, opts.out ?? defaultOut(opts.template));
137
+ await promises.mkdir(nodePath.dirname(outPath), { recursive: true });
138
+ await promises.writeFile(outPath, res.bytes);
139
+ return { path: outPath, bytes: res.bytes.length, format: "pdf" };
140
+ }
141
+ function defaultOut(template) {
142
+ const base = nodePath.basename(template).replace(/\.canvakit\.html$/i, "").replace(/\.html$/i, "");
143
+ return nodePath.join(nodePath.dirname(template), `${base || "deck"}.pdf`);
144
+ }
145
+ async function exists(p) {
146
+ try {
147
+ await promises.access(p);
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ function normalizeOverlayPath(p) {
154
+ return p.replace(/^\.\//, "").replace(/^\/+/, "");
155
+ }
156
+ function withDesignKitOverlay(inner, slug, content) {
157
+ const virtual = `_design/${slug}.md`;
158
+ const matches = (p) => normalizeOverlayPath(p) === virtual;
159
+ return {
160
+ async readFile(p) {
161
+ if (matches(p)) return content;
162
+ return inner.readFile(p);
163
+ },
164
+ async writeFile(p, contents) {
165
+ return inner.writeFile(p, contents);
166
+ },
167
+ async exists(p) {
168
+ if (matches(p)) return true;
169
+ return inner.exists(p);
170
+ },
171
+ async readdir(p, opts) {
172
+ return inner.readdir(p, opts);
173
+ }
174
+ };
175
+ }
176
+ function defaultIllustrationOut(template) {
177
+ const base = nodePath.basename(template).replace(/\.canvakit\.html$/i, "").replace(/\.html$/i, "");
178
+ return nodePath.join(nodePath.dirname(template), `${base || "figure"}.png`);
179
+ }
180
+ function readPngDimensions(buf) {
181
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
182
+ }
183
+ async function renderIllustration(opts) {
184
+ const cwd = opts.cwd ?? process.cwd();
185
+ const absTemplate = nodePath.resolve(cwd, opts.template);
186
+ const templateDir = nodePath.dirname(absTemplate);
187
+ let templateRaw;
188
+ try {
189
+ templateRaw = await promises.readFile(absTemplate, "utf-8");
190
+ } catch (err) {
191
+ throw new Error(
192
+ `renderIllustration: cannot read template ${absTemplate}: ${err instanceof Error ? err.message : String(err)}`
193
+ );
194
+ }
195
+ let filesystem = nodeFilesystem(templateDir);
196
+ let design = opts.design;
197
+ if (opts.kitFile) {
198
+ const absKitFile = nodePath.resolve(cwd, opts.kitFile);
199
+ let kitContent;
200
+ try {
201
+ kitContent = await promises.readFile(absKitFile, "utf-8");
202
+ } catch (err) {
203
+ throw new Error(
204
+ `renderIllustration: cannot read kitFile ${absKitFile}: ${err instanceof Error ? err.message : String(err)}`
205
+ );
206
+ }
207
+ const slug = nodePath.basename(opts.kitFile).replace(/\.design\.md$/i, "").replace(/\.md$/i, "");
208
+ if (!slug) {
209
+ throw new Error(
210
+ `renderIllustration: kitFile ${absKitFile} has no usable slug (its basename reduces to an empty string)`
211
+ );
212
+ }
213
+ filesystem = withDesignKitOverlay(filesystem, slug, kitContent);
214
+ design = `kit:${slug}`;
215
+ }
216
+ const extensions = [
217
+ designkitExtension({
218
+ fonts: opts.fonts ?? "link",
219
+ ...design ? { overrideDesign: design } : {}
220
+ })
221
+ ];
222
+ const res = await exportCanvas(
223
+ {
224
+ template: templateRaw,
225
+ templatePath: nodePath.basename(absTemplate),
226
+ filesystem,
227
+ extensions,
228
+ variables: opts.variables ?? {}
229
+ },
230
+ {
231
+ format: "png",
232
+ renderer: cdpChromeRenderer(),
233
+ page: { scale: opts.scale ?? 2 }
234
+ }
235
+ );
236
+ const errored = Object.values(res.statuses ?? {}).find(
237
+ (s) => s.status === "error"
238
+ );
239
+ if (errored) {
240
+ throw new Error(
241
+ `renderIllustration: source error [${errored.status}]: ${errored.reason}`
242
+ );
243
+ }
244
+ const outPath = nodePath.resolve(
245
+ cwd,
246
+ opts.out ?? defaultIllustrationOut(opts.template)
247
+ );
248
+ await promises.mkdir(nodePath.dirname(outPath), { recursive: true });
249
+ await promises.writeFile(outPath, res.bytes);
250
+ const { width, height } = readPngDimensions(res.bytes);
251
+ return {
252
+ path: outPath,
253
+ bytes: res.bytes.length,
254
+ width,
255
+ height,
256
+ format: "png"
257
+ };
258
+ }
259
+ var renderDeckInput = z.object({
260
+ template: z.string().describe("Path to the canvakit template (*.canvakit.html)."),
261
+ data: z.string().optional().describe("Optional override for the data source path (name or path)."),
262
+ theme: z.string().optional().describe(
263
+ "Theme: a brand NAME (\u2192 themes/<name>.theme.json) or an explicit path."
264
+ ),
265
+ out: z.string().optional().describe("Output PDF path. Defaults to <template>.pdf.")
266
+ });
267
+ var renderDeckOutput = z.object({
268
+ path: z.string(),
269
+ bytes: z.number(),
270
+ format: z.literal("pdf")
271
+ });
272
+ var render_deck = defineTool({
273
+ id: "render_deck",
274
+ name: "render_deck",
275
+ version: "0.1.0",
276
+ description: "Render a canvakit deck template to a PDF, injecting a chosen theme (brand name or path) and optional data source. Wraps canvakit's programmatic render; writes the PDF and returns its path, byte size, and format.",
277
+ inputSchema: renderDeckInput,
278
+ outputSchema: renderDeckOutput,
279
+ // Writes a PDF to the filesystem — a real side effect on the `file` class.
280
+ mutates: ["file:out"],
281
+ idempotent: true,
282
+ costClass: "metered",
283
+ tags: ["canvakit", "render", "pdf", "deck"]
284
+ });
285
+ var renderDeckImpl = implementTool(
286
+ render_deck,
287
+ async ({ input }) => renderDeck(input)
288
+ );
289
+ defineDriver({
290
+ id: "canvakit.render-deck.builtin",
291
+ name: "canvakit render_deck (builtin)",
292
+ version: "0.1.0",
293
+ kind: "builtin",
294
+ description: "In-process builtin provider for the render_deck contract, backed by @canvakit/export's programmatic render.",
295
+ implements: [{ tool: "render_deck", version: "^0.1.0" }],
296
+ implementations: [renderDeckImpl]
297
+ });
298
+ var renderIllustrationInput = z.object({
299
+ template: z.string().describe("Path to the canvakit template (*.canvakit.html)."),
300
+ out: z.string().optional().describe("Output PNG path. Defaults to <template dir>/<name>.png."),
301
+ kitFile: z.string().optional().describe(
302
+ "Design kit FILE (a .design.md), relative to cwd. Mounted as _design/<slug>.md for this render only."
303
+ ),
304
+ design: z.string().optional().describe(
305
+ "Explicit designkit ref (kit:<slug>, dk:<preset>, ws:<path>). Ignored when kitFile is set."
306
+ ),
307
+ variables: z.record(z.string(), z.string()).optional().describe("Template variables (frontmatter variables overrides)."),
308
+ scale: z.number().min(1).max(4).optional().describe("Device scale factor for the screenshot. Default 2.")
309
+ });
310
+ var renderIllustrationOutput = z.object({
311
+ path: z.string().describe("Absolute path of the written PNG."),
312
+ bytes: z.number().describe("Byte length of the written PNG."),
313
+ width: z.number().describe("Pixel width, read from the PNG IHDR chunk."),
314
+ height: z.number().describe("Pixel height, read from the PNG IHDR chunk."),
315
+ format: z.literal("png")
316
+ });
317
+ var render_illustration = defineTool({
318
+ id: "render_illustration",
319
+ name: "render_illustration",
320
+ version: "0.1.0",
321
+ description: "Render a canvakit HTML template to a PNG figure (full page, 2x), styled by a designkit kit file or ref. Returns path, size in bytes and pixel dimensions.",
322
+ inputSchema: renderIllustrationInput,
323
+ outputSchema: renderIllustrationOutput,
324
+ mutates: ["file:out"],
325
+ idempotent: true,
326
+ costClass: "metered",
327
+ tags: ["canvakit", "designkit", "render", "png", "illustration", "figure"]
328
+ });
329
+ var renderIllustrationImpl = implementTool(
330
+ render_illustration,
331
+ async ({ input }) => renderIllustration(input)
332
+ );
333
+ defineDriver({
334
+ id: "canvakit.render-illustration.builtin",
335
+ name: "canvakit render_illustration (builtin)",
336
+ version: "0.1.0",
337
+ kind: "builtin",
338
+ description: "In-process builtin provider for the render_illustration contract, backed by @canvakit/export's programmatic render over the CDP Chrome renderer.",
339
+ implements: [{ tool: "render_illustration", version: "^0.1.0" }],
340
+ implementations: [renderIllustrationImpl]
341
+ });
342
+
343
+ // src/cli.ts
344
+ function usage() {
345
+ return "usage: canvakit-tool illustration --template <path> [--out <path>] [--kit <kitFile>] [--design <ref>] [--var k=v]... [--scale n]";
346
+ }
347
+ function parseVars(pairs) {
348
+ const out = {};
349
+ for (const pair of pairs ?? []) {
350
+ const eq = pair.indexOf("=");
351
+ if (eq < 0) {
352
+ throw new Error(`--var expects k=v, got "${pair}"`);
353
+ }
354
+ out[pair.slice(0, eq)] = pair.slice(eq + 1);
355
+ }
356
+ return out;
357
+ }
358
+ function parseScale(raw) {
359
+ const n = Number(raw);
360
+ if (!Number.isFinite(n) || n < 1 || n > 4) {
361
+ throw new Error(`--scale expects a number between 1 and 4, got "${raw}"`);
362
+ }
363
+ return n;
364
+ }
365
+ async function runIllustration(argv) {
366
+ const { values } = parseArgs({
367
+ args: argv,
368
+ options: {
369
+ template: { type: "string" },
370
+ out: { type: "string" },
371
+ kit: { type: "string" },
372
+ design: { type: "string" },
373
+ var: { type: "string", multiple: true },
374
+ scale: { type: "string" }
375
+ },
376
+ allowPositionals: false
377
+ });
378
+ if (!values.template) {
379
+ throw new Error("--template is required");
380
+ }
381
+ const result = await renderIllustration({
382
+ template: values.template,
383
+ out: values.out,
384
+ kitFile: values.kit,
385
+ design: values.design,
386
+ variables: parseVars(values.var),
387
+ scale: values.scale !== void 0 ? parseScale(values.scale) : void 0,
388
+ cwd: process.cwd()
389
+ });
390
+ process.stdout.write(`${JSON.stringify(result)}
391
+ `);
392
+ }
393
+ async function main() {
394
+ const [subcommand, ...rest] = process.argv.slice(2);
395
+ if (subcommand !== "illustration") {
396
+ process.stderr.write(`${usage()}
397
+ `);
398
+ process.exit(2);
399
+ }
400
+ try {
401
+ await runIllustration(rest);
402
+ } catch (err) {
403
+ const message = err instanceof Error ? err.message : String(err);
404
+ process.stdout.write(`${JSON.stringify({ error: message })}
405
+ `);
406
+ process.exit(1);
407
+ }
408
+ }
409
+ await main();
410
+ //# sourceMappingURL=cli.mjs.map
411
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/cli.ts"],"names":["resolve","fs"],"mappings":";;;;;;;;;;;;;;;AA+CA,SAAS,eAAe,OAAA,EAAiC;AACvD,EAAA,MAAM,GAAA,GAAe,iBAAQ,OAAO,CAAA;AACpC,EAAA,MAAMA,QAAAA,GAAU,CAAC,CAAA,KAAuB,QAAA,CAAA,OAAA,CAAQ,KAAK,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAC,CAAA;AAC1E,EAAA,OAAO;AAAA,IACL,MAAM,SAAS,CAAA,EAAG;AAChB,MAAA,OAAOC,QAAA,CAAG,QAAA,CAASD,QAAAA,CAAQ,CAAC,CAAC,CAAA;AAAA,IAC/B,CAAA;AAAA,IACA,MAAM,SAAA,CAAU,CAAA,EAAG,QAAA,EAAU;AAC3B,MAAA,MAAM,IAAA,GAAOA,SAAQ,CAAC,CAAA;AACtB,MAAA,MAAMC,QAAA,CAAG,MAAe,QAAA,CAAA,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC1D,MAAA,MAAMA,QAAA,CAAG,SAAA,CAAU,IAAA,EAAM,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AAA,IACjB,KAAK,MAAA,CAAO,GAAA;AAAA,IACZ,SAAS,MAAA,CAAO,GAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,SAAA,EAAW,SAAA,CAAU,MAAA,CAAO,GAAG,CAAA;AAAA,IAC/B,OAAO,MAAA,CAAO,KAAA,KAAU,SAAY,UAAA,CAAW,MAAA,CAAO,KAAK,CAAA,GAAI,MAAA;AAAA,IAC/D,GAAA,EAAK,QAAQ,GAAA;AAAI,GAClB,CAAA;AAED,EAAA,OAAA,CAAQ,OAAO,KAAA,CAAM,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAM,CAAC;AAAA,CAAI,CAAA;AACpD;AAEA,eAAe,IAAA,GAAsB;AACnC,EAAA,MAAM,CAAC,YAAY,GAAG,IAAI,IAAI,OAAA,CAAQ,IAAA,CAAK,MAAM,CAAC,CAAA;AAElD,EAAA,IAAI,eAAe,cAAA,EAAgB;AACjC,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,KAAA,EAAO;AAAA,CAAI,CAAA;AACnC,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,UAAU,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,IAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,EAAG,IAAA,CAAK,UAAU,EAAE,KAAA,EAAO,OAAA,EAAS,CAAC;AAAA,CAAI,CAAA;AAC9D,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF;AAEA,MAAM,IAAA,EAAK","file":"cli.mjs","sourcesContent":["/**\n * @canvakit/tool — canvakit render as an agentproto primitive.\n *\n * The standalone deck renderer (`decks/<deck>/render.mjs`) is JS glue: it string-\n * swaps a theme path in a template's frontmatter and shells out to the\n * `canvakit` CLI. This package re-expresses the same capability as a proper\n * agentproto tool:\n *\n * - `renderDeck(opts)` — the plain async primitive (resolve template + data\n * + theme, then `exportCanvas` → a PDF on disk).\n * - `render_deck` — the AIP-14 TOOL contract (`defineTool`): identity,\n * input/output zod schemas, side-effect profile.\n * - `renderDeckDriver` — the AIP-30 builtin DRIVER (`defineDriver`) binding\n * the contract to `renderDeck` via `implementTool`.\n *\n * - `renderIllustration(opts)` — the plain async primitive for a single\n * canvakit figure: template + a designkit kit (file\n * or ref) → a full-page PNG via the CDP renderer.\n * - `render_illustration` — the AIP-14 TOOL contract.\n * - `renderIllustrationDriver` — the AIP-30 builtin DRIVER.\n *\n * Vendor-neutral: no brand names live here. A \"theme\" is either a bare NAME\n * (resolved to `themes/<name>.theme.json` next to the template) or an explicit\n * path — brand themes are only ever test inputs.\n */\n\nimport { promises as fs } from \"node:fs\"\nimport * as nodePath from \"node:path\"\nimport { z } from \"zod\"\n\nimport {\n exportCanvas,\n cdpChromeRenderer,\n type ExportFormat,\n} from \"@canvakit/export\"\nimport { designkitExtension, type FontMode } from \"@canvakit/designkit\"\nimport type { FilesystemEntry, FilesystemLike } from \"@canvakit/core\"\n\nimport { defineTool } from \"@agentproto/tool\"\nimport { defineDriver, implementTool } from \"@agentproto/driver\"\n\n// ---------------------------------------------------------------------------\n// filesystem — a minimal node-backed FilesystemLike, resolving every canvakit\n// (forward-slash, root-relative) path against a base directory. Mirrors the\n// CLI's `createLocalFs` without taking a dependency on the CLI package.\n// ---------------------------------------------------------------------------\n\nfunction nodeFilesystem(baseDir: string): FilesystemLike {\n const abs = nodePath.resolve(baseDir)\n const resolve = (p: string) => nodePath.resolve(abs, p.replace(/^\\/+/, \"\"))\n return {\n async readFile(p) {\n return fs.readFile(resolve(p))\n },\n async writeFile(p, contents) {\n const full = resolve(p)\n await fs.mkdir(nodePath.dirname(full), { recursive: true })\n await fs.writeFile(full, contents)\n },\n async exists(p) {\n try {\n await fs.access(resolve(p))\n return true\n } catch {\n return false\n }\n },\n async readdir(p): Promise<ReadonlyArray<FilesystemEntry>> {\n try {\n const found = await fs.readdir(resolve(p), { withFileTypes: true })\n return found.map(e => ({\n name: e.name,\n type: e.isDirectory() ? \"directory\" : \"file\",\n }))\n } catch {\n return []\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// theme / data injection — point a named `file` source at a chosen path by\n// rewriting its `path:` in the template frontmatter. Same effect as render.mjs\n// (which regex-swaps the theme path), but scoped to a specific source key so it\n// stays correct for any template following the `d`=data / `t`=theme convention.\n// ---------------------------------------------------------------------------\n\n/** True when a theme value is an explicit path rather than a bare brand name. */\nfunction looksLikePath(theme: string): boolean {\n return theme.includes(\"/\") || theme.toLowerCase().endsWith(\".json\")\n}\n\n/**\n * Resolve a theme value to a template-dir-relative path.\n * - a bare NAME → `themes/<name>.theme.json` (next to the template)\n * - an explicit path (absolute or cwd-relative) → re-based onto the template\n * directory, since canvakit resolves `file` sources from there.\n */\nfunction resolveThemePath(\n theme: string,\n templateDir: string,\n cwd: string\n): string {\n if (!looksLikePath(theme)) return `themes/${theme}.theme.json`\n const abs = nodePath.resolve(cwd, theme)\n const rel = nodePath.relative(templateDir, abs)\n if (rel.startsWith(\"..\") || nodePath.isAbsolute(rel)) {\n throw new Error(\n `renderDeck: theme path \"${theme}\" resolves outside the template directory ` +\n `(${templateDir}); themes must live under the template so canvakit can resolve them.`\n )\n }\n return rel.split(nodePath.sep).join(\"/\")\n}\n\n/** Re-base an explicit data path (absolute/cwd-relative) onto the template dir. */\nfunction resolveDataPath(\n data: string,\n templateDir: string,\n cwd: string\n): string {\n const abs = nodePath.resolve(cwd, data)\n const rel = nodePath.relative(templateDir, abs)\n if (rel.startsWith(\"..\") || nodePath.isAbsolute(rel)) {\n throw new Error(\n `renderDeck: data path \"${data}\" resolves outside the template directory ` +\n `(${templateDir}); data must live under the template so canvakit can resolve it.`\n )\n }\n return rel.split(nodePath.sep).join(\"/\")\n}\n\n/**\n * Rewrite the `path:` of a named `file` source in the template frontmatter.\n * Matches `<key>:` then the first following `path:` line at deeper indent,\n * preserving whatever quote style the author used.\n */\nfunction swapSourcePath(\n templateRaw: string,\n sourceKey: string,\n newPath: string\n): string {\n const re = new RegExp(\n `(\\\\n[ \\\\t]*${sourceKey}:[ \\\\t]*\\\\n(?:[ \\\\t]+[^\\\\n]*\\\\n)*?[ \\\\t]+path:[ \\\\t]*)([\"']?)[^\"'\\\\n]+\\\\2`\n )\n if (!re.test(templateRaw)) {\n throw new Error(\n `renderDeck: no \\`${sourceKey}\\` file source with a \\`path:\\` found in the template frontmatter`\n )\n }\n return templateRaw.replace(re, (_m, prefix: string, quote: string) => {\n const q = quote || '\"'\n return `${prefix}${q}${newPath}${q}`\n })\n}\n\n// ---------------------------------------------------------------------------\n// renderDeck — the plain primitive.\n// ---------------------------------------------------------------------------\n\nexport interface RenderDeckOptions {\n /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */\n template: string\n /** Optional override for the data (`d`) source path (name or path). */\n data?: string\n /** Theme: a brand NAME (`themes/<name>.theme.json`) or an explicit path. */\n theme?: string\n /** Output PDF path, relative to `cwd`. Defaults to `<template>.pdf`. */\n out?: string\n /** Font emission for the designkit bridge. Default `embed` (self-contained). */\n fonts?: FontMode\n /** Base directory for relative paths. Defaults to `process.cwd()`. */\n cwd?: string\n}\n\nexport interface RenderDeckResult {\n /** Absolute path of the written PDF. */\n path: string\n /** Byte length of the written PDF. */\n bytes: number\n /** Always `\"pdf\"`. */\n format: \"pdf\"\n}\n\n/**\n * Render a canvakit deck template to a PDF: inject the chosen theme (and data,\n * if overridden) into the template's `file` sources, then run the programmatic\n * `exportCanvas`. No temp file, no shell-out — the swap happens in memory and\n * sources resolve from the template's own directory.\n */\nexport async function renderDeck(\n opts: RenderDeckOptions\n): Promise<RenderDeckResult> {\n const cwd = opts.cwd ?? process.cwd()\n const absTemplate = nodePath.resolve(cwd, opts.template)\n const templateDir = nodePath.dirname(absTemplate)\n\n let templateRaw: string\n try {\n templateRaw = await fs.readFile(absTemplate, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderDeck: cannot read template ${absTemplate}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n\n if (opts.data) {\n templateRaw = swapSourcePath(\n templateRaw,\n \"d\",\n resolveDataPath(opts.data, templateDir, cwd)\n )\n }\n\n if (opts.theme) {\n const themePath = resolveThemePath(opts.theme, templateDir, cwd)\n if (!(await exists(nodePath.join(templateDir, themePath)))) {\n throw new Error(\n `renderDeck: no theme at ${nodePath.join(templateDir, themePath)}`\n )\n }\n templateRaw = swapSourcePath(templateRaw, \"t\", themePath)\n }\n\n const filesystem = nodeFilesystem(templateDir)\n const extensions = [designkitExtension({ fonts: opts.fonts ?? \"embed\" })]\n\n const res = await exportCanvas(\n {\n // `templatePath` is the basename so `file` sources resolve from\n // `templateDir` (dirname(\"\") === \"\" → the filesystem's own base).\n template: templateRaw,\n templatePath: nodePath.basename(absTemplate),\n filesystem,\n extensions,\n },\n { format: \"pdf\" satisfies ExportFormat }\n )\n\n const errored = Object.values(res.statuses ?? {}).find(\n s => s.status === \"error\"\n )\n if (errored) {\n throw new Error(\n `renderDeck: source error [${errored.status}]: ${errored.reason}`\n )\n }\n\n const outPath = nodePath.resolve(cwd, opts.out ?? defaultOut(opts.template))\n await fs.mkdir(nodePath.dirname(outPath), { recursive: true })\n await fs.writeFile(outPath, res.bytes)\n\n return { path: outPath, bytes: res.bytes.length, format: \"pdf\" }\n}\n\nfunction defaultOut(template: string): string {\n const base = nodePath\n .basename(template)\n .replace(/\\.canvakit\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n return nodePath.join(nodePath.dirname(template), `${base || \"deck\"}.pdf`)\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p)\n return true\n } catch {\n return false\n }\n}\n\n// ---------------------------------------------------------------------------\n// renderIllustration — the plain primitive for a single canvakit figure.\n// ---------------------------------------------------------------------------\n\n/** Strip a leading `/` or `./` so a virtual/overlay path compares cleanly. */\nfunction normalizeOverlayPath(p: string): string {\n return p.replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\")\n}\n\n/**\n * Wrap a filesystem so the virtual path `_design/<slug>.md` resolves to a kit\n * file's content, while every other path delegates to the inner filesystem.\n * This is how `kitFile` (an arbitrary `.design.md` anywhere under `cwd`) is\n * mounted for `designkitExtension({ overrideDesign: \"kit:<slug>\" })` without\n * copying it next to the template.\n *\n * @internal exported only so the test suite can exercise it directly.\n */\nexport function withDesignKitOverlay(\n inner: FilesystemLike,\n slug: string,\n content: string\n): FilesystemLike {\n const virtual = `_design/${slug}.md`\n const matches = (p: string): boolean => normalizeOverlayPath(p) === virtual\n return {\n async readFile(p) {\n if (matches(p)) return content\n return inner.readFile(p)\n },\n async writeFile(p, contents) {\n return inner.writeFile(p, contents)\n },\n async exists(p) {\n if (matches(p)) return true\n return inner.exists(p)\n },\n async readdir(p, opts) {\n return inner.readdir(p, opts)\n },\n }\n}\n\nexport interface RenderIllustrationOptions {\n /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */\n template: string\n /** Output PNG path, relative to `cwd`. Defaults to `<template dir>/<name>.png`. */\n out?: string\n /** Design kit FILE (a `.design.md`), relative to `cwd`. Mounted as `_design/<slug>.md` for this render only. */\n kitFile?: string\n /** Explicit designkit ref (`kit:<slug>`, `dk:<preset>`, `ws:<path>`). Ignored when `kitFile` is set. */\n design?: string\n /** Template variables (frontmatter `variables` overrides). */\n variables?: Record<string, string>\n /** Device scale factor for the screenshot. Default 2. */\n scale?: number\n /** Font emission. Default `link` (Google Fonts). */\n fonts?: FontMode\n /** Base directory for relative paths. Defaults to `process.cwd()`. */\n cwd?: string\n}\n\nexport interface RenderIllustrationResult {\n /** Absolute path of the written PNG. */\n path: string\n /** Byte length of the written PNG. */\n bytes: number\n /** Pixel width, read from the PNG IHDR chunk. */\n width: number\n /** Pixel height, read from the PNG IHDR chunk. */\n height: number\n /** Always `\"png\"`. */\n format: \"png\"\n}\n\nfunction defaultIllustrationOut(template: string): string {\n const base = nodePath\n .basename(template)\n .replace(/\\.canvakit\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n return nodePath.join(nodePath.dirname(template), `${base || \"figure\"}.png`)\n}\n\n/** Read width/height from a PNG's IHDR chunk (always the first chunk, at byte 16/20). */\nexport function readPngDimensions(buf: Buffer): {\n width: number\n height: number\n} {\n return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }\n}\n\n/**\n * Render a single canvakit figure template to a full-page PNG at 2x (default),\n * styled by a designkit kit file or ref. Unlike `renderDeck` (which swaps a\n * `file` source's `path:`), styling here goes entirely through the designkit\n * context extension's `overrideDesign` — no frontmatter rewriting.\n */\nexport async function renderIllustration(\n opts: RenderIllustrationOptions\n): Promise<RenderIllustrationResult> {\n const cwd = opts.cwd ?? process.cwd()\n const absTemplate = nodePath.resolve(cwd, opts.template)\n const templateDir = nodePath.dirname(absTemplate)\n\n let templateRaw: string\n try {\n templateRaw = await fs.readFile(absTemplate, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderIllustration: cannot read template ${absTemplate}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n\n let filesystem: FilesystemLike = nodeFilesystem(templateDir)\n let design: string | undefined = opts.design\n if (opts.kitFile) {\n const absKitFile = nodePath.resolve(cwd, opts.kitFile)\n let kitContent: string\n try {\n kitContent = await fs.readFile(absKitFile, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderIllustration: cannot read kitFile ${absKitFile}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n const slug = nodePath\n .basename(opts.kitFile)\n .replace(/\\.design\\.md$/i, \"\")\n .replace(/\\.md$/i, \"\")\n if (!slug) {\n // The `kit:` scheme resolver only warns and falls through to \"no\n // design\" on an empty slug (registry.ts) — reject it loudly here\n // instead, since no caller ever *means* to pass a kitFile whose\n // basename reduces to nothing. A kitFile with no frontmatter, by\n // contrast, is a documented-valid prose-only design (parse.ts) and\n // must NOT be rejected here.\n throw new Error(\n `renderIllustration: kitFile ${absKitFile} has no usable slug (its basename reduces to an empty string)`\n )\n }\n filesystem = withDesignKitOverlay(filesystem, slug, kitContent)\n design = `kit:${slug}`\n }\n\n const extensions = [\n designkitExtension({\n fonts: opts.fonts ?? \"link\",\n ...(design ? { overrideDesign: design } : {}),\n }),\n ]\n\n const res = await exportCanvas(\n {\n template: templateRaw,\n templatePath: nodePath.basename(absTemplate),\n filesystem,\n extensions,\n variables: opts.variables ?? {},\n },\n {\n format: \"png\" satisfies ExportFormat,\n renderer: cdpChromeRenderer(),\n page: { scale: opts.scale ?? 2 },\n }\n )\n\n const errored = Object.values(res.statuses ?? {}).find(\n s => s.status === \"error\"\n )\n if (errored) {\n throw new Error(\n `renderIllustration: source error [${errored.status}]: ${errored.reason}`\n )\n }\n\n const outPath = nodePath.resolve(\n cwd,\n opts.out ?? defaultIllustrationOut(opts.template)\n )\n await fs.mkdir(nodePath.dirname(outPath), { recursive: true })\n await fs.writeFile(outPath, res.bytes)\n\n const { width, height } = readPngDimensions(res.bytes)\n\n return {\n path: outPath,\n bytes: res.bytes.length,\n width,\n height,\n format: \"png\",\n }\n}\n\n// ---------------------------------------------------------------------------\n// render_deck — the AIP-14 TOOL contract.\n// ---------------------------------------------------------------------------\n\nconst renderDeckInput = z.object({\n template: z\n .string()\n .describe(\"Path to the canvakit template (*.canvakit.html).\"),\n data: z\n .string()\n .optional()\n .describe(\"Optional override for the data source path (name or path).\"),\n theme: z\n .string()\n .optional()\n .describe(\n \"Theme: a brand NAME (→ themes/<name>.theme.json) or an explicit path.\"\n ),\n out: z\n .string()\n .optional()\n .describe(\"Output PDF path. Defaults to <template>.pdf.\"),\n})\n\nconst renderDeckOutput = z.object({\n path: z.string(),\n bytes: z.number(),\n format: z.literal(\"pdf\"),\n})\n\nexport type RenderDeckInput = z.infer<typeof renderDeckInput>\nexport type RenderDeckOutput = z.infer<typeof renderDeckOutput>\n\nexport const render_deck = defineTool<RenderDeckInput, RenderDeckOutput>({\n id: \"render_deck\",\n name: \"render_deck\",\n version: \"0.1.0\",\n description:\n \"Render a canvakit deck template to a PDF, injecting a chosen theme (brand name or path) and optional data source. Wraps canvakit's programmatic render; writes the PDF and returns its path, byte size, and format.\",\n inputSchema: renderDeckInput,\n outputSchema: renderDeckOutput,\n // Writes a PDF to the filesystem — a real side effect on the `file` class.\n mutates: [\"file:out\"],\n idempotent: true,\n costClass: \"metered\",\n tags: [\"canvakit\", \"render\", \"pdf\", \"deck\"],\n})\n\n// ---------------------------------------------------------------------------\n// renderDeckDriver — the AIP-30 builtin DRIVER binding the contract to the body.\n// ---------------------------------------------------------------------------\n\nconst renderDeckImpl = implementTool(render_deck, async ({ input }) =>\n renderDeck(input)\n)\n\nexport const renderDeckDriver = defineDriver({\n id: \"canvakit.render-deck.builtin\",\n name: \"canvakit render_deck (builtin)\",\n version: \"0.1.0\",\n kind: \"builtin\",\n description:\n \"In-process builtin provider for the render_deck contract, backed by @canvakit/export's programmatic render.\",\n implements: [{ tool: \"render_deck\", version: \"^0.1.0\" }],\n implementations: [renderDeckImpl],\n})\n\n// ---------------------------------------------------------------------------\n// render_illustration — the AIP-14 TOOL contract.\n// ---------------------------------------------------------------------------\n\nconst renderIllustrationInput = z.object({\n template: z\n .string()\n .describe(\"Path to the canvakit template (*.canvakit.html).\"),\n out: z\n .string()\n .optional()\n .describe(\"Output PNG path. Defaults to <template dir>/<name>.png.\"),\n kitFile: z\n .string()\n .optional()\n .describe(\n \"Design kit FILE (a .design.md), relative to cwd. Mounted as _design/<slug>.md for this render only.\"\n ),\n design: z\n .string()\n .optional()\n .describe(\n \"Explicit designkit ref (kit:<slug>, dk:<preset>, ws:<path>). Ignored when kitFile is set.\"\n ),\n variables: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Template variables (frontmatter variables overrides).\"),\n scale: z\n .number()\n .min(1)\n .max(4)\n .optional()\n .describe(\"Device scale factor for the screenshot. Default 2.\"),\n})\n\nconst renderIllustrationOutput = z.object({\n path: z.string().describe(\"Absolute path of the written PNG.\"),\n bytes: z.number().describe(\"Byte length of the written PNG.\"),\n width: z.number().describe(\"Pixel width, read from the PNG IHDR chunk.\"),\n height: z.number().describe(\"Pixel height, read from the PNG IHDR chunk.\"),\n format: z.literal(\"png\"),\n})\n\nexport type RenderIllustrationInput = z.infer<typeof renderIllustrationInput>\nexport type RenderIllustrationOutput = z.infer<typeof renderIllustrationOutput>\n\nexport const render_illustration = defineTool<\n RenderIllustrationInput,\n RenderIllustrationOutput\n>({\n id: \"render_illustration\",\n name: \"render_illustration\",\n version: \"0.1.0\",\n description:\n \"Render a canvakit HTML template to a PNG figure (full page, 2x), styled by a designkit kit file or ref. Returns path, size in bytes and pixel dimensions.\",\n inputSchema: renderIllustrationInput,\n outputSchema: renderIllustrationOutput,\n mutates: [\"file:out\"],\n idempotent: true,\n costClass: \"metered\",\n tags: [\"canvakit\", \"designkit\", \"render\", \"png\", \"illustration\", \"figure\"],\n})\n\n// ---------------------------------------------------------------------------\n// renderIllustrationDriver — the AIP-30 builtin DRIVER binding the contract.\n// ---------------------------------------------------------------------------\n\nconst renderIllustrationImpl = implementTool(\n render_illustration,\n async ({ input }) => renderIllustration(input)\n)\n\nexport const renderIllustrationDriver = defineDriver({\n id: \"canvakit.render-illustration.builtin\",\n name: \"canvakit render_illustration (builtin)\",\n version: \"0.1.0\",\n kind: \"builtin\",\n description:\n \"In-process builtin provider for the render_illustration contract, backed by @canvakit/export's programmatic render over the CDP Chrome renderer.\",\n implements: [{ tool: \"render_illustration\", version: \"^0.1.0\" }],\n implementations: [renderIllustrationImpl],\n})\n","#!/usr/bin/env node\n/**\n * `canvakit-tool` CLI — the cli-driver entry point for the tools in this\n * package. Currently one subcommand:\n *\n * illustration --template <p> [--out <p>] [--kit <kitFile>] [--design <ref>]\n * [--var k=v]... [--scale n]\n *\n * Parses with `node:util` `parseArgs` (no new dependency), calls\n * `renderIllustration`, and prints the result as ONE line of JSON on stdout —\n * the driver contract a `kind: cli` DRIVER.md expects (`outputFormat: json`).\n */\nimport { parseArgs } from \"node:util\"\n\nimport { renderIllustration } from \"./index.js\"\n\nfunction usage(): string {\n return (\n \"usage: canvakit-tool illustration --template <path> [--out <path>] \" +\n \"[--kit <kitFile>] [--design <ref>] [--var k=v]... [--scale n]\"\n )\n}\n\nfunction parseVars(pairs: string[] | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n for (const pair of pairs ?? []) {\n const eq = pair.indexOf(\"=\")\n if (eq < 0) {\n throw new Error(`--var expects k=v, got \"${pair}\"`)\n }\n out[pair.slice(0, eq)] = pair.slice(eq + 1)\n }\n return out\n}\n\n/** Mirrors `render_illustration`'s zod bound (1..4) — the CLI calls the plain\n * `renderIllustration` primitive directly, bypassing that schema, so an\n * invalid `--scale` must be rejected here instead of reaching Chrome as NaN. */\nfunction parseScale(raw: string): number {\n const n = Number(raw)\n if (!Number.isFinite(n) || n < 1 || n > 4) {\n throw new Error(`--scale expects a number between 1 and 4, got \"${raw}\"`)\n }\n return n\n}\n\nasync function runIllustration(argv: string[]): Promise<void> {\n const { values } = parseArgs({\n args: argv,\n options: {\n template: { type: \"string\" },\n out: { type: \"string\" },\n kit: { type: \"string\" },\n design: { type: \"string\" },\n var: { type: \"string\", multiple: true },\n scale: { type: \"string\" },\n },\n allowPositionals: false,\n })\n\n if (!values.template) {\n throw new Error(\"--template is required\")\n }\n\n const result = await renderIllustration({\n template: values.template,\n out: values.out,\n kitFile: values.kit,\n design: values.design,\n variables: parseVars(values.var),\n scale: values.scale !== undefined ? parseScale(values.scale) : undefined,\n cwd: process.cwd(),\n })\n\n process.stdout.write(`${JSON.stringify(result)}\\n`)\n}\n\nasync function main(): Promise<void> {\n const [subcommand, ...rest] = process.argv.slice(2)\n\n if (subcommand !== \"illustration\") {\n process.stderr.write(`${usage()}\\n`)\n process.exit(2)\n }\n\n try {\n await runIllustration(rest)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n process.stdout.write(`${JSON.stringify({ error: message })}\\n`)\n process.exit(1)\n }\n}\n\nawait main()\n"]}
@@ -0,0 +1,145 @@
1
+ import * as _agentproto_driver from '@agentproto/driver';
2
+ import * as _agentproto_tool from '@agentproto/tool';
3
+ import { z } from 'zod';
4
+ import { FontMode } from '@canvakit/designkit';
5
+ import { FilesystemLike } from '@canvakit/core';
6
+
7
+ interface RenderDeckOptions {
8
+ /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */
9
+ template: string;
10
+ /** Optional override for the data (`d`) source path (name or path). */
11
+ data?: string;
12
+ /** Theme: a brand NAME (`themes/<name>.theme.json`) or an explicit path. */
13
+ theme?: string;
14
+ /** Output PDF path, relative to `cwd`. Defaults to `<template>.pdf`. */
15
+ out?: string;
16
+ /** Font emission for the designkit bridge. Default `embed` (self-contained). */
17
+ fonts?: FontMode;
18
+ /** Base directory for relative paths. Defaults to `process.cwd()`. */
19
+ cwd?: string;
20
+ }
21
+ interface RenderDeckResult {
22
+ /** Absolute path of the written PDF. */
23
+ path: string;
24
+ /** Byte length of the written PDF. */
25
+ bytes: number;
26
+ /** Always `"pdf"`. */
27
+ format: "pdf";
28
+ }
29
+ /**
30
+ * Render a canvakit deck template to a PDF: inject the chosen theme (and data,
31
+ * if overridden) into the template's `file` sources, then run the programmatic
32
+ * `exportCanvas`. No temp file, no shell-out — the swap happens in memory and
33
+ * sources resolve from the template's own directory.
34
+ */
35
+ declare function renderDeck(opts: RenderDeckOptions): Promise<RenderDeckResult>;
36
+ /**
37
+ * Wrap a filesystem so the virtual path `_design/<slug>.md` resolves to a kit
38
+ * file's content, while every other path delegates to the inner filesystem.
39
+ * This is how `kitFile` (an arbitrary `.design.md` anywhere under `cwd`) is
40
+ * mounted for `designkitExtension({ overrideDesign: "kit:<slug>" })` without
41
+ * copying it next to the template.
42
+ *
43
+ * @internal exported only so the test suite can exercise it directly.
44
+ */
45
+ declare function withDesignKitOverlay(inner: FilesystemLike, slug: string, content: string): FilesystemLike;
46
+ interface RenderIllustrationOptions {
47
+ /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */
48
+ template: string;
49
+ /** Output PNG path, relative to `cwd`. Defaults to `<template dir>/<name>.png`. */
50
+ out?: string;
51
+ /** Design kit FILE (a `.design.md`), relative to `cwd`. Mounted as `_design/<slug>.md` for this render only. */
52
+ kitFile?: string;
53
+ /** Explicit designkit ref (`kit:<slug>`, `dk:<preset>`, `ws:<path>`). Ignored when `kitFile` is set. */
54
+ design?: string;
55
+ /** Template variables (frontmatter `variables` overrides). */
56
+ variables?: Record<string, string>;
57
+ /** Device scale factor for the screenshot. Default 2. */
58
+ scale?: number;
59
+ /** Font emission. Default `link` (Google Fonts). */
60
+ fonts?: FontMode;
61
+ /** Base directory for relative paths. Defaults to `process.cwd()`. */
62
+ cwd?: string;
63
+ }
64
+ interface RenderIllustrationResult {
65
+ /** Absolute path of the written PNG. */
66
+ path: string;
67
+ /** Byte length of the written PNG. */
68
+ bytes: number;
69
+ /** Pixel width, read from the PNG IHDR chunk. */
70
+ width: number;
71
+ /** Pixel height, read from the PNG IHDR chunk. */
72
+ height: number;
73
+ /** Always `"png"`. */
74
+ format: "png";
75
+ }
76
+ /** Read width/height from a PNG's IHDR chunk (always the first chunk, at byte 16/20). */
77
+ declare function readPngDimensions(buf: Buffer): {
78
+ width: number;
79
+ height: number;
80
+ };
81
+ /**
82
+ * Render a single canvakit figure template to a full-page PNG at 2x (default),
83
+ * styled by a designkit kit file or ref. Unlike `renderDeck` (which swaps a
84
+ * `file` source's `path:`), styling here goes entirely through the designkit
85
+ * context extension's `overrideDesign` — no frontmatter rewriting.
86
+ */
87
+ declare function renderIllustration(opts: RenderIllustrationOptions): Promise<RenderIllustrationResult>;
88
+ declare const renderDeckInput: z.ZodObject<{
89
+ template: z.ZodString;
90
+ data: z.ZodOptional<z.ZodString>;
91
+ theme: z.ZodOptional<z.ZodString>;
92
+ out: z.ZodOptional<z.ZodString>;
93
+ }, z.core.$strip>;
94
+ declare const renderDeckOutput: z.ZodObject<{
95
+ path: z.ZodString;
96
+ bytes: z.ZodNumber;
97
+ format: z.ZodLiteral<"pdf">;
98
+ }, z.core.$strip>;
99
+ type RenderDeckInput = z.infer<typeof renderDeckInput>;
100
+ type RenderDeckOutput = z.infer<typeof renderDeckOutput>;
101
+ declare const render_deck: _agentproto_tool.ToolHandle<{
102
+ template: string;
103
+ data?: string | undefined;
104
+ theme?: string | undefined;
105
+ out?: string | undefined;
106
+ }, {
107
+ path: string;
108
+ bytes: number;
109
+ format: "pdf";
110
+ }, _agentproto_tool.ToolContext>;
111
+ declare const renderDeckDriver: _agentproto_driver.DriverHandle;
112
+ declare const renderIllustrationInput: z.ZodObject<{
113
+ template: z.ZodString;
114
+ out: z.ZodOptional<z.ZodString>;
115
+ kitFile: z.ZodOptional<z.ZodString>;
116
+ design: z.ZodOptional<z.ZodString>;
117
+ variables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
118
+ scale: z.ZodOptional<z.ZodNumber>;
119
+ }, z.core.$strip>;
120
+ declare const renderIllustrationOutput: z.ZodObject<{
121
+ path: z.ZodString;
122
+ bytes: z.ZodNumber;
123
+ width: z.ZodNumber;
124
+ height: z.ZodNumber;
125
+ format: z.ZodLiteral<"png">;
126
+ }, z.core.$strip>;
127
+ type RenderIllustrationInput = z.infer<typeof renderIllustrationInput>;
128
+ type RenderIllustrationOutput = z.infer<typeof renderIllustrationOutput>;
129
+ declare const render_illustration: _agentproto_tool.ToolHandle<{
130
+ template: string;
131
+ out?: string | undefined;
132
+ kitFile?: string | undefined;
133
+ design?: string | undefined;
134
+ variables?: Record<string, string> | undefined;
135
+ scale?: number | undefined;
136
+ }, {
137
+ path: string;
138
+ bytes: number;
139
+ width: number;
140
+ height: number;
141
+ format: "png";
142
+ }, _agentproto_tool.ToolContext>;
143
+ declare const renderIllustrationDriver: _agentproto_driver.DriverHandle;
144
+
145
+ export { type RenderDeckInput, type RenderDeckOptions, type RenderDeckOutput, type RenderDeckResult, type RenderIllustrationInput, type RenderIllustrationOptions, type RenderIllustrationOutput, type RenderIllustrationResult, readPngDimensions, renderDeck, renderDeckDriver, renderIllustration, renderIllustrationDriver, render_deck, render_illustration, withDesignKitOverlay };
package/dist/index.mjs ADDED
@@ -0,0 +1,343 @@
1
+ import { promises } from 'fs';
2
+ import * as nodePath from 'path';
3
+ import { z } from 'zod';
4
+ import { exportCanvas, cdpChromeRenderer } from '@canvakit/export';
5
+ import { designkitExtension } from '@canvakit/designkit';
6
+ import { defineTool } from '@agentproto/tool';
7
+ import { implementTool, defineDriver } from '@agentproto/driver';
8
+
9
+ /**
10
+ * @canvakit/tool v0.1.0
11
+ * canvakit render as an agentproto primitive (render_deck).
12
+ */
13
+
14
+ function nodeFilesystem(baseDir) {
15
+ const abs = nodePath.resolve(baseDir);
16
+ const resolve2 = (p) => nodePath.resolve(abs, p.replace(/^\/+/, ""));
17
+ return {
18
+ async readFile(p) {
19
+ return promises.readFile(resolve2(p));
20
+ },
21
+ async writeFile(p, contents) {
22
+ const full = resolve2(p);
23
+ await promises.mkdir(nodePath.dirname(full), { recursive: true });
24
+ await promises.writeFile(full, contents);
25
+ },
26
+ async exists(p) {
27
+ try {
28
+ await promises.access(resolve2(p));
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ },
34
+ async readdir(p) {
35
+ try {
36
+ const found = await promises.readdir(resolve2(p), { withFileTypes: true });
37
+ return found.map((e) => ({
38
+ name: e.name,
39
+ type: e.isDirectory() ? "directory" : "file"
40
+ }));
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+ };
46
+ }
47
+ function looksLikePath(theme) {
48
+ return theme.includes("/") || theme.toLowerCase().endsWith(".json");
49
+ }
50
+ function resolveThemePath(theme, templateDir, cwd) {
51
+ if (!looksLikePath(theme)) return `themes/${theme}.theme.json`;
52
+ const abs = nodePath.resolve(cwd, theme);
53
+ const rel = nodePath.relative(templateDir, abs);
54
+ if (rel.startsWith("..") || nodePath.isAbsolute(rel)) {
55
+ throw new Error(
56
+ `renderDeck: theme path "${theme}" resolves outside the template directory (${templateDir}); themes must live under the template so canvakit can resolve them.`
57
+ );
58
+ }
59
+ return rel.split(nodePath.sep).join("/");
60
+ }
61
+ function resolveDataPath(data, templateDir, cwd) {
62
+ const abs = nodePath.resolve(cwd, data);
63
+ const rel = nodePath.relative(templateDir, abs);
64
+ if (rel.startsWith("..") || nodePath.isAbsolute(rel)) {
65
+ throw new Error(
66
+ `renderDeck: data path "${data}" resolves outside the template directory (${templateDir}); data must live under the template so canvakit can resolve it.`
67
+ );
68
+ }
69
+ return rel.split(nodePath.sep).join("/");
70
+ }
71
+ function swapSourcePath(templateRaw, sourceKey, newPath) {
72
+ const re = new RegExp(
73
+ `(\\n[ \\t]*${sourceKey}:[ \\t]*\\n(?:[ \\t]+[^\\n]*\\n)*?[ \\t]+path:[ \\t]*)(["']?)[^"'\\n]+\\2`
74
+ );
75
+ if (!re.test(templateRaw)) {
76
+ throw new Error(
77
+ `renderDeck: no \`${sourceKey}\` file source with a \`path:\` found in the template frontmatter`
78
+ );
79
+ }
80
+ return templateRaw.replace(re, (_m, prefix, quote) => {
81
+ const q = quote || '"';
82
+ return `${prefix}${q}${newPath}${q}`;
83
+ });
84
+ }
85
+ async function renderDeck(opts) {
86
+ const cwd = opts.cwd ?? process.cwd();
87
+ const absTemplate = nodePath.resolve(cwd, opts.template);
88
+ const templateDir = nodePath.dirname(absTemplate);
89
+ let templateRaw;
90
+ try {
91
+ templateRaw = await promises.readFile(absTemplate, "utf-8");
92
+ } catch (err) {
93
+ throw new Error(
94
+ `renderDeck: cannot read template ${absTemplate}: ${err instanceof Error ? err.message : String(err)}`
95
+ );
96
+ }
97
+ if (opts.data) {
98
+ templateRaw = swapSourcePath(
99
+ templateRaw,
100
+ "d",
101
+ resolveDataPath(opts.data, templateDir, cwd)
102
+ );
103
+ }
104
+ if (opts.theme) {
105
+ const themePath = resolveThemePath(opts.theme, templateDir, cwd);
106
+ if (!await exists(nodePath.join(templateDir, themePath))) {
107
+ throw new Error(
108
+ `renderDeck: no theme at ${nodePath.join(templateDir, themePath)}`
109
+ );
110
+ }
111
+ templateRaw = swapSourcePath(templateRaw, "t", themePath);
112
+ }
113
+ const filesystem = nodeFilesystem(templateDir);
114
+ const extensions = [designkitExtension({ fonts: opts.fonts ?? "embed" })];
115
+ const res = await exportCanvas(
116
+ {
117
+ // `templatePath` is the basename so `file` sources resolve from
118
+ // `templateDir` (dirname("") === "" → the filesystem's own base).
119
+ template: templateRaw,
120
+ templatePath: nodePath.basename(absTemplate),
121
+ filesystem,
122
+ extensions
123
+ },
124
+ { format: "pdf" }
125
+ );
126
+ const errored = Object.values(res.statuses ?? {}).find(
127
+ (s) => s.status === "error"
128
+ );
129
+ if (errored) {
130
+ throw new Error(
131
+ `renderDeck: source error [${errored.status}]: ${errored.reason}`
132
+ );
133
+ }
134
+ const outPath = nodePath.resolve(cwd, opts.out ?? defaultOut(opts.template));
135
+ await promises.mkdir(nodePath.dirname(outPath), { recursive: true });
136
+ await promises.writeFile(outPath, res.bytes);
137
+ return { path: outPath, bytes: res.bytes.length, format: "pdf" };
138
+ }
139
+ function defaultOut(template) {
140
+ const base = nodePath.basename(template).replace(/\.canvakit\.html$/i, "").replace(/\.html$/i, "");
141
+ return nodePath.join(nodePath.dirname(template), `${base || "deck"}.pdf`);
142
+ }
143
+ async function exists(p) {
144
+ try {
145
+ await promises.access(p);
146
+ return true;
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ function normalizeOverlayPath(p) {
152
+ return p.replace(/^\.\//, "").replace(/^\/+/, "");
153
+ }
154
+ function withDesignKitOverlay(inner, slug, content) {
155
+ const virtual = `_design/${slug}.md`;
156
+ const matches = (p) => normalizeOverlayPath(p) === virtual;
157
+ return {
158
+ async readFile(p) {
159
+ if (matches(p)) return content;
160
+ return inner.readFile(p);
161
+ },
162
+ async writeFile(p, contents) {
163
+ return inner.writeFile(p, contents);
164
+ },
165
+ async exists(p) {
166
+ if (matches(p)) return true;
167
+ return inner.exists(p);
168
+ },
169
+ async readdir(p, opts) {
170
+ return inner.readdir(p, opts);
171
+ }
172
+ };
173
+ }
174
+ function defaultIllustrationOut(template) {
175
+ const base = nodePath.basename(template).replace(/\.canvakit\.html$/i, "").replace(/\.html$/i, "");
176
+ return nodePath.join(nodePath.dirname(template), `${base || "figure"}.png`);
177
+ }
178
+ function readPngDimensions(buf) {
179
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
180
+ }
181
+ async function renderIllustration(opts) {
182
+ const cwd = opts.cwd ?? process.cwd();
183
+ const absTemplate = nodePath.resolve(cwd, opts.template);
184
+ const templateDir = nodePath.dirname(absTemplate);
185
+ let templateRaw;
186
+ try {
187
+ templateRaw = await promises.readFile(absTemplate, "utf-8");
188
+ } catch (err) {
189
+ throw new Error(
190
+ `renderIllustration: cannot read template ${absTemplate}: ${err instanceof Error ? err.message : String(err)}`
191
+ );
192
+ }
193
+ let filesystem = nodeFilesystem(templateDir);
194
+ let design = opts.design;
195
+ if (opts.kitFile) {
196
+ const absKitFile = nodePath.resolve(cwd, opts.kitFile);
197
+ let kitContent;
198
+ try {
199
+ kitContent = await promises.readFile(absKitFile, "utf-8");
200
+ } catch (err) {
201
+ throw new Error(
202
+ `renderIllustration: cannot read kitFile ${absKitFile}: ${err instanceof Error ? err.message : String(err)}`
203
+ );
204
+ }
205
+ const slug = nodePath.basename(opts.kitFile).replace(/\.design\.md$/i, "").replace(/\.md$/i, "");
206
+ if (!slug) {
207
+ throw new Error(
208
+ `renderIllustration: kitFile ${absKitFile} has no usable slug (its basename reduces to an empty string)`
209
+ );
210
+ }
211
+ filesystem = withDesignKitOverlay(filesystem, slug, kitContent);
212
+ design = `kit:${slug}`;
213
+ }
214
+ const extensions = [
215
+ designkitExtension({
216
+ fonts: opts.fonts ?? "link",
217
+ ...design ? { overrideDesign: design } : {}
218
+ })
219
+ ];
220
+ const res = await exportCanvas(
221
+ {
222
+ template: templateRaw,
223
+ templatePath: nodePath.basename(absTemplate),
224
+ filesystem,
225
+ extensions,
226
+ variables: opts.variables ?? {}
227
+ },
228
+ {
229
+ format: "png",
230
+ renderer: cdpChromeRenderer(),
231
+ page: { scale: opts.scale ?? 2 }
232
+ }
233
+ );
234
+ const errored = Object.values(res.statuses ?? {}).find(
235
+ (s) => s.status === "error"
236
+ );
237
+ if (errored) {
238
+ throw new Error(
239
+ `renderIllustration: source error [${errored.status}]: ${errored.reason}`
240
+ );
241
+ }
242
+ const outPath = nodePath.resolve(
243
+ cwd,
244
+ opts.out ?? defaultIllustrationOut(opts.template)
245
+ );
246
+ await promises.mkdir(nodePath.dirname(outPath), { recursive: true });
247
+ await promises.writeFile(outPath, res.bytes);
248
+ const { width, height } = readPngDimensions(res.bytes);
249
+ return {
250
+ path: outPath,
251
+ bytes: res.bytes.length,
252
+ width,
253
+ height,
254
+ format: "png"
255
+ };
256
+ }
257
+ var renderDeckInput = z.object({
258
+ template: z.string().describe("Path to the canvakit template (*.canvakit.html)."),
259
+ data: z.string().optional().describe("Optional override for the data source path (name or path)."),
260
+ theme: z.string().optional().describe(
261
+ "Theme: a brand NAME (\u2192 themes/<name>.theme.json) or an explicit path."
262
+ ),
263
+ out: z.string().optional().describe("Output PDF path. Defaults to <template>.pdf.")
264
+ });
265
+ var renderDeckOutput = z.object({
266
+ path: z.string(),
267
+ bytes: z.number(),
268
+ format: z.literal("pdf")
269
+ });
270
+ var render_deck = defineTool({
271
+ id: "render_deck",
272
+ name: "render_deck",
273
+ version: "0.1.0",
274
+ description: "Render a canvakit deck template to a PDF, injecting a chosen theme (brand name or path) and optional data source. Wraps canvakit's programmatic render; writes the PDF and returns its path, byte size, and format.",
275
+ inputSchema: renderDeckInput,
276
+ outputSchema: renderDeckOutput,
277
+ // Writes a PDF to the filesystem — a real side effect on the `file` class.
278
+ mutates: ["file:out"],
279
+ idempotent: true,
280
+ costClass: "metered",
281
+ tags: ["canvakit", "render", "pdf", "deck"]
282
+ });
283
+ var renderDeckImpl = implementTool(
284
+ render_deck,
285
+ async ({ input }) => renderDeck(input)
286
+ );
287
+ var renderDeckDriver = defineDriver({
288
+ id: "canvakit.render-deck.builtin",
289
+ name: "canvakit render_deck (builtin)",
290
+ version: "0.1.0",
291
+ kind: "builtin",
292
+ description: "In-process builtin provider for the render_deck contract, backed by @canvakit/export's programmatic render.",
293
+ implements: [{ tool: "render_deck", version: "^0.1.0" }],
294
+ implementations: [renderDeckImpl]
295
+ });
296
+ var renderIllustrationInput = z.object({
297
+ template: z.string().describe("Path to the canvakit template (*.canvakit.html)."),
298
+ out: z.string().optional().describe("Output PNG path. Defaults to <template dir>/<name>.png."),
299
+ kitFile: z.string().optional().describe(
300
+ "Design kit FILE (a .design.md), relative to cwd. Mounted as _design/<slug>.md for this render only."
301
+ ),
302
+ design: z.string().optional().describe(
303
+ "Explicit designkit ref (kit:<slug>, dk:<preset>, ws:<path>). Ignored when kitFile is set."
304
+ ),
305
+ variables: z.record(z.string(), z.string()).optional().describe("Template variables (frontmatter variables overrides)."),
306
+ scale: z.number().min(1).max(4).optional().describe("Device scale factor for the screenshot. Default 2.")
307
+ });
308
+ var renderIllustrationOutput = z.object({
309
+ path: z.string().describe("Absolute path of the written PNG."),
310
+ bytes: z.number().describe("Byte length of the written PNG."),
311
+ width: z.number().describe("Pixel width, read from the PNG IHDR chunk."),
312
+ height: z.number().describe("Pixel height, read from the PNG IHDR chunk."),
313
+ format: z.literal("png")
314
+ });
315
+ var render_illustration = defineTool({
316
+ id: "render_illustration",
317
+ name: "render_illustration",
318
+ version: "0.1.0",
319
+ description: "Render a canvakit HTML template to a PNG figure (full page, 2x), styled by a designkit kit file or ref. Returns path, size in bytes and pixel dimensions.",
320
+ inputSchema: renderIllustrationInput,
321
+ outputSchema: renderIllustrationOutput,
322
+ mutates: ["file:out"],
323
+ idempotent: true,
324
+ costClass: "metered",
325
+ tags: ["canvakit", "designkit", "render", "png", "illustration", "figure"]
326
+ });
327
+ var renderIllustrationImpl = implementTool(
328
+ render_illustration,
329
+ async ({ input }) => renderIllustration(input)
330
+ );
331
+ var renderIllustrationDriver = defineDriver({
332
+ id: "canvakit.render-illustration.builtin",
333
+ name: "canvakit render_illustration (builtin)",
334
+ version: "0.1.0",
335
+ kind: "builtin",
336
+ description: "In-process builtin provider for the render_illustration contract, backed by @canvakit/export's programmatic render over the CDP Chrome renderer.",
337
+ implements: [{ tool: "render_illustration", version: "^0.1.0" }],
338
+ implementations: [renderIllustrationImpl]
339
+ });
340
+
341
+ export { readPngDimensions, renderDeck, renderDeckDriver, renderIllustration, renderIllustrationDriver, render_deck, render_illustration, withDesignKitOverlay };
342
+ //# sourceMappingURL=index.mjs.map
343
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["resolve","fs"],"mappings":";;;;;;;;;;;;;AA+CA,SAAS,eAAe,OAAA,EAAiC;AACvD,EAAA,MAAM,GAAA,GAAe,iBAAQ,OAAO,CAAA;AACpC,EAAA,MAAMA,QAAAA,GAAU,CAAC,CAAA,KAAuB,QAAA,CAAA,OAAA,CAAQ,KAAK,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAC,CAAA;AAC1E,EAAA,OAAO;AAAA,IACL,MAAM,SAAS,CAAA,EAAG;AAChB,MAAA,OAAOC,QAAA,CAAG,QAAA,CAASD,QAAAA,CAAQ,CAAC,CAAC,CAAA;AAAA,IAC/B,CAAA;AAAA,IACA,MAAM,SAAA,CAAU,CAAA,EAAG,QAAA,EAAU;AAC3B,MAAA,MAAM,IAAA,GAAOA,SAAQ,CAAC,CAAA;AACtB,MAAA,MAAMC,QAAA,CAAG,MAAe,QAAA,CAAA,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC1D,MAAA,MAAMA,QAAA,CAAG,SAAA,CAAU,IAAA,EAAM,QAAQ,CAAA;AAAA,IACnC,CAAA;AAAA,IACA,MAAM,OAAO,CAAA,EAAG;AACd,MAAA,IAAI;AACF,QA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;AAAA,EACA,EAAA,EAAI,qBAAA;AAAA,EACJ,IAAA,EAAM,qBAAA;AAAA,EACN,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EACE,2JAAA;AAAA,EACF,WAAA,EAAa,uBAAA;AAAA,EACb,YAAA,EAAc,wBAAA;AAAA,EACd,OAAA,EAAS,CAAC,UAAU,CAAA;AAAA,EACpB,UAAA,EAAY,IAAA;AAAA,EACZ,SAAA,EAAW,SAAA;AAAA,EACX,MAAM,CAAC,UAAA,EAAY,aAAa,QAAA,EAAU,KAAA,EAAO,gBAAgB,QAAQ;AAC3E,CAAC;AAMD,IAAM,sBAAA,GAAyB,aAAA;AAAA,EAC7B,mBAAA;AAAA,EACA,OAAO,EAAE,KAAA,EAAM,KAAM,mBAAmB,KAAK;AAC/C,CAAA;AAEO,IAAM,2BAA2B,YAAA,CAAa;AAAA,EACnD,EAAA,EAAI,sCAAA;AAAA,EACJ,IAAA,EAAM,wCAAA;AAAA,EACN,OAAA,EAAS,OAAA;AAAA,EACT,IAAA,EAAM,SAAA;AAAA,EACN,WAAA,EACE,kJAAA;AAAA,EACF,YAAY,CAAC,EAAE,MAAM,qBAAA,EAAuB,OAAA,EAAS,UAAU,CAAA;AAAA,EAC/D,eAAA,EAAiB,CAAC,sBAAsB;AAC1C,CAAC","file":"index.mjs","sourcesContent":["/**\n * @canvakit/tool — canvakit render as an agentproto primitive.\n *\n * The standalone deck renderer (`decks/<deck>/render.mjs`) is JS glue: it string-\n * swaps a theme path in a template's frontmatter and shells out to the\n * `canvakit` CLI. This package re-expresses the same capability as a proper\n * agentproto tool:\n *\n * - `renderDeck(opts)` — the plain async primitive (resolve template + data\n * + theme, then `exportCanvas` → a PDF on disk).\n * - `render_deck` — the AIP-14 TOOL contract (`defineTool`): identity,\n * input/output zod schemas, side-effect profile.\n * - `renderDeckDriver` — the AIP-30 builtin DRIVER (`defineDriver`) binding\n * the contract to `renderDeck` via `implementTool`.\n *\n * - `renderIllustration(opts)` — the plain async primitive for a single\n * canvakit figure: template + a designkit kit (file\n * or ref) → a full-page PNG via the CDP renderer.\n * - `render_illustration` — the AIP-14 TOOL contract.\n * - `renderIllustrationDriver` — the AIP-30 builtin DRIVER.\n *\n * Vendor-neutral: no brand names live here. A \"theme\" is either a bare NAME\n * (resolved to `themes/<name>.theme.json` next to the template) or an explicit\n * path — brand themes are only ever test inputs.\n */\n\nimport { promises as fs } from \"node:fs\"\nimport * as nodePath from \"node:path\"\nimport { z } from \"zod\"\n\nimport {\n exportCanvas,\n cdpChromeRenderer,\n type ExportFormat,\n} from \"@canvakit/export\"\nimport { designkitExtension, type FontMode } from \"@canvakit/designkit\"\nimport type { FilesystemEntry, FilesystemLike } from \"@canvakit/core\"\n\nimport { defineTool } from \"@agentproto/tool\"\nimport { defineDriver, implementTool } from \"@agentproto/driver\"\n\n// ---------------------------------------------------------------------------\n// filesystem — a minimal node-backed FilesystemLike, resolving every canvakit\n// (forward-slash, root-relative) path against a base directory. Mirrors the\n// CLI's `createLocalFs` without taking a dependency on the CLI package.\n// ---------------------------------------------------------------------------\n\nfunction nodeFilesystem(baseDir: string): FilesystemLike {\n const abs = nodePath.resolve(baseDir)\n const resolve = (p: string) => nodePath.resolve(abs, p.replace(/^\\/+/, \"\"))\n return {\n async readFile(p) {\n return fs.readFile(resolve(p))\n },\n async writeFile(p, contents) {\n const full = resolve(p)\n await fs.mkdir(nodePath.dirname(full), { recursive: true })\n await fs.writeFile(full, contents)\n },\n async exists(p) {\n try {\n await fs.access(resolve(p))\n return true\n } catch {\n return false\n }\n },\n async readdir(p): Promise<ReadonlyArray<FilesystemEntry>> {\n try {\n const found = await fs.readdir(resolve(p), { withFileTypes: true })\n return found.map(e => ({\n name: e.name,\n type: e.isDirectory() ? \"directory\" : \"file\",\n }))\n } catch {\n return []\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// theme / data injection — point a named `file` source at a chosen path by\n// rewriting its `path:` in the template frontmatter. Same effect as render.mjs\n// (which regex-swaps the theme path), but scoped to a specific source key so it\n// stays correct for any template following the `d`=data / `t`=theme convention.\n// ---------------------------------------------------------------------------\n\n/** True when a theme value is an explicit path rather than a bare brand name. */\nfunction looksLikePath(theme: string): boolean {\n return theme.includes(\"/\") || theme.toLowerCase().endsWith(\".json\")\n}\n\n/**\n * Resolve a theme value to a template-dir-relative path.\n * - a bare NAME → `themes/<name>.theme.json` (next to the template)\n * - an explicit path (absolute or cwd-relative) → re-based onto the template\n * directory, since canvakit resolves `file` sources from there.\n */\nfunction resolveThemePath(\n theme: string,\n templateDir: string,\n cwd: string\n): string {\n if (!looksLikePath(theme)) return `themes/${theme}.theme.json`\n const abs = nodePath.resolve(cwd, theme)\n const rel = nodePath.relative(templateDir, abs)\n if (rel.startsWith(\"..\") || nodePath.isAbsolute(rel)) {\n throw new Error(\n `renderDeck: theme path \"${theme}\" resolves outside the template directory ` +\n `(${templateDir}); themes must live under the template so canvakit can resolve them.`\n )\n }\n return rel.split(nodePath.sep).join(\"/\")\n}\n\n/** Re-base an explicit data path (absolute/cwd-relative) onto the template dir. */\nfunction resolveDataPath(\n data: string,\n templateDir: string,\n cwd: string\n): string {\n const abs = nodePath.resolve(cwd, data)\n const rel = nodePath.relative(templateDir, abs)\n if (rel.startsWith(\"..\") || nodePath.isAbsolute(rel)) {\n throw new Error(\n `renderDeck: data path \"${data}\" resolves outside the template directory ` +\n `(${templateDir}); data must live under the template so canvakit can resolve it.`\n )\n }\n return rel.split(nodePath.sep).join(\"/\")\n}\n\n/**\n * Rewrite the `path:` of a named `file` source in the template frontmatter.\n * Matches `<key>:` then the first following `path:` line at deeper indent,\n * preserving whatever quote style the author used.\n */\nfunction swapSourcePath(\n templateRaw: string,\n sourceKey: string,\n newPath: string\n): string {\n const re = new RegExp(\n `(\\\\n[ \\\\t]*${sourceKey}:[ \\\\t]*\\\\n(?:[ \\\\t]+[^\\\\n]*\\\\n)*?[ \\\\t]+path:[ \\\\t]*)([\"']?)[^\"'\\\\n]+\\\\2`\n )\n if (!re.test(templateRaw)) {\n throw new Error(\n `renderDeck: no \\`${sourceKey}\\` file source with a \\`path:\\` found in the template frontmatter`\n )\n }\n return templateRaw.replace(re, (_m, prefix: string, quote: string) => {\n const q = quote || '\"'\n return `${prefix}${q}${newPath}${q}`\n })\n}\n\n// ---------------------------------------------------------------------------\n// renderDeck — the plain primitive.\n// ---------------------------------------------------------------------------\n\nexport interface RenderDeckOptions {\n /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */\n template: string\n /** Optional override for the data (`d`) source path (name or path). */\n data?: string\n /** Theme: a brand NAME (`themes/<name>.theme.json`) or an explicit path. */\n theme?: string\n /** Output PDF path, relative to `cwd`. Defaults to `<template>.pdf`. */\n out?: string\n /** Font emission for the designkit bridge. Default `embed` (self-contained). */\n fonts?: FontMode\n /** Base directory for relative paths. Defaults to `process.cwd()`. */\n cwd?: string\n}\n\nexport interface RenderDeckResult {\n /** Absolute path of the written PDF. */\n path: string\n /** Byte length of the written PDF. */\n bytes: number\n /** Always `\"pdf\"`. */\n format: \"pdf\"\n}\n\n/**\n * Render a canvakit deck template to a PDF: inject the chosen theme (and data,\n * if overridden) into the template's `file` sources, then run the programmatic\n * `exportCanvas`. No temp file, no shell-out — the swap happens in memory and\n * sources resolve from the template's own directory.\n */\nexport async function renderDeck(\n opts: RenderDeckOptions\n): Promise<RenderDeckResult> {\n const cwd = opts.cwd ?? process.cwd()\n const absTemplate = nodePath.resolve(cwd, opts.template)\n const templateDir = nodePath.dirname(absTemplate)\n\n let templateRaw: string\n try {\n templateRaw = await fs.readFile(absTemplate, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderDeck: cannot read template ${absTemplate}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n\n if (opts.data) {\n templateRaw = swapSourcePath(\n templateRaw,\n \"d\",\n resolveDataPath(opts.data, templateDir, cwd)\n )\n }\n\n if (opts.theme) {\n const themePath = resolveThemePath(opts.theme, templateDir, cwd)\n if (!(await exists(nodePath.join(templateDir, themePath)))) {\n throw new Error(\n `renderDeck: no theme at ${nodePath.join(templateDir, themePath)}`\n )\n }\n templateRaw = swapSourcePath(templateRaw, \"t\", themePath)\n }\n\n const filesystem = nodeFilesystem(templateDir)\n const extensions = [designkitExtension({ fonts: opts.fonts ?? \"embed\" })]\n\n const res = await exportCanvas(\n {\n // `templatePath` is the basename so `file` sources resolve from\n // `templateDir` (dirname(\"\") === \"\" → the filesystem's own base).\n template: templateRaw,\n templatePath: nodePath.basename(absTemplate),\n filesystem,\n extensions,\n },\n { format: \"pdf\" satisfies ExportFormat }\n )\n\n const errored = Object.values(res.statuses ?? {}).find(\n s => s.status === \"error\"\n )\n if (errored) {\n throw new Error(\n `renderDeck: source error [${errored.status}]: ${errored.reason}`\n )\n }\n\n const outPath = nodePath.resolve(cwd, opts.out ?? defaultOut(opts.template))\n await fs.mkdir(nodePath.dirname(outPath), { recursive: true })\n await fs.writeFile(outPath, res.bytes)\n\n return { path: outPath, bytes: res.bytes.length, format: \"pdf\" }\n}\n\nfunction defaultOut(template: string): string {\n const base = nodePath\n .basename(template)\n .replace(/\\.canvakit\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n return nodePath.join(nodePath.dirname(template), `${base || \"deck\"}.pdf`)\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p)\n return true\n } catch {\n return false\n }\n}\n\n// ---------------------------------------------------------------------------\n// renderIllustration — the plain primitive for a single canvakit figure.\n// ---------------------------------------------------------------------------\n\n/** Strip a leading `/` or `./` so a virtual/overlay path compares cleanly. */\nfunction normalizeOverlayPath(p: string): string {\n return p.replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\")\n}\n\n/**\n * Wrap a filesystem so the virtual path `_design/<slug>.md` resolves to a kit\n * file's content, while every other path delegates to the inner filesystem.\n * This is how `kitFile` (an arbitrary `.design.md` anywhere under `cwd`) is\n * mounted for `designkitExtension({ overrideDesign: \"kit:<slug>\" })` without\n * copying it next to the template.\n *\n * @internal exported only so the test suite can exercise it directly.\n */\nexport function withDesignKitOverlay(\n inner: FilesystemLike,\n slug: string,\n content: string\n): FilesystemLike {\n const virtual = `_design/${slug}.md`\n const matches = (p: string): boolean => normalizeOverlayPath(p) === virtual\n return {\n async readFile(p) {\n if (matches(p)) return content\n return inner.readFile(p)\n },\n async writeFile(p, contents) {\n return inner.writeFile(p, contents)\n },\n async exists(p) {\n if (matches(p)) return true\n return inner.exists(p)\n },\n async readdir(p, opts) {\n return inner.readdir(p, opts)\n },\n }\n}\n\nexport interface RenderIllustrationOptions {\n /** Path to the canvakit template (`*.canvakit.html`), relative to `cwd`. */\n template: string\n /** Output PNG path, relative to `cwd`. Defaults to `<template dir>/<name>.png`. */\n out?: string\n /** Design kit FILE (a `.design.md`), relative to `cwd`. Mounted as `_design/<slug>.md` for this render only. */\n kitFile?: string\n /** Explicit designkit ref (`kit:<slug>`, `dk:<preset>`, `ws:<path>`). Ignored when `kitFile` is set. */\n design?: string\n /** Template variables (frontmatter `variables` overrides). */\n variables?: Record<string, string>\n /** Device scale factor for the screenshot. Default 2. */\n scale?: number\n /** Font emission. Default `link` (Google Fonts). */\n fonts?: FontMode\n /** Base directory for relative paths. Defaults to `process.cwd()`. */\n cwd?: string\n}\n\nexport interface RenderIllustrationResult {\n /** Absolute path of the written PNG. */\n path: string\n /** Byte length of the written PNG. */\n bytes: number\n /** Pixel width, read from the PNG IHDR chunk. */\n width: number\n /** Pixel height, read from the PNG IHDR chunk. */\n height: number\n /** Always `\"png\"`. */\n format: \"png\"\n}\n\nfunction defaultIllustrationOut(template: string): string {\n const base = nodePath\n .basename(template)\n .replace(/\\.canvakit\\.html$/i, \"\")\n .replace(/\\.html$/i, \"\")\n return nodePath.join(nodePath.dirname(template), `${base || \"figure\"}.png`)\n}\n\n/** Read width/height from a PNG's IHDR chunk (always the first chunk, at byte 16/20). */\nexport function readPngDimensions(buf: Buffer): {\n width: number\n height: number\n} {\n return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }\n}\n\n/**\n * Render a single canvakit figure template to a full-page PNG at 2x (default),\n * styled by a designkit kit file or ref. Unlike `renderDeck` (which swaps a\n * `file` source's `path:`), styling here goes entirely through the designkit\n * context extension's `overrideDesign` — no frontmatter rewriting.\n */\nexport async function renderIllustration(\n opts: RenderIllustrationOptions\n): Promise<RenderIllustrationResult> {\n const cwd = opts.cwd ?? process.cwd()\n const absTemplate = nodePath.resolve(cwd, opts.template)\n const templateDir = nodePath.dirname(absTemplate)\n\n let templateRaw: string\n try {\n templateRaw = await fs.readFile(absTemplate, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderIllustration: cannot read template ${absTemplate}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n\n let filesystem: FilesystemLike = nodeFilesystem(templateDir)\n let design: string | undefined = opts.design\n if (opts.kitFile) {\n const absKitFile = nodePath.resolve(cwd, opts.kitFile)\n let kitContent: string\n try {\n kitContent = await fs.readFile(absKitFile, \"utf-8\")\n } catch (err) {\n throw new Error(\n `renderIllustration: cannot read kitFile ${absKitFile}: ${\n err instanceof Error ? err.message : String(err)\n }`\n )\n }\n const slug = nodePath\n .basename(opts.kitFile)\n .replace(/\\.design\\.md$/i, \"\")\n .replace(/\\.md$/i, \"\")\n if (!slug) {\n // The `kit:` scheme resolver only warns and falls through to \"no\n // design\" on an empty slug (registry.ts) — reject it loudly here\n // instead, since no caller ever *means* to pass a kitFile whose\n // basename reduces to nothing. A kitFile with no frontmatter, by\n // contrast, is a documented-valid prose-only design (parse.ts) and\n // must NOT be rejected here.\n throw new Error(\n `renderIllustration: kitFile ${absKitFile} has no usable slug (its basename reduces to an empty string)`\n )\n }\n filesystem = withDesignKitOverlay(filesystem, slug, kitContent)\n design = `kit:${slug}`\n }\n\n const extensions = [\n designkitExtension({\n fonts: opts.fonts ?? \"link\",\n ...(design ? { overrideDesign: design } : {}),\n }),\n ]\n\n const res = await exportCanvas(\n {\n template: templateRaw,\n templatePath: nodePath.basename(absTemplate),\n filesystem,\n extensions,\n variables: opts.variables ?? {},\n },\n {\n format: \"png\" satisfies ExportFormat,\n renderer: cdpChromeRenderer(),\n page: { scale: opts.scale ?? 2 },\n }\n )\n\n const errored = Object.values(res.statuses ?? {}).find(\n s => s.status === \"error\"\n )\n if (errored) {\n throw new Error(\n `renderIllustration: source error [${errored.status}]: ${errored.reason}`\n )\n }\n\n const outPath = nodePath.resolve(\n cwd,\n opts.out ?? defaultIllustrationOut(opts.template)\n )\n await fs.mkdir(nodePath.dirname(outPath), { recursive: true })\n await fs.writeFile(outPath, res.bytes)\n\n const { width, height } = readPngDimensions(res.bytes)\n\n return {\n path: outPath,\n bytes: res.bytes.length,\n width,\n height,\n format: \"png\",\n }\n}\n\n// ---------------------------------------------------------------------------\n// render_deck — the AIP-14 TOOL contract.\n// ---------------------------------------------------------------------------\n\nconst renderDeckInput = z.object({\n template: z\n .string()\n .describe(\"Path to the canvakit template (*.canvakit.html).\"),\n data: z\n .string()\n .optional()\n .describe(\"Optional override for the data source path (name or path).\"),\n theme: z\n .string()\n .optional()\n .describe(\n \"Theme: a brand NAME (→ themes/<name>.theme.json) or an explicit path.\"\n ),\n out: z\n .string()\n .optional()\n .describe(\"Output PDF path. Defaults to <template>.pdf.\"),\n})\n\nconst renderDeckOutput = z.object({\n path: z.string(),\n bytes: z.number(),\n format: z.literal(\"pdf\"),\n})\n\nexport type RenderDeckInput = z.infer<typeof renderDeckInput>\nexport type RenderDeckOutput = z.infer<typeof renderDeckOutput>\n\nexport const render_deck = defineTool<RenderDeckInput, RenderDeckOutput>({\n id: \"render_deck\",\n name: \"render_deck\",\n version: \"0.1.0\",\n description:\n \"Render a canvakit deck template to a PDF, injecting a chosen theme (brand name or path) and optional data source. Wraps canvakit's programmatic render; writes the PDF and returns its path, byte size, and format.\",\n inputSchema: renderDeckInput,\n outputSchema: renderDeckOutput,\n // Writes a PDF to the filesystem — a real side effect on the `file` class.\n mutates: [\"file:out\"],\n idempotent: true,\n costClass: \"metered\",\n tags: [\"canvakit\", \"render\", \"pdf\", \"deck\"],\n})\n\n// ---------------------------------------------------------------------------\n// renderDeckDriver — the AIP-30 builtin DRIVER binding the contract to the body.\n// ---------------------------------------------------------------------------\n\nconst renderDeckImpl = implementTool(render_deck, async ({ input }) =>\n renderDeck(input)\n)\n\nexport const renderDeckDriver = defineDriver({\n id: \"canvakit.render-deck.builtin\",\n name: \"canvakit render_deck (builtin)\",\n version: \"0.1.0\",\n kind: \"builtin\",\n description:\n \"In-process builtin provider for the render_deck contract, backed by @canvakit/export's programmatic render.\",\n implements: [{ tool: \"render_deck\", version: \"^0.1.0\" }],\n implementations: [renderDeckImpl],\n})\n\n// ---------------------------------------------------------------------------\n// render_illustration — the AIP-14 TOOL contract.\n// ---------------------------------------------------------------------------\n\nconst renderIllustrationInput = z.object({\n template: z\n .string()\n .describe(\"Path to the canvakit template (*.canvakit.html).\"),\n out: z\n .string()\n .optional()\n .describe(\"Output PNG path. Defaults to <template dir>/<name>.png.\"),\n kitFile: z\n .string()\n .optional()\n .describe(\n \"Design kit FILE (a .design.md), relative to cwd. Mounted as _design/<slug>.md for this render only.\"\n ),\n design: z\n .string()\n .optional()\n .describe(\n \"Explicit designkit ref (kit:<slug>, dk:<preset>, ws:<path>). Ignored when kitFile is set.\"\n ),\n variables: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Template variables (frontmatter variables overrides).\"),\n scale: z\n .number()\n .min(1)\n .max(4)\n .optional()\n .describe(\"Device scale factor for the screenshot. Default 2.\"),\n})\n\nconst renderIllustrationOutput = z.object({\n path: z.string().describe(\"Absolute path of the written PNG.\"),\n bytes: z.number().describe(\"Byte length of the written PNG.\"),\n width: z.number().describe(\"Pixel width, read from the PNG IHDR chunk.\"),\n height: z.number().describe(\"Pixel height, read from the PNG IHDR chunk.\"),\n format: z.literal(\"png\"),\n})\n\nexport type RenderIllustrationInput = z.infer<typeof renderIllustrationInput>\nexport type RenderIllustrationOutput = z.infer<typeof renderIllustrationOutput>\n\nexport const render_illustration = defineTool<\n RenderIllustrationInput,\n RenderIllustrationOutput\n>({\n id: \"render_illustration\",\n name: \"render_illustration\",\n version: \"0.1.0\",\n description:\n \"Render a canvakit HTML template to a PNG figure (full page, 2x), styled by a designkit kit file or ref. Returns path, size in bytes and pixel dimensions.\",\n inputSchema: renderIllustrationInput,\n outputSchema: renderIllustrationOutput,\n mutates: [\"file:out\"],\n idempotent: true,\n costClass: \"metered\",\n tags: [\"canvakit\", \"designkit\", \"render\", \"png\", \"illustration\", \"figure\"],\n})\n\n// ---------------------------------------------------------------------------\n// renderIllustrationDriver — the AIP-30 builtin DRIVER binding the contract.\n// ---------------------------------------------------------------------------\n\nconst renderIllustrationImpl = implementTool(\n render_illustration,\n async ({ input }) => renderIllustration(input)\n)\n\nexport const renderIllustrationDriver = defineDriver({\n id: \"canvakit.render-illustration.builtin\",\n name: \"canvakit render_illustration (builtin)\",\n version: \"0.1.0\",\n kind: \"builtin\",\n description:\n \"In-process builtin provider for the render_illustration contract, backed by @canvakit/export's programmatic render over the CDP Chrome renderer.\",\n implements: [{ tool: \"render_illustration\", version: \"^0.1.0\" }],\n implementations: [renderIllustrationImpl],\n})\n"]}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@canvakit/tool",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "canvakit render as an agentproto primitive — `render_deck` (template + theme -> PDF) and `render_illustration` (template + designkit kit -> PNG) as AIP-14 tool contracts + AIP-30 builtin drivers, wrapping @canvakit/export's programmatic render. A `canvakit-tool` CLI exposes render_illustration for cli-kind drivers.",
5
+ "keywords": [
6
+ "canvakit",
7
+ "agentproto",
8
+ "aip-14",
9
+ "aip-30",
10
+ "render",
11
+ "deck",
12
+ "pdf",
13
+ "tool"
14
+ ],
15
+ "license": "FSL-1.1-ALv2",
16
+ "type": "module",
17
+ "main": "dist/index.mjs",
18
+ "module": "dist/index.mjs",
19
+ "types": "dist/index.d.ts",
20
+ "bin": {
21
+ "canvakit-tool": "dist/cli.mjs"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.mjs",
27
+ "default": "./dist/index.mjs"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@agentproto/driver": "^0.4.6",
41
+ "@agentproto/tool": "^0.8.2",
42
+ "@canvakit/core": "^0.2.0",
43
+ "@canvakit/designkit": "^0.2.0",
44
+ "@canvakit/export": "^0.2.0",
45
+ "zod": "^4.4.3"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^25.6.2",
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^3.2.4",
52
+ "@canvakit/tooling": "0.0.0"
53
+ },
54
+ "homepage": "https://canvakit.sh",
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "https://github.com/openagentik/canvakit",
58
+ "directory": "packages/tool"
59
+ },
60
+ "bugs": {
61
+ "url": "https://github.com/openagentik/canvakit/issues"
62
+ },
63
+ "scripts": {
64
+ "dev": "tsup --watch",
65
+ "build": "tsup",
66
+ "clean": "rm -rf dist",
67
+ "check-types": "tsc --noEmit",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest"
70
+ }
6
71
  }