@imgly/codesign-mcp 0.3.7-next.20260929141300.g06dc965 → 0.4.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.
@@ -1,2 +1,2 @@
1
- export declare const IMGLY_CESDK_LICENSE = "7qtEF71BdueuKdKLVaqwoKDOZ2Q_G0q5lxEl7ZB65vtWOeDoWIOl5URmJEYsrTjK";
1
+ export declare const IMGLY_CESDK_LICENSE = "kCgJ_4vzZqNJpokVQ3aVWRkbYdTuVGV_peaxlLFHep2MMEKtKVOgfebazUicfkNa";
2
2
  //# sourceMappingURL=license.generated.d.ts.map
@@ -1,4 +1,4 @@
1
1
  // AUTO-GENERATED by scripts/generate-license.mjs — do not edit.
2
2
  // Empty unless IMGLY_CESDK_LICENSE was set at build/publish time.
3
- export const IMGLY_CESDK_LICENSE = "7qtEF71BdueuKdKLVaqwoKDOZ2Q_G0q5lxEl7ZB65vtWOeDoWIOl5URmJEYsrTjK";
3
+ export const IMGLY_CESDK_LICENSE = "kCgJ_4vzZqNJpokVQ3aVWRkbYdTuVGV_peaxlLFHep2MMEKtKVOgfebazUicfkNa";
4
4
  //# sourceMappingURL=license.generated.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"license.generated.js","sourceRoot":"","sources":["../../src/cli/license.generated.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAChE,kEAAkE;AAClE,MAAM,CAAC,MAAM,mBAAmB,GAAG,kEAAkE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-license.mjs — do not edit.\n// Empty unless IMGLY_CESDK_LICENSE was set at build/publish time.\nexport const IMGLY_CESDK_LICENSE = \"7qtEF71BdueuKdKLVaqwoKDOZ2Q_G0q5lxEl7ZB65vtWOeDoWIOl5URmJEYsrTjK\";\n"]}
1
+ {"version":3,"file":"license.generated.js","sourceRoot":"","sources":["../../src/cli/license.generated.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAChE,kEAAkE;AAClE,MAAM,CAAC,MAAM,mBAAmB,GAAG,kEAAkE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-license.mjs — do not edit.\n// Empty unless IMGLY_CESDK_LICENSE was set at build/publish time.\nexport const IMGLY_CESDK_LICENSE = \"kCgJ_4vzZqNJpokVQ3aVWRkbYdTuVGV_peaxlLFHep2MMEKtKVOgfebazUicfkNa\";\n"]}
@@ -1,4 +1,4 @@
1
1
  export declare const RELEASE_BUILD = true;
2
- export declare const CHANNEL = "next";
2
+ export declare const CHANNEL = "stable";
3
3
  export declare const DEV_ENV_HELP = "";
4
4
  //# sourceMappingURL=release-flags.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"release-flags.generated.d.ts","sourceRoot":"","sources":["../../src/cli/release-flags.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,OAAO,CAAC;AAElC,eAAO,MAAM,OAAO,SAAS,CAAC;AAG9B,eAAO,MAAM,YAAY,KAAK,CAAC"}
1
+ {"version":3,"file":"release-flags.generated.d.ts","sourceRoot":"","sources":["../../src/cli/release-flags.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,OAAO,CAAC;AAElC,eAAO,MAAM,OAAO,WAAW,CAAC;AAGhC,eAAO,MAAM,YAAY,KAAK,CAAC"}
@@ -2,7 +2,7 @@
2
2
  // True only when IMGLY_RELEASE_BUILD=true was set at build/publish time.
3
3
  export const RELEASE_BUILD = true;
4
4
  // Build profile: stable | next | canary. See src/flags/manifest.ts.
5
- export const CHANNEL = 'next';
5
+ export const CHANNEL = 'stable';
6
6
  // The frozen-knob --help section. Empty in a release build, so the names
7
7
  // are absent from the published dist, not just unprinted.
8
8
  export const DEV_ENV_HELP = "";
@@ -1 +1 @@
1
- {"version":3,"file":"release-flags.generated.js","sourceRoot":"","sources":["../../src/cli/release-flags.generated.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,yEAAyE;AACzE,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC;AAClC,oEAAoE;AACpE,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC;AAC9B,yEAAyE;AACzE,0DAA0D;AAC1D,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-release-flags.mjs — do not edit.\n// True only when IMGLY_RELEASE_BUILD=true was set at build/publish time.\nexport const RELEASE_BUILD = true;\n// Build profile: stable | next | canary. See src/flags/manifest.ts.\nexport const CHANNEL = 'next';\n// The frozen-knob --help section. Empty in a release build, so the names\n// are absent from the published dist, not just unprinted.\nexport const DEV_ENV_HELP = \"\";\n"]}
1
+ {"version":3,"file":"release-flags.generated.js","sourceRoot":"","sources":["../../src/cli/release-flags.generated.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,yEAAyE;AACzE,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC;AAClC,oEAAoE;AACpE,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC;AAChC,yEAAyE;AACzE,0DAA0D;AAC1D,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC","sourcesContent":["// AUTO-GENERATED by scripts/generate-release-flags.mjs — do not edit.\n// True only when IMGLY_RELEASE_BUILD=true was set at build/publish time.\nexport const RELEASE_BUILD = true;\n// Build profile: stable | next | canary. See src/flags/manifest.ts.\nexport const CHANNEL = 'stable';\n// The frozen-knob --help section. Empty in a release build, so the names\n// are absent from the published dist, not just unprinted.\nexport const DEV_ENV_HELP = \"\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"export.d.ts","sourceRoot":"","sources":["../../src/tools/export.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAO1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EACV,2BAA2B,EAE5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AAC;IACzB,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,gBAAgB,CAAC,CAAC,GAAG,OAAO,EAC1C,IAAI,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAC/B,2BAA2B,CA00B7B"}
@@ -19,6 +19,19 @@ import { engineFallbackWarning, resolvedEngineFlavor } from './engine.js';
19
19
  import { avUnavailableMessage, engineCapabilities } from '../capability.js';
20
20
  import { classifyThrow } from './errors.js';
21
21
  import { NOOP_TELEMETRY_SINK, SpanRecorder, summarizeResult, toErrorShape } from './spans.js';
22
+ /** True when walking up from `blockId` reaches `sceneId`; an id the engine rejects counts as attached, so the encode reports it. */
23
+ function isAttachedToScene(getParent, blockId, sceneId) {
24
+ try {
25
+ for (let b = blockId; b !== null; b = getParent(b)) {
26
+ if (b === sceneId)
27
+ return true;
28
+ }
29
+ return false;
30
+ }
31
+ catch {
32
+ return true;
33
+ }
34
+ }
22
35
  // `format` alone names the deliverable: it determines the kind of artifact
23
36
  // (and with it the engine code path and output filename), the mime type, and
24
37
  // the file extension.
@@ -763,6 +776,7 @@ export function createExportTool(opts) {
763
776
  const exportVideo = eng.block.exportVideo?.bind(eng.block);
764
777
  const forceLoadResources = eng.block.forceLoadResources?.bind(eng.block);
765
778
  const findAll = eng.block.findAll?.bind(eng.block);
779
+ const getParent = eng.block.getParent?.bind(eng.block);
766
780
  // The engine may have booted (and fallen back) during this call.
767
781
  const caps = await engineCapabilities({
768
782
  flavor: engineFlavor,
@@ -771,12 +785,20 @@ export function createExportTool(opts) {
771
785
  if (!caps.video ||
772
786
  !exportVideo ||
773
787
  !forceLoadResources ||
774
- !findAll) {
788
+ !findAll ||
789
+ !getParent) {
775
790
  return {
776
791
  ok: false,
777
792
  message: `export: ${avUnavailableMessage('format=mp4 (video export)', caps)}`
778
793
  };
779
794
  }
795
+ // exportVideo on a detached block kills the process (issues/@cesdk/node-native/01a0ed5f-6c49-705d-8b29-cdd246f4fbd3_exportvideo-detached-page-sigtrap).
796
+ if (!isAttachedToScene(getParent, blockId, eng.scene.get())) {
797
+ return {
798
+ ok: false,
799
+ message: `export: block ${blockId} exists in revision ${revId} but is not attached to the scene, so it has nothing to play. Append it to the scene (or to a page that is) in your next \`edit\` — a page made with \`engine.design.create\` and no parent stays detached — or omit \`blockId\` to export the whole document.`
800
+ };
801
+ }
780
802
  const encodeOnce = () => rec.time('engine_execute', async () => {
781
803
  // Force-load every referenced resource first, or the encoder
782
804
  // races the asset fetch (black frames / silent audio).
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","sourceRoot":"","sources":["../../src/tools/export.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,4EAA4E;AAC5E,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,IAAI,MAAM,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAG1E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EACL,mBAAmB,EACnB,eAAe,EAChB,MAAM,4BAA4B,CAAC;AASpC,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAkB,MAAM,aAAa,CAAC;AAE5D,OAAO,EACL,mBAAmB,EACnB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wBACrC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBACtD;oBACD,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACpE,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACjC,GAAG,CAAC,KAAK;wBACP,CAAC,CAAC,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE;wBAChC,CAAC,CAAC,WAAW;4BACX,CAAC,CAAC,EAAE,KAAK,EAAE,YAAY,CAAC,WAAW,CAAC,EAAE;4BACtC,CAAC,CAAC,EAAE,CAAC;iBACV,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// packages/codesign-mcp/src/tools/export.ts\n//\n// `export` — spec §6.2. Writes a revision-pinned pdf/image/video artifact into\n// `exports/<shard>/<rev>/<kind>.<ext>` (`pdf.pdf`, `image.png`, `video.mp4`,\n// …) and returns a workspace URI envelope: `uri` (the durable `workspace://`\n// handle) plus `httpUrl` (the `/r/` fetch link). The workspace's on-disk\n// location is disclosed only as an echo of a caller-chosen `outPath` — when\n// omitted, the workspace handle is the only way to reach the bytes; when\n// provided, `outPath` confirms the local write succeeded.\nimport { performance } from 'node:perf_hooks';\nimport { dirname, isAbsolute, resolve as resolvePath } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { promises as nodeFs } from 'node:fs';\nimport { isResourcesStillLoadingError } from '../engine/engine-errors.js';\nimport type { Mutex } from '../engine/mutex.js';\nimport type { EngineSession } from '../engine/session.js';\nimport { findStaleHead } from '../revisions/drift.js';\nimport { findUnjudged, unjudgedNoticeText } from '../revisions/scorecards.js';\nimport {\n checklistNoticeText,\n verifyChecklist\n} from '../revisions/checklists.js';\nimport type { RevisionStore } from '../revisions/store.js';\nimport type { Revision } from '../revisions/types.js';\nimport type {\n CodesignMcpToolRegistration,\n ToolCallContext\n} from '../server.js';\nimport type { ViewerUrlBuilder } from '../viewer/url-builder.js';\nimport type { WorkspaceFS } from '../workspace/types.js';\nimport {\n type EngineFlavor,\n engineFallbackWarning,\n resolvedEngineFlavor\n} from './engine.js';\nimport { avUnavailableMessage, engineCapabilities } from '../capability.js';\nimport { classifyThrow, type ErrorCode } from './errors.js';\nimport type { ResolvedPdfxArgs } from './export-formats/pdfx.js';\nimport {\n NOOP_TELEMETRY_SINK,\n SpanRecorder,\n summarizeResult,\n toErrorShape,\n type TelemetrySink\n} from './spans.js';\n\ntype Target = 'pdf' | 'image' | 'video' | 'pdfx' | 'html' | 'design';\ntype Format =\n | 'pdf'\n | 'png'\n | 'jpeg'\n | 'webp'\n | 'svg'\n | 'pdfx'\n | 'html'\n | 'mp4'\n | 'imgly';\n\ntype CallResult = Awaited<ReturnType<CodesignMcpToolRegistration['call']>>;\n\ntype DeliverOutcome =\n | { ok: true; result: CallResult }\n | { ok: false; result: CallResult; errorCode: ErrorCode; error?: unknown };\n\ninterface MinimalEngine {\n scene: {\n get(): number | null;\n getPages(): number[];\n saveToArchive(): Promise<Blob>;\n };\n block: {\n // The engine's object-options signature. Its deprecated\n // `export(id, mimeType, options)` overload validates `options` against a\n // stale struct that rejects newer keys — `exportPdfWithDeviceCMYK` throws\n // \"Invalid arguments\" there even though the .d.ts types it as accepted.\n export(\n blockId: number,\n options: {\n mimeType: string;\n exportPdfWithDeviceCMYK?: boolean;\n }\n ): Promise<Blob>;\n exportVideo?(\n blockId: number,\n options?: {\n mimeType?: string;\n framerate?: number;\n onProgress?: (rendered: number, encoded: number, total: number) => void;\n }\n ): Promise<Blob>;\n forceLoadResources?(blockIds: number[]): Promise<void>;\n getPlaybackTime?(blockId: number): number;\n setPlaybackTime?(blockId: number, time: number): void;\n findByType?(type: string): number[];\n getString?(blockId: number, property: string): string;\n findAll?(): number[];\n };\n}\n\ninterface ExportArgs {\n format: Format;\n revision: string;\n blockId?: number;\n pdfx?: unknown;\n html?: unknown;\n fps?: unknown;\n outPath?: string;\n}\n\ninterface FormatSpec {\n target: Target;\n mime: string;\n ext: string;\n /** 'engine' = built-in encoder; 'pdfx'/'html' = plugin adapter in export-formats/; 'archive' = the .imgly design bundle. */\n kind: 'engine' | 'pdfx' | 'html' | 'archive';\n}\n\n// `format` alone names the deliverable: it determines the kind of artifact\n// (and with it the engine code path and output filename), the mime type, and\n// the file extension.\nconst FORMATS: Record<Format, FormatSpec> = {\n pdf: { target: 'pdf', mime: 'application/pdf', ext: 'pdf', kind: 'engine' },\n png: { target: 'image', mime: 'image/png', ext: 'png', kind: 'engine' },\n jpeg: { target: 'image', mime: 'image/jpeg', ext: 'jpg', kind: 'engine' },\n webp: { target: 'image', mime: 'image/webp', ext: 'webp', kind: 'engine' },\n svg: { target: 'image', mime: 'image/svg+xml', ext: 'svg', kind: 'engine' },\n pdfx: { target: 'pdfx', mime: 'application/pdf', ext: 'pdf', kind: 'pdfx' },\n html: { target: 'html', mime: 'text/html', ext: 'html', kind: 'html' },\n mp4: { target: 'video', mime: 'video/mp4', ext: 'mp4', kind: 'engine' },\n // target 'design' + ext 'imgly' makes the generic\n // `exports/<shard>/<rest>/<target>.<ext>` rule reproduce the path `save`\n // wrote, so `workspace://` URIs handed out by `save` stay valid. `mime` is\n // inert here (as it is for html) — saveToArchive picks the container.\n imgly: {\n target: 'design',\n mime: 'application/zip',\n ext: 'imgly',\n kind: 'archive'\n }\n};\n\n// Literal dynamic imports — esbuild inlines these in single-file mode (CODE-69\n// SEA bundle) while Node loads them on first use, so an unused exporter costs\n// nothing at boot.\nconst EXPORTER_MODULES = {\n pdfx: () => import('./export-formats/pdfx.js'),\n html: () => import('./export-formats/html.js')\n} as const;\nexport type ExporterModules = typeof EXPORTER_MODULES;\n\nfunction formatSpec(format: string): FormatSpec | undefined {\n // hasOwnProperty guard: `format: \"toString\"` must not resolve via the\n // object prototype.\n return Object.prototype.hasOwnProperty.call(FORMATS, format)\n ? FORMATS[format as Format]\n : undefined;\n}\n\nconst PROGRESS_MIN_INTERVAL_MS = 1000;\n\n/** `fps` default when the caller omits it, and the accepted ceiling. */\nconst DEFAULT_VIDEO_FPS = 30;\nconst MAX_VIDEO_FPS = 120;\n\n// The encoder can report \"busy\" briefly after a previous exportVideo resolved;\n// absorb that window. (The Linux permanent wedge of 1.77–1.79 no longer\n// reproduces on 1.82.0; the unskipped stress test guards it.)\nconst ENCODER_BUSY_MARKER = 'currently encoding';\nconst ENCODER_BUSY_DELAYS_MS = [250, 500, 1000, 2000, 4000];\n\nfunction isEncoderBusyError(err: unknown): boolean {\n return err instanceof Error && err.message.includes(ENCODER_BUSY_MARKER);\n}\n\n/**\n * Map exportVideo's per-frame onProgress to MCP progress at ~1/s. The engine\n * fires per encoded frame (a 30s clip at 30fps ≈ 900 calls); unthrottled,\n * that floods the client. The final tick (encoded >= total) always sends.\n */\nfunction throttledVideoProgress(\n report: NonNullable<ToolCallContext['progress']> | undefined\n): ((rendered: number, encoded: number, total: number) => void) | undefined {\n if (!report) return undefined;\n let lastSent = -Infinity;\n return (_rendered, encoded, total) => {\n const now = performance.now();\n if (encoded < total && now - lastSent < PROGRESS_MIN_INTERVAL_MS) return;\n lastSent = now;\n report({ progress: encoded, total, message: 'encoding' });\n };\n}\n\n// Local write-through — real disk fs, NOT the workspace abstraction. The\n// caller chose this path explicitly, so echoing it back is a confirmation,\n// not a workspace-path leak. Runs AFTER the workspace write: a failed copy\n// never loses the export — the returned error text carries the still-valid\n// workspace handles. Shared by the standard delivery tail and the html\n// early-return, the two places an artifact leaves the tool.\nasync function writeOutPathCopy(\n rec: SpanRecorder,\n outPath: string,\n bytes: Uint8Array,\n /** Where the artifact still is, and the field the caller reads it from. */\n handle: { name: 'httpUrl' | 'fileUrl'; where: string }\n): Promise<{ path: string } | { error: unknown; errorText: string }> {\n try {\n await nodeFs.mkdir(dirname(outPath), { recursive: true });\n await rec.time('outpath_write', async () => {\n await nodeFs.writeFile(outPath, bytes);\n });\n return { path: outPath };\n } catch (err) {\n // An unwritable/invalid outPath (EACCES, EROFS, ENOTDIR, …) is bad\n // caller input, not an internal fault — answer with recovery guidance\n // instead of leaking a raw stack as an MCP -32603.\n if (typeof (err as { code?: string }).code !== 'string') throw err;\n return {\n error: err,\n errorText: `export: could not write outPath \"${outPath}\" — ${(err as Error).message}. The artifact is safe at ${handle.where}. Retry with a writable absolute path, or omit \\`outPath\\` and use \\`${handle.name}\\`.`\n };\n }\n}\n\nfunction buildDescription(\n allowLocalPath: boolean,\n viewerDisabled: boolean\n): string {\n const handle = viewerDisabled\n ? '`{ fileUrl, bytes, format, revision }`'\n : '`{ uri, httpUrl, bytes, format, revision }`';\n const handleCopy = viewerDisabled\n ? '. `fileUrl` is a `file://` URI for the artifact on this machine — that IS the deliverable, and the only handle: give it to the user.'\n : '. `uri` (a `workspace://` URI) is the durable handle. `httpUrl` is a fetch link tied to this process — fetch it to download the bytes to disk, or hand it to the user.';\n return [\n `Export a revision to a final deliverable — \\`format\\` picks it: \\`pdf\\` (print PDF), \\`png\\`/\\`jpeg\\`/\\`webp\\` (image), \\`svg\\` (vector SVG), \\`pdfx\\` (print-ready PDF/X), \\`html\\` (responsive HTML5), \\`mp4\\` (video), \\`imgly\\` (editable design file). Renders \\`blockId\\` — or the whole document when \\`blockId\\` is omitted — and writes the result into the workspace under \\`exports/<shard>/<rev>/\\` (revision-pinned, deterministic).`,\n '',\n `Returns JSON: ${handle}` +\n (allowLocalPath ? ' (plus `path` when you pass `outPath`)' : '') +\n handleCopy,\n ...(allowLocalPath\n ? [\n '',\n \"`outPath` (optional, absolute path including the filename): ALSO write the artifact to that local path — the workspace copy is still written, and the response then carries `path`. Use it when the file is wanted on disk, and always when your environment cannot fetch localhost URLs (sandboxed harnesses, e.g. Claude Cowork — target your session's outputs folder there).\"\n ]\n : []),\n '',\n \"`format=svg` is the engine's vector export: text is outlined into paths (renders identically everywhere, but is not editable text in the SVG), and raster images are embedded in the file at source resolution — an SVG of a photo-heavy design can be much larger than its source images.\",\n '',\n '`format=imgly` writes a portable, self-contained `.imgly` design file (scene + all asset bytes bundled) — the inverse of `import`, and the only format that stays editable. Whole-design only: `blockId` is not accepted. Every `edit` already auto-persists to the workspace, so you never need this to keep your work — use it to take an editable copy OUT: hand it to a human, back it up, move it between servers.',\n '',\n '`format=pdfx` runs the print PDF through a PDF/X conversion (Ghostscript): CMYK with an embedded ICC profile and PDF/X conformance markers, ready for a print shop. Tune it via the optional `pdfx` object — conformance standard (X-4 default / X-3), output profile (fogra39/gracol/srgb/custom), transparency flattening, OutputIntent metadata. Conversion adds a few seconds.',\n '',\n '`format=html` renders ONE page (`blockId` required — pass a page id) to responsive HTML5. Default is a single self-contained `.html` (assets inlined; animated designs get a CDN GSAP player injected so the file plays as-is); `html: { assets: \"external\" }` delivers html + separate image/font files as one `.zip`.',\n '',\n '`format=mp4` renders the authored timeline of the block (typically a page) to an H.264 `mp4`; duration and resolution come from the scene; frame rate is `fps` (default 30). Requires the native engine (the default). Long encodes report MCP progress notifications when the client sends a progressToken.'\n ].join('\\n');\n}\n\nfunction buildExportInputSchema(allowLocalPath: boolean) {\n const properties: Record<string, unknown> = {\n format: {\n enum: [\n 'pdf',\n 'png',\n 'jpeg',\n 'webp',\n 'svg',\n 'pdfx',\n 'html',\n 'mp4',\n 'imgly'\n ],\n description:\n 'The deliverable: pdf → print PDF; png/jpeg/webp → image; svg → vector SVG; pdfx → print-ready PDF/X; html → HTML5 page; mp4 → video; imgly → editable design file.'\n },\n revision: { type: 'string' as const },\n blockId: {\n type: 'integer' as const,\n description:\n 'The page or block to render. Omit to export the whole document — for `format=pdf` a multi-page PDF, for an image format one composite image of all pages.' +\n ' Required for format=html (pass a page id).' +\n ' Required for `format=mp4` (pass a page id).'\n },\n pdfx: {\n type: 'object' as const,\n description:\n 'Options for `format=pdfx` only (invalid with any other format). Omit entirely for sensible print defaults: PDF/X-4, fogra39, embedded ICC.',\n properties: {\n outputStandard: {\n enum: ['PDF/X-4', 'PDF/X-3'],\n description:\n 'PDF/X conformance target. PDF/X-4 (default) keeps live transparency. PDF/X-3 is the older PDF 1.4 standard — it flattens transparency by default and can rasterize gradients/alpha content.'\n },\n outputProfile: {\n enum: ['fogra39', 'gracol', 'srgb', 'custom'],\n description:\n \"Target printing condition / ICC output profile. fogra39 (default) = ISO Coated v2 (ECI), European offset. gracol = GRACoL 2013 CRPC6, US commercial. srgb = keep RGB, for digital distribution. custom = supply the print shop's ICC file via profileUri.\"\n },\n profileUri: {\n type: 'string' as const,\n description:\n 'Required with outputProfile=\"custom\" (invalid otherwise): an https:// URL or absolute local file path of the .icc profile to embed.'\n },\n flattenTransparency: {\n type: 'boolean' as const,\n description:\n 'PDF/X-3 only (default true there): rasterize transparent content for strict compliance. false keeps transparency live — better fidelity, may not validate. Ignored on PDF/X-4.'\n },\n embedICCProfile: {\n type: 'boolean' as const,\n description:\n 'Default true. false → plain CMYK (or RGB) PDF with no embedded ICC profile, OutputIntent, or PDF/X markers — for prepress pipelines that apply their own profile.'\n },\n title: {\n type: 'string' as const,\n description: \"PDF document title. Defaults to the design's title.\"\n },\n outputConditionIdentifier: {\n type: 'string' as const,\n description:\n 'Overrides the PDF\\'s /OutputConditionIdentifier — the REGISTERED printing-condition name preflight tools and print shops check (e.g. \"FOGRA39\", \"CGATS 21.2\"). Defaults from outputProfile; with a custom profile, your print shop tells you what to put here.'\n },\n outputCondition: {\n type: 'string' as const,\n description:\n 'Overrides /OutputCondition — the human-readable printing-condition description (e.g. \"ISO Coated v2 (ECI)\"). Defaults from outputProfile.'\n }\n },\n additionalProperties: false\n },\n html: {\n type: 'object' as const,\n description:\n 'Options for `format=html` only (invalid with any other format).',\n properties: {\n assets: {\n enum: ['embedded', 'external'],\n description:\n 'embedded (default): one self-contained .html, assets inlined as data URLs — viewable anywhere as-is. external: html + separate image/font files, delivered as one .zip.'\n }\n },\n additionalProperties: false\n },\n fps: {\n type: 'number' as const,\n exclusiveMinimum: 0,\n maximum: MAX_VIDEO_FPS,\n description: `Frames per second for \\`format=mp4\\` only (invalid with any other format). Default ${DEFAULT_VIDEO_FPS}. Common values: 24, 25, 30, 60.`\n }\n };\n if (allowLocalPath) {\n properties.outPath = {\n type: 'string' as const,\n description:\n 'Absolute path (including filename) to ALSO write the artifact to — the workspace copy is still written, and the response then carries `path`. Use when you need the file on disk and cannot fetch localhost URLs (sandboxed harnesses).'\n };\n }\n return {\n type: 'object' as const,\n properties,\n required: ['format', 'revision'],\n additionalProperties: false\n };\n}\n\nexport interface CreateExportToolOptions<E = unknown> {\n fs: WorkspaceFS;\n store: RevisionStore;\n session: EngineSession<E>;\n /** Builds the `httpUrl` for workspace-written artifacts (the `/r/` route). */\n urlBuilder: ViewerUrlBuilder;\n /** Guards the shared engine — load-then-export must not interleave with another session's edit (see engine/mutex.ts). */\n engineLock: Mutex;\n /** Diagnostics telemetry port. Absent → no-op (no timing overhead beyond a few clocks). */\n telemetry?: TelemetrySink;\n /** Resolved engine flavor probe; injected by tests. Default: the real one. */\n engineFlavor?: () => EngineFlavor | undefined;\n /** Why the engine fell back to WASM; injected by tests. Default: the real one. */\n fallbackReason?: () => string | undefined;\n /** Encoder-busy retry backoff schedule; injected by tests. */\n encoderBusyDelaysMs?: number[];\n /** Lazy exporter-adapter modules; injected by tests. Default: the real dynamic imports. */\n exporterModules?: ExporterModules;\n /** Local(true)/Hosted(false): advertise + honour `outPath` — the same\n * signal that gates `import`'s `{ path }` arm (the process shares the\n * caller's disk). Default false. */\n allowLocalPath?: boolean;\n /** IMGLY_DISABLE_VIEWER: hand back `fileUrl` (the artifact on this machine)\n * instead of the viewer-origin `httpUrl`. Needs {@link localRoot}; without\n * one (object-store backend) `httpUrl` stays — it is a presigned download,\n * not a viewer link. */\n viewerDisabled?: boolean;\n /** Absolute path the workspace is rooted at, when it is a real directory. */\n localRoot?: string;\n}\n\nexport function createExportTool<E = unknown>(\n opts: CreateExportToolOptions<E>\n): CodesignMcpToolRegistration {\n const {\n fs,\n store,\n session,\n urlBuilder,\n engineLock,\n engineFlavor = resolvedEngineFlavor,\n fallbackReason = engineFallbackWarning,\n encoderBusyDelaysMs = ENCODER_BUSY_DELAYS_MS,\n exporterModules = EXPORTER_MODULES,\n allowLocalPath = false\n } = opts;\n const telemetry = opts.telemetry ?? NOOP_TELEMETRY_SINK;\n // With no browser to open, a viewer-origin URL is not a deliverable — the\n // file on disk is. Undefined (so `httpUrl` stays) unless the flag is set AND\n // the workspace is a real directory; an object-store backend has no path,\n // and its `httpUrl` is a presigned download rather than a viewer link.\n const fileUrlFor = (relPath: string): string | undefined =>\n opts.viewerDisabled === true && opts.localRoot !== undefined\n ? pathToFileURL(resolvePath(opts.localRoot, relPath)).href\n : undefined;\n // The one place an artifact leaves this tool: workspace write, handles,\n // optional local copy, stale-revision note, envelope. Every format funnels\n // through it, so the tail cannot drift per-format.\n const deliver = async (args: {\n rec: SpanRecorder;\n relPath: string;\n bytes: Uint8Array;\n format: string;\n revision: string;\n root: string;\n outPath?: string;\n /** Every text string in the delivered scene — for checklist copy items.\n * Undefined when the export path could not collect them (copy items are\n * then skipped rather than false-alarmed). */\n sceneTexts?: string[];\n }): Promise<DeliverOutcome> => {\n const { rec, relPath, bytes, format, revision, root, outPath, sceneTexts } =\n args;\n await rec.time('workspace_write', async () => {\n await fs.writeFile(relPath, bytes);\n });\n const uri = `workspace://${relPath}`;\n const httpUrl = await urlBuilder.forDownload(relPath);\n const fileUrl = fileUrlFor(relPath);\n let path: string | undefined;\n if (outPath !== undefined) {\n const copied = await writeOutPathCopy(rec, outPath, bytes, {\n name: fileUrl !== undefined ? 'fileUrl' : 'httpUrl',\n where: fileUrl ?? `${uri} (download: ${httpUrl})`\n });\n if ('errorText' in copied) {\n return {\n ok: false,\n errorCode: 'outpath_write_failed',\n error: copied.error,\n result: {\n isError: true,\n content: [{ type: 'text' as const, text: copied.errorText }]\n }\n };\n }\n path = copied.path;\n }\n // Exporting an older revision is legitimate (pinned permalinks, version\n // comparison), so the deliverable is produced either way — but shipping a\n // stale file unknowingly is the costliest miss, so flag it like `preview`\n // does (informational; findStaleHead never throws). Same contract for the\n // judge gate: every export is a deliverable, and one the latest scorecard\n // does not cover gets the re-judge reminder (findUnjudged never throws\n // either).\n const staleHead = await findStaleHead(store, revision, root);\n const unjudged = await findUnjudged(store, revision, root);\n // acceptance gate: same contract as the judge gate — informational,\n // never throws, never blocks the deliverable (checklists.ts).\n const unmetChecklist = await (async () => {\n try {\n const checklist = await store.latestChecklist(root);\n if (checklist === undefined || checklist.items.length === 0)\n return undefined;\n const unmet = await verifyChecklist(checklist.items, {\n sceneTexts,\n fileExists: async (p) => {\n try {\n await nodeFs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n });\n return unmet.length > 0 ? unmet : undefined;\n } catch {\n return undefined;\n }\n })();\n return {\n ok: true,\n result: {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n ...(fileUrl !== undefined ? { fileUrl } : { uri, httpUrl }),\n bytes: bytes.byteLength,\n format,\n revision,\n ...(path !== undefined ? { path } : {})\n })\n },\n ...(staleHead !== undefined\n ? [\n {\n type: 'text' as const,\n text:\n `Note: this file exports a STALE revision — the design has newer revision(s); ` +\n `the latest is ${staleHead.id} (${staleHead.excerpt}). To export the current ` +\n `design, rerun export with that revision.`\n }\n ]\n : []),\n ...(unjudged !== undefined\n ? [{ type: 'text' as const, text: unjudgedNoticeText(unjudged) }]\n : []),\n ...(unmetChecklist !== undefined\n ? [\n {\n type: 'text' as const,\n text: checklistNoticeText(unmetChecklist)\n }\n ]\n : [])\n ]\n }\n };\n };\n return {\n name: 'export',\n description: buildDescription(\n allowLocalPath,\n opts.viewerDisabled === true && opts.localRoot !== undefined\n ),\n inputSchema: buildExportInputSchema(allowLocalPath),\n telemetrySelfReported: true,\n call: async (rawArgs, ctx) => {\n const rec = new SpanRecorder();\n const startedAt = performance.now();\n let result: CallResult | undefined;\n let threw: unknown;\n let revision: string | undefined;\n let exportError: unknown;\n // Set at each failure return below; the finally falls back to the\n // classifier for anything that escaped as a throw.\n let errorCode: ErrorCode | undefined;\n let pdfxResolved:\n | { outputStandard: string; outputProfile: string }\n | undefined;\n let htmlAssetsUsed: string | undefined;\n try {\n result = await (async (): Promise<CallResult> => {\n const args = (rawArgs ?? {}) as Partial<ExportArgs>;\n if (\n typeof args.format !== 'string' ||\n typeof args.revision !== 'string'\n ) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format and revision are required.'\n }\n ]\n };\n }\n if (args.outPath !== undefined && !allowLocalPath) {\n errorCode = 'feature_disabled';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `outPath` is not supported on this (hosted) backend. Omit it — the artifact is written to the workspace and returned as `httpUrl`; fetch that URL to download the bytes.'\n }\n ]\n };\n }\n if (\n args.outPath !== undefined &&\n (typeof args.outPath !== 'string' || !isAbsolute(args.outPath))\n ) {\n // Schemas are advisory; and a relative path would resolve against\n // the SERVER's cwd, not the caller's — a wrong-place trap.\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`outPath\\` must be an absolute path (including the filename) — got \"${String(args.outPath)}\". Relative paths would resolve against the server's working directory, not yours.`\n }\n ]\n };\n }\n const spec = formatSpec(args.format);\n if (!spec) {\n errorCode = 'unknown_format';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: unknown format=\"${args.format}\". Valid formats: pdf, png, jpeg, webp, svg, pdfx, html, mp4, imgly.`\n }\n ]\n };\n }\n if (args.pdfx !== undefined && spec.kind !== 'pdfx') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`pdfx\\` options are only valid with format=pdfx (got format=${args.format}).`\n }\n ]\n };\n }\n if (args.html !== undefined && spec.kind !== 'html') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`html\\` options are only valid with format=html (got format=${args.format}).`\n }\n ]\n };\n }\n if (args.fps !== undefined && spec.target !== 'video') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`fps\\` is only valid with format=mp4 (got format=${args.format}).`\n }\n ]\n };\n }\n if (\n args.fps !== undefined &&\n (typeof args.fps !== 'number' ||\n !Number.isFinite(args.fps) ||\n args.fps <= 0 ||\n args.fps > MAX_VIDEO_FPS)\n ) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`fps\\` must be a number greater than 0 and at most ${MAX_VIDEO_FPS} — got ${JSON.stringify(args.fps)}. Omit it for the default ${DEFAULT_VIDEO_FPS}.`\n }\n ]\n };\n }\n const target = spec.target;\n if (target === 'video') {\n const caps = await engineCapabilities({\n flavor: engineFlavor,\n fallbackWarning: fallbackReason\n });\n if (!caps.video) {\n errorCode = 'engine_unsupported';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: ${avUnavailableMessage('format=mp4 (video export)', caps)}`\n }\n ]\n };\n }\n }\n let rev: Revision;\n try {\n rev = await rec.time('workspace_read', () =>\n store.read(args.revision as string)\n );\n } catch (err) {\n if ((err as { code?: string }).code === 'ENOENT') {\n errorCode = 'unknown_revision';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: unknown revision \"${args.revision}\". Call \\`list\\` to see the workspace's designs and their latest revisions.`\n }\n ]\n };\n }\n throw err;\n }\n if (args.blockId !== undefined && typeof args.blockId !== 'number') {\n // Schemas are advisory — a malformed id must not silently become\n // a whole-document export.\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `blockId` must be an integer (or omitted to export the whole document).'\n }\n ]\n };\n }\n if (spec.kind === 'archive' && args.blockId !== undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `blockId` is not valid with format=imgly — an `.imgly` archive is always the whole design; omit `blockId`.'\n }\n ]\n };\n }\n if (target === 'video' && args.blockId === undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format=mp4 requires `blockId` — pass the id of the page to render.'\n }\n ]\n };\n }\n if (spec.kind === 'html' && args.blockId === undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format=html requires `blockId` — the exporter renders exactly one page; pass the id of the page to render (use `inspect` to see the pages).'\n }\n ]\n };\n }\n if (spec.kind === 'html') {\n const mod = await exporterModules.html();\n const htmlArgs = mod.resolveHtmlArgs(args.html);\n if (!htmlArgs.ok) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: htmlArgs.message }]\n };\n }\n htmlAssetsUsed = htmlArgs.assets;\n const htmlBlockId = args.blockId as number; // guarded above\n const revIdHtml = args.revision;\n const sceneHtml = rev.scene;\n type HtmlOutcome =\n | { ok: true; files: Awaited<ReturnType<typeof mod.renderHtml>> }\n | { ok: false; message: string; error?: unknown };\n const beforeHtmlLock = performance.now();\n const rendered = await engineLock.runExclusive<HtmlOutcome>(\n async () => {\n rec.add('lock_wait', performance.now() - beforeHtmlLock);\n const slot = await rec.time('engine_scene_load', async () => {\n await session.populate(revIdHtml, sceneHtml);\n return session.acquire(revIdHtml);\n });\n const pageIndex = mod.derivePageIndex(slot.engine, htmlBlockId);\n if (pageIndex === null) {\n return {\n ok: false,\n message: `export: block ${htmlBlockId} is not a page in revision ${revIdHtml} — format=html renders exactly one page. Pass a page id (use \\`inspect\\` to see the revision's pages).`\n };\n }\n // @imgly/html-exporter's bundle rasterizes image/graphic\n // blocks via engine.block.export internally — the same\n // encode that races an in-flight font/image fetch and throws\n // ENCODE.NOT_ALL_RESOURCES_LOADED (CODE-94) without this\n // barrier. Mirrors the still-render path just below.\n try {\n const engHtml = slot.engine as MinimalEngine;\n const forceLoadResources =\n engHtml.block.forceLoadResources?.bind(engHtml.block);\n if (forceLoadResources) {\n await rec.time('engine_resource_load', () =>\n forceLoadResources([htmlBlockId])\n );\n }\n const files = await rec.time('html_export', () =>\n mod.renderHtml(slot.engine, pageIndex, htmlArgs.assets)\n );\n return { ok: true, files };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not render page ${htmlBlockId} to HTML in revision ${revIdHtml} — the scene's resources (fonts/images) were still loading when the encode ran. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : `export: HTML export failed for page ${htmlBlockId} in revision ${revIdHtml}. ${detail}`\n };\n }\n }\n );\n if (!rendered.ok) {\n exportError = rendered.error;\n errorCode = classifyThrow(rendered.error) ?? 'render_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: rendered.message }]\n };\n }\n // Zip packing / GSAP injection is pure — outside the engine lock.\n const deliverable = await rec.time('zip_assemble', () =>\n mod.assembleHtmlDeliverable(rendered.files, htmlArgs.assets)\n );\n const shardH = args.revision.slice(0, 2);\n const restH = args.revision.slice(2);\n const relPathH = `exports/${shardH}/${restH}/html.${deliverable.ext}`;\n const deliveredH = await deliver({\n rec,\n relPath: relPathH,\n bytes: deliverable.bytes,\n format: args.format,\n revision: args.revision,\n root: rev.meta.root,\n ...(args.outPath !== undefined ? { outPath: args.outPath } : {})\n });\n if (!deliveredH.ok) {\n exportError = deliveredH.error;\n errorCode = deliveredH.errorCode;\n return deliveredH.result;\n }\n revision = args.revision;\n return deliveredH.result;\n }\n type PdfxModule = Awaited<ReturnType<ExporterModules['pdfx']>>;\n let pdfxPrep:\n | {\n mod: PdfxModule;\n args: ResolvedPdfxArgs;\n customProfile?: Blob;\n }\n | undefined;\n if (spec.kind === 'pdfx') {\n const mod = await exporterModules.pdfx();\n const title = await store.currentTitle(rev.meta.root);\n const resolved = mod.resolvePdfxArgs(args.pdfx, { title });\n if (!resolved.ok) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: resolved.message }]\n };\n }\n pdfxResolved = {\n // The telemetry sink's token gate rejects '/', so record the\n // standard as a gate-safe token — the schema/adapter keep the\n // verbatim 'PDF/X-4' / 'PDF/X-3' names throughout.\n outputStandard:\n resolved.args.outputStandard === 'PDF/X-4' ? 'pdfx4' : 'pdfx3',\n outputProfile: resolved.args.outputProfile\n };\n let customProfile: Blob | undefined;\n if (resolved.args.customProfileUri !== undefined) {\n const prof = await rec.time('profile_fetch', () =>\n mod.resolveCustomProfile(\n resolved.args.customProfileUri as string\n )\n );\n if (!prof.ok) {\n errorCode = 'profile_fetch_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: prof.message }]\n };\n }\n customProfile = prof.profile;\n }\n pdfxPrep = { mod, args: resolved.args, customProfile };\n }\n // Capture validated args into locals so the locked closure keeps the\n // type narrowing the top-level guards established.\n const revId = args.revision;\n const requestedBlockId = args.blockId;\n const mime = spec.mime;\n const sceneBytes = rev.scene;\n const outPath = args.outPath;\n type EncodeOutcome =\n | { ok: true; bytes: Uint8Array }\n | { ok: false; message: string; error?: unknown };\n // load-into-engine then export reads the shared engine across awaits —\n // serialize against any concurrent engine-touching tool call.\n const beforeLock = performance.now();\n let deliveredSceneTexts: string[] | undefined;\n const outcome = await engineLock.runExclusive<EncodeOutcome>(\n async () => {\n rec.add('lock_wait', performance.now() - beforeLock);\n const slot = await rec.time('engine_scene_load', async () => {\n await session.populate(revId, sceneBytes);\n return session.acquire(revId);\n });\n const eng = slot.engine as MinimalEngine;\n // For the acceptance gate's copy items: every text string in\n // the scene being delivered. Best-effort — a collect failure\n // degrades to \"copy items unverified\", never a failed export.\n try {\n if (eng.block.findByType && eng.block.getString) {\n deliveredSceneTexts = eng.block\n .findByType('//ly.img.ubq/text')\n .map((id) => eng.block.getString!(id, 'text/text'));\n }\n } catch {\n deliveredSceneTexts = undefined;\n }\n if (spec.kind === 'archive') {\n try {\n // saveToArchive bundles \"all assets that were accessible\n // when this function was called\" (SceneAPI). Measured on the\n // 1.81.0-nightly.20260805 pin that under-describes in-flight\n // loads — the engine awaits those — but is exact for an\n // unreachable one: without this barrier the archive ships\n // silently truncated, with it the export fails loudly. So a\n // missing forceLoadResources must throw, not skip.\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n if (!forceLoadResources) {\n throw new Error(\n 'export: this engine build has no block.forceLoadResources — refusing to archive, ' +\n 'since the .imgly would silently omit unloaded asset bytes.'\n );\n }\n await rec.time('engine_resource_load', () =>\n forceLoadResources(eng.scene.getPages())\n );\n const blob = await rec.time('engine_execute', () =>\n eng.scene.saveToArchive()\n );\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not archive revision ${revId} — the scene's resources (fonts/images) were still loading when the archive was written. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : `export: could not archive revision ${revId}. ${detail}`\n };\n }\n }\n // No explicit blockId → the whole document. Resolve the scene\n // root only now, after acquire() made this revision's scene\n // current — resolving earlier would read whatever scene another\n // call left loaded.\n const blockId = requestedBlockId ?? eng.scene.get();\n if (blockId === null) {\n return {\n ok: false,\n message: `export: revision ${revId} has no scene root to export — the snapshot may be corrupt. Load a known-good revision (see \\`list\\`) or pass an explicit \\`blockId\\`.`\n };\n }\n if (target === 'video') {\n // Bind up front: the methods are optional on MinimalEngine and\n // unbound engine methods lose their `this`.\n const exportVideo = eng.block.exportVideo?.bind(eng.block);\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n const findAll = eng.block.findAll?.bind(eng.block);\n // The engine may have booted (and fallen back) during this call.\n const caps = await engineCapabilities({\n flavor: engineFlavor,\n fallbackWarning: fallbackReason\n });\n if (\n !caps.video ||\n !exportVideo ||\n !forceLoadResources ||\n !findAll\n ) {\n return {\n ok: false,\n message: `export: ${avUnavailableMessage('format=mp4 (video export)', caps)}`\n };\n }\n const encodeOnce = (): Promise<Blob> =>\n rec.time('engine_execute', async () => {\n // Force-load every referenced resource first, or the encoder\n // races the asset fetch (black frames / silent audio).\n await forceLoadResources(findAll());\n return exportVideo(blockId, {\n mimeType: mime,\n framerate:\n (args.fps as number | undefined) ?? DEFAULT_VIDEO_FPS,\n onProgress: throttledVideoProgress(ctx?.progress)\n });\n });\n // The encode parks the playhead on its last frame (issues/@cesdk/node-native/01a0ddbd-eb12-780a-9edf-03bbbf46ba86_exportvideo-leaves-playhead-at-last-frame).\n let parkedTime: number | undefined;\n try {\n parkedTime = eng.block.getPlaybackTime?.(blockId);\n } catch {\n /* a bad id: the encode below reports it legibly */\n }\n try {\n let blob: Blob;\n for (let attempt = 0; ; attempt++) {\n try {\n blob = await encodeOnce();\n break;\n } catch (err) {\n if (\n !isEncoderBusyError(err) ||\n attempt >= encoderBusyDelaysMs.length\n ) {\n throw err;\n }\n // See ENCODER_BUSY_MARKER: the previous export is still\n // releasing the encode service — wait it out.\n rec.add(\n 'encoder_busy_wait',\n encoderBusyDelaysMs[attempt]\n );\n await new Promise((r) =>\n setTimeout(r, encoderBusyDelaysMs[attempt])\n );\n }\n }\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isEncoderBusyError(err)\n ? `export: the video encoder is still busy releasing a previous export — the server already waited ~${Math.round(\n encoderBusyDelaysMs.reduce((a, b) => a + b, 0) / 1000\n )}s for it. Retry this exact export call in a few seconds; if it keeps failing, the encoder is stuck — restart the MCP server. ${detail}`\n : `export: video export failed for block ${blockId} in revision ${revId}. If that block id isn't in this revision's scene, double-check it (use \\`inspect\\`); otherwise the engine failed to load a resource or encode. ${detail}`\n };\n } finally {\n try {\n if (parkedTime !== undefined)\n eng.block.setPlaybackTime?.(blockId, parkedTime);\n } catch {\n session.markDirty(slot);\n }\n }\n }\n // We loaded `revId` under the lock just above, so the correct scene\n // is current. Force-load the block's resources before encoding —\n // the same barrier the video path runs — or the still render\n // races any in-flight font/image fetch and throws\n // ENCODE.NOT_ALL_RESOURCES_LOADED (CODE-94). If the render still\n // throws, return a legible tool error the model can act on\n // (mirroring `edit`'s dirty-on-throw path) instead of rethrowing\n // into an opaque MCP -32603 — distinguishing a resource-load\n // race (retryable) from a bad block id.\n try {\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n if (forceLoadResources) {\n await rec.time('engine_resource_load', () =>\n forceLoadResources([blockId])\n );\n }\n // CMYK and CMYK-valued spot colors export as their native\n // color spaces (DeviceCMYK / DeviceN) rather than being\n // downconverted to RGB — this is a print backend. The flag is\n // PDF-only, scoped to the pdf target; pdfx runs its own PDF/X\n // color pipeline. Must use the object-options signature: the\n // deprecated (id, mimeType, options) overload rejects this flag\n // at runtime (\"Invalid arguments\").\n const exportOptions = {\n mimeType: mime,\n ...(target === 'pdf' ? { exportPdfWithDeviceCMYK: true } : {})\n };\n const blob = await rec.time('engine_execute', () =>\n eng.block.export(blockId, exportOptions)\n );\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not render block ${blockId} in revision ${revId} — the scene's resources (fonts/images) were still loading when the encode ran. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : requestedBlockId === undefined\n ? `export: could not render the whole document (scene root ${blockId}) in revision ${revId} — the engine failed to encode it. ${detail}`\n : `export: could not render block ${blockId} in revision ${revId}. That block id isn't in this revision's scene — double-check the id (use \\`inspect\\` to see the revision's structure), it may have been removed in this revision — or omit \\`blockId\\` to export the whole document. ${detail}`\n };\n }\n }\n );\n if (!outcome.ok) {\n exportError = outcome.error;\n errorCode = classifyThrow(outcome.error) ?? 'render_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: outcome.message }]\n };\n }\n let bytes = outcome.bytes;\n if (pdfxPrep) {\n // Ghostscript WASM (~2–5 s, memory-heavy) — deliberately OUTSIDE the engine\n // lock: it never touches the engine, so concurrent edits need not wait.\n try {\n bytes = await rec.time('plugin_convert', () =>\n pdfxPrep.mod.convertPdfToPdfx(\n bytes,\n pdfxPrep.args,\n pdfxPrep.customProfile\n )\n );\n } catch (err) {\n exportError = err;\n errorCode = 'pdfx_convert_failed';\n const detail =\n err instanceof Error ? (err.stack ?? err.message) : String(err);\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: the PDF/X conversion failed (the base PDF exported fine). If the message mentions a size limit, the intermediate PDF exceeded the converter's 100 MB cap — export page-by-page with \\`blockId\\`. Otherwise this is a converter (Ghostscript) failure. ${detail}`\n }\n ]\n };\n }\n }\n const shard = args.revision.slice(0, 2);\n const rest = args.revision.slice(2);\n const relPath = `exports/${shard}/${rest}/${target}.${spec.ext}`;\n const delivered = await deliver({\n rec,\n relPath,\n bytes,\n format: args.format,\n revision: revId,\n root: rev.meta.root,\n ...(outPath !== undefined ? { outPath } : {}),\n ...(deliveredSceneTexts !== undefined\n ? { sceneTexts: deliveredSceneTexts }\n : {})\n });\n if (!delivered.ok) {\n exportError = delivered.error;\n errorCode = delivered.errorCode;\n return delivered.result;\n }\n revision = args.revision;\n return delivered.result;\n })();\n return result;\n } catch (err) {\n threw = err;\n throw err;\n } finally {\n const a = rawArgs as { format?: unknown } | null | undefined;\n const fmt = typeof a?.format === 'string' ? a.format : undefined;\n const fmtSpec = fmt ? formatSpec(fmt) : undefined;\n const resolvedCode = errorCode ?? classifyThrow(threw);\n telemetry.record({\n tool: 'export',\n succeeded: threw === undefined && result?.isError !== true,\n ...(resolvedCode ? { errorCode: resolvedCode } : {}),\n totalMs: performance.now() - startedAt,\n spans: rec.list(),\n args: rawArgs,\n // What was exported (print-PDF vs image vs video): the schema-enum\n // format plus the deliverable kind derived from it — the sink's\n // token gate drops anything else a client sent.\n toolFields: {\n ...(fmt ? { format: fmt } : {}),\n ...(fmtSpec ? { target: fmtSpec.target } : {}),\n ...(pdfxResolved ? pdfxResolved : {}),\n ...(htmlAssetsUsed ? { assets: htmlAssetsUsed } : {})\n },\n ...(result !== undefined ? { result: summarizeResult(result) } : {}),\n ...(revision ? { revision } : {}),\n ...(threw\n ? { error: toErrorShape(threw) }\n : exportError\n ? { error: toErrorShape(exportError) }\n : {})\n });\n }\n }\n };\n}\n"]}
1
+ {"version":3,"file":"export.js","sourceRoot":"","sources":["../../src/tools/export.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,4EAA4E;AAC5E,yEAAyE;AACzE,0DAA0D;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,IAAI,MAAM,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAG1E,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EACL,mBAAmB,EACnB,eAAe,EAChB,MAAM,4BAA4B,CAAC;AASpC,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,oBAAoB,EAAE,kBAAkB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C,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE;wBAChC,CAAC,CAAC,WAAW;4BACX,CAAC,CAAC,EAAE,KAAK,EAAE,YAAY,CAAC,WAAW,CAAC,EAAE;4BACtC,CAAC,CAAC,EAAE,CAAC;iBACV,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// packages/codesign-mcp/src/tools/export.ts\n//\n// `export` — spec §6.2. Writes a revision-pinned pdf/image/video artifact into\n// `exports/<shard>/<rev>/<kind>.<ext>` (`pdf.pdf`, `image.png`, `video.mp4`,\n// …) and returns a workspace URI envelope: `uri` (the durable `workspace://`\n// handle) plus `httpUrl` (the `/r/` fetch link). The workspace's on-disk\n// location is disclosed only as an echo of a caller-chosen `outPath` — when\n// omitted, the workspace handle is the only way to reach the bytes; when\n// provided, `outPath` confirms the local write succeeded.\nimport { performance } from 'node:perf_hooks';\nimport { dirname, isAbsolute, resolve as resolvePath } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { promises as nodeFs } from 'node:fs';\nimport { isResourcesStillLoadingError } from '../engine/engine-errors.js';\nimport type { Mutex } from '../engine/mutex.js';\nimport type { EngineSession } from '../engine/session.js';\nimport { findStaleHead } from '../revisions/drift.js';\nimport { findUnjudged, unjudgedNoticeText } from '../revisions/scorecards.js';\nimport {\n checklistNoticeText,\n verifyChecklist\n} from '../revisions/checklists.js';\nimport type { RevisionStore } from '../revisions/store.js';\nimport type { Revision } from '../revisions/types.js';\nimport type {\n CodesignMcpToolRegistration,\n ToolCallContext\n} from '../server.js';\nimport type { ViewerUrlBuilder } from '../viewer/url-builder.js';\nimport type { WorkspaceFS } from '../workspace/types.js';\nimport {\n type EngineFlavor,\n engineFallbackWarning,\n resolvedEngineFlavor\n} from './engine.js';\nimport { avUnavailableMessage, engineCapabilities } from '../capability.js';\nimport { classifyThrow, type ErrorCode } from './errors.js';\nimport type { ResolvedPdfxArgs } from './export-formats/pdfx.js';\nimport {\n NOOP_TELEMETRY_SINK,\n SpanRecorder,\n summarizeResult,\n toErrorShape,\n type TelemetrySink\n} from './spans.js';\n\ntype Target = 'pdf' | 'image' | 'video' | 'pdfx' | 'html' | 'design';\ntype Format =\n | 'pdf'\n | 'png'\n | 'jpeg'\n | 'webp'\n | 'svg'\n | 'pdfx'\n | 'html'\n | 'mp4'\n | 'imgly';\n\ntype CallResult = Awaited<ReturnType<CodesignMcpToolRegistration['call']>>;\n\ntype DeliverOutcome =\n | { ok: true; result: CallResult }\n | { ok: false; result: CallResult; errorCode: ErrorCode; error?: unknown };\n\ninterface MinimalEngine {\n scene: {\n get(): number | null;\n getPages(): number[];\n saveToArchive(): Promise<Blob>;\n };\n block: {\n // The engine's object-options signature. Its deprecated\n // `export(id, mimeType, options)` overload validates `options` against a\n // stale struct that rejects newer keys — `exportPdfWithDeviceCMYK` throws\n // \"Invalid arguments\" there even though the .d.ts types it as accepted.\n export(\n blockId: number,\n options: {\n mimeType: string;\n exportPdfWithDeviceCMYK?: boolean;\n }\n ): Promise<Blob>;\n exportVideo?(\n blockId: number,\n options?: {\n mimeType?: string;\n framerate?: number;\n onProgress?: (rendered: number, encoded: number, total: number) => void;\n }\n ): Promise<Blob>;\n forceLoadResources?(blockIds: number[]): Promise<void>;\n getPlaybackTime?(blockId: number): number;\n setPlaybackTime?(blockId: number, time: number): void;\n findByType?(type: string): number[];\n getString?(blockId: number, property: string): string;\n findAll?(): number[];\n getParent?(blockId: number): number | null;\n };\n}\n\n/** True when walking up from `blockId` reaches `sceneId`; an id the engine rejects counts as attached, so the encode reports it. */\nfunction isAttachedToScene(\n getParent: (blockId: number) => number | null,\n blockId: number,\n sceneId: number | null\n): boolean {\n try {\n for (let b: number | null = blockId; b !== null; b = getParent(b)) {\n if (b === sceneId) return true;\n }\n return false;\n } catch {\n return true;\n }\n}\n\ninterface ExportArgs {\n format: Format;\n revision: string;\n blockId?: number;\n pdfx?: unknown;\n html?: unknown;\n fps?: unknown;\n outPath?: string;\n}\n\ninterface FormatSpec {\n target: Target;\n mime: string;\n ext: string;\n /** 'engine' = built-in encoder; 'pdfx'/'html' = plugin adapter in export-formats/; 'archive' = the .imgly design bundle. */\n kind: 'engine' | 'pdfx' | 'html' | 'archive';\n}\n\n// `format` alone names the deliverable: it determines the kind of artifact\n// (and with it the engine code path and output filename), the mime type, and\n// the file extension.\nconst FORMATS: Record<Format, FormatSpec> = {\n pdf: { target: 'pdf', mime: 'application/pdf', ext: 'pdf', kind: 'engine' },\n png: { target: 'image', mime: 'image/png', ext: 'png', kind: 'engine' },\n jpeg: { target: 'image', mime: 'image/jpeg', ext: 'jpg', kind: 'engine' },\n webp: { target: 'image', mime: 'image/webp', ext: 'webp', kind: 'engine' },\n svg: { target: 'image', mime: 'image/svg+xml', ext: 'svg', kind: 'engine' },\n pdfx: { target: 'pdfx', mime: 'application/pdf', ext: 'pdf', kind: 'pdfx' },\n html: { target: 'html', mime: 'text/html', ext: 'html', kind: 'html' },\n mp4: { target: 'video', mime: 'video/mp4', ext: 'mp4', kind: 'engine' },\n // target 'design' + ext 'imgly' makes the generic\n // `exports/<shard>/<rest>/<target>.<ext>` rule reproduce the path `save`\n // wrote, so `workspace://` URIs handed out by `save` stay valid. `mime` is\n // inert here (as it is for html) — saveToArchive picks the container.\n imgly: {\n target: 'design',\n mime: 'application/zip',\n ext: 'imgly',\n kind: 'archive'\n }\n};\n\n// Literal dynamic imports — esbuild inlines these in single-file mode (CODE-69\n// SEA bundle) while Node loads them on first use, so an unused exporter costs\n// nothing at boot.\nconst EXPORTER_MODULES = {\n pdfx: () => import('./export-formats/pdfx.js'),\n html: () => import('./export-formats/html.js')\n} as const;\nexport type ExporterModules = typeof EXPORTER_MODULES;\n\nfunction formatSpec(format: string): FormatSpec | undefined {\n // hasOwnProperty guard: `format: \"toString\"` must not resolve via the\n // object prototype.\n return Object.prototype.hasOwnProperty.call(FORMATS, format)\n ? FORMATS[format as Format]\n : undefined;\n}\n\nconst PROGRESS_MIN_INTERVAL_MS = 1000;\n\n/** `fps` default when the caller omits it, and the accepted ceiling. */\nconst DEFAULT_VIDEO_FPS = 30;\nconst MAX_VIDEO_FPS = 120;\n\n// The encoder can report \"busy\" briefly after a previous exportVideo resolved;\n// absorb that window. (The Linux permanent wedge of 1.77–1.79 no longer\n// reproduces on 1.82.0; the unskipped stress test guards it.)\nconst ENCODER_BUSY_MARKER = 'currently encoding';\nconst ENCODER_BUSY_DELAYS_MS = [250, 500, 1000, 2000, 4000];\n\nfunction isEncoderBusyError(err: unknown): boolean {\n return err instanceof Error && err.message.includes(ENCODER_BUSY_MARKER);\n}\n\n/**\n * Map exportVideo's per-frame onProgress to MCP progress at ~1/s. The engine\n * fires per encoded frame (a 30s clip at 30fps ≈ 900 calls); unthrottled,\n * that floods the client. The final tick (encoded >= total) always sends.\n */\nfunction throttledVideoProgress(\n report: NonNullable<ToolCallContext['progress']> | undefined\n): ((rendered: number, encoded: number, total: number) => void) | undefined {\n if (!report) return undefined;\n let lastSent = -Infinity;\n return (_rendered, encoded, total) => {\n const now = performance.now();\n if (encoded < total && now - lastSent < PROGRESS_MIN_INTERVAL_MS) return;\n lastSent = now;\n report({ progress: encoded, total, message: 'encoding' });\n };\n}\n\n// Local write-through — real disk fs, NOT the workspace abstraction. The\n// caller chose this path explicitly, so echoing it back is a confirmation,\n// not a workspace-path leak. Runs AFTER the workspace write: a failed copy\n// never loses the export — the returned error text carries the still-valid\n// workspace handles. Shared by the standard delivery tail and the html\n// early-return, the two places an artifact leaves the tool.\nasync function writeOutPathCopy(\n rec: SpanRecorder,\n outPath: string,\n bytes: Uint8Array,\n /** Where the artifact still is, and the field the caller reads it from. */\n handle: { name: 'httpUrl' | 'fileUrl'; where: string }\n): Promise<{ path: string } | { error: unknown; errorText: string }> {\n try {\n await nodeFs.mkdir(dirname(outPath), { recursive: true });\n await rec.time('outpath_write', async () => {\n await nodeFs.writeFile(outPath, bytes);\n });\n return { path: outPath };\n } catch (err) {\n // An unwritable/invalid outPath (EACCES, EROFS, ENOTDIR, …) is bad\n // caller input, not an internal fault — answer with recovery guidance\n // instead of leaking a raw stack as an MCP -32603.\n if (typeof (err as { code?: string }).code !== 'string') throw err;\n return {\n error: err,\n errorText: `export: could not write outPath \"${outPath}\" — ${(err as Error).message}. The artifact is safe at ${handle.where}. Retry with a writable absolute path, or omit \\`outPath\\` and use \\`${handle.name}\\`.`\n };\n }\n}\n\nfunction buildDescription(\n allowLocalPath: boolean,\n viewerDisabled: boolean\n): string {\n const handle = viewerDisabled\n ? '`{ fileUrl, bytes, format, revision }`'\n : '`{ uri, httpUrl, bytes, format, revision }`';\n const handleCopy = viewerDisabled\n ? '. `fileUrl` is a `file://` URI for the artifact on this machine — that IS the deliverable, and the only handle: give it to the user.'\n : '. `uri` (a `workspace://` URI) is the durable handle. `httpUrl` is a fetch link tied to this process — fetch it to download the bytes to disk, or hand it to the user.';\n return [\n `Export a revision to a final deliverable — \\`format\\` picks it: \\`pdf\\` (print PDF), \\`png\\`/\\`jpeg\\`/\\`webp\\` (image), \\`svg\\` (vector SVG), \\`pdfx\\` (print-ready PDF/X), \\`html\\` (responsive HTML5), \\`mp4\\` (video), \\`imgly\\` (editable design file). Renders \\`blockId\\` — or the whole document when \\`blockId\\` is omitted — and writes the result into the workspace under \\`exports/<shard>/<rev>/\\` (revision-pinned, deterministic).`,\n '',\n `Returns JSON: ${handle}` +\n (allowLocalPath ? ' (plus `path` when you pass `outPath`)' : '') +\n handleCopy,\n ...(allowLocalPath\n ? [\n '',\n \"`outPath` (optional, absolute path including the filename): ALSO write the artifact to that local path — the workspace copy is still written, and the response then carries `path`. Use it when the file is wanted on disk, and always when your environment cannot fetch localhost URLs (sandboxed harnesses, e.g. Claude Cowork — target your session's outputs folder there).\"\n ]\n : []),\n '',\n \"`format=svg` is the engine's vector export: text is outlined into paths (renders identically everywhere, but is not editable text in the SVG), and raster images are embedded in the file at source resolution — an SVG of a photo-heavy design can be much larger than its source images.\",\n '',\n '`format=imgly` writes a portable, self-contained `.imgly` design file (scene + all asset bytes bundled) — the inverse of `import`, and the only format that stays editable. Whole-design only: `blockId` is not accepted. Every `edit` already auto-persists to the workspace, so you never need this to keep your work — use it to take an editable copy OUT: hand it to a human, back it up, move it between servers.',\n '',\n '`format=pdfx` runs the print PDF through a PDF/X conversion (Ghostscript): CMYK with an embedded ICC profile and PDF/X conformance markers, ready for a print shop. Tune it via the optional `pdfx` object — conformance standard (X-4 default / X-3), output profile (fogra39/gracol/srgb/custom), transparency flattening, OutputIntent metadata. Conversion adds a few seconds.',\n '',\n '`format=html` renders ONE page (`blockId` required — pass a page id) to responsive HTML5. Default is a single self-contained `.html` (assets inlined; animated designs get a CDN GSAP player injected so the file plays as-is); `html: { assets: \"external\" }` delivers html + separate image/font files as one `.zip`.',\n '',\n '`format=mp4` renders the authored timeline of the block (typically a page) to an H.264 `mp4`; duration and resolution come from the scene; frame rate is `fps` (default 30). Requires the native engine (the default). Long encodes report MCP progress notifications when the client sends a progressToken.'\n ].join('\\n');\n}\n\nfunction buildExportInputSchema(allowLocalPath: boolean) {\n const properties: Record<string, unknown> = {\n format: {\n enum: [\n 'pdf',\n 'png',\n 'jpeg',\n 'webp',\n 'svg',\n 'pdfx',\n 'html',\n 'mp4',\n 'imgly'\n ],\n description:\n 'The deliverable: pdf → print PDF; png/jpeg/webp → image; svg → vector SVG; pdfx → print-ready PDF/X; html → HTML5 page; mp4 → video; imgly → editable design file.'\n },\n revision: { type: 'string' as const },\n blockId: {\n type: 'integer' as const,\n description:\n 'The page or block to render. Omit to export the whole document — for `format=pdf` a multi-page PDF, for an image format one composite image of all pages.' +\n ' Required for format=html (pass a page id).' +\n ' Required for `format=mp4` (pass a page id).'\n },\n pdfx: {\n type: 'object' as const,\n description:\n 'Options for `format=pdfx` only (invalid with any other format). Omit entirely for sensible print defaults: PDF/X-4, fogra39, embedded ICC.',\n properties: {\n outputStandard: {\n enum: ['PDF/X-4', 'PDF/X-3'],\n description:\n 'PDF/X conformance target. PDF/X-4 (default) keeps live transparency. PDF/X-3 is the older PDF 1.4 standard — it flattens transparency by default and can rasterize gradients/alpha content.'\n },\n outputProfile: {\n enum: ['fogra39', 'gracol', 'srgb', 'custom'],\n description:\n \"Target printing condition / ICC output profile. fogra39 (default) = ISO Coated v2 (ECI), European offset. gracol = GRACoL 2013 CRPC6, US commercial. srgb = keep RGB, for digital distribution. custom = supply the print shop's ICC file via profileUri.\"\n },\n profileUri: {\n type: 'string' as const,\n description:\n 'Required with outputProfile=\"custom\" (invalid otherwise): an https:// URL or absolute local file path of the .icc profile to embed.'\n },\n flattenTransparency: {\n type: 'boolean' as const,\n description:\n 'PDF/X-3 only (default true there): rasterize transparent content for strict compliance. false keeps transparency live — better fidelity, may not validate. Ignored on PDF/X-4.'\n },\n embedICCProfile: {\n type: 'boolean' as const,\n description:\n 'Default true. false → plain CMYK (or RGB) PDF with no embedded ICC profile, OutputIntent, or PDF/X markers — for prepress pipelines that apply their own profile.'\n },\n title: {\n type: 'string' as const,\n description: \"PDF document title. Defaults to the design's title.\"\n },\n outputConditionIdentifier: {\n type: 'string' as const,\n description:\n 'Overrides the PDF\\'s /OutputConditionIdentifier — the REGISTERED printing-condition name preflight tools and print shops check (e.g. \"FOGRA39\", \"CGATS 21.2\"). Defaults from outputProfile; with a custom profile, your print shop tells you what to put here.'\n },\n outputCondition: {\n type: 'string' as const,\n description:\n 'Overrides /OutputCondition — the human-readable printing-condition description (e.g. \"ISO Coated v2 (ECI)\"). Defaults from outputProfile.'\n }\n },\n additionalProperties: false\n },\n html: {\n type: 'object' as const,\n description:\n 'Options for `format=html` only (invalid with any other format).',\n properties: {\n assets: {\n enum: ['embedded', 'external'],\n description:\n 'embedded (default): one self-contained .html, assets inlined as data URLs — viewable anywhere as-is. external: html + separate image/font files, delivered as one .zip.'\n }\n },\n additionalProperties: false\n },\n fps: {\n type: 'number' as const,\n exclusiveMinimum: 0,\n maximum: MAX_VIDEO_FPS,\n description: `Frames per second for \\`format=mp4\\` only (invalid with any other format). Default ${DEFAULT_VIDEO_FPS}. Common values: 24, 25, 30, 60.`\n }\n };\n if (allowLocalPath) {\n properties.outPath = {\n type: 'string' as const,\n description:\n 'Absolute path (including filename) to ALSO write the artifact to — the workspace copy is still written, and the response then carries `path`. Use when you need the file on disk and cannot fetch localhost URLs (sandboxed harnesses).'\n };\n }\n return {\n type: 'object' as const,\n properties,\n required: ['format', 'revision'],\n additionalProperties: false\n };\n}\n\nexport interface CreateExportToolOptions<E = unknown> {\n fs: WorkspaceFS;\n store: RevisionStore;\n session: EngineSession<E>;\n /** Builds the `httpUrl` for workspace-written artifacts (the `/r/` route). */\n urlBuilder: ViewerUrlBuilder;\n /** Guards the shared engine — load-then-export must not interleave with another session's edit (see engine/mutex.ts). */\n engineLock: Mutex;\n /** Diagnostics telemetry port. Absent → no-op (no timing overhead beyond a few clocks). */\n telemetry?: TelemetrySink;\n /** Resolved engine flavor probe; injected by tests. Default: the real one. */\n engineFlavor?: () => EngineFlavor | undefined;\n /** Why the engine fell back to WASM; injected by tests. Default: the real one. */\n fallbackReason?: () => string | undefined;\n /** Encoder-busy retry backoff schedule; injected by tests. */\n encoderBusyDelaysMs?: number[];\n /** Lazy exporter-adapter modules; injected by tests. Default: the real dynamic imports. */\n exporterModules?: ExporterModules;\n /** Local(true)/Hosted(false): advertise + honour `outPath` — the same\n * signal that gates `import`'s `{ path }` arm (the process shares the\n * caller's disk). Default false. */\n allowLocalPath?: boolean;\n /** IMGLY_DISABLE_VIEWER: hand back `fileUrl` (the artifact on this machine)\n * instead of the viewer-origin `httpUrl`. Needs {@link localRoot}; without\n * one (object-store backend) `httpUrl` stays — it is a presigned download,\n * not a viewer link. */\n viewerDisabled?: boolean;\n /** Absolute path the workspace is rooted at, when it is a real directory. */\n localRoot?: string;\n}\n\nexport function createExportTool<E = unknown>(\n opts: CreateExportToolOptions<E>\n): CodesignMcpToolRegistration {\n const {\n fs,\n store,\n session,\n urlBuilder,\n engineLock,\n engineFlavor = resolvedEngineFlavor,\n fallbackReason = engineFallbackWarning,\n encoderBusyDelaysMs = ENCODER_BUSY_DELAYS_MS,\n exporterModules = EXPORTER_MODULES,\n allowLocalPath = false\n } = opts;\n const telemetry = opts.telemetry ?? NOOP_TELEMETRY_SINK;\n // With no browser to open, a viewer-origin URL is not a deliverable — the\n // file on disk is. Undefined (so `httpUrl` stays) unless the flag is set AND\n // the workspace is a real directory; an object-store backend has no path,\n // and its `httpUrl` is a presigned download rather than a viewer link.\n const fileUrlFor = (relPath: string): string | undefined =>\n opts.viewerDisabled === true && opts.localRoot !== undefined\n ? pathToFileURL(resolvePath(opts.localRoot, relPath)).href\n : undefined;\n // The one place an artifact leaves this tool: workspace write, handles,\n // optional local copy, stale-revision note, envelope. Every format funnels\n // through it, so the tail cannot drift per-format.\n const deliver = async (args: {\n rec: SpanRecorder;\n relPath: string;\n bytes: Uint8Array;\n format: string;\n revision: string;\n root: string;\n outPath?: string;\n /** Every text string in the delivered scene — for checklist copy items.\n * Undefined when the export path could not collect them (copy items are\n * then skipped rather than false-alarmed). */\n sceneTexts?: string[];\n }): Promise<DeliverOutcome> => {\n const { rec, relPath, bytes, format, revision, root, outPath, sceneTexts } =\n args;\n await rec.time('workspace_write', async () => {\n await fs.writeFile(relPath, bytes);\n });\n const uri = `workspace://${relPath}`;\n const httpUrl = await urlBuilder.forDownload(relPath);\n const fileUrl = fileUrlFor(relPath);\n let path: string | undefined;\n if (outPath !== undefined) {\n const copied = await writeOutPathCopy(rec, outPath, bytes, {\n name: fileUrl !== undefined ? 'fileUrl' : 'httpUrl',\n where: fileUrl ?? `${uri} (download: ${httpUrl})`\n });\n if ('errorText' in copied) {\n return {\n ok: false,\n errorCode: 'outpath_write_failed',\n error: copied.error,\n result: {\n isError: true,\n content: [{ type: 'text' as const, text: copied.errorText }]\n }\n };\n }\n path = copied.path;\n }\n // Exporting an older revision is legitimate (pinned permalinks, version\n // comparison), so the deliverable is produced either way — but shipping a\n // stale file unknowingly is the costliest miss, so flag it like `preview`\n // does (informational; findStaleHead never throws). Same contract for the\n // judge gate: every export is a deliverable, and one the latest scorecard\n // does not cover gets the re-judge reminder (findUnjudged never throws\n // either).\n const staleHead = await findStaleHead(store, revision, root);\n const unjudged = await findUnjudged(store, revision, root);\n // acceptance gate: same contract as the judge gate — informational,\n // never throws, never blocks the deliverable (checklists.ts).\n const unmetChecklist = await (async () => {\n try {\n const checklist = await store.latestChecklist(root);\n if (checklist === undefined || checklist.items.length === 0)\n return undefined;\n const unmet = await verifyChecklist(checklist.items, {\n sceneTexts,\n fileExists: async (p) => {\n try {\n await nodeFs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n });\n return unmet.length > 0 ? unmet : undefined;\n } catch {\n return undefined;\n }\n })();\n return {\n ok: true,\n result: {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({\n ...(fileUrl !== undefined ? { fileUrl } : { uri, httpUrl }),\n bytes: bytes.byteLength,\n format,\n revision,\n ...(path !== undefined ? { path } : {})\n })\n },\n ...(staleHead !== undefined\n ? [\n {\n type: 'text' as const,\n text:\n `Note: this file exports a STALE revision — the design has newer revision(s); ` +\n `the latest is ${staleHead.id} (${staleHead.excerpt}). To export the current ` +\n `design, rerun export with that revision.`\n }\n ]\n : []),\n ...(unjudged !== undefined\n ? [{ type: 'text' as const, text: unjudgedNoticeText(unjudged) }]\n : []),\n ...(unmetChecklist !== undefined\n ? [\n {\n type: 'text' as const,\n text: checklistNoticeText(unmetChecklist)\n }\n ]\n : [])\n ]\n }\n };\n };\n return {\n name: 'export',\n description: buildDescription(\n allowLocalPath,\n opts.viewerDisabled === true && opts.localRoot !== undefined\n ),\n inputSchema: buildExportInputSchema(allowLocalPath),\n telemetrySelfReported: true,\n call: async (rawArgs, ctx) => {\n const rec = new SpanRecorder();\n const startedAt = performance.now();\n let result: CallResult | undefined;\n let threw: unknown;\n let revision: string | undefined;\n let exportError: unknown;\n // Set at each failure return below; the finally falls back to the\n // classifier for anything that escaped as a throw.\n let errorCode: ErrorCode | undefined;\n let pdfxResolved:\n | { outputStandard: string; outputProfile: string }\n | undefined;\n let htmlAssetsUsed: string | undefined;\n try {\n result = await (async (): Promise<CallResult> => {\n const args = (rawArgs ?? {}) as Partial<ExportArgs>;\n if (\n typeof args.format !== 'string' ||\n typeof args.revision !== 'string'\n ) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format and revision are required.'\n }\n ]\n };\n }\n if (args.outPath !== undefined && !allowLocalPath) {\n errorCode = 'feature_disabled';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `outPath` is not supported on this (hosted) backend. Omit it — the artifact is written to the workspace and returned as `httpUrl`; fetch that URL to download the bytes.'\n }\n ]\n };\n }\n if (\n args.outPath !== undefined &&\n (typeof args.outPath !== 'string' || !isAbsolute(args.outPath))\n ) {\n // Schemas are advisory; and a relative path would resolve against\n // the SERVER's cwd, not the caller's — a wrong-place trap.\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`outPath\\` must be an absolute path (including the filename) — got \"${String(args.outPath)}\". Relative paths would resolve against the server's working directory, not yours.`\n }\n ]\n };\n }\n const spec = formatSpec(args.format);\n if (!spec) {\n errorCode = 'unknown_format';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: unknown format=\"${args.format}\". Valid formats: pdf, png, jpeg, webp, svg, pdfx, html, mp4, imgly.`\n }\n ]\n };\n }\n if (args.pdfx !== undefined && spec.kind !== 'pdfx') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`pdfx\\` options are only valid with format=pdfx (got format=${args.format}).`\n }\n ]\n };\n }\n if (args.html !== undefined && spec.kind !== 'html') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`html\\` options are only valid with format=html (got format=${args.format}).`\n }\n ]\n };\n }\n if (args.fps !== undefined && spec.target !== 'video') {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`fps\\` is only valid with format=mp4 (got format=${args.format}).`\n }\n ]\n };\n }\n if (\n args.fps !== undefined &&\n (typeof args.fps !== 'number' ||\n !Number.isFinite(args.fps) ||\n args.fps <= 0 ||\n args.fps > MAX_VIDEO_FPS)\n ) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: \\`fps\\` must be a number greater than 0 and at most ${MAX_VIDEO_FPS} — got ${JSON.stringify(args.fps)}. Omit it for the default ${DEFAULT_VIDEO_FPS}.`\n }\n ]\n };\n }\n const target = spec.target;\n if (target === 'video') {\n const caps = await engineCapabilities({\n flavor: engineFlavor,\n fallbackWarning: fallbackReason\n });\n if (!caps.video) {\n errorCode = 'engine_unsupported';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: ${avUnavailableMessage('format=mp4 (video export)', caps)}`\n }\n ]\n };\n }\n }\n let rev: Revision;\n try {\n rev = await rec.time('workspace_read', () =>\n store.read(args.revision as string)\n );\n } catch (err) {\n if ((err as { code?: string }).code === 'ENOENT') {\n errorCode = 'unknown_revision';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: unknown revision \"${args.revision}\". Call \\`list\\` to see the workspace's designs and their latest revisions.`\n }\n ]\n };\n }\n throw err;\n }\n if (args.blockId !== undefined && typeof args.blockId !== 'number') {\n // Schemas are advisory — a malformed id must not silently become\n // a whole-document export.\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `blockId` must be an integer (or omitted to export the whole document).'\n }\n ]\n };\n }\n if (spec.kind === 'archive' && args.blockId !== undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: `blockId` is not valid with format=imgly — an `.imgly` archive is always the whole design; omit `blockId`.'\n }\n ]\n };\n }\n if (target === 'video' && args.blockId === undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format=mp4 requires `blockId` — pass the id of the page to render.'\n }\n ]\n };\n }\n if (spec.kind === 'html' && args.blockId === undefined) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'export: format=html requires `blockId` — the exporter renders exactly one page; pass the id of the page to render (use `inspect` to see the pages).'\n }\n ]\n };\n }\n if (spec.kind === 'html') {\n const mod = await exporterModules.html();\n const htmlArgs = mod.resolveHtmlArgs(args.html);\n if (!htmlArgs.ok) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: htmlArgs.message }]\n };\n }\n htmlAssetsUsed = htmlArgs.assets;\n const htmlBlockId = args.blockId as number; // guarded above\n const revIdHtml = args.revision;\n const sceneHtml = rev.scene;\n type HtmlOutcome =\n | { ok: true; files: Awaited<ReturnType<typeof mod.renderHtml>> }\n | { ok: false; message: string; error?: unknown };\n const beforeHtmlLock = performance.now();\n const rendered = await engineLock.runExclusive<HtmlOutcome>(\n async () => {\n rec.add('lock_wait', performance.now() - beforeHtmlLock);\n const slot = await rec.time('engine_scene_load', async () => {\n await session.populate(revIdHtml, sceneHtml);\n return session.acquire(revIdHtml);\n });\n const pageIndex = mod.derivePageIndex(slot.engine, htmlBlockId);\n if (pageIndex === null) {\n return {\n ok: false,\n message: `export: block ${htmlBlockId} is not a page in revision ${revIdHtml} — format=html renders exactly one page. Pass a page id (use \\`inspect\\` to see the revision's pages).`\n };\n }\n // @imgly/html-exporter's bundle rasterizes image/graphic\n // blocks via engine.block.export internally — the same\n // encode that races an in-flight font/image fetch and throws\n // ENCODE.NOT_ALL_RESOURCES_LOADED (CODE-94) without this\n // barrier. Mirrors the still-render path just below.\n try {\n const engHtml = slot.engine as MinimalEngine;\n const forceLoadResources =\n engHtml.block.forceLoadResources?.bind(engHtml.block);\n if (forceLoadResources) {\n await rec.time('engine_resource_load', () =>\n forceLoadResources([htmlBlockId])\n );\n }\n const files = await rec.time('html_export', () =>\n mod.renderHtml(slot.engine, pageIndex, htmlArgs.assets)\n );\n return { ok: true, files };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not render page ${htmlBlockId} to HTML in revision ${revIdHtml} — the scene's resources (fonts/images) were still loading when the encode ran. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : `export: HTML export failed for page ${htmlBlockId} in revision ${revIdHtml}. ${detail}`\n };\n }\n }\n );\n if (!rendered.ok) {\n exportError = rendered.error;\n errorCode = classifyThrow(rendered.error) ?? 'render_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: rendered.message }]\n };\n }\n // Zip packing / GSAP injection is pure — outside the engine lock.\n const deliverable = await rec.time('zip_assemble', () =>\n mod.assembleHtmlDeliverable(rendered.files, htmlArgs.assets)\n );\n const shardH = args.revision.slice(0, 2);\n const restH = args.revision.slice(2);\n const relPathH = `exports/${shardH}/${restH}/html.${deliverable.ext}`;\n const deliveredH = await deliver({\n rec,\n relPath: relPathH,\n bytes: deliverable.bytes,\n format: args.format,\n revision: args.revision,\n root: rev.meta.root,\n ...(args.outPath !== undefined ? { outPath: args.outPath } : {})\n });\n if (!deliveredH.ok) {\n exportError = deliveredH.error;\n errorCode = deliveredH.errorCode;\n return deliveredH.result;\n }\n revision = args.revision;\n return deliveredH.result;\n }\n type PdfxModule = Awaited<ReturnType<ExporterModules['pdfx']>>;\n let pdfxPrep:\n | {\n mod: PdfxModule;\n args: ResolvedPdfxArgs;\n customProfile?: Blob;\n }\n | undefined;\n if (spec.kind === 'pdfx') {\n const mod = await exporterModules.pdfx();\n const title = await store.currentTitle(rev.meta.root);\n const resolved = mod.resolvePdfxArgs(args.pdfx, { title });\n if (!resolved.ok) {\n errorCode = 'bad_args';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: resolved.message }]\n };\n }\n pdfxResolved = {\n // The telemetry sink's token gate rejects '/', so record the\n // standard as a gate-safe token — the schema/adapter keep the\n // verbatim 'PDF/X-4' / 'PDF/X-3' names throughout.\n outputStandard:\n resolved.args.outputStandard === 'PDF/X-4' ? 'pdfx4' : 'pdfx3',\n outputProfile: resolved.args.outputProfile\n };\n let customProfile: Blob | undefined;\n if (resolved.args.customProfileUri !== undefined) {\n const prof = await rec.time('profile_fetch', () =>\n mod.resolveCustomProfile(\n resolved.args.customProfileUri as string\n )\n );\n if (!prof.ok) {\n errorCode = 'profile_fetch_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: prof.message }]\n };\n }\n customProfile = prof.profile;\n }\n pdfxPrep = { mod, args: resolved.args, customProfile };\n }\n // Capture validated args into locals so the locked closure keeps the\n // type narrowing the top-level guards established.\n const revId = args.revision;\n const requestedBlockId = args.blockId;\n const mime = spec.mime;\n const sceneBytes = rev.scene;\n const outPath = args.outPath;\n type EncodeOutcome =\n | { ok: true; bytes: Uint8Array }\n | { ok: false; message: string; error?: unknown };\n // load-into-engine then export reads the shared engine across awaits —\n // serialize against any concurrent engine-touching tool call.\n const beforeLock = performance.now();\n let deliveredSceneTexts: string[] | undefined;\n const outcome = await engineLock.runExclusive<EncodeOutcome>(\n async () => {\n rec.add('lock_wait', performance.now() - beforeLock);\n const slot = await rec.time('engine_scene_load', async () => {\n await session.populate(revId, sceneBytes);\n return session.acquire(revId);\n });\n const eng = slot.engine as MinimalEngine;\n // For the acceptance gate's copy items: every text string in\n // the scene being delivered. Best-effort — a collect failure\n // degrades to \"copy items unverified\", never a failed export.\n try {\n if (eng.block.findByType && eng.block.getString) {\n deliveredSceneTexts = eng.block\n .findByType('//ly.img.ubq/text')\n .map((id) => eng.block.getString!(id, 'text/text'));\n }\n } catch {\n deliveredSceneTexts = undefined;\n }\n if (spec.kind === 'archive') {\n try {\n // saveToArchive bundles \"all assets that were accessible\n // when this function was called\" (SceneAPI). Measured on the\n // 1.81.0-nightly.20260805 pin that under-describes in-flight\n // loads — the engine awaits those — but is exact for an\n // unreachable one: without this barrier the archive ships\n // silently truncated, with it the export fails loudly. So a\n // missing forceLoadResources must throw, not skip.\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n if (!forceLoadResources) {\n throw new Error(\n 'export: this engine build has no block.forceLoadResources — refusing to archive, ' +\n 'since the .imgly would silently omit unloaded asset bytes.'\n );\n }\n await rec.time('engine_resource_load', () =>\n forceLoadResources(eng.scene.getPages())\n );\n const blob = await rec.time('engine_execute', () =>\n eng.scene.saveToArchive()\n );\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not archive revision ${revId} — the scene's resources (fonts/images) were still loading when the archive was written. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : `export: could not archive revision ${revId}. ${detail}`\n };\n }\n }\n // No explicit blockId → the whole document. Resolve the scene\n // root only now, after acquire() made this revision's scene\n // current — resolving earlier would read whatever scene another\n // call left loaded.\n const blockId = requestedBlockId ?? eng.scene.get();\n if (blockId === null) {\n return {\n ok: false,\n message: `export: revision ${revId} has no scene root to export — the snapshot may be corrupt. Load a known-good revision (see \\`list\\`) or pass an explicit \\`blockId\\`.`\n };\n }\n if (target === 'video') {\n // Bind up front: the methods are optional on MinimalEngine and\n // unbound engine methods lose their `this`.\n const exportVideo = eng.block.exportVideo?.bind(eng.block);\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n const findAll = eng.block.findAll?.bind(eng.block);\n const getParent = eng.block.getParent?.bind(eng.block);\n // The engine may have booted (and fallen back) during this call.\n const caps = await engineCapabilities({\n flavor: engineFlavor,\n fallbackWarning: fallbackReason\n });\n if (\n !caps.video ||\n !exportVideo ||\n !forceLoadResources ||\n !findAll ||\n !getParent\n ) {\n return {\n ok: false,\n message: `export: ${avUnavailableMessage('format=mp4 (video export)', caps)}`\n };\n }\n // exportVideo on a detached block kills the process (issues/@cesdk/node-native/01a0ed5f-6c49-705d-8b29-cdd246f4fbd3_exportvideo-detached-page-sigtrap).\n if (!isAttachedToScene(getParent, blockId, eng.scene.get())) {\n return {\n ok: false,\n message: `export: block ${blockId} exists in revision ${revId} but is not attached to the scene, so it has nothing to play. Append it to the scene (or to a page that is) in your next \\`edit\\` — a page made with \\`engine.design.create\\` and no parent stays detached — or omit \\`blockId\\` to export the whole document.`\n };\n }\n const encodeOnce = (): Promise<Blob> =>\n rec.time('engine_execute', async () => {\n // Force-load every referenced resource first, or the encoder\n // races the asset fetch (black frames / silent audio).\n await forceLoadResources(findAll());\n return exportVideo(blockId, {\n mimeType: mime,\n framerate:\n (args.fps as number | undefined) ?? DEFAULT_VIDEO_FPS,\n onProgress: throttledVideoProgress(ctx?.progress)\n });\n });\n // The encode parks the playhead on its last frame (issues/@cesdk/node-native/01a0ddbd-eb12-780a-9edf-03bbbf46ba86_exportvideo-leaves-playhead-at-last-frame).\n let parkedTime: number | undefined;\n try {\n parkedTime = eng.block.getPlaybackTime?.(blockId);\n } catch {\n /* a bad id: the encode below reports it legibly */\n }\n try {\n let blob: Blob;\n for (let attempt = 0; ; attempt++) {\n try {\n blob = await encodeOnce();\n break;\n } catch (err) {\n if (\n !isEncoderBusyError(err) ||\n attempt >= encoderBusyDelaysMs.length\n ) {\n throw err;\n }\n // See ENCODER_BUSY_MARKER: the previous export is still\n // releasing the encode service — wait it out.\n rec.add(\n 'encoder_busy_wait',\n encoderBusyDelaysMs[attempt]\n );\n await new Promise((r) =>\n setTimeout(r, encoderBusyDelaysMs[attempt])\n );\n }\n }\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isEncoderBusyError(err)\n ? `export: the video encoder is still busy releasing a previous export — the server already waited ~${Math.round(\n encoderBusyDelaysMs.reduce((a, b) => a + b, 0) / 1000\n )}s for it. Retry this exact export call in a few seconds; if it keeps failing, the encoder is stuck — restart the MCP server. ${detail}`\n : `export: video export failed for block ${blockId} in revision ${revId}. If that block id isn't in this revision's scene, double-check it (use \\`inspect\\`); otherwise the engine failed to load a resource or encode. ${detail}`\n };\n } finally {\n try {\n if (parkedTime !== undefined)\n eng.block.setPlaybackTime?.(blockId, parkedTime);\n } catch {\n session.markDirty(slot);\n }\n }\n }\n // We loaded `revId` under the lock just above, so the correct scene\n // is current. Force-load the block's resources before encoding —\n // the same barrier the video path runs — or the still render\n // races any in-flight font/image fetch and throws\n // ENCODE.NOT_ALL_RESOURCES_LOADED (CODE-94). If the render still\n // throws, return a legible tool error the model can act on\n // (mirroring `edit`'s dirty-on-throw path) instead of rethrowing\n // into an opaque MCP -32603 — distinguishing a resource-load\n // race (retryable) from a bad block id.\n try {\n const forceLoadResources = eng.block.forceLoadResources?.bind(\n eng.block\n );\n if (forceLoadResources) {\n await rec.time('engine_resource_load', () =>\n forceLoadResources([blockId])\n );\n }\n // CMYK and CMYK-valued spot colors export as their native\n // color spaces (DeviceCMYK / DeviceN) rather than being\n // downconverted to RGB — this is a print backend. The flag is\n // PDF-only, scoped to the pdf target; pdfx runs its own PDF/X\n // color pipeline. Must use the object-options signature: the\n // deprecated (id, mimeType, options) overload rejects this flag\n // at runtime (\"Invalid arguments\").\n const exportOptions = {\n mimeType: mime,\n ...(target === 'pdf' ? { exportPdfWithDeviceCMYK: true } : {})\n };\n const blob = await rec.time('engine_execute', () =>\n eng.block.export(blockId, exportOptions)\n );\n return {\n ok: true,\n bytes: new Uint8Array(await blob.arrayBuffer())\n };\n } catch (err) {\n const detail =\n err instanceof Error\n ? (err.stack ?? err.message)\n : String(err);\n return {\n ok: false,\n error: err,\n message: isResourcesStillLoadingError(err)\n ? `export: could not render block ${blockId} in revision ${revId} — the scene's resources (fonts/images) were still loading when the encode ran. Retry the export; if it keeps failing, a font or image URI in this scene never finishes loading — check the URIs your edit set. ${detail}`\n : requestedBlockId === undefined\n ? `export: could not render the whole document (scene root ${blockId}) in revision ${revId} — the engine failed to encode it. ${detail}`\n : `export: could not render block ${blockId} in revision ${revId}. That block id isn't in this revision's scene — double-check the id (use \\`inspect\\` to see the revision's structure), it may have been removed in this revision — or omit \\`blockId\\` to export the whole document. ${detail}`\n };\n }\n }\n );\n if (!outcome.ok) {\n exportError = outcome.error;\n errorCode = classifyThrow(outcome.error) ?? 'render_failed';\n return {\n isError: true,\n content: [{ type: 'text' as const, text: outcome.message }]\n };\n }\n let bytes = outcome.bytes;\n if (pdfxPrep) {\n // Ghostscript WASM (~2–5 s, memory-heavy) — deliberately OUTSIDE the engine\n // lock: it never touches the engine, so concurrent edits need not wait.\n try {\n bytes = await rec.time('plugin_convert', () =>\n pdfxPrep.mod.convertPdfToPdfx(\n bytes,\n pdfxPrep.args,\n pdfxPrep.customProfile\n )\n );\n } catch (err) {\n exportError = err;\n errorCode = 'pdfx_convert_failed';\n const detail =\n err instanceof Error ? (err.stack ?? err.message) : String(err);\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `export: the PDF/X conversion failed (the base PDF exported fine). If the message mentions a size limit, the intermediate PDF exceeded the converter's 100 MB cap — export page-by-page with \\`blockId\\`. Otherwise this is a converter (Ghostscript) failure. ${detail}`\n }\n ]\n };\n }\n }\n const shard = args.revision.slice(0, 2);\n const rest = args.revision.slice(2);\n const relPath = `exports/${shard}/${rest}/${target}.${spec.ext}`;\n const delivered = await deliver({\n rec,\n relPath,\n bytes,\n format: args.format,\n revision: revId,\n root: rev.meta.root,\n ...(outPath !== undefined ? { outPath } : {}),\n ...(deliveredSceneTexts !== undefined\n ? { sceneTexts: deliveredSceneTexts }\n : {})\n });\n if (!delivered.ok) {\n exportError = delivered.error;\n errorCode = delivered.errorCode;\n return delivered.result;\n }\n revision = args.revision;\n return delivered.result;\n })();\n return result;\n } catch (err) {\n threw = err;\n throw err;\n } finally {\n const a = rawArgs as { format?: unknown } | null | undefined;\n const fmt = typeof a?.format === 'string' ? a.format : undefined;\n const fmtSpec = fmt ? formatSpec(fmt) : undefined;\n const resolvedCode = errorCode ?? classifyThrow(threw);\n telemetry.record({\n tool: 'export',\n succeeded: threw === undefined && result?.isError !== true,\n ...(resolvedCode ? { errorCode: resolvedCode } : {}),\n totalMs: performance.now() - startedAt,\n spans: rec.list(),\n args: rawArgs,\n // What was exported (print-PDF vs image vs video): the schema-enum\n // format plus the deliverable kind derived from it — the sink's\n // token gate drops anything else a client sent.\n toolFields: {\n ...(fmt ? { format: fmt } : {}),\n ...(fmtSpec ? { target: fmtSpec.target } : {}),\n ...(pdfxResolved ? pdfxResolved : {}),\n ...(htmlAssetsUsed ? { assets: htmlAssetsUsed } : {})\n },\n ...(result !== undefined ? { result: summarizeResult(result) } : {}),\n ...(revision ? { revision } : {}),\n ...(threw\n ? { error: toErrorShape(threw) }\n : exportError\n ? { error: toErrorShape(exportError) }\n : {})\n });\n }\n }\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imgly/codesign-mcp",
3
- "version": "0.3.7-next.20260929141300.g06dc965",
3
+ "version": "0.4.0",
4
4
  "description": "A real design engine for your AI agent: generate designs and print-ready PDFs, over MCP.",
5
5
  "keywords": [
6
6
  "mcp",