@enhance-eng/enhance 0.1.25 → 0.1.37

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as canvasRenderPendingSchema, $n as canvasRenderStateSchema, An as canvasPrototypePropsSchema, B as canvasCaptureCapabilityInputSchema, Bn as applyCanvasOperationsInputSchema, C as canvasSnapshotToken, Cn as applyCanvasTypographyPatch, Cr as canvasAdditionalStyleSchema, Dt as assertCanvasReferenceNodes, E as resolveCanvasSnapshot, En as canvasTextPropsWithContent, Er as listCanvasesOutputSchema, Fn as beginCanvasActivityOutputSchema, Ft as transcriptOutputSchema, G as canvasRenderCapabilityInputSchema, Gn as getCanvasDocumentOutputSchema, Gt as createPrototypeArtifactOutputSchema, Hn as getCanvasMutationOutputSchema, I as canvasDuplicateCapabilityInputSchema, J as prototypePublishCapabilityInputSchema, Jt as getPrototypePublishStatusOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kt as foldPrototypeArtifactPath, Ln as createCanvasPreparationOutputSchema, Mn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, Mt as parseCanvasReference, N as canvasAssetImportOutputSchema, Nn as canvasReferencePageOf, Nt as PartialBatchError, On as canvasCaptureSchema, Ot as canvasReferenceNodeIds, P as canvasArrangeCapabilityInputSchema, Pn as resolveCanvasReference, Pt as CliError, Qt as getMeOutputSchema, Rn as getCanvasPreparationOutputSchema, S as canvasExchangeDigest, Sr as canvasImageAssetIdentityFromPath, St as CANVAS_HTML_LIMITS, T as encodeCanvasExchangeToken, Tn as canvasTextChangeBetween, Tt as canvasEditCapabilityInputSchema, U as canvasApplyCapabilityInputSchema, Un as canvasLayoutWithoutCssProperties, Ut as PROTOTYPE_ARTIFACT_MANIFEST_PATH, Vn as applyCanvasOperationsOutputSchema, Vt as getRecordingOutputSchema, W as canvasReadCapabilityInputSchema, Wn as mapCanvasFontSources, Wt as attachPrototypeArtifactOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as createCanvasConversionOutputSchema, Xt as prototypeArtifactPathSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as canvasNodeStylePatchSchema, Yt as prototypeArtifactManifestSchema, Z as canvasRenderBatchRequestSchema, Zn as getCanvasConversionOutputSchema, Zt as submitPrototypeArtifactOutputSchema, _r as canvasAssetUploadOutputSchema, ar as getCanvasRenderOutputSchema, br as canvasFontAssetIdentityFromPath, bt as canvasMakeEditableCapabilityInputSchema, cr as textOf, dt as canvasTranscriptCursorSchema, en as cliAuthConfigurationSchema, fr as canvasAuthoredStyleDeclarations, ft as canvasResourcesCursorSchema, gr as canvasCssValue, gt as canvasFindInputSchema, ht as canvasFindCursorSchema, ir as downloadCanvasRenderOutputSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as canvasRecordingPropsSchema, jt as hasCanvasReferenceScope, k as operationStatusInputSchema, kn as canvasConversionMetadataSchema, lr as canvasReadableSceneDocumentSchema, lt as canvasUpdateHtmlCapabilityInputSchema, nr as createCanvasRenderOutputSchema, nt as canvasRenderRequestSchema, or as RENDER_MAX_OUTPUT_PIXELS, ot as canvasOutlineCursorSchema, pr as canvasAxisStyleProperties, q as commentAttentionCapabilityInputSchema, qn as MAX_CANVAS_OPERATIONS, qt as getPrototypeArtifactCapabilitiesOutputSchema, rn as listOrganisationsOutputSchema, rr as createRecordingSnapshotOutputSchema, rt as canvasRenderFileSchema, s as toRemoteError, st as canvasReadInputSchema, tn as createAgentTokenOutputSchema, ur as canvasSceneDocumentSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as reserveCanvasAssetInputSchema, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wn as canvasCssTypographyOwners, xr as MAX_CANVAS_IMAGE_BYTES, yr as reserveCanvasAssetOutputSchema, zn as PAGE_KIND } from "./cli-output-identity.lib-DpON8As5.mjs";
2
+ import { $ as canvasRenderPendingSchema, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as applyCanvasOperationsOutputSchema, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Dn as canvasPrototypePropsSchema, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, Fn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, G as canvasRenderCapabilityInputSchema, Gn as getCanvasDocumentOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as canvasLayoutWithoutCssProperties, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as canvasReferencePageOf, J as prototypePublishCapabilityInputSchema, Jn as canvasNodeStylePatchSchema, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kt as prototypeArtifactManifestSchema, Ln as resolveCanvasReference, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, Nn as createCanvasPreparationOutputSchema, On as canvasRecordingPropsSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as getCanvasPreparationOutputSchema, Qn as canvasRenderStateSchema, Qt as createAgentTokenOutputSchema, Rn as PAGE_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as textOf, Ut as foldPrototypeArtifactPath, Vn as getCanvasMutationOutputSchema, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as mapCanvasFontSources, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasConversionOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as createCanvasConversionOutputSchema, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasImageAssetIdentityFromPath, ar as canvasReadableSceneDocumentSchema, bn as applyCanvasTypographyPatch, bt as canvasMakeEditableCapabilityInputSchema, cr as canvasAuthoredStyleDeclarations, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, fr as canvasCssValue, ft as canvasResourcesCursorSchema, gr as canvasFontAssetIdentityFromPath, gt as canvasFindInputSchema, hr as reserveCanvasAssetOutputSchema, ht as canvasFindCursorSchema, ir as getCanvasRenderOutputSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as AGENT_CLIENT_HEADER, jt as CliError, k as operationStatusInputSchema, kn as beginCanvasActivityOutputSchema, kt as parseCanvasReference, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, mr as reserveCanvasAssetInputSchema, nr as createRecordingSnapshotOutputSchema, nt as canvasRenderRequestSchema, or as canvasSceneDocumentSchema, ot as canvasOutlineCursorSchema, pr as canvasAssetUploadOutputSchema, q as commentAttentionCapabilityInputSchema, qt as prototypeArtifactPathSchema, rr as downloadCanvasRenderOutputSchema, rt as canvasRenderFileSchema, s as toRemoteError, st as canvasReadInputSchema, tr as createCanvasRenderOutputSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasAdditionalStyleSchema, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as listCanvasesOutputSchema, zn as applyCanvasOperationsInputSchema } from "./cli-output-identity.lib-i4KnVAYs.mjs";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
5
5
  import { homedir, tmpdir } from "node:os";
@@ -8,10 +8,11 @@ import { chmodSync, constants, createReadStream, createWriteStream, mkdirSync, w
8
8
  import path from "node:path";
9
9
  import { createHash, randomBytes, randomUUID } from "node:crypto";
10
10
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
- import { mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
11
+ import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
12
12
  import { isDeepStrictEqual } from "node:util";
13
13
  import { generate, parse } from "css-tree";
14
14
  import { parseFragment, serialize, serializeOuter } from "parse5";
15
+ import { performance as performance$1 } from "node:perf_hooks";
15
16
  import { Readable, Transform } from "node:stream";
16
17
  import { pipeline } from "node:stream/promises";
17
18
  import { ZipFile } from "yazl";
@@ -68,10 +69,38 @@ const canvasAdditionalStylePatchBetween = (before, after) => {
68
69
  };
69
70
  };
70
71
 
72
+ //#endregion
73
+ //#region ../../packages/contract/src/canvas/canvas-html-source.lib.ts
74
+ const OMITTED_ELEMENTS = /* @__PURE__ */ new Set([
75
+ "base",
76
+ "embed",
77
+ "iframe",
78
+ "link",
79
+ "meta",
80
+ "object",
81
+ "script"
82
+ ]);
83
+ const EXECUTABLE_URL = /^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu;
84
+ const UNSAFE_STYLE = /javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu;
85
+ const canRetainCanvasHtmlElement = (tag) => !OMITTED_ELEMENTS.has(tag.toLowerCase());
86
+ const canRetainCanvasHtmlStyle = (style) => !UNSAFE_STYLE.test(style);
87
+ const canRetainCanvasHtmlAttribute = (name, value) => {
88
+ const property = name.toLowerCase();
89
+ if (property === "srcdoc" || /^on/iu.test(property)) return false;
90
+ if (property === "style") return canRetainCanvasHtmlStyle(value);
91
+ return ![
92
+ "href",
93
+ "src",
94
+ "action",
95
+ "formaction",
96
+ "xlink:href"
97
+ ].includes(property) || !EXECUTABLE_URL.test(value.replaceAll(/[\p{Control}\s]/gu, ""));
98
+ };
99
+
71
100
  //#endregion
72
101
  //#region ../../packages/contract/src/canvas/canvas-image-resources.lib.ts
73
102
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
74
- const mapPaint = (paint, map) => {
103
+ const mapImagePaint = (paint, map) => {
75
104
  if (!isRecord(paint) || paint["kind"] !== "image" || typeof paint["assetId"] !== "string") return paint;
76
105
  const assetId = map(paint["assetId"]);
77
106
  return assetId === paint["assetId"] ? paint : {
@@ -79,6 +108,16 @@ const mapPaint = (paint, map) => {
79
108
  assetId
80
109
  };
81
110
  };
111
+ const mapPaint = (paint, map) => {
112
+ const active = mapImagePaint(paint, map);
113
+ if (!isRecord(active) || !isRecord(active["alternatives"])) return active;
114
+ const alternatives = active["alternatives"];
115
+ const next = Object.fromEntries(Object.entries(alternatives).map(([kind, held]) => [kind, mapImagePaint(held, map)]));
116
+ return Object.entries(next).every(([kind, held]) => alternatives[kind] === held) ? active : {
117
+ ...active,
118
+ alternatives: next
119
+ };
120
+ };
82
121
  const mapRichText = (value, map) => {
83
122
  if (!Array.isArray(value)) return value;
84
123
  return value.map((run) => {
@@ -87,6 +126,10 @@ const mapRichText = (value, map) => {
87
126
  return {
88
127
  ...run,
89
128
  ...fills !== void 0 && { fills: fills.map((paint) => mapPaint(paint, map)) },
129
+ ...isRecord(run["stroke"]) && { stroke: {
130
+ ...run["stroke"],
131
+ paint: mapPaint(run["stroke"]["paint"], map)
132
+ } },
90
133
  ...Array.isArray(run["children"]) && { children: mapRichText(run["children"], map) }
91
134
  };
92
135
  });
@@ -167,9 +210,9 @@ const createAuthUseCase = (credentials, remote, browser) => ({
167
210
  await credentials.write(created.token);
168
211
  return status;
169
212
  },
170
- status: async () => {
213
+ status: async (requestRemote = remote) => {
171
214
  if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
172
- return authenticated(await remote.query("person.me", {}));
215
+ return authenticated(await requestRemote.query("person.me", {}));
173
216
  },
174
217
  logout: async () => ({ loggedOut: await credentials.remove() })
175
218
  });
@@ -190,13 +233,16 @@ const pngDimensions = (body) => {
190
233
  };
191
234
  const downloadVerifiedRenderPng = async (remote, job) => {
192
235
  if (job.result.canvasId !== job.canvasId || job.result.requestedVersion !== job.requestedVersion || job.result.loadedVersion !== job.requestedVersion || JSON.stringify(job.result.target) !== JSON.stringify(job.target)) throw new CliError("INTERNAL", "The completed render evidence does not match its requested canvas, revision or target.", `Do not use the image. Report render job ${job.id}.`);
193
- if (job.result.width * job.result.height > Math.min(job.maxOutputPixels ?? 16e6, 16e6)) throw new CliError("INTERNAL", "The completed render exceeds its authorised output pixel limit.", `Do not use the image. Report render job ${job.id}.`, { reason: "RENDER_BUDGET_UNSUPPORTED" });
236
+ if (job.maxOutputPixels !== void 0 && job.result.width * job.result.height > job.maxOutputPixels) throw new CliError("INTERNAL", "The completed render exceeds its authorised output pixel limit.", `Do not use the image. Report render job ${job.id}.`, { reason: "RENDER_BUDGET_UNSUPPORTED" });
194
237
  const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
195
238
  if (!signed.success || signed.data.jobId !== job.id || signed.data.download.bytes !== job.result.bytes) throw new CliError("INTERNAL", "The API returned an invalid render download response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
196
239
  const body = await remote.download(signed.data.download.url);
197
240
  const dimensions = pngDimensions(body);
198
241
  if (dimensions === null || body.byteLength !== job.result.bytes || dimensions.width !== job.result.width || dimensions.height !== job.result.height) throw new CliError("INTERNAL", "The downloaded render did not match its completed job metadata.", `Do not use the image. Report render job ${job.id}.`);
199
- return body;
242
+ return {
243
+ body,
244
+ ...signed.data.source !== void 0 && { source: signed.data.source }
245
+ };
200
246
  };
201
247
 
202
248
  //#endregion
@@ -211,7 +257,8 @@ const nextCommands = (job) => {
211
257
  if (job.target.kind !== "node") return [inspect];
212
258
  return [inspect, `enhance canvas node --canvas ${job.canvasId} --node-id ${job.target.nodeId}`];
213
259
  };
214
- const resultFrom = (job, written) => ({
260
+ const resultFrom = (job, written, source) => ({
261
+ ...source !== void 0 && { source },
215
262
  jobId: job.id,
216
263
  operation: {
217
264
  kind: "canvas-render",
@@ -236,10 +283,13 @@ const resultFrom = (job, written) => ({
236
283
  ...written.deleteAfter !== null && { deleteAfter: written.deleteAfter.toISOString() },
237
284
  next: nextCommands(job)
238
285
  });
239
- const writeRenderArtifact = async (remote, files, job, input) => resultFrom(job, files.write({
240
- body: await downloadVerifiedRenderPng(remote, job),
241
- ...input
242
- }));
286
+ const writeRenderArtifact = async (remote, files, job, input) => {
287
+ const downloaded = await downloadVerifiedRenderPng(remote, job);
288
+ return resultFrom(job, files.write({
289
+ body: downloaded.body,
290
+ ...input
291
+ }), downloaded.source);
292
+ };
243
293
 
244
294
  //#endregion
245
295
  //#region src/application/render-canvas.composite.ts
@@ -296,7 +346,7 @@ const awaitJob = async (remote, input) => {
296
346
  });
297
347
  }
298
348
  await wait$2(POLL_MS$3);
299
- job = await readJob(remote, job.id);
349
+ job = job.purpose === "inspection" && job.state === "queued" && job.attempt > 0 ? await input.resume() : await readJob(remote, job.id);
300
350
  }
301
351
  if (job.state !== "succeeded") throw terminalFailure$1(job);
302
352
  return job;
@@ -325,6 +375,7 @@ const executeRender = async (dependencies, input) => {
325
375
  requireRenderBudget(initial, input);
326
376
  const job = await awaitJob(dependencies.remote, {
327
377
  initial,
378
+ resume: async () => requestRenderJob(dependencies.remote, input),
328
379
  deadline: Date.now() + input.timeoutMs,
329
380
  timeoutMs: input.timeoutMs,
330
381
  retryClientToken: input.retryClientToken,
@@ -344,7 +395,7 @@ const executeRender = async (dependencies, input) => {
344
395
  jobId: job.id
345
396
  },
346
397
  pixelsDelivered: false,
347
- next: ["Read operation_status with includeImage true. Do not create another render."]
398
+ next: ["Read operation_status with includeImage true. Do not create another render.", "If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it."]
348
399
  };
349
400
  return await writeRenderArtifact(dependencies.remote, dependencies.files, job, {
350
401
  outputPath: input.outputPath,
@@ -494,7 +545,7 @@ const union = (boxes) => {
494
545
  const apply = async (remote, input) => {
495
546
  const response = await remote.mutate(APPLY_PROCEDURE, {
496
547
  ...input,
497
- documentFormatVersion: 5
548
+ documentFormatVersion: 11
498
549
  });
499
550
  const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
500
551
  if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
@@ -829,11 +880,7 @@ const additionalOperation = (node, styles) => {
829
880
  if (!result.success) throw new CliError("BAD_REQUEST", `Style ${property} is not safe CSS.`, "Use a valid CSS property without imports, expressions, or executable URLs.");
830
881
  held.set(id, result.data);
831
882
  }
832
- const declarations = [];
833
- for (const declaration of held.values()) {
834
- if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
835
- declarations.push(declaration);
836
- }
883
+ const declarations = held.values().toArray();
837
884
  const requested = declarations.length === 0 && node.additionalStyles === void 0 ? void 0 : { declarations };
838
885
  const patch = canvasAdditionalStylePatchBetween(node.additionalStyles, requested);
839
886
  return patch === null ? null : {
@@ -1242,7 +1289,6 @@ const assertCanvasReferenceOperations = (reference, document, operations) => {
1242
1289
 
1243
1290
  //#endregion
1244
1291
  //#region src/application/edit-canvas.composite.ts
1245
- const MAX_EDIT_TARGETS = 1e3;
1246
1292
  const targetIds = (edit) => {
1247
1293
  switch (edit.kind) {
1248
1294
  case "set_text":
@@ -1258,9 +1304,7 @@ const scopeIds = (edit, scene) => {
1258
1304
  return targetIds(edit);
1259
1305
  };
1260
1306
  const validateTargets = (input, scene) => {
1261
- if (input.edits.length === 0 || input.edits.length > 1e3) throw new CliError("BAD_REQUEST", "The edit batch exceeds the canonical operation limit.", "Split larger changes into bounded batches.");
1262
1307
  const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
1263
- if (ids.size > MAX_EDIT_TARGETS) throw new CliError("BAD_REQUEST", "A batch may target at most 1,000 nodes.", "Split the edit into smaller batches.");
1264
1308
  for (const id of ids) requireCanvasNode(scene, id);
1265
1309
  const reference = {
1266
1310
  canvasId: input.canvasId,
@@ -1281,11 +1325,11 @@ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
1281
1325
  const parsed = applyCanvasOperationsInputSchema.safeParse({
1282
1326
  canvasId: input.canvasId,
1283
1327
  mutationId: input.mutationId,
1284
- documentFormatVersion: 5,
1328
+ documentFormatVersion: 11,
1285
1329
  baseVersion: input.baseVersion,
1286
1330
  operations: plan.operations
1287
1331
  });
1288
- if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit exceeds canonical canvas limits.", parsed.error.issues[0]?.message ?? "Reduce the edit batch.");
1332
+ if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit contains an invalid canvas operation.", parsed.error.issues[0]?.message ?? "Check the edit’s node references and values.");
1289
1333
  const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
1290
1334
  return {
1291
1335
  ...result,
@@ -1307,20 +1351,19 @@ const fromCapabilityReference = (catalog, id) => {
1307
1351
  };
1308
1352
 
1309
1353
  //#endregion
1310
- //#region src/application/operation-detail-page.use-case.ts
1311
- const MAX_PAGE_BYTES$2 = 48e3;
1312
- const boundedOperationPage = (entries, offset, limit) => {
1313
- if (offset > entries.length) throw new CliError("BAD_REQUEST", "The operation detail offset is out of range.", "Restart status pagination at offset 0.");
1354
+ //#region src/application/result-page.use-case.ts
1355
+ const TARGET_PAGE_BYTES = 48e3;
1356
+ const boundedResultPage = (entries, offset, limit, maxBytes = TARGET_PAGE_BYTES) => {
1357
+ if (offset > entries.length) throw new CliError("BAD_REQUEST", "The result page offset is out of range.", "Restart pagination at offset 0.");
1314
1358
  const selected = [];
1315
1359
  let bytes = 2;
1316
1360
  const offered = entries.slice(offset, offset + limit);
1317
1361
  for (const entry of offered) {
1318
1362
  const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
1319
- if (bytes + size > MAX_PAGE_BYTES$2) break;
1363
+ if (selected.length > 0 && bytes + size > maxBytes) break;
1320
1364
  selected.push(entry);
1321
1365
  bytes += size;
1322
1366
  }
1323
- if (selected.length === 0 && offset < entries.length) throw new CliError("BAD_REQUEST", "One operation detail exceeds the inline result budget.", "Read the full operation through its comprehensive CLI command.");
1324
1367
  const nextOffset = offset + selected.length;
1325
1368
  return {
1326
1369
  entries: selected,
@@ -1382,7 +1425,7 @@ const canvasConversionStatus = (job, page) => ({
1382
1425
  destination: job.destination,
1383
1426
  result: conversionSummary(job),
1384
1427
  failure: job.failure,
1385
- details: boundedOperationPage(conversionEntries(job), page.offset, page.limit),
1428
+ details: boundedResultPage(conversionEntries(job), page.offset, page.limit),
1386
1429
  warnings: job.state === "succeeded" ? ["This receipt does not verify visual fidelity. Render the committed root to inspect it."] : []
1387
1430
  });
1388
1431
 
@@ -1747,6 +1790,8 @@ const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (i
1747
1790
 
1748
1791
  //#endregion
1749
1792
  //#region src/application/prototype-publication.use-case.ts
1793
+ const STATUS_TIMEOUT_MS = 15e3;
1794
+ const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1750
1795
  const INITIAL_POLL_MS = 50;
1751
1796
  const MAX_POLL_MS = 1e3;
1752
1797
  const TERMINAL_STATES = /* @__PURE__ */ new Set([
@@ -1767,6 +1812,8 @@ const reserveAndUpload = async (remote, input, artifact, reserved) => {
1767
1812
  ...input.prototypeId !== null && { prototypeId: input.prototypeId },
1768
1813
  clientToken: input.clientToken,
1769
1814
  nodeId: input.nodeId,
1815
+ ...input.targetMode !== void 0 && { targetMode: input.targetMode },
1816
+ ...input.canvasPageId !== void 0 && { canvasPageId: input.canvasPageId },
1770
1817
  title: input.title,
1771
1818
  entryPath: artifact.manifest.entryPath,
1772
1819
  artifact: artifact.identity,
@@ -1801,25 +1848,79 @@ const preparePrototypePublication = async (remote, artifacts, input, reserved) =
1801
1848
  await artifact.dispose();
1802
1849
  }
1803
1850
  };
1804
- const readPublication = async (remote, input) => {
1805
- const parsed = getPrototypePublishStatusOutputSchema.safeParse(await remote.query(PUBLICATION_PROCEDURES[3], input));
1806
- if (!parsed.success || parsed.data.deploymentId !== input.deploymentId) throw invalidResponse$1("status");
1807
- return parsed.data;
1851
+ const readPublication = async (remote, input, timeoutMs) => {
1852
+ const abort = new AbortController();
1853
+ const expired = Promise.withResolvers();
1854
+ const timer = setTimeout(() => {
1855
+ abort.abort();
1856
+ expired.reject(new CliError("INTERNAL", "The prototype status request timed out.", "Check this deployment again; keep its existing client token.", {
1857
+ reason: "STATUS_TIMEOUT",
1858
+ deploymentId: input.deploymentId
1859
+ }));
1860
+ }, timeoutMs);
1861
+ try {
1862
+ const response = await Promise.race([remote.query(PUBLICATION_PROCEDURES[3], input, { signal: abort.signal }), expired.promise]);
1863
+ const parsed = getPrototypePublishStatusOutputSchema.safeParse(response);
1864
+ if (!parsed.success || parsed.data.deploymentId !== input.deploymentId) throw invalidResponse$1("status");
1865
+ return parsed.data;
1866
+ } finally {
1867
+ clearTimeout(timer);
1868
+ }
1808
1869
  };
1809
1870
  const waitForPrototypePublication = async (remote, input, waitMs) => {
1810
- const deadline = Date.now() + waitMs;
1871
+ const deadline = performance.now() + waitMs;
1811
1872
  let pollMs = INITIAL_POLL_MS;
1812
- let status = await readPublication(remote, input);
1873
+ let status = await readPublication(remote, input, waitMs > 0 ? Math.min(STATUS_TIMEOUT_MS, waitMs) : STATUS_TIMEOUT_MS);
1813
1874
  while (!TERMINAL_STATES.has(status.state)) {
1814
- const remainingMs = deadline - Date.now();
1875
+ const remainingMs = deadline - performance.now();
1815
1876
  if (remainingMs <= 0) return status;
1816
- await setTimeout$1(Math.min(pollMs, remainingMs));
1877
+ await delay(Math.min(pollMs, remainingMs));
1817
1878
  pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1818
- status = await readPublication(remote, input);
1879
+ const timeLeft = deadline - performance.now();
1880
+ if (timeLeft <= 0) return status;
1881
+ try {
1882
+ status = await readPublication(remote, input, Math.min(STATUS_TIMEOUT_MS, timeLeft));
1883
+ } catch (error) {
1884
+ if (error instanceof CliError && error.fields?.["reason"] === "STATUS_TIMEOUT") return status;
1885
+ throw error;
1886
+ }
1819
1887
  }
1820
1888
  return status;
1821
1889
  };
1822
1890
 
1891
+ //#endregion
1892
+ //#region src/application/prototype-publication-outcome.use-case.ts
1893
+ const SOURCE_FAILURES = [
1894
+ "BAD_ARTIFACT",
1895
+ "ARTIFACT_INTEGRITY",
1896
+ "FILE_INTEGRITY",
1897
+ "FILE_TOO_LARGE",
1898
+ "FILE_COUNT_",
1899
+ "MANIFEST_",
1900
+ "PATH_",
1901
+ "ENTRY_",
1902
+ "EXPANDED_",
1903
+ "ZIP_INVALID",
1904
+ "ZIP_ENCRYPTED",
1905
+ "ZIP_PATH_ENCODING",
1906
+ "ZIP_COMPRESSION",
1907
+ "ZIP_ENTRY_TYPE"
1908
+ ];
1909
+ const toPrototypePublicationFailure = (publication) => {
1910
+ const failure = publication.failure;
1911
+ const isBuildFailure = SOURCE_FAILURES.some((prefix) => failure.code.startsWith(prefix));
1912
+ return {
1913
+ isBuildFailure,
1914
+ nextAction: isBuildFailure ? "fix_build" : "retry_new_publication",
1915
+ failure: {
1916
+ code: failure.code,
1917
+ message: failure.message,
1918
+ remediation: isBuildFailure ? "Correct the named build problem and publish a new artifact with a new clientToken." : "This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure."
1919
+ }
1920
+ };
1921
+ };
1922
+ const prototypePublicationWarnings = (publication) => publication.unavailableFiles?.map((file) => `Unavailable published file: ${file.path} (${file.code}).`) ?? [];
1923
+
1823
1924
  //#endregion
1824
1925
  //#region src/application/publish-canvas-prototype.composite.ts
1825
1926
  const PROCEDURES = ["prototype.getArtifactCapabilities", "prototype.attach"];
@@ -1860,7 +1961,7 @@ const attach = async (remote, input, publication) => {
1860
1961
  if (!parsed.success) throw new Error("Invalid prototype attachment response");
1861
1962
  const result = parsed.data;
1862
1963
  const receipt = result.attachment;
1863
- if (receipt === void 0 || result.canvasId !== reference.canvasId || result.deploymentId !== publication.deploymentId || result.prototypeId !== publication.prototypeId || result.nodeId !== publication.nodeId || result.version !== receipt.version || receipt.outcome === "committed" && (receipt.mutationId !== input.clientToken || receipt.previousVersion !== input.baseVersion || receipt.version !== input.baseVersion + 1) || receipt.outcome === "no_op" && receipt.version !== input.baseVersion) throw new Error("Unconfirmed prototype attachment receipt");
1964
+ if (receipt === void 0 || result.canvasId !== reference.canvasId || result.deploymentId !== publication.deploymentId || result.prototypeId !== publication.prototypeId || result.nodeId !== publication.nodeId || result.version !== receipt.version || receipt.outcome === "committed" && (receipt.mutationId !== input.clientToken || receipt.version !== receipt.previousVersion + 1) || receipt.outcome === "no_op" && receipt.version !== input.baseVersion) throw new Error("Unconfirmed prototype attachment receipt");
1864
1965
  return {
1865
1966
  ...result,
1866
1967
  attachment: receipt
@@ -1883,8 +1984,8 @@ const attachReady = async (remote, input, base, publication) => {
1883
1984
  ...base,
1884
1985
  attachmentStatus: isConflict ? "conflict" : isRejected ? "not_attempted" : "not_confirmed",
1885
1986
  failure,
1886
- nextAction: isConflict || isRejected ? "replan_attachment" : "retry_same_request",
1887
- warnings: ["The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; a changed baseVersion, scope or destination requires a new clientToken."]
1987
+ nextAction: failure.code === "UNAUTHORIZED" || failure.code === "FORBIDDEN" ? "restore_access" : isConflict || isRejected ? "replan_attachment" : "retry_same_request",
1988
+ warnings: [...base.warnings, "The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent."]
1888
1989
  };
1889
1990
  }
1890
1991
  };
@@ -1901,16 +2002,25 @@ const finishPublication = async (remote, input, canvasId, publication) => {
1901
2002
  attachment: null,
1902
2003
  failure: null,
1903
2004
  nextAction: "check_status",
1904
- warnings: []
2005
+ warnings: prototypePublicationWarnings(publication)
1905
2006
  };
1906
- if (publication.state === "failed" || publication.state === "abandoned") return {
2007
+ if (publication.state === "failed") {
2008
+ const { nextAction, failure } = toPrototypePublicationFailure(publication);
2009
+ return {
2010
+ ...base,
2011
+ attachmentStatus: "not_attempted",
2012
+ nextAction,
2013
+ failure
2014
+ };
2015
+ }
2016
+ if (publication.state === "abandoned") return {
1907
2017
  ...base,
1908
2018
  attachmentStatus: "not_attempted",
1909
- nextAction: "fix_build",
2019
+ nextAction: "retry_new_publication",
1910
2020
  failure: {
1911
- code: publication.state === "failed" ? publication.failure.code : "NOT_FOUND",
1912
- message: publication.state === "failed" ? publication.failure.message : "The deployment was abandoned.",
1913
- remediation: "Correct the build and publish a new artifact with a new clientToken."
2021
+ code: "NOT_FOUND",
2022
+ message: "The deployment was abandoned.",
2023
+ remediation: "Publish the same build explicitly with a new clientToken if it is still needed."
1914
2024
  }
1915
2025
  };
1916
2026
  if (publication.state !== "ready") return base;
@@ -1924,6 +2034,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
1924
2034
  if (input.source.kind === "build") deploymentId = (await preparePrototypePublication(remote, artifacts, {
1925
2035
  ...input.source,
1926
2036
  canvasId: reference.canvasId,
2037
+ ...reference.pageId !== void 0 && { canvasPageId: reference.pageId },
1927
2038
  clientToken: input.clientToken
1928
2039
  }, (reservedId) => {
1929
2040
  deploymentId = reservedId;
@@ -1947,7 +2058,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
1947
2058
  attachmentStatus: "not_attempted",
1948
2059
  attachment: null,
1949
2060
  failure: failureOf$1(error),
1950
- nextAction: "retry_same_request",
2061
+ nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
1951
2062
  warnings: ["An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication."]
1952
2063
  };
1953
2064
  }
@@ -1958,10 +2069,23 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
1958
2069
  const PUBLISH_WAIT_MS = 3e5;
1959
2070
  const PUBLISH_PROTOTYPE_PROCEDURES = ["prototype.attach"];
1960
2071
  const invalidResponse = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
1961
- const requireSuccessfulIngestion = (status) => {
1962
- if (status.state !== "failed") return;
1963
- const { failure } = status;
1964
- throw new CliError("BAD_REQUEST", failure.message, "Fix the build and publish it with a new client token.", failure.path === void 0 ? void 0 : { path: failure.path });
2072
+ const requireReadyPublication = (status) => {
2073
+ if (status.state === "failed") {
2074
+ const failure = toPrototypePublicationFailure(status);
2075
+ throw new CliError(failure.isBuildFailure ? "BAD_REQUEST" : "INTERNAL", failure.failure.message, failure.failure.remediation, {
2076
+ reason: failure.failure.code,
2077
+ deploymentId: status.deploymentId,
2078
+ nextAction: failure.nextAction,
2079
+ ...status.failure.path !== void 0 && { path: status.failure.path }
2080
+ });
2081
+ }
2082
+ if (status.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${status.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
2083
+ if (status.state !== "ready") throw new CliError("INTERNAL", "Prototype ingestion is still processing.", "Check this deployment status, then resume the same source and client token; do not reserve a second publication.", {
2084
+ reason: "INGESTION_PENDING",
2085
+ state: status.state,
2086
+ processedFiles: String(status.processedFiles),
2087
+ deploymentId: status.deploymentId
2088
+ });
1965
2089
  };
1966
2090
  const executePublish = async (remote, artifacts, input) => {
1967
2091
  const progress = { deploymentId: null };
@@ -1973,9 +2097,7 @@ const executePublish = async (remote, artifacts, input) => {
1973
2097
  canvasId: input.canvasId,
1974
2098
  deploymentId: created.deploymentId
1975
2099
  }, PUBLISH_WAIT_MS);
1976
- requireSuccessfulIngestion(status);
1977
- if (status.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${created.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
1978
- if (status.state !== "ready") throw new Error("prototype ingestion is still running");
2100
+ requireReadyPublication(status);
1979
2101
  const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[0], {
1980
2102
  canvasId: input.canvasId,
1981
2103
  deploymentId: created.deploymentId,
@@ -1987,12 +2109,21 @@ const executePublish = async (remote, artifacts, input) => {
1987
2109
  fileCount: status.fileCount,
1988
2110
  totalBytes: status.totalBytes,
1989
2111
  alreadyExists: created.alreadyExists,
1990
- next: [attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
2112
+ warnings: prototypePublicationWarnings(status),
2113
+ next: [attached.data.canvasUrl ?? attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
1991
2114
  };
1992
2115
  } catch (error) {
1993
2116
  if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
1994
2117
  if (progress.deploymentId === null) throw error;
1995
- throw new PartialBatchError(`Prototype deployment ${progress.deploymentId} was created, but publishing did not complete.`, `Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`);
2118
+ throw new PartialBatchError(error instanceof CliError ? error.message : `Prototype deployment ${progress.deploymentId} has no confirmed completion.`, `${error instanceof CliError ? `${error.remediation} ` : ""}Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`, {
2119
+ code: error instanceof CliError ? error.code : "INTERNAL",
2120
+ fields: {
2121
+ ...error instanceof CliError && error.fields,
2122
+ canvasId: input.canvasId,
2123
+ deploymentId: progress.deploymentId,
2124
+ clientToken: input.clientToken
2125
+ }
2126
+ });
1996
2127
  }
1997
2128
  };
1998
2129
  const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
@@ -2138,7 +2269,7 @@ const mutationStatus = async (remote, input) => {
2138
2269
  kind: "canvas-mutation",
2139
2270
  state: "committed",
2140
2271
  receipt: canvasWriteReceipt(found.result, operation.fingerprint),
2141
- affected: boundedOperationPage(affectedEntries(found.result), offset, limit)
2272
+ affected: boundedResultPage(affectedEntries(found.result), offset, limit)
2142
2273
  };
2143
2274
  };
2144
2275
  const renderStatus = async (remote, input) => {
@@ -2152,10 +2283,11 @@ const renderStatus = async (remote, input) => {
2152
2283
  state: job.state,
2153
2284
  phase: job.phase,
2154
2285
  requestedVersion: job.requestedVersion,
2286
+ attempt: job.attempt,
2155
2287
  target: job.target,
2156
2288
  sourceState: job.sourceState ?? null,
2157
2289
  evidence,
2158
- details: boundedOperationPage(renderEntries(job), offset, limit),
2290
+ details: boundedResultPage(renderEntries(job), offset, limit),
2159
2291
  failure: job.failure,
2160
2292
  pixelsDelivered: false,
2161
2293
  warnings: ["Status reports stored render evidence. It does not deliver or inspect the image."]
@@ -2194,7 +2326,7 @@ const readStatus = async (remote, input) => {
2194
2326
  const { operation, offset, limit } = input;
2195
2327
  switch (operation.kind) {
2196
2328
  case "canvas-asset":
2197
- boundedOperationPage([], offset, limit);
2329
+ boundedResultPage([], offset, limit);
2198
2330
  return assetStatus(remote, operation);
2199
2331
  case "canvas-mutation": return mutationStatus(remote, {
2200
2332
  ...input,
@@ -2225,7 +2357,7 @@ const readStatus = async (remote, input) => {
2225
2357
  });
2226
2358
  }
2227
2359
  case "prototype-deployment":
2228
- boundedOperationPage([], offset, limit);
2360
+ boundedResultPage([], offset, limit);
2229
2361
  return {
2230
2362
  kind: "prototype-deployment",
2231
2363
  operation,
@@ -2408,14 +2540,14 @@ const CONTENT_TYPES$1 = {
2408
2540
  ".woff": "font/woff",
2409
2541
  ".woff2": "font/woff2"
2410
2542
  };
2411
- const badFile = () => new CliError("BAD_REQUEST", "Choose one supported regular image or font file of at most 20 MiB.", "Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.");
2543
+ const badFile = () => new CliError("BAD_REQUEST", "Choose one supported regular image or font file.", "Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.");
2412
2544
  const readFile$1 = async (filePath) => {
2413
2545
  const contentType = CONTENT_TYPES$1[path.extname(filePath).toLowerCase()];
2414
2546
  if (contentType === void 0) throw badFile();
2415
2547
  const file = await open(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
2416
2548
  try {
2417
2549
  const stats = await file.stat();
2418
- if (!stats.isFile() || stats.size === 0 || stats.size > 20971520) throw badFile();
2550
+ if (!stats.isFile() || stats.size === 0) throw badFile();
2419
2551
  const buffer = Buffer.alloc(stats.size + 1);
2420
2552
  let bytes = 0;
2421
2553
  while (bytes < buffer.byteLength) {
@@ -2447,7 +2579,7 @@ const createCanvasAssetFileAdapter = (filePath) => ({ read: async () => {
2447
2579
 
2448
2580
  //#endregion
2449
2581
  //#region src/application/find-canvas.composite.ts
2450
- const MAX_PAGE_BYTES$1 = 48e3;
2582
+ const MAX_PAGE_BYTES = 48e3;
2451
2583
  const DISCOVERY_PROCEDURES = ["canvas.list", "organisation.list"];
2452
2584
  const readItems = async (remote, input) => {
2453
2585
  const [canvasValue, teamValue] = await Promise.all([remote.query(DISCOVERY_PROCEDURES[0], {
@@ -2496,7 +2628,7 @@ const boundedItems = (items) => {
2496
2628
  let bytes = 2;
2497
2629
  for (const entry of items) {
2498
2630
  const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
2499
- if (bytes + size > MAX_PAGE_BYTES$1) break;
2631
+ if (bytes + size > MAX_PAGE_BYTES) break;
2500
2632
  selected.push(entry);
2501
2633
  bytes += size;
2502
2634
  }
@@ -2538,6 +2670,14 @@ const createFindCanvasComposite = (remote) => ({ execute: async (input) => {
2538
2670
  //#endregion
2539
2671
  //#region src/application/canvas-preparation.use-case.ts
2540
2672
  const POLL_MS = 250;
2673
+ const readPreparation = async (remote, jobId) => {
2674
+ try {
2675
+ return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
2676
+ } catch (error) {
2677
+ if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
2678
+ return null;
2679
+ }
2680
+ };
2541
2681
  const waitForPreparation = async (remote, initial, waitMs) => {
2542
2682
  const deadline = Date.now() + waitMs;
2543
2683
  let job = initial;
@@ -2545,7 +2685,9 @@ const waitForPreparation = async (remote, initial, waitMs) => {
2545
2685
  const remaining = deadline - Date.now();
2546
2686
  if (remaining <= 0) break;
2547
2687
  await setTimeout$1(Math.min(POLL_MS, remaining));
2548
- job = getCanvasPreparationOutputSchema.parse(await remote.query("canvas.render.preparation.get", { jobId: initial.id })).job;
2688
+ const status = await readPreparation(remote, initial.id);
2689
+ if (status === null) return job;
2690
+ job = getCanvasPreparationOutputSchema.parse(status.value).job;
2549
2691
  if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
2550
2692
  }
2551
2693
  return job;
@@ -2589,7 +2731,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
2589
2731
  const request = applyCanvasOperationsInputSchema.parse({
2590
2732
  canvasId: job.canvasId,
2591
2733
  mutationId: input.clientToken,
2592
- documentFormatVersion: 5,
2734
+ documentFormatVersion: 11,
2593
2735
  baseVersion: input.baseVersion,
2594
2736
  operations: job.result.operations,
2595
2737
  requestContext: {
@@ -2681,8 +2823,7 @@ const projectCanvasEditableHtml = (document, rootNodeId) => {
2681
2823
  const seen = /* @__PURE__ */ new Set();
2682
2824
  const opaqueNodeIds = [];
2683
2825
  const childrenByParent = canvasChildrenByParent(document);
2684
- const visit = (nodeId, depth) => {
2685
- if (depth > CANVAS_HTML_LIMITS.depth || seen.size >= CANVAS_HTML_LIMITS.nodes) return fail("This editable subtree exceeds the depth or node budget. Read a smaller root.");
2826
+ const visit = (nodeId) => {
2686
2827
  if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
2687
2828
  seen.add(nodeId);
2688
2829
  const node = requireCanvasNode(document, nodeId);
@@ -2702,16 +2843,14 @@ const projectCanvasEditableHtml = (document, rootNodeId) => {
2702
2843
  opaque: isOpaque,
2703
2844
  styles,
2704
2845
  text: isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
2705
- children: isOpaque ? [] : children.map((id) => visit(id, depth + 1))
2846
+ children: isOpaque ? [] : children.map((id) => visit(id))
2706
2847
  };
2707
2848
  };
2708
- const root = visit(rootNodeId, 0);
2709
- const html = serialize$1(root);
2710
- if (html.length > CANVAS_HTML_LIMITS.characters) return fail("This editable subtree exceeds the inline HTML budget. Read a smaller root.");
2849
+ const root = visit(rootNodeId);
2711
2850
  return {
2712
2851
  projectionVersion: 1,
2713
2852
  root,
2714
- html,
2853
+ html: serialize$1(root),
2715
2854
  opaqueNodeIds
2716
2855
  };
2717
2856
  };
@@ -2721,17 +2860,27 @@ const elements = (children) => children.flatMap((child) => {
2721
2860
  return fail("Container content must contain identified elements; text belongs inside its retained span.");
2722
2861
  });
2723
2862
  const canvasEditableHtmlFragment = (html) => {
2724
- if (html.length > CANVAS_HTML_LIMITS.characters) return fail("The submitted HTML exceeds the inline budget.");
2725
- return parseFragment(html, {
2863
+ const fragment = parseFragment(html, {
2726
2864
  sourceCodeLocationInfo: true,
2727
2865
  onParseError: (error) => fail(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
2728
2866
  });
2867
+ const pending = [fragment];
2868
+ while (pending.length > 0) {
2869
+ const parent = pending.pop();
2870
+ if (parent === void 0) break;
2871
+ parent.childNodes = parent.childNodes.filter((child) => !("tagName" in child) || canRetainCanvasHtmlElement(child.tagName));
2872
+ const children = parent.childNodes.filter((child) => "tagName" in child);
2873
+ for (const child of children) {
2874
+ child.attrs = child.attrs.filter((attribute) => canRetainCanvasHtmlAttribute(attribute.name, attribute.value));
2875
+ pending.push(child);
2876
+ }
2877
+ }
2878
+ return fragment;
2729
2879
  };
2730
2880
  const parseCanvasEditableHtml = (html) => {
2731
2881
  const fragment = canvasEditableHtmlFragment(html);
2732
2882
  const seen = /* @__PURE__ */ new Set();
2733
- const visit = (element, depth) => {
2734
- if (depth > CANVAS_HTML_LIMITS.depth || seen.size >= CANVAS_HTML_LIMITS.nodes) return fail("The submitted HTML exceeds the depth or node budget.");
2883
+ const visit = (element) => {
2735
2884
  if (element.tagName !== "div" && element.tagName !== "span") return fail(`Unsupported retained element: ${element.tagName}.`);
2736
2885
  const attrs = Object.fromEntries(element.attrs.map((attr) => {
2737
2886
  if (!ATTRIBUTES.has(attr.name) || attr.namespace !== void 0) return fail(`Unsupported attribute: ${attr.name}.`);
@@ -2755,13 +2904,13 @@ const parseCanvasEditableHtml = (html) => {
2755
2904
  opaque: marker === "true",
2756
2905
  text,
2757
2906
  styles: styleValues(attrs["style"] ?? ""),
2758
- children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child, depth + 1))
2907
+ children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child))
2759
2908
  };
2760
2909
  };
2761
2910
  const roots = elements(fragment.childNodes);
2762
2911
  const root = roots[0];
2763
2912
  if (root === void 0 || roots.length !== 1) return fail("An editable update must contain exactly its original root.");
2764
- return visit(root, 0);
2913
+ return visit(root);
2765
2914
  };
2766
2915
 
2767
2916
  //#endregion
@@ -2937,18 +3086,6 @@ const offsetOf = (input, snapshot, digest) => {
2937
3086
  if (cursor.version !== snapshot.version) throw new CliError("CONFLICT", "The canvas changed between resource pages.", "Restart the read at the current revision.");
2938
3087
  return cursor.offset;
2939
3088
  };
2940
- const boundedPage = (envelope, all, offset, limit) => {
2941
- const resources = [];
2942
- const candidates = all.slice(offset, offset + limit);
2943
- for (const entry of candidates) {
2944
- const candidate = envelope([...resources, entry]);
2945
- if (Buffer.byteLength(JSON.stringify(candidate)) > MAX_RESULT_BYTES) break;
2946
- resources.push(entry);
2947
- }
2948
- const result = envelope(resources);
2949
- if (resources.length === 0 && offset < all.length || Buffer.byteLength(JSON.stringify(result)) > MAX_RESULT_BYTES) throw new CliError("BAD_REQUEST", "One resource or scope exceeds the bounded read budget.", "Choose a smaller selection or inspect the resource in the editor.");
2950
- return result;
2951
- };
2952
3089
  const readCanvasResources = (input, snapshot) => {
2953
3090
  const scope = resolveCanvasReference(snapshot.reference, snapshot.scene);
2954
3091
  if (!scope.ok) throw new CliError("NOT_FOUND", "The requested canvas scope is unavailable.", "Copy a current page or selection link; do not broaden the request.");
@@ -2985,18 +3122,12 @@ const readCanvasResources = (input, snapshot) => {
2985
3122
  ]
2986
3123
  };
2987
3124
  };
2988
- return boundedPage(envelope, all, offset, input.limit);
3125
+ const budget = MAX_RESULT_BYTES - Buffer.byteLength(JSON.stringify(envelope([])));
3126
+ return envelope(boundedResultPage(all, offset, input.limit, budget).entries);
2989
3127
  };
2990
3128
 
2991
3129
  //#endregion
2992
3130
  //#region src/application/canvas-transcript-page.use-case.ts
2993
- const MAX_PAGE_BYTES = 48e3;
2994
- const boundedCues = (offered) => {
2995
- const cues = [...offered];
2996
- while (Buffer.byteLength(JSON.stringify(cues), "utf8") > MAX_PAGE_BYTES) cues.pop();
2997
- if (cues.length === 0 && offered.length > 0) throw new CliError("BAD_REQUEST", "One transcript cue exceeds the inline evidence budget.", "Read this source through the comprehensive transcript CLI; no partial cue was returned.");
2998
- return cues;
2999
- };
3000
3131
  const canvasTranscriptPage = (transcript, request, scope) => {
3001
3132
  if (transcript.state !== "ready") {
3002
3133
  if (request.cursor !== void 0) throw new CliError("CONFLICT", "The transcript changed during pagination.", "Restart the read.");
@@ -3013,7 +3144,7 @@ const canvasTranscriptPage = (transcript, request, scope) => {
3013
3144
  const matching = transcript.cues.filter((cue) => cue.endMs >= request.startMs && (request.endMs === void 0 || cue.startMs < request.endMs));
3014
3145
  const offset = held?.offset ?? 0;
3015
3146
  if (offset > matching.length) throw new CliError("BAD_REQUEST", "Transcript cursor offset is out of range.", "Restart the read.");
3016
- const cues = boundedCues(matching.slice(offset, offset + request.limit));
3147
+ const cues = boundedResultPage(matching, offset, request.limit).entries;
3017
3148
  const nextOffset = offset + cues.length;
3018
3149
  return {
3019
3150
  state: "ready",
@@ -3233,7 +3364,7 @@ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (in
3233
3364
  };
3234
3365
  const request = applyCanvasOperationsInputSchema.safeParse({
3235
3366
  canvasId,
3236
- documentFormatVersion: 5,
3367
+ documentFormatVersion: 11,
3237
3368
  mutationId: input.clientToken,
3238
3369
  baseVersion: input.baseVersion,
3239
3370
  operations,
@@ -3371,30 +3502,25 @@ const EMPTY_COMPILATION = {
3371
3502
  const finishCanvasHtmlReconciliation = (document, prepared, compiled = EMPTY_COMPILATION) => {
3372
3503
  const staged = stagedInsertions(document, compiled, prepared);
3373
3504
  const root = boundRoot(prepared.root, compiled.idMap);
3374
- const operations = [
3505
+ return [
3375
3506
  ...prepared.operations,
3376
3507
  ...compiled.operations,
3377
3508
  ...canvasHtmlStructureOperations(staged, root, prepared.removed)
3378
3509
  ];
3379
- if (operations.length > 1e3) return invalid$2("The complete edit exceeds the canonical operation budget.");
3380
- return operations;
3381
3510
  };
3382
3511
 
3383
3512
  //#endregion
3384
3513
  //#region src/application/canvas-html-update-source.use-case.ts
3385
- const MAX_NODES = CANVAS_HTML_LIMITS.nodes;
3386
3514
  const identity = (element) => element.attrs.find((attribute) => attribute.name === "data-enhance-id")?.value;
3387
3515
  const invalid$1 = (message) => {
3388
3516
  throw new CliError("BAD_REQUEST", message, "Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.");
3389
3517
  };
3390
- const collectElements = (children, depth = 0) => {
3391
- if (depth > CANVAS_HTML_LIMITS.depth) return invalid$1("The submitted HTML exceeds the depth budget.");
3392
- return children.flatMap((child) => "tagName" in child ? [child, ...collectElements(child.childNodes, depth + 1)] : []);
3518
+ const collectElements = (children) => {
3519
+ return children.flatMap((child) => "tagName" in child ? [child, ...collectElements(child.childNodes)] : []);
3393
3520
  };
3394
3521
  const parseCanvasHtmlUpdate = (html) => {
3395
3522
  const fragment = canvasEditableHtmlFragment(html);
3396
3523
  const elements = collectElements(fragment.childNodes);
3397
- if (elements.length > MAX_NODES) return invalid$1("The HTML exceeds the node budget.");
3398
3524
  const reservedIds = new Set(elements.map((element) => identity(element)));
3399
3525
  const fragments = [];
3400
3526
  const visit = (element, parentId) => {
@@ -3405,7 +3531,6 @@ const parseCanvasHtmlUpdate = (html) => {
3405
3531
  };
3406
3532
  if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
3407
3533
  if ([element, ...collectElements(element.childNodes)].some((node) => node.attrs.some((attribute) => ["data-enhance-id", "data-enhance-opaque"].includes(attribute.name)))) return invalid$1("A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.");
3408
- if (fragments.length >= CANVAS_HTML_LIMITS.newSubtrees) return invalid$1("One update can compile at most 32 new subtrees.");
3409
3534
  let key = `new_${String(fragments.length)}`;
3410
3535
  while (reservedIds.has(key)) key = `_${key}`;
3411
3536
  reservedIds.add(key);
@@ -3705,15 +3830,12 @@ const targetFailure = (error, target) => {
3705
3830
  };
3706
3831
  };
3707
3832
  const plannedTargets = (request, clientTokens) => {
3708
- const unassigned = request.targets.filter((target) => target.maxOutputPixels === void 0).length;
3709
- const assignedPixels = request.targets.reduce((sum, target) => sum + (target.maxOutputPixels ?? 0), 0);
3710
- const sharedLimit = Math.floor((RENDER_MAX_OUTPUT_PIXELS - assignedPixels) / Math.max(unassigned, 1));
3711
3833
  return request.targets.map(({ id, maxOutputPixels, ...target }) => {
3712
3834
  const retryClientToken = clientTokens.get(id);
3713
3835
  if (retryClientToken === void 0) throw new TypeError("A batch target has no native render request key.");
3714
3836
  return {
3715
3837
  id,
3716
- maxOutputPixels: maxOutputPixels ?? sharedLimit,
3838
+ maxOutputPixels,
3717
3839
  input: canvasRenderRequest({
3718
3840
  ...request,
3719
3841
  ...target
@@ -3730,34 +3852,24 @@ const renderTarget = async (render, target) => {
3730
3852
  const file = canvasRenderFileSchema.safeParse(returned);
3731
3853
  if (!file.success) return canvasRenderPendingSchema.parse(returned);
3732
3854
  const pixels = file.data.width * file.data.height;
3733
- if (!Number.isSafeInteger(pixels) || pixels <= 0 || pixels > target.maxOutputPixels) throw new CliError("INTERNAL", "The render exceeded its allocated pixel budget.", "Update the API and renderer together, then retry.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
3855
+ if (!Number.isSafeInteger(pixels) || pixels <= 0 || target.maxOutputPixels !== void 0 && pixels > target.maxOutputPixels) throw new CliError("INTERNAL", "The render exceeded its allocated pixel budget.", "Update the API and renderer together, then retry.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
3734
3856
  return file.data;
3735
3857
  } catch (error) {
3736
3858
  return targetFailure(error, target);
3737
3859
  }
3738
3860
  };
3739
- const NOT_STARTED = {
3740
- state: "not_started",
3741
- error: {
3742
- code: "INTERNAL",
3743
- message: "Earlier work could not enforce the render budget.",
3744
- remediation: "Update the API and renderer together before retrying this batch."
3745
- }
3746
- };
3747
3861
  const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered, clientTokens) => {
3748
3862
  const request = canvasRenderBatchRequestSchema.parse(offered);
3749
3863
  const targets = plannedTargets(request, clientTokens);
3750
3864
  const results = [];
3751
3865
  let renderedPixels = 0;
3752
- let isIncompatible = false;
3753
3866
  for (const target of targets) {
3754
- const outcome = isIncompatible ? NOT_STARTED : await renderTarget(render, target);
3867
+ const outcome = await renderTarget(render, target);
3755
3868
  if ("jobId" in outcome) renderedPixels += outcome.width * outcome.height;
3756
- if ("error" in outcome && outcome.error.fields?.["reason"] === "RENDER_BUDGET_UNSUPPORTED") isIncompatible = true;
3757
3869
  results.push({
3758
3870
  id: target.id,
3759
3871
  target: target.input.target,
3760
- maxOutputPixels: target.maxOutputPixels,
3872
+ ...target.maxOutputPixels !== void 0 && { maxOutputPixels: target.maxOutputPixels },
3761
3873
  outcome
3762
3874
  });
3763
3875
  }
@@ -3768,7 +3880,6 @@ const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered,
3768
3880
  canvasId: first.input.canvasId,
3769
3881
  requestedVersion: request.expectedVersion,
3770
3882
  complete: results.every((result) => "jobId" in result.outcome),
3771
- maxOutputPixels: RENDER_MAX_OUTPUT_PIXELS,
3772
3883
  renderedPixels,
3773
3884
  results,
3774
3885
  next: ["Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken."]
@@ -3831,13 +3942,17 @@ const hashingTransform = (source, completed) => {
3831
3942
  callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
3832
3943
  return;
3833
3944
  }
3834
- completed({
3835
- path: source.path,
3836
- contentType: source.contentType,
3837
- bytes,
3838
- sha256: hash.digest("hex")
3839
- });
3840
- callback();
3945
+ try {
3946
+ completed({
3947
+ path: source.path,
3948
+ contentType: source.contentType,
3949
+ bytes,
3950
+ sha256: hash.digest("hex")
3951
+ });
3952
+ callback();
3953
+ } catch (error) {
3954
+ callback(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype manifest failed"));
3955
+ }
3841
3956
  }
3842
3957
  });
3843
3958
  };
@@ -3848,7 +3963,7 @@ const addManifest = (input) => {
3848
3963
  files: input.files.map((file) => input.completed.get(file.path))
3849
3964
  });
3850
3965
  const body = Buffer.from(JSON.stringify(manifest), "utf8");
3851
- if (body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
3966
+ if (input.limits.manifestBytes !== void 0 && body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
3852
3967
  input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
3853
3968
  mtime: NORMALIZED_MTIME,
3854
3969
  mode: REGULAR_FILE_MODE,
@@ -3874,7 +3989,12 @@ const addPrototypeFile = (zip, input, complete) => {
3874
3989
  ...options,
3875
3990
  size: source.bytes
3876
3991
  }, (callback) => {
3877
- callback(null, createReadStream(source.absolutePath).pipe(hashingTransform(source, complete)));
3992
+ const stream = createReadStream(source.absolutePath);
3993
+ const hashing = hashingTransform(source, complete);
3994
+ stream.on("error", (error) => hashing.destroy(error));
3995
+ hashing.on("error", (error) => zip.emit("error", error));
3996
+ hashing.on("close", () => stream.destroy());
3997
+ callback(null, stream.pipe(hashing));
3878
3998
  });
3879
3999
  return;
3880
4000
  }
@@ -3887,14 +4007,35 @@ const addPrototypeFile = (zip, input, complete) => {
3887
4007
  sha256: createHash("sha256").update(content).digest("hex")
3888
4008
  });
3889
4009
  };
3890
- const addPrototypeFiles = async (zip, files, complete) => {
3891
- for (let offset = 0; offset < files.length; offset += READ_BATCH_SIZE) {
3892
- const batch = await Promise.all(files.slice(offset, offset + READ_BATCH_SIZE).map(async (source) => ({
3893
- source,
3894
- content: source.bytes <= SMALL_FILE_BYTES ? await readFile(source.absolutePath) : null
3895
- })));
3896
- for (const input of batch) addPrototypeFile(zip, input, complete);
4010
+ const addAvailableFiles = (zip, batch, complete) => {
4011
+ const included = [];
4012
+ for (const available of batch) {
4013
+ if (available === null) continue;
4014
+ addPrototypeFile(zip, available, complete);
4015
+ included.push(available.source);
3897
4016
  }
4017
+ return included;
4018
+ };
4019
+ const addPrototypeFiles = async (zip, input, complete) => {
4020
+ const included = [];
4021
+ for (let offset = 0; offset < input.files.length; offset += READ_BATCH_SIZE) {
4022
+ const batch = await Promise.all(input.files.slice(offset, offset + READ_BATCH_SIZE).map(async (source) => {
4023
+ try {
4024
+ const content = source.bytes <= SMALL_FILE_BYTES ? await readFile(source.absolutePath) : null;
4025
+ if (content === null) await access(source.absolutePath, constants.R_OK);
4026
+ if (content !== null && content.byteLength !== source.bytes) throw new Error(`prototype file ${source.path} changed while it was packaged`);
4027
+ return {
4028
+ source,
4029
+ content
4030
+ };
4031
+ } catch (error) {
4032
+ if (source.path === input.entryPath) throw error;
4033
+ return null;
4034
+ }
4035
+ }));
4036
+ included.push(...addAvailableFiles(zip, batch, complete));
4037
+ }
4038
+ return included;
3898
4039
  };
3899
4040
  const createPrototypeZipAdapter = async (input) => {
3900
4041
  const zip = new ZipFile();
@@ -3907,16 +4048,22 @@ const createPrototypeZipAdapter = async (input) => {
3907
4048
  const packaged = { manifest: null };
3908
4049
  const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
3909
4050
  zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
3910
- const complete = (file) => {
3911
- completed.set(file.path, file);
3912
- if (packaged.manifest === null && completed.size === input.files.length) packaged.manifest = addManifest({
4051
+ let included = null;
4052
+ const finish = () => {
4053
+ if (included !== null && packaged.manifest === null && completed.size === included.length) packaged.manifest = addManifest({
3913
4054
  zip,
3914
4055
  completed,
3915
- ...input
4056
+ ...input,
4057
+ files: included
3916
4058
  });
3917
4059
  };
4060
+ const complete = (file) => {
4061
+ completed.set(file.path, file);
4062
+ finish();
4063
+ };
3918
4064
  try {
3919
- await addPrototypeFiles(zip, input.files, complete);
4065
+ included = await addPrototypeFiles(zip, input, complete);
4066
+ finish();
3920
4067
  } catch (error) {
3921
4068
  hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed"));
3922
4069
  await output;
@@ -3928,7 +4075,8 @@ const createPrototypeZipAdapter = async (input) => {
3928
4075
  return {
3929
4076
  manifest: packaged.manifest,
3930
4077
  bytes: artifactStats.size,
3931
- sha256: hash.digest("hex")
4078
+ sha256: hash.digest("hex"),
4079
+ unavailableFileCount: input.files.length - completed.size
3932
4080
  };
3933
4081
  };
3934
4082
 
@@ -3975,9 +4123,13 @@ const validatePath = (relativePath, limits) => {
3975
4123
  if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
3976
4124
  if (byteLength(relativePath) > limits.pathBytes) throw badRequest(`The prototype path ${relativePath} is too long.`, `Shorten it to at most ${String(limits.pathBytes)} UTF-8 bytes.`);
3977
4125
  };
3978
- const walk = async (root, directory, ancestors, limits) => {
4126
+ const walk = async (root, directory, ancestors, options) => {
4127
+ const { limits, unavailable } = options;
3979
4128
  const resolvedDirectory = await realpath(directory);
3980
- if (ancestors.has(resolvedDirectory)) throw badRequest(`Cannot package the circular directory link at ${directory}.`, "Pass a directory tree that can be read once from top to bottom.");
4129
+ if (ancestors.has(resolvedDirectory)) {
4130
+ unavailable();
4131
+ return [];
4132
+ }
3981
4133
  const nextAncestors = new Set(ancestors).add(resolvedDirectory);
3982
4134
  const { readdir } = await import("node:fs/promises");
3983
4135
  const entries = await readdir(directory, { withFileTypes: true });
@@ -3987,10 +4139,17 @@ const walk = async (root, directory, ancestors, limits) => {
3987
4139
  const absolutePath = path.join(directory, entry.name);
3988
4140
  const stats = await statsFor(absolutePath);
3989
4141
  if (stats?.isDirectory() === true) {
3990
- files.push(...await walk(root, absolutePath, nextAncestors, limits));
4142
+ try {
4143
+ files.push(...await walk(root, absolutePath, nextAncestors, options));
4144
+ } catch {
4145
+ unavailable();
4146
+ }
4147
+ continue;
4148
+ }
4149
+ if (stats?.isFile() !== true) {
4150
+ unavailable();
3991
4151
  continue;
3992
4152
  }
3993
- if (stats?.isFile() !== true) throw badRequest(`Cannot read ${absolutePath} as a prototype file.`, "Pass a directory containing only regular files and directory links.");
3994
4153
  const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
3995
4154
  validatePath(relativePath, limits);
3996
4155
  files.push({
@@ -4004,7 +4163,7 @@ const walk = async (root, directory, ancestors, limits) => {
4004
4163
  };
4005
4164
  const validateSources = (files, entryPath, limits) => {
4006
4165
  if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
4007
- if (files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
4166
+ if (limits.fileCount !== void 0 && files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
4008
4167
  const folded = /* @__PURE__ */ new Set();
4009
4168
  let totalBytes = 0;
4010
4169
  for (const file of files) {
@@ -4013,12 +4172,20 @@ const validateSources = (files, entryPath, limits) => {
4013
4172
  folded.add(key);
4014
4173
  if (file.bytes > limits.fileBytes) throw badRequest(`The prototype file ${file.path} is too large.`, `This environment accepts ${String(limits.fileBytes)} bytes in one runtime file.`);
4015
4174
  totalBytes += file.bytes;
4016
- if (totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
4175
+ if (limits.expandedBytes !== void 0 && totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
4017
4176
  }
4018
4177
  const entry = files.find((file) => file.path === entryPath);
4019
4178
  if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
4020
4179
  if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
4021
4180
  };
4181
+ const reportPackaging = (fileCount, unavailableFileCount) => {
4182
+ try {
4183
+ performance$1.mark("enhance.prototype.packaging", { detail: {
4184
+ fileCount,
4185
+ unavailableFileCount
4186
+ } });
4187
+ } catch {}
4188
+ };
4022
4189
  const packageArtifact = async (input) => {
4023
4190
  const root = path.resolve(input.directory);
4024
4191
  const rootStats = await statsFor(root);
@@ -4026,7 +4193,13 @@ const packageArtifact = async (input) => {
4026
4193
  if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
4027
4194
  const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
4028
4195
  validatePath(entryPath, input.limits);
4029
- const files = await walk(root, root, /* @__PURE__ */ new Set(), input.limits);
4196
+ let unavailableFileCount = 0;
4197
+ const files = await walk(root, root, /* @__PURE__ */ new Set(), {
4198
+ limits: input.limits,
4199
+ unavailable: () => {
4200
+ unavailableFileCount += 1;
4201
+ }
4202
+ });
4030
4203
  validateSources(files, entryPath, input.limits);
4031
4204
  const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
4032
4205
  const artifactPath = path.join(tempDirectory, "artifact.zip");
@@ -4037,6 +4210,8 @@ const packageArtifact = async (input) => {
4037
4210
  entryPath,
4038
4211
  limits: input.limits
4039
4212
  });
4213
+ unavailableFileCount += packaged.unavailableFileCount;
4214
+ reportPackaging(packaged.manifest.files.length, unavailableFileCount);
4040
4215
  return {
4041
4216
  identity: {
4042
4217
  protocolVersion: 1,
@@ -4315,6 +4490,27 @@ const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
4315
4490
 
4316
4491
  //#endregion
4317
4492
  //#region src/infrastructure/environment-profile.lib.ts
4493
+ const CLI_DEVELOPMENT_PROFILE = {
4494
+ apiUrl: "https://api.enhance3.karunalabs.ai",
4495
+ commandName: "enhance-dev",
4496
+ configDirectoryName: "enhance-development",
4497
+ environment: "development",
4498
+ mcpServiceName: "enhance-dev-mcp"
4499
+ };
4500
+ const CLI_PRODUCTION_PROFILE = {
4501
+ apiUrl: "https://api.enhancelabs.ai",
4502
+ commandName: "enhance",
4503
+ configDirectoryName: "enhance",
4504
+ environment: "production",
4505
+ mcpServiceName: "enhance-mcp"
4506
+ };
4507
+ const normalizedApi = (value) => URL.canParse(value) ? new URL(value).href.replace(/\/+$/u, "") : value;
4508
+ const rejectCredentialCollision = (apiUrl, directory, homeDirectory, production) => {
4509
+ const origin = URL.canParse(apiUrl) ? new URL(apiUrl).origin : null;
4510
+ const resolved = path.resolve(directory);
4511
+ const development = CLI_DEVELOPMENT_PROFILE;
4512
+ if (origin === new URL(development.apiUrl).origin && resolved === path.resolve(homeDirectory, ".config", production.configDirectoryName) || origin === new URL(production.apiUrl).origin && resolved === path.resolve(homeDirectory, ".config", development.configDirectoryName)) throw new TypeError("Enhance cannot share credentials between production and development. Use Enhance Development (enhance-dev-mcp) with ~/.config/enhance-development, then reconnect production separately.");
4513
+ };
4318
4514
  const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
4319
4515
  const resolveCliConfig = (variables, homeDirectory, release) => {
4320
4516
  const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
@@ -4323,9 +4519,9 @@ const resolveCliConfig = (variables, homeDirectory, release) => {
4323
4519
  const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
4324
4520
  const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
4325
4521
  if (release.environment === "development") {
4326
- if (requestedApi !== void 0 && requestedApi !== release.apiUrl) throw new TypeError(`Enhance development cannot use ${requestedApi}`);
4522
+ if (requestedApi !== void 0 && normalizedApi(requestedApi) !== normalizedApi(release.apiUrl)) throw new TypeError("Enhance development cannot use this API. Use the bundled development endpoint.");
4327
4523
  if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
4328
- }
4524
+ } else rejectCredentialCollision(requestedApi ?? release.apiUrl, requestedConfigDirectory ?? expectedConfigDirectory, homeDirectory, release);
4329
4525
  return {
4330
4526
  apiUrl: requestedApi ?? release.apiUrl,
4331
4527
  commandName: release.commandName,
@@ -4356,14 +4552,7 @@ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables
4356
4552
 
4357
4553
  //#endregion
4358
4554
  //#region src/infrastructure/environment.config.ts
4359
- const releaseProfile = {
4360
- apiUrl: "https://api.enhancelabs.ai",
4361
- commandName: "enhance",
4362
- configDirectoryName: "enhance",
4363
- environment: "production",
4364
- mcpServiceName: "enhance-mcp"
4365
- };
4366
- const readCliEnvironment = () => resolveCliConfig(process.env, homedir(), releaseProfile);
4555
+ const readCliEnvironment = () => resolveCliConfig(process.env, homedir(), CLI_PRODUCTION_PROFILE);
4367
4556
  const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
4368
4557
  const readLocalMcpEnvironment = () => {
4369
4558
  const profile = z.enum(["legacy", "canvas"]).default("legacy").parse(process.env["ENHANCE_MCP_PROFILE"]);
@@ -4379,6 +4568,7 @@ const readLocalMcpEnvironment = () => {
4379
4568
 
4380
4569
  //#endregion
4381
4570
  //#region src/infrastructure/http-remote.adapter.ts
4571
+ const DIRECT_CLIENT = { path: "direct_cli" };
4382
4572
  const HEALTH_TIMEOUT_MS = 4e3;
4383
4573
  const NOT_FOUND_STATUS = 404;
4384
4574
  const FORBIDDEN_STATUS = 403;
@@ -4405,13 +4595,14 @@ const fetchApi = async (input, init) => {
4405
4595
  if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
4406
4596
  return response;
4407
4597
  };
4408
- const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
4598
+ const clientFor = (apiUrl, token, idempotencyKey = null, clientMetadata = DIRECT_CLIENT) => createTRPCUntypedClient({ links: [httpLink({
4409
4599
  url: `${apiUrl}/trpc`,
4410
4600
  fetch: async (input, init) => fetchApi(input, {
4411
4601
  ...init,
4412
4602
  signal: init?.signal ?? null
4413
4603
  }),
4414
4604
  headers: {
4605
+ [AGENT_CLIENT_HEADER]: JSON.stringify(clientMetadata),
4415
4606
  ...token !== null && { authorization: `Bearer ${token}` },
4416
4607
  ...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
4417
4608
  }
@@ -4475,32 +4666,33 @@ const health = async (apiUrl) => {
4475
4666
  };
4476
4667
  }
4477
4668
  };
4478
- const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
4669
+ const upload = async (input) => {
4670
+ const isStreaming = !(input.body instanceof Uint8Array);
4671
+ const body = isStreaming ? Readable.toWeb(input.body) : input.body;
4672
+ const request = {
4673
+ method: "PUT",
4674
+ headers: input.headers,
4675
+ body,
4676
+ ...isStreaming && { duplex: "half" }
4677
+ };
4678
+ const response = await fetch(input.url, request);
4679
+ if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
4680
+ const etag = response.headers.get("etag");
4681
+ if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
4682
+ return etag.replaceAll("\"", "");
4683
+ };
4684
+ const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey, clientMetadata = DIRECT_CLIENT) => {
4479
4685
  const normalized = apiUrl.replace(/\/$/, "");
4480
4686
  return {
4481
4687
  authenticationConfig: async () => authenticationConfig(normalized),
4482
4688
  oauthMetadata,
4483
4689
  exchangeOauthCode,
4484
- query: async (path, input) => remoteRequest(async () => clientFor(normalized, await credentials.read()).query(path, input)),
4485
- queryWithToken: async (path, input, token) => remoteRequest(async () => clientFor(normalized, token).query(path, input)),
4486
- mutate: async (procedure, input) => remoteRequest(async () => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input)),
4487
- mutateWithToken: async (procedure, input, token) => remoteRequest(async () => clientFor(normalized, token).mutation(procedure, input)),
4690
+ query: async (path, input, options) => remoteRequest(async () => clientFor(normalized, await credentials.read(), null, clientMetadata).query(path, input, options)),
4691
+ queryWithToken: async (path, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).query(path, input)),
4692
+ mutate: async (procedure, input) => remoteRequest(async () => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input), clientMetadata).mutation(procedure, input)),
4693
+ mutateWithToken: async (procedure, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).mutation(procedure, input)),
4488
4694
  download,
4489
- upload: async (input) => {
4490
- const isStreaming = !(input.body instanceof Uint8Array);
4491
- const body = isStreaming ? Readable.toWeb(input.body) : input.body;
4492
- const request = {
4493
- method: "PUT",
4494
- headers: input.headers,
4495
- body,
4496
- ...isStreaming && { duplex: "half" }
4497
- };
4498
- const response = await fetch(input.url, request);
4499
- if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
4500
- const etag = response.headers.get("etag");
4501
- if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
4502
- return etag.replaceAll("\"", "");
4503
- },
4695
+ upload,
4504
4696
  health: async () => health(normalized)
4505
4697
  };
4506
4698
  };
@@ -4528,4 +4720,4 @@ const createMutationKeyAdapter = () => {
4528
4720
  };
4529
4721
 
4530
4722
  //#endregion
4531
- export { sceneAtVersion as _, readRemoteMcpEnvironment as a, createRenderCanvasComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, assertCanvasReferenceOperations as g, createEditCanvasComposite as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, fromCapabilityReference as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, createApplyCanvasComposite as v, createAuthUseCase as x, createCanvasActivityComposite as y };
4723
+ export { createAuthUseCase as S, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, createRenderCanvasComposite as x, createApplyCanvasComposite as y };