@enhance-eng/enhance 0.1.160 → 0.1.165

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,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import { $ as canvasRenderBatchRequestSchema, $n as wholeCanvasDocumentOutputSchema, $t as cliAuthConfigurationSchema, An as canvasRecordingPropsSchema, Ar as canvasAdditionalStyleSchema, At as hasCanvasReferenceScope, Bn as FRAME_KIND, Bt as getRecordingOutputSchema, Cn as canvasCssTypographyOwners, Cr as reserveCanvasAssetOutputSchema, D as encodeCanvasExchangeToken, Dn as canvasCaptureSchema, Dr as canvasRichTextValueOf, Dt as canvasReferenceNodeIds, E as decodeCanvasExchangeToken, Er as canvasRichTextOf, Et as assertCanvasReferenceNodes, F as canvasAssetImportOutputSchema, G as canvasApplyCapabilityInputSchema, Gn as TEXT_KIND, Gt as foldPrototypeArtifactPath, H as canvasCaptureCapabilityInputSchema, Hn as IMAGE_KIND, Ht as PROTOTYPE_ARTIFACT_MANIFEST_PATH, I as canvasArrangeCapabilityInputSchema, In as AGENT_CLIENT_HEADER, Ir as listCanvasesOutputSchema, J as canvasWriteHtmlCapabilityInputSchema, Jn as getCanvasMutationOutputSchema, Jt as prototypeArtifactManifestSchema, K as canvasReadCapabilityInputSchema, Kn as applyCanvasOperationsInputSchema, Kt as getPrototypeArtifactCapabilitiesOutputSchema, Mn as canvasReferencePageOf, Mr as canvasBlendModeSchema, Mt as PartialBatchError, N as canvasAssetImportCapabilityInputSchema, Nn as resolveCanvasReference, Nr as canvasPaintSchema, Nt as CliError, O as resolveCanvasSnapshot, On as canvasConversionMetadataSchema, Or as hasCanvasRichTextPaints, Pn as beginCanvasActivityOutputSchema, Pt as transcriptOutputSchema, Q as transcriptReadCapabilityInputSchema, R as canvasDuplicateCapabilityInputSchema, Rn as createCanvasPreparationOutputSchema, Sn as applyCanvasTypographyPatch, Sr as reserveCanvasAssetInputSchema, St as canvasMakeEditableCapabilityInputSchema, T as canvasSnapshotToken, Tn as canvasTextPropsWithContent, Tr as canvasImageAssetIdentityFromPath, Un as PAGE_KIND, Ut as attachPrototypeArtifactOutputSchema, Vn as GROUP_KIND, Wn as RECTANGLE_KIND, Wt as createPrototypeArtifactOutputSchema, X as prototypePublishCapabilityInputSchema, Xn as textOf, Xt as submitPrototypeArtifactOutputSchema, Y as commentAttentionCapabilityInputSchema, Yn as canvasLayoutWithoutCssProperties, Yt as prototypeArtifactPathSchema, Z as recordingSnapshotCapabilityInputSchema, Zn as mapCanvasFontSources, Zt as getMeOutputSchema, _t as canvasFindCursorSchema, ar as canvasRenderStateSchema, at as canvasRenderFileSchema, b as canvasPrototypeCapabilityInputSchema, br as canvasCssValue, bt as canvasInsertHtmlCapabilityInputSchema, cr as createCanvasRenderOutputSchema, ct as canvasOutlineCursorSchema, d as toRemoteError, dr as getCanvasRenderOutputSchema, dt as canvasUpdateHtmlCapabilityInputSchema, en as createAgentTokenOutputSchema, fr as canvasReadableSceneDocumentSchema, ft as canvasUpdateHtmlInputSchema, gr as canvasAxisStyleProperties, hr as canvasAuthoredStyleDeclarations, it as canvasRenderRequestSchema, j as operationStatusInputSchema, jn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, jr as CANVAS_BLEND_MODES, jt as parseCanvasReference, kn as canvasPrototypePropsSchema, kr as CANVAS_RICH_TEXT_STYLE_PROPERTIES, lr as createRecordingSnapshotOutputSchema, lt as canvasReadInputSchema, mt as canvasResourcesCursorSchema, nn as listOrganisationsOutputSchema, nr as createCanvasConversionOutputSchema, ot as canvasRemoveCapabilityInputSchema, pr as canvasSceneDocumentSchema, pt as canvasTranscriptCursorSchema, q as canvasRenderCapabilityInputSchema, qn as applyCanvasOperationsOutputSchema, qt as getPrototypePublishStatusOutputSchema, rr as getCanvasConversionOutputSchema, tr as canvasNodeStylePatchSchema, tt as canvasRenderPendingSchema, ur as downloadCanvasRenderOutputSchema, vt as canvasFindInputSchema, w as canvasExchangeDigest, wn as canvasTextChangeBetween, wr as canvasFontAssetIdentityFromPath, wt as canvasEditCapabilityInputSchema, xr as canvasAssetUploadOutputSchema, yr as canvasCssTokens, zn as getCanvasPreparationOutputSchema } from "./cli-output-identity.lib-DrfKWcGw.mjs";
2
+ import { $n as canvasTextPropsWithContent, $r as canvasLayoutPositionOf, $t as inSurfaceWords, A as recordingSnapshotCapabilityInputSchema, Ar as wholeCanvasDocumentOutputSchema, At as canvasSnapshotToken, Br as createRecordingSnapshotOutputSchema, Bt as canvasResourcesCursorSchema, Cn as submitPrototypeArtifactOutputSchema, Cr as applyCanvasOperationsInputSchema, D as canvasWriteHtmlCapabilityInputSchema, Dn as createAgentTokenOutputSchema, Dr as textOf, E as canvasRenderCapabilityInputSchema, En as cliAuthConfigurationSchema, Er as canvasLayoutWithoutCssProperties, F as canvasPrototypeCapabilityInputSchema, Ft as canvasReadInputSchema, Gt as hasCanvasReferenceScope, Hr as getCanvasRenderOutputSchema, Ht as canvasReferenceNodeIds, Ir as canvasRenderStateSchema, J as canvasDuplicateCapabilityInputSchema, Jt as callOf, K as canvasArrangeCapabilityInputSchema, Kr as canvasBoxSourceOf, Kt as parseCanvasReference, Lt as canvasUpdateHtmlCapabilityInputSchema, M as canvasCapturePageCapabilityInputSchema, Mr as canvasNodeStylePatchSchema, Mt as encodeCanvasExchangeToken, Nr as createCanvasConversionOutputSchema, Nt as resolveCanvasSnapshot, O as commentAttentionCapabilityInputSchema, Or as mapCanvasFontSources, Pr as getCanvasConversionOutputSchema, Pt as canvasOutlineCursorSchema, Q as canvasAssetImportCapabilityInputSchema, Qn as canvasTextChangeBetween, Qt as diagnosisStep, Rt as canvasUpdateHtmlInputSchema, Sn as prototypeArtifactPathSchema, Sr as TEXT_KIND, T as canvasReadCapabilityInputSchema, Tr as getCanvasMutationOutputSchema, Tt as inputProblemSummary, U as canvasCaptureCapabilityInputSchema, Ur as canvasReadableSceneDocumentSchema, V as operationStatusInputSchema, Vr as downloadCanvasRenderOutputSchema, Vt as assertCanvasReferenceNodes, Wr as canvasSceneDocumentSchema, Xn as applyCanvasTypographyPatch, Xr as canvasAxisStyleProperties, Xt as commandName, Yn as createCapturePassOutputSchema, Yr as canvasAuthoredStyleDeclarations, Yt as cliPathOf, Zn as canvasCssTypographyOwners, Zr as canvasCssPixelValue, Zt as currentNodeIdStep, _n as createPrototypeArtifactOutputSchema, _r as GROUP_KIND, _t as canvasInsertHtmlCapabilityInputSchema, ai as reserveCanvasAssetOutputSchema, an as CliError, ar as canvasRecordingPropsSchema, bn as getPrototypePublishStatusOutputSchema, br as RECTANGLE_KIND, cr as canvasReferencePageOf, ct as canvasRemoveCapabilityInputSchema, di as hasCanvasRichTextPaints, en as inputName, et as canvasAssetImportOutputSchema, fi as CANVAS_RICH_TEXT_STYLE_PROPERTIES, fr as AGENT_CLIENT_HEADER, ft as canvasFindCursorSchema, g as toRemoteError, gi as canvasPaintSchema, gn as attachPrototypeArtifactOutputSchema, gr as FRAME_KIND, gt as listedCanvasesAnswerSchema, hi as canvasBlendModeSchema, hn as PROTOTYPE_ARTIFACT_MANIFEST_PATH, hr as getCanvasPreparationOutputSchema, ii as reserveCanvasAssetInputSchema, in as PartialBatchError, ir as canvasPrototypePropsSchema, j as transcriptReadCapabilityInputSchema, jt as decodeCanvasExchangeToken, k as prototypePublishCapabilityInputSchema, kn as listOrganisationsOutputSchema, kt as canvasExchangeDigest, li as canvasRichTextOf, lr as resolveCanvasReference, mi as CANVAS_BLEND_MODES, mr as createCanvasPreparationOutputSchema, ni as canvasCssValue, nr as canvasCaptureSchema, oi as canvasFontAssetIdentityFromPath, on as isFormatRefusalError, or as captureLandingSchema, ot as canvasRenderRequestSchema, pi as canvasAdditionalStyleSchema, pn as getRecordingOutputSchema, pt as canvasFindInputSchema, qr as canvasRecordedBoxNoteFor, qt as readStoredCanvasScene, ri as canvasAssetUploadOutputSchema, rr as canvasConversionMetadataSchema, rt as canvasRenderPendingSchema, si as canvasImageAssetIdentityFromPath, sn as transcriptOutputSchema, sr as DEFAULT_CANVAS_REFERENCE_PAGE_ID, st as canvasRenderFileSchema, ti as canvasCssTokens, tn as layerListName, tr as CAPTURE_LANDING_CONVERTING, tt as canvasRenderBatchRequestSchema, ui as canvasRichTextValueOf, ur as beginCanvasActivityOutputSchema, vn as foldPrototypeArtifactPath, vr as IMAGE_KIND, w as canvasApplyCapabilityInputSchema, wn as getMeOutputSchema, wr as applyCanvasOperationsOutputSchema, wt as inputProblemFields, xn as prototypeArtifactManifestSchema, xr as SCREEN_KIND, xt as canvasEditCapabilityInputSchema, yn as getPrototypeArtifactCapabilitiesOutputSchema, yr as PAGE_KIND, yt as canvasMakeEditableCapabilityInputSchema, zr as createCanvasRenderOutputSchema, zt as canvasTranscriptCursorSchema } from "./cli-output-identity.lib-Z9ISwnoo.mjs";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
5
+ import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
6
+ import path from "node:path";
5
7
  import { homedir, tmpdir } from "node:os";
6
8
  import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";
7
- import { chmodSync, constants, createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
8
- import path from "node:path";
9
+ import { generate, lexer, parse } from "css-tree";
9
10
  import { createHash, randomBytes, randomUUID } from "node:crypto";
11
+ import { chmodSync, constants, createReadStream, createWriteStream, existsSync, mkdirSync, openAsBlob, writeFileSync } from "node:fs";
10
12
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
- import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
12
13
  import { isDeepStrictEqual } from "node:util";
13
- import { generate, parse } from "css-tree";
14
14
  import { parseFragment, serialize, serializeOuter } from "parse5";
15
15
  import { performance as performance$1 } from "node:perf_hooks";
16
- import { Readable, Transform } from "node:stream";
16
+ import { Transform } from "node:stream";
17
17
  import { pipeline } from "node:stream/promises";
18
18
  import { ZipFile } from "yazl";
19
19
  import { createTRPCUntypedClient, httpLink } from "@trpc/client";
@@ -1030,6 +1030,36 @@ const canvasRadialGradientSvg = (paint) => {
1030
1030
  return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasRadialGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
1031
1031
  };
1032
1032
 
1033
+ //#endregion
1034
+ //#region ../../packages/contract/src/canvas/capture-swap.lib.ts
1035
+ /** The destination of the one swap: its picture, replaced once, and only while it is a picture. */
1036
+ const captureSwapDestination = (pictureNodeId) => ({
1037
+ kind: "replace",
1038
+ targetNodeId: pictureNodeId,
1039
+ onlyPicture: true
1040
+ });
1041
+ /**
1042
+ * The one swap every capture path sends: a converted frame, re-rooted on its picture's id, that
1043
+ * replaces the picture in place. The editor's request and an agent's both end in this, so the two
1044
+ * cannot drift; the API refuses it as capture-already-landed once the picture is a frame.
1045
+ */
1046
+ const captureSwapOf = (operation, pictureNodeId) => {
1047
+ const renamed = (id) => id === operation.rootNodeId ? pictureNodeId : id;
1048
+ return {
1049
+ ...operation,
1050
+ destination: captureSwapDestination(pictureNodeId),
1051
+ rootNodeId: pictureNodeId,
1052
+ nodes: Object.fromEntries(Object.entries(operation.nodes).map(([id, node]) => [renamed(id), {
1053
+ ...node,
1054
+ id: renamed(id)
1055
+ }])),
1056
+ relationships: Object.fromEntries(Object.entries(operation.relationships).map(([id, relation]) => [renamed(id), {
1057
+ ...relation,
1058
+ parentId: renamed(relation.parentId)
1059
+ }]))
1060
+ };
1061
+ };
1062
+
1033
1063
  //#endregion
1034
1064
  //#region src/application/auth.use-case.ts
1035
1065
  const TOKEN = /^enh_[\w-]{43}$/;
@@ -1098,7 +1128,7 @@ const downloadVerifiedRenderPng = async (remote, job) => {
1098
1128
  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}.`);
1099
1129
  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" });
1100
1130
  const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
1101
- 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.");
1131
+ 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.", diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
1102
1132
  const body = await remote.download(signed.data.download.url);
1103
1133
  const dimensions = pngDimensions(body);
1104
1134
  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}.`);
@@ -1110,15 +1140,43 @@ const downloadVerifiedRenderPng = async (remote, job) => {
1110
1140
 
1111
1141
  //#endregion
1112
1142
  //#region src/application/render-artifact.use-case.ts
1143
+ /** The call that renders one layer at the version a write left the canvas at. */
1144
+ const renderNodeCall = (canvasId, nodeId, version) => callOf("canvas.render", {
1145
+ cli: `--canvas ${canvasId} --node-id ${nodeId} --expected-version ${String(version)}`,
1146
+ mcp: {
1147
+ canvasRef: canvasId,
1148
+ expectedVersion: version,
1149
+ target: {
1150
+ kind: "node",
1151
+ nodeId
1152
+ }
1153
+ }
1154
+ });
1113
1155
  const nextCommands = (job) => {
1114
- const inspect = `enhance canvas inspect --canvas ${job.canvasId}`;
1156
+ const inspect = callOf("canvas.inspect", {
1157
+ cli: `--canvas ${job.canvasId}`,
1158
+ mcp: { canvasId: job.canvasId }
1159
+ });
1115
1160
  if (job.result.sourceState !== void 0) return [
1116
- "Inspect the PNG at path before persisting this moment.",
1117
- `enhance recording snapshot --canvas ${job.canvasId} --recording-id ${job.result.sourceState.recordingId} --at-ms ${String(job.result.sourceState.settledAtMs)}`,
1161
+ "Inspect the PNG at picture before persisting this moment.",
1162
+ callOf("recording.snapshot", {
1163
+ cli: `--canvas ${job.canvasId} --recording-id ${job.result.sourceState.recordingId} --at-ms ${String(job.result.sourceState.settledAtMs)}`,
1164
+ mcp: {
1165
+ canvasId: job.canvasId,
1166
+ recordingId: job.result.sourceState.recordingId,
1167
+ atMs: job.result.sourceState.settledAtMs
1168
+ }
1169
+ }),
1118
1170
  inspect
1119
1171
  ];
1120
1172
  if (job.target.kind !== "node") return [inspect];
1121
- return [inspect, `enhance canvas node --canvas ${job.canvasId} --node-id ${job.target.nodeId}`];
1173
+ return [inspect, callOf("canvas.node", {
1174
+ cli: `--canvas ${job.canvasId} --node-id ${job.target.nodeId}`,
1175
+ mcp: {
1176
+ canvasId: job.canvasId,
1177
+ nodeId: job.target.nodeId
1178
+ }
1179
+ })];
1122
1180
  };
1123
1181
  const resultFrom = (job, written, source) => ({
1124
1182
  ...source !== void 0 && { source },
@@ -1140,6 +1198,7 @@ const resultFrom = (job, written, source) => ({
1140
1198
  contentType: job.result.contentType,
1141
1199
  bytes: job.result.bytes,
1142
1200
  warnings: job.result.warnings,
1201
+ picture: written.path,
1143
1202
  path: written.path,
1144
1203
  sensitive: true,
1145
1204
  cleanup: written.temporary ? "unlink-after-use" : "caller-owned",
@@ -1159,12 +1218,22 @@ const writeRenderArtifact = async (remote, files, job, input) => {
1159
1218
  const POLL_MS$3 = 250;
1160
1219
  const PROGRESS_HEARTBEAT_MS$1 = 5e3;
1161
1220
  const RENDER_CANVAS_PROCEDURES = ["canvas.render.create", "canvas.render.get"];
1162
- const invalidResponse$3 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
1221
+ const ENHANCE_FAULT = "the fault is in Enhance, not in this request: tell the person and report the job id.";
1222
+ const invalidResponse$3 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
1163
1223
  const terminalFailure$1 = (job) => {
1164
1224
  const failure = job.failure;
1165
1225
  if (failure === null) return invalidResponse$3("render job");
1166
1226
  const code = failure.reason === "VERSION_CHANGED" ? "CONFLICT" : failure.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : failure.reason === "TARGET_INVALID" || failure.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL";
1167
- const remediation = failure.reason === "VERSION_CHANGED" ? `Run 'enhance canvas inspect --canvas ${job.canvasId}', then render its returned version.` : failure.reason === "TARGET_NOT_FOUND" ? `Run 'enhance canvas tree --canvas ${job.canvasId}' and choose a current node id.` : failure.retryable ? "Retry the render. If it repeats, run `enhance doctor` and report the job id." : "Change the target or scale using the failure details, then retry.";
1227
+ const remediation = failure.reason === "VERSION_CHANGED" ? `${inSurfaceWords({
1228
+ cli: `Run 'enhance canvas inspect --canvas ${job.canvasId}'`,
1229
+ mcp: "Read the canvas again"
1230
+ })}, then render its returned version.` : failure.reason === "TARGET_NOT_FOUND" ? `${inSurfaceWords({
1231
+ cli: `Run 'enhance canvas tree --canvas ${job.canvasId}'`,
1232
+ mcp: "Read the canvas again"
1233
+ })} and choose a current node id.` : failure.retryable ? `Retry the render. If it repeats, ${inSurfaceWords({
1234
+ cli: "run `enhance doctor` and report the job id.",
1235
+ mcp: ENHANCE_FAULT
1236
+ })}` : "Change the target or scale using the failure details, then retry.";
1168
1237
  return new CliError(code, failure.message, remediation, {
1169
1238
  jobId: job.id,
1170
1239
  reason: failure.reason,
@@ -1203,7 +1272,13 @@ const awaitJob = async (remote, input) => {
1203
1272
  }
1204
1273
  if (currentTime >= input.deadline) {
1205
1274
  if (input.timeoutOutcome === "pending") return job;
1206
- throw new CliError("INTERNAL", `Render ${job.id} did not finish before the local timeout.`, `Retry the exact command with --client-token ${input.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`, {
1275
+ throw new CliError("INTERNAL", `Render ${job.id} did not finish before the local timeout.`, `Retry the exact ${inSurfaceWords({
1276
+ cli: "command",
1277
+ mcp: "request"
1278
+ })} with ${inputName("clientToken")} ${input.retryClientToken} and a larger ${inputName("timeoutMs")}. If the render remains unavailable, ${inSurfaceWords({
1279
+ cli: "run `enhance doctor` and report the job id.",
1280
+ mcp: ENHANCE_FAULT
1281
+ })}`, {
1207
1282
  jobId: job.id,
1208
1283
  phase: job.phase
1209
1284
  });
@@ -1233,6 +1308,7 @@ const requireRenderBudget = (job, input) => {
1233
1308
  if (input.maxOutputPixels !== void 0 && job.maxOutputPixels !== input.maxOutputPixels) throw new CliError("INTERNAL", "This API does not preserve the requested render pixel budget.", "Update the API and renderer together before rendering a batch.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
1234
1309
  };
1235
1310
  const executeRender = async (dependencies, input) => {
1311
+ if (input.outputPath !== null && !input.overwrite) dependencies.files.refuseExisting(input.outputPath);
1236
1312
  const initial = await requestRenderJob(dependencies.remote, input);
1237
1313
  try {
1238
1314
  requireRenderBudget(initial, input);
@@ -1258,7 +1334,7 @@ const executeRender = async (dependencies, input) => {
1258
1334
  jobId: job.id
1259
1335
  },
1260
1336
  pixelsDelivered: false,
1261
- 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."]
1337
+ next: [`Read ${commandName("operation.status")} with ${inputName("includeImage", "input")} true. Do not create another render.`, `If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same ${inputName("clientToken")} to retry it.`]
1262
1338
  };
1263
1339
  return await writeRenderArtifact(dependencies.remote, dependencies.files, job, {
1264
1340
  outputPath: input.outputPath,
@@ -1276,7 +1352,7 @@ const executeRender = async (dependencies, input) => {
1276
1352
  jobId: initial.id,
1277
1353
  operation
1278
1354
  });
1279
- throw new CliError("INTERNAL", "The native render outcome could not be confirmed.", "Read operation_status or retry with the identical request and clientToken.", {
1355
+ throw new CliError("INTERNAL", "The native render outcome could not be confirmed.", `Read ${commandName("operation.status")} or retry with the identical request and ${inputName("clientToken")}.`, {
1280
1356
  jobId: initial.id,
1281
1357
  operation
1282
1358
  });
@@ -1289,160 +1365,6 @@ const createRenderCanvasComposite = (remote, files, now, progress = () => null)
1289
1365
  progress
1290
1366
  }, input) });
1291
1367
 
1292
- //#endregion
1293
- //#region src/application/canvas-activity.composite.ts
1294
- const PROCEDURES$1 = {
1295
- begin: "canvas.realtime.activity.begin",
1296
- renew: "canvas.realtime.activity.renew",
1297
- end: "canvas.realtime.activity.end"
1298
- };
1299
- const ignoreFailure = async (operation) => {
1300
- try {
1301
- await operation();
1302
- return true;
1303
- } catch {
1304
- return false;
1305
- }
1306
- };
1307
- const liveHandle = (remote, initial, activityId, renewAfterMs) => {
1308
- let target = initial;
1309
- let isFinished = false;
1310
- let isRenewing = false;
1311
- const renew = async () => {
1312
- if (isFinished || isRenewing) return;
1313
- isRenewing = true;
1314
- await ignoreFailure(async () => remote.mutate(PROCEDURES$1.renew, {
1315
- ...target,
1316
- nodeIds: [...target.nodeIds],
1317
- activityId
1318
- }));
1319
- isRenewing = false;
1320
- };
1321
- const timer = setInterval(() => void renew(), renewAfterMs);
1322
- return {
1323
- activityId,
1324
- update: async (next) => {
1325
- if (isFinished) return;
1326
- target = {
1327
- ...target,
1328
- ...next
1329
- };
1330
- await renew();
1331
- },
1332
- finish: async () => {
1333
- if (isFinished) return;
1334
- isFinished = true;
1335
- clearInterval(timer);
1336
- await ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
1337
- canvasId: target.canvasId,
1338
- activityId
1339
- }));
1340
- }
1341
- };
1342
- };
1343
- const createCanvasActivityComposite = (remote) => ({
1344
- begin: async (target) => {
1345
- try {
1346
- const parsed = beginCanvasActivityOutputSchema.safeParse(await remote.mutate(PROCEDURES$1.begin, {
1347
- ...target,
1348
- nodeIds: [...target.nodeIds]
1349
- }));
1350
- return parsed.success ? liveHandle(remote, target, parsed.data.activityId, parsed.data.renewAfterMs) : null;
1351
- } catch {
1352
- return null;
1353
- }
1354
- },
1355
- finish: async (canvasId, activityId) => ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
1356
- canvasId,
1357
- activityId
1358
- }))
1359
- });
1360
-
1361
- //#endregion
1362
- //#region src/application/apply-canvas.composite.ts
1363
- const APPLY_PROCEDURE = "canvas.applyOperations";
1364
- const MAX_ACTIVITY_NODE_IDS$1 = 100;
1365
- const BOX_OPERATION_TYPES = /* @__PURE__ */ new Set([
1366
- "insertPrototype",
1367
- "insertText",
1368
- "setBox"
1369
- ]);
1370
- const hasOperationBox = (operation) => BOX_OPERATION_TYPES.has(operation.op);
1371
- const activityPhase = (input) => {
1372
- if (input.operations.some((operation) => operation.op === "insertNode" || operation.op === "insertText")) return "creating";
1373
- if (input.operations.some((operation) => operation.op === "remove")) return "deleting";
1374
- return "writing";
1375
- };
1376
- const operationNodeIds = (operation) => {
1377
- if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
1378
- if (operation.op === "insertNode") return [operation.node.id];
1379
- return [operation.nodeId];
1380
- };
1381
- const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operation) => operationNodeIds(operation)))].slice(0, MAX_ACTIVITY_NODE_IDS$1);
1382
- const operationBox = (operation) => {
1383
- if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
1384
- if (operation.op === "insertNode") return operation.node.box ?? null;
1385
- if (hasOperationBox(operation)) return operation.box === "default" ? null : operation.box;
1386
- return null;
1387
- };
1388
- const union = (boxes) => {
1389
- const first = boxes[0];
1390
- if (first === void 0) return null;
1391
- let x1 = first.x;
1392
- let y1 = first.y;
1393
- let x2 = first.x + first.width;
1394
- let y2 = first.y + first.height;
1395
- for (const box of boxes.slice(1)) {
1396
- x1 = Math.min(x1, box.x);
1397
- y1 = Math.min(y1, box.y);
1398
- x2 = Math.max(x2, box.x + box.width);
1399
- y2 = Math.max(y2, box.y + box.height);
1400
- }
1401
- return {
1402
- x: x1,
1403
- y: y1,
1404
- width: x2 - x1,
1405
- height: y2 - y1
1406
- };
1407
- };
1408
- const apply = async (remote, input) => {
1409
- const response = await remote.mutate(APPLY_PROCEDURE, {
1410
- ...input,
1411
- documentFormatVersion: 15
1412
- });
1413
- const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
1414
- 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.");
1415
- return parsed.data;
1416
- };
1417
- const createApplyCanvasComposite = (remote) => ({ execute: async (input, options) => {
1418
- if (options?.activity === false) return apply(remote, input);
1419
- const activity = await createCanvasActivityComposite(remote).begin({
1420
- canvasId: input.canvasId,
1421
- phase: activityPhase(input),
1422
- nodeIds: activityNodeIds(input),
1423
- bounds: union(input.operations.flatMap((operation) => {
1424
- const box = operationBox(operation);
1425
- return box === null ? [] : [box];
1426
- }))
1427
- });
1428
- try {
1429
- return await apply(remote, input);
1430
- } finally {
1431
- await activity?.finish();
1432
- }
1433
- } });
1434
-
1435
- //#endregion
1436
- //#region src/application/canvas-scene-at-version.use-case.ts
1437
- const sceneAtVersion = async (input, canvasId, expectedVersion) => {
1438
- const held = wholeCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
1439
- if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
1440
- if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(held.data.version)} before submitting a new edit.`);
1441
- const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
1442
- if (scene.success) return scene.data;
1443
- throw new CliError("INTERNAL", "The stored canvas is not an editable scene.", "Open the canvas in the editor and repair or recreate the invalid document.");
1444
- };
1445
-
1446
1368
  //#endregion
1447
1369
  //#region src/application/canvas-structure-document.use-case.ts
1448
1370
  const ROOT_CANVAS_NODE_ID = "root";
@@ -1469,7 +1391,7 @@ const canCanvasNodeContainChildren = (node) => node !== void 0 && [
1469
1391
  const requireCanvasNode = (document, nodeId) => {
1470
1392
  const node = document.nodes[nodeId];
1471
1393
  if (node !== void 0) return node;
1472
- throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
1394
+ throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, currentNodeIdStep());
1473
1395
  };
1474
1396
  const canvasDescendantIds = (document, nodeId) => {
1475
1397
  const found = /* @__PURE__ */ new Set();
@@ -1549,7 +1471,7 @@ const duplicateOne = (context) => {
1549
1471
  const source = requireCanvasNode(document, input.id);
1550
1472
  if (input.id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be duplicated.", "Duplicate one or more root children instead.");
1551
1473
  const sourceParentage = document.relationships[input.id];
1552
- if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, "Choose a reachable node from canvas tree.");
1474
+ if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, `Choose a reachable node from ${layerListName()}.`);
1553
1475
  const parentId = input.parentId ?? sourceParentage.parentId;
1554
1476
  if (!canCanvasNodeContainChildren(document.nodes[parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${parentId} cannot contain duplicates.`, "Choose a frame, group, or root as the destination.");
1555
1477
  const map = duplicateMap(document, input.id, nextId);
@@ -1609,7 +1531,7 @@ const siblingDestination = (input, state) => {
1609
1531
  const siblingId = "before" in input ? input.before : input.after;
1610
1532
  if (siblingId === input.nodeId || state.document.nodes[siblingId] === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is not a valid move target.`, "Choose another current sibling node.");
1611
1533
  const parentId = state.parentOf.get(siblingId);
1612
- if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, "Choose a reachable sibling from canvas tree.");
1534
+ if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, `Choose a reachable sibling from ${layerListName()}.`);
1613
1535
  const siblingIndex = (state.children.get(parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId).indexOf(siblingId);
1614
1536
  return {
1615
1537
  parentId,
@@ -2905,7 +2827,10 @@ const fillElementsOf = (node) => {
2905
2827
  const fills = (node.appearance?.fills ?? []).filter((paint) => paint.visible);
2906
2828
  return fills.some((paint) => fillNeedsElement(paint)) || fills.length > 0 && canvasProgressiveBlurOf(node) !== null ? fills : [];
2907
2829
  };
2908
- /** A captured dashed border with no edited pattern stays CSS's, which the browser draws exactly. */
2830
+ /**
2831
+ * A captured dashed border or outline with no edited pattern stays CSS's, which the browser draws
2832
+ * exactly.
2833
+ */
2909
2834
  const canvasBorderDrawsWithCssStyle = (border) => border.style === "solid" || border.dashOrigin === "css" && border.dashPattern === void 0 && border.dashCap === void 0;
2910
2835
  /**
2911
2836
  * One solid paint on an inside border with a CSS style stays CSS border-color on the layer. Anything
@@ -2937,7 +2862,9 @@ const isCanvasContourOutlinePaint = (node) => {
2937
2862
  const [only, ...others] = visibleStrokePaints(node.appearance?.outline);
2938
2863
  return (node.appearance?.radius?.smoothing ?? 0) > 0 && others.length === 0 && only?.kind === "solid" && !isCanvasBlendedPaint(only);
2939
2864
  };
2940
- /** One solid paint on an undashed outline stays CSS outline-color; anything else is a ring. */
2865
+ /**
2866
+ * One solid paint on an outline with a CSS style stays CSS outline-color; anything else is a ring.
2867
+ */
2941
2868
  const outlineElementsOf = (node) => {
2942
2869
  const outline = node.appearance?.outline;
2943
2870
  if (outline === void 0 || node.geometry !== void 0 || !STROKE_OWNERS.has(node.component) || outline.width <= 0 || isCanvasContourOutlinePaint(node)) return [];
@@ -2946,7 +2873,7 @@ const outlineElementsOf = (node) => {
2946
2873
  kind: "outline",
2947
2874
  paints: [paint]
2948
2875
  }));
2949
- return paints.length > 1 || outline.style !== "solid" || paints.some((paint) => paint.kind !== "solid") ? [{
2876
+ return paints.length > 1 || !canvasBorderDrawsWithCssStyle(outline) || paints.some((paint) => paint.kind !== "solid") ? [{
2950
2877
  kind: "outline",
2951
2878
  paints
2952
2879
  }] : [];
@@ -3990,6 +3917,158 @@ const canvasGeometryClipOf = (document, node, maskSource) => {
3990
3917
  };
3991
3918
  };
3992
3919
 
3920
+ //#endregion
3921
+ //#region src/application/canvas-style-check.use-case.ts
3922
+ /** Command aliases for a size mode, which `canvasStyleOperations` turns into a layout edit. */
3923
+ const SIZE_MODE_ALIASES = {
3924
+ width: ["fill", "hug"],
3925
+ height: ["fill", "hug"]
3926
+ };
3927
+ /** CSS for SVG shapes only. On a layer, which is an HTML box, they look like a position and move nothing. */
3928
+ const SVG_ONLY_POSITIONS = /* @__PURE__ */ new Set(["x", "y"]);
3929
+ const VENDOR_PREFIX = /^-(?:webkit|moz|ms)-/u;
3930
+ /** The CSS library cannot match a value until these are substituted, which only a browser does. */
3931
+ const SUBSTITUTED_LATER = /\b(?:var|env)\(/iu;
3932
+ /** Every property takes `initial`, so only a name the CSS library does not know fails to match it. */
3933
+ const isKnownProperty = (property) => lexer.matchProperty(property, "initial").error === null;
3934
+ const unusableStyle = (property, value) => {
3935
+ if (property.startsWith("--") || VENDOR_PREFIX.test(property)) return null;
3936
+ if (SVG_ONLY_POSITIONS.has(property) || !isKnownProperty(property)) return "name";
3937
+ if (SIZE_MODE_ALIASES[property]?.includes(String(value)) === true) return null;
3938
+ const literal = canvasCssValue(property, value).replace(/\s*!important\s*$/iu, "").trim();
3939
+ if (SUBSTITUTED_LATER.test(literal) || lexer.matchProperty(property, literal).error === null) return null;
3940
+ return canvasAdditionalStyleSchema.shape.value.safeParse(literal).success ? "value" : "unsafe";
3941
+ };
3942
+ const listed = (items) => new Intl.ListFormat("en-GB", { type: "conjunction" }).format(items);
3943
+ const REFUSALS = [
3944
+ [
3945
+ "name",
3946
+ "is not a CSS property",
3947
+ "are not CSS properties"
3948
+ ],
3949
+ [
3950
+ "unsafe",
3951
+ "is not safe CSS",
3952
+ "are not safe CSS"
3953
+ ],
3954
+ [
3955
+ "value",
3956
+ "is not a value its property takes",
3957
+ "are not values their properties take"
3958
+ ]
3959
+ ];
3960
+ /**
3961
+ * Refuses an agent's edit when any style in it is one a browser would drop: a name that is not a
3962
+ * CSS property, or a value its property cannot take. Clearing a style is never refused, so a
3963
+ * stored property this check does not know can still be removed.
3964
+ */
3965
+ const requireUsableCanvasStyles = (edits) => {
3966
+ const found = {
3967
+ name: /* @__PURE__ */ new Set(),
3968
+ unsafe: /* @__PURE__ */ new Set(),
3969
+ value: /* @__PURE__ */ new Set()
3970
+ };
3971
+ const written = [...edits].flatMap((styles) => Object.entries(styles));
3972
+ for (const [property, value] of written) {
3973
+ const reason = value === null ? null : unusableStyle(property, value);
3974
+ if (reason !== null) found[reason].add(reason === "name" ? property : `${property}: ${canvasCssValue(property, value ?? "")}`);
3975
+ }
3976
+ const refusals = REFUSALS.filter(([reason]) => found[reason].size > 0).map(([reason, one, many]) => `${listed(found[reason])} ${found[reason].size === 1 ? one : many}`);
3977
+ if (refusals.length === 0) return;
3978
+ throw new CliError("BAD_REQUEST", `${refusals.join("; ")}.`, `Nothing was written. Use CSS property names and values: left and top in pixels position a layer, a bare number is read as pixels, and a custom property (--name) is kept as given. ${inSurfaceWords({
3979
+ cli: "canvas update-html",
3980
+ mcp: commandName("canvas.updateHtml")
3981
+ })} stores a property this command does not know.`);
3982
+ };
3983
+
3984
+ //#endregion
3985
+ //#region src/application/canvas-style-position.use-case.ts
3986
+ const POSITION_AXES = {
3987
+ x: {
3988
+ moved: "left",
3989
+ size: "horizontal",
3990
+ insets: [
3991
+ "left",
3992
+ "right",
3993
+ "inset",
3994
+ "inset-inline",
3995
+ "inset-inline-start",
3996
+ "inset-inline-end"
3997
+ ]
3998
+ },
3999
+ y: {
4000
+ moved: "top",
4001
+ size: "vertical",
4002
+ insets: [
4003
+ "top",
4004
+ "bottom",
4005
+ "inset",
4006
+ "inset-block",
4007
+ "inset-block-start",
4008
+ "inset-block-end"
4009
+ ]
4010
+ }
4011
+ };
4012
+ const POSITION_AXIS_NAMES = ["x", "y"];
4013
+ const INSET_PROPERTIES = new Set(POSITION_AXIS_NAMES.flatMap((axis) => POSITION_AXES[axis].insets));
4014
+ const isInsetWrite = ([property, value]) => value !== null && INSET_PROPERTIES.has(property);
4015
+ /**
4016
+ * Whether the canvas draws the layer somewhere other than its box although nothing on the layer
4017
+ * says so: a far-edge or scaled constraint under a Hug or Fill parent, a parent that keeps a
4018
+ * scrollbar gutter, or a captured parent-relative position. Such a layer keeps its style.
4019
+ */
4020
+ const isDrawnAwayFromBox = (document, node, axis) => {
4021
+ const parentId = document.relationships[node.id]?.parentId;
4022
+ const parent = parentId === void 0 ? void 0 : document.nodes[parentId];
4023
+ const constraint = node.constraints?.[axis];
4024
+ const parentSize = parent?.layout?.[POSITION_AXES[axis].size];
4025
+ const source = node.props?.["source"];
4026
+ return constraint !== void 0 && constraint !== "start" && parentSize !== void 0 && parentSize.mode !== "fixed" || parent?.layout?.scrollbarGutter !== void 0 || typeof source === "object" && source !== null && "captureRelativePosition" in source;
4027
+ };
4028
+ const isBoxPlaced = (document, node, axis) => {
4029
+ if (node.box === void 0 || canvasLayoutPositionOf(node) !== "absolute") return false;
4030
+ const authored = canvasAuthoredStyleDeclarations(node);
4031
+ return POSITION_AXES[axis].insets.every((property) => authored[property] === void 0) && node.layout?.positionParent?.[axis] === void 0 && !isDrawnAwayFromBox(document, node, axis);
4032
+ };
4033
+ const pixelsOf = (property, value) => canvasCssPixelValue(canvasCssValue(property, value).toLowerCase().replace(/\s*!important\s*$/u, ""));
4034
+ /**
4035
+ * Gives a layer's position one owner. On an axis the canvas draws from the box, a pixel `left`
4036
+ * or `top` becomes a move of the box, as a drag is, and any other inset is refused, so every
4037
+ * read of the box agrees with the picture. `layerAfter` gives the layer as some of the edit's
4038
+ * styles leave it.
4039
+ */
4040
+ const canvasBoxMove = (document, styles, layerAfter) => {
4041
+ const insets = Object.entries(styles).filter((entry) => isInsetWrite(entry));
4042
+ if (insets.length === 0) return {
4043
+ box: void 0,
4044
+ stored: styles
4045
+ };
4046
+ const node = layerAfter(Object.fromEntries(Object.entries(styles).filter((entry) => !isInsetWrite(entry))));
4047
+ const placedAxes = POSITION_AXIS_NAMES.filter((axis) => isBoxPlaced(document, node, axis));
4048
+ const moved = {};
4049
+ const movedProperties = /* @__PURE__ */ new Set();
4050
+ const refused = [];
4051
+ for (const [property, value] of insets) {
4052
+ const axis = placedAxes.find((placed) => POSITION_AXES[placed].insets.includes(property));
4053
+ const pixels = axis !== void 0 && value !== null && property === POSITION_AXES[axis].moved ? pixelsOf(property, value) : void 0;
4054
+ if (axis !== void 0 && pixels !== void 0) {
4055
+ moved[axis] = pixels;
4056
+ movedProperties.add(property);
4057
+ } else if (axis !== void 0) refused.push(`${property}: ${String(value)}`);
4058
+ }
4059
+ if (refused.length > 0) throw new CliError("BAD_REQUEST", `${refused.join(", ")} cannot position layer ${node.id}: the canvas draws it at its box, which takes only left and top in pixels.`, `Nothing was written. Pass left and top in pixels, or place the layer with ${inSurfaceWords({
4060
+ cli: "canvas arrange",
4061
+ mcp: commandName("canvas.arrange")
4062
+ })}.`);
4063
+ return {
4064
+ box: node.box === void 0 || movedProperties.size === 0 ? void 0 : {
4065
+ ...node.box,
4066
+ ...moved
4067
+ },
4068
+ stored: Object.fromEntries(Object.entries(styles).filter(([property]) => !movedProperties.has(property)))
4069
+ };
4070
+ };
4071
+
3993
4072
  //#endregion
3994
4073
  //#region src/application/canvas-typography-operations.use-case.ts
3995
4074
  const canvasTypographyOperation = (node, styles) => {
@@ -4059,7 +4138,8 @@ const cssValues = (document, node, styles) => {
4059
4138
  }
4060
4139
  return result;
4061
4140
  };
4062
- const operationsForNode = (document, node, source) => {
4141
+ /** The operations, and the layer as they leave it, for what the canvas will draw next. */
4142
+ const plannedStyles = (document, node, source) => {
4063
4143
  const styles = cssValues(document, node, source);
4064
4144
  const additional = additionalOperation(node, styles);
4065
4145
  const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
@@ -4078,17 +4158,30 @@ const operationsForNode = (document, node, source) => {
4078
4158
  nodeId: node.id,
4079
4159
  appearance: { clear: [...replaced] }
4080
4160
  }] : [];
4081
- return [
4082
- ...Object.keys(stylePatch).length > 0 ? [{
4083
- op: "setStyles",
4084
- nodeId: node.id,
4085
- styles: canvasNodeStylePatchSchema.parse(stylePatch)
4086
- }] : [],
4087
- ...clearNative,
4088
- ...typography === null ? [] : [typography],
4089
- ...layout === null ? [] : [layout],
4090
- ...additional === null ? [] : [additional]
4091
- ];
4161
+ if (layout?.op === "setLayout") Object.assign(next, { layout: layout.layout === "default" ? void 0 : layout.layout });
4162
+ return {
4163
+ operations: [
4164
+ ...Object.keys(stylePatch).length > 0 ? [{
4165
+ op: "setStyles",
4166
+ nodeId: node.id,
4167
+ styles: canvasNodeStylePatchSchema.parse(stylePatch)
4168
+ }] : [],
4169
+ ...clearNative,
4170
+ ...typography === null ? [] : [typography],
4171
+ ...layout === null ? [] : [layout],
4172
+ ...additional === null ? [] : [additional]
4173
+ ],
4174
+ after: next
4175
+ };
4176
+ };
4177
+ const operationsForNode = (document, node, source) => {
4178
+ const layerAfter = (styles) => plannedStyles(document, node, styles).after;
4179
+ const move = canvasBoxMove(document, source, layerAfter);
4180
+ return [...plannedStyles(document, node, move.stored).operations, ...move.box === void 0 ? [] : [{
4181
+ op: "setBox",
4182
+ nodeId: node.id,
4183
+ box: move.box
4184
+ }]];
4092
4185
  };
4093
4186
  const mergedUpdates = (updates) => {
4094
4187
  const merged = /* @__PURE__ */ new Map();
@@ -4103,15 +4196,27 @@ const mergedUpdates = (updates) => {
4103
4196
  }
4104
4197
  return merged;
4105
4198
  };
4106
- const canvasStyleOperations = (document, updates) => {
4107
- const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
4199
+ const styleOperations = (document, updates, operationsOf) => {
4200
+ const operations = [...updates].flatMap(([nodeId, styles]) => {
4108
4201
  const node = document.nodes[nodeId];
4109
- if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
4110
- return operationsForNode(document, node, styles);
4202
+ if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, currentNodeIdStep("current stable node ids"));
4203
+ return operationsOf(document, node, styles);
4111
4204
  });
4112
4205
  if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
4113
4206
  return operations;
4114
4207
  };
4208
+ /**
4209
+ * The operations for styles an agent typed. Refuses the whole edit when any style is one the
4210
+ * canvas cannot use, and moves the box for a position on a layer its box places.
4211
+ */
4212
+ const canvasStyleOperations = (document, updates) => {
4213
+ const merged = mergedUpdates(updates);
4214
+ requireUsableCanvasStyles(merged.values());
4215
+ return styleOperations(document, merged, operationsForNode);
4216
+ };
4217
+ const storedOperationsForNode = (document, node, styles) => plannedStyles(document, node, styles).operations;
4218
+ /** The operations for styles a page arrived with: every safe declaration is stored as written. */
4219
+ const canvasStoredStyleOperations = (document, updates) => styleOperations(document, mergedUpdates(updates), storedOperationsForNode);
4115
4220
 
4116
4221
  //#endregion
4117
4222
  //#region src/application/canvas-edit-operations.use-case.ts
@@ -4131,6 +4236,7 @@ const PLANNED_OPERATIONS = /* @__PURE__ */ new Set([
4131
4236
  "insertNode",
4132
4237
  "setText",
4133
4238
  "setLabel",
4239
+ "setBox",
4134
4240
  "setStyles",
4135
4241
  "setAppearance",
4136
4242
  "setTypography",
@@ -4150,7 +4256,7 @@ const projectPresentation = (node, field, value) => {
4150
4256
  const projectNode = (node, operation) => {
4151
4257
  switch (operation.op) {
4152
4258
  case "setText":
4153
- if (node.component !== "text") throw new CliError("BAD_REQUEST", `Canvas node ${node.id} is not editable text.`, "Use the text node id from canvas tree.");
4259
+ if (node.component !== "text") throw new CliError("BAD_REQUEST", `Canvas node ${node.id} is not editable text.`, `Use the text node id from ${layerListName()}.`);
4154
4260
  return {
4155
4261
  ...node,
4156
4262
  props: {
@@ -4163,6 +4269,12 @@ const projectNode = (node, operation) => {
4163
4269
  label: operation.label,
4164
4270
  labelOrigin: "user"
4165
4271
  };
4272
+ case "setBox": {
4273
+ const next = { ...node };
4274
+ if (operation.box === "default") Reflect.deleteProperty(next, "box");
4275
+ else next.box = operation.box;
4276
+ return next;
4277
+ }
4166
4278
  case "setStyles": return projectStyles(node, operation);
4167
4279
  case "setAppearance": {
4168
4280
  const appearance = { ...node.appearance };
@@ -4317,7 +4429,7 @@ const requiredIds = (operation, document) => {
4317
4429
  }
4318
4430
  return [operation.nodeId];
4319
4431
  };
4320
- const insertedIds = (operation) => {
4432
+ const insertedIds$1 = (operation) => {
4321
4433
  if (operation.op === "insertNode") return [operation.node.id];
4322
4434
  if (operation.op === "insertText" || operation.op === "insertPrototype") return [operation.nodeId];
4323
4435
  if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
@@ -4391,7 +4503,7 @@ const structurePatch = (document, operation) => {
4391
4503
  };
4392
4504
  };
4393
4505
  const validateOperation = (reference, held, scope, operation) => {
4394
- const inserted = insertedIds(operation);
4506
+ const inserted = insertedIds$1(operation);
4395
4507
  const canInsertAtRoot = reference.nodeIds.length === 0 && (inserted.length > 0 || operation.op === "move" || operation.op === "setParentage");
4396
4508
  const denied = [...requiredIds(operation, held).filter((id) => !canInsertAtRoot || id !== "root"), ...inserted.filter((id) => held.nodes[id] !== void 0)].filter((id) => !scope.has(id));
4397
4509
  if (denied.length > 0) outside(denied);
@@ -4429,450 +4541,1637 @@ const assertCanvasReferenceOperations = (reference, document, operations) => {
4429
4541
  };
4430
4542
 
4431
4543
  //#endregion
4432
- //#region src/application/edit-canvas.composite.ts
4433
- const targetIds = (edit) => {
4434
- switch (edit.kind) {
4435
- case "set_text":
4436
- case "rename": return [edit.nodeId];
4437
- case "set_styles": return edit.nodeIds;
4438
- case "duplicate": return [...edit.nodeIds, ...edit.parentId === void 0 ? [] : [edit.parentId]];
4439
- case "move": return [edit.nodeId, edit.destination.kind === "parent" ? edit.destination.parentId : edit.destination.nodeId];
4440
- }
4544
+ //#region src/application/canvas-activity.composite.ts
4545
+ const PROCEDURES$1 = {
4546
+ begin: "canvas.realtime.activity.begin",
4547
+ renew: "canvas.realtime.activity.renew",
4548
+ end: "canvas.realtime.activity.end"
4441
4549
  };
4442
- const scopeIds = (edit, scene) => {
4443
- if (edit.kind === "duplicate") return [...edit.nodeIds, ...edit.parentId === void 0 || edit.nodeIds.every((id) => scene.relationships[id]?.parentId === edit.parentId) ? [] : [edit.parentId]];
4444
- if (edit.kind === "move" && edit.destination.kind === "parent" && scene.relationships[edit.nodeId]?.parentId === edit.destination.parentId) return [edit.nodeId];
4445
- return targetIds(edit);
4550
+ const ignoreFailure = async (operation) => {
4551
+ try {
4552
+ await operation();
4553
+ return true;
4554
+ } catch {
4555
+ return false;
4556
+ }
4446
4557
  };
4447
- const validateTargets = (input, scene) => {
4448
- const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
4449
- for (const id of ids) requireCanvasNode(scene, id);
4450
- const reference = {
4451
- canvasId: input.canvasId,
4452
- nodeIds: input.nodeIds ?? [],
4453
- ...input.pageId !== void 0 && { pageId: input.pageId }
4558
+ const liveHandle = (remote, initial, activityId, renewAfterMs) => {
4559
+ let target = initial;
4560
+ let isFinished = false;
4561
+ let isRenewing = false;
4562
+ const renew = async () => {
4563
+ if (isFinished || isRenewing) return;
4564
+ isRenewing = true;
4565
+ await ignoreFailure(async () => remote.mutate(PROCEDURES$1.renew, {
4566
+ ...target,
4567
+ nodeIds: [...target.nodeIds],
4568
+ activityId
4569
+ }));
4570
+ isRenewing = false;
4571
+ };
4572
+ const timer = setInterval(() => void renew(), renewAfterMs);
4573
+ return {
4574
+ activityId,
4575
+ update: async (next) => {
4576
+ if (isFinished) return;
4577
+ target = {
4578
+ ...target,
4579
+ ...next
4580
+ };
4581
+ await renew();
4582
+ },
4583
+ finish: async () => {
4584
+ if (isFinished) return;
4585
+ isFinished = true;
4586
+ clearInterval(timer);
4587
+ await ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
4588
+ canvasId: target.canvasId,
4589
+ activityId
4590
+ }));
4591
+ }
4592
+ };
4593
+ };
4594
+ const createCanvasActivityComposite = (remote) => ({
4595
+ begin: async (target) => {
4596
+ try {
4597
+ const parsed = beginCanvasActivityOutputSchema.safeParse(await remote.mutate(PROCEDURES$1.begin, {
4598
+ ...target,
4599
+ nodeIds: [...target.nodeIds]
4600
+ }));
4601
+ return parsed.success ? liveHandle(remote, target, parsed.data.activityId, parsed.data.renewAfterMs) : null;
4602
+ } catch {
4603
+ return null;
4604
+ }
4605
+ },
4606
+ finish: async (canvasId, activityId) => ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
4607
+ canvasId,
4608
+ activityId
4609
+ }))
4610
+ });
4611
+
4612
+ //#endregion
4613
+ //#region src/application/apply-canvas.composite.ts
4614
+ const APPLY_PROCEDURE = "canvas.applyOperations";
4615
+ const MAX_ACTIVITY_NODE_IDS$1 = 100;
4616
+ const BOX_OPERATION_TYPES = /* @__PURE__ */ new Set([
4617
+ "insertPrototype",
4618
+ "insertText",
4619
+ "setBox"
4620
+ ]);
4621
+ const hasOperationBox = (operation) => BOX_OPERATION_TYPES.has(operation.op);
4622
+ const activityPhase = (input) => {
4623
+ if (input.operations.some((operation) => operation.op === "insertNode" || operation.op === "insertText")) return "creating";
4624
+ if (input.operations.some((operation) => operation.op === "remove")) return "deleting";
4625
+ return "writing";
4626
+ };
4627
+ const operationNodeIds = (operation) => {
4628
+ if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
4629
+ if (operation.op === "insertNode") return [operation.node.id];
4630
+ return [operation.nodeId];
4631
+ };
4632
+ const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operation) => operationNodeIds(operation)))].slice(0, MAX_ACTIVITY_NODE_IDS$1);
4633
+ const operationBox = (operation) => {
4634
+ if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
4635
+ if (operation.op === "insertNode") return operation.node.box ?? null;
4636
+ if (hasOperationBox(operation)) return operation.box === "default" ? null : operation.box;
4637
+ return null;
4638
+ };
4639
+ const union = (boxes) => {
4640
+ const first = boxes[0];
4641
+ if (first === void 0) return null;
4642
+ let x1 = first.x;
4643
+ let y1 = first.y;
4644
+ let x2 = first.x + first.width;
4645
+ let y2 = first.y + first.height;
4646
+ for (const box of boxes.slice(1)) {
4647
+ x1 = Math.min(x1, box.x);
4648
+ y1 = Math.min(y1, box.y);
4649
+ x2 = Math.max(x2, box.x + box.width);
4650
+ y2 = Math.max(y2, box.y + box.height);
4651
+ }
4652
+ return {
4653
+ x: x1,
4654
+ y: y1,
4655
+ width: x2 - x1,
4656
+ height: y2 - y1
4454
4657
  };
4658
+ };
4659
+ const apply = async (remote, input) => {
4660
+ const response = await remote.mutate(APPLY_PROCEDURE, {
4661
+ ...input,
4662
+ documentFormatVersion: 15
4663
+ });
4664
+ const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
4665
+ if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
4666
+ return parsed.data;
4667
+ };
4668
+ const createApplyCanvasComposite = (remote) => ({ execute: async (input, options) => {
4669
+ if (options?.activity === false) return apply(remote, input);
4670
+ const activity = await createCanvasActivityComposite(remote).begin({
4671
+ canvasId: input.canvasId,
4672
+ phase: activityPhase(input),
4673
+ nodeIds: activityNodeIds(input),
4674
+ bounds: union(input.operations.flatMap((operation) => {
4675
+ const box = operationBox(operation);
4676
+ return box === null ? [] : [box];
4677
+ }))
4678
+ });
4679
+ try {
4680
+ return await apply(remote, input);
4681
+ } finally {
4682
+ await activity?.finish();
4683
+ }
4684
+ } });
4685
+
4686
+ //#endregion
4687
+ //#region src/application/canvas-receipt.use-case.ts
4688
+ const MAX_RECEIPT_NODE_IDS = 40;
4689
+ const canvasWriteReceipt = (commit, fingerprint) => {
4690
+ let remaining = MAX_RECEIPT_NODE_IDS;
4691
+ const take = (ids) => {
4692
+ const selected = ids.slice(0, remaining);
4693
+ remaining -= selected.length;
4694
+ return selected;
4695
+ };
4696
+ const insertedNodeIds = take(commit.insertedNodeIds);
4697
+ const changedNodeIds = take(commit.changedNodeIds);
4698
+ const removedNodeIds = take(commit.removedNodeIds);
4699
+ const total = commit.insertedNodeIds.length + commit.changedNodeIds.length + commit.removedNodeIds.length;
4700
+ return {
4701
+ outcome: "committed",
4702
+ canvasId: commit.canvasId,
4703
+ mutationId: commit.mutationId,
4704
+ previousVersion: commit.previousVersion,
4705
+ version: commit.version,
4706
+ operation: {
4707
+ kind: "canvas-mutation",
4708
+ canvasId: commit.canvasId,
4709
+ mutationId: commit.mutationId,
4710
+ fingerprint
4711
+ },
4712
+ affected: {
4713
+ insertedNodeIds,
4714
+ changedNodeIds,
4715
+ removedNodeIds,
4716
+ complete: total <= MAX_RECEIPT_NODE_IDS,
4717
+ total
4718
+ },
4719
+ ...commit.copiedNodeIds !== void 0 && { identities: {
4720
+ entries: Object.entries(commit.copiedNodeIds).toSorted(([left], [right]) => left.localeCompare(right, "en")).slice(0, MAX_RECEIPT_NODE_IDS).map(([sourceNodeId, nodeId]) => ({
4721
+ sourceNodeId,
4722
+ nodeId
4723
+ })),
4724
+ complete: Object.keys(commit.copiedNodeIds).length <= MAX_RECEIPT_NODE_IDS,
4725
+ total: Object.keys(commit.copiedNodeIds).length
4726
+ } },
4727
+ verification: { rendered: false },
4728
+ warnings: []
4729
+ };
4730
+ };
4731
+
4732
+ //#endregion
4733
+ //#region src/application/canvas-scene-at-version.use-case.ts
4734
+ const namedAsGiven = (version, given) => {
4735
+ const stated = String(version);
4736
+ if (given === "flag") return `${inputName("baseVersion")} ${stated}`;
4737
+ if (given === "input" || given === "placed") return inSurfaceWords({
4738
+ cli: `the baseVersion ${stated} given in --input`,
4739
+ mcp: `baseVersion ${stated}`
4740
+ });
4741
+ return given === "snapshot" ? `version ${stated}, at which the snapshot token was read` : `version ${stated}, which this call expected`;
4742
+ };
4743
+ const readAgain = (current, given) => given === "snapshot" ? `Read the layer again with ${commandName("canvas.read")}: its answer holds the layer and a snapshot token at version ${String(current)}. Edit that answer before submitting a new edit.` : `${inSurfaceWords({
4744
+ cli: "Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>'",
4745
+ mcp: `Read the intended scope again with ${commandName("canvas.read")}`
4746
+ })} and reconcile against version ${String(current)} before submitting a new edit.`;
4747
+ const nextStepAt = (current, given) => given === "placed" ? `Nothing was placed. Place again with baseVersion ${String(current)}. Every placement moves the canvas on: its answer's frame.version is the next placement's baseVersion.` : `An earlier identical request may already have committed. Do not repeat it with a new client token. ${readAgain(current, given)}`;
4748
+ /**
4749
+ * The canvas at a version, with the web address the API answered for it: null from an API older
4750
+ * than the field.
4751
+ */
4752
+ const canvasAtVersion = async (input, canvasId, expectedVersion, given) => {
4753
+ const held = wholeCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
4754
+ if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", diagnosisStep("Run `enhance doctor` and report incompatible API and CLI versions."));
4755
+ if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches ${namedAsGiven(expectedVersion, given)}.`, nextStepAt(held.data.version, given));
4756
+ return {
4757
+ scene: readStoredCanvasScene(held.data.document),
4758
+ url: held.data.url ?? null
4759
+ };
4760
+ };
4761
+ const sceneAtVersion = async (input, canvasId, expectedVersion, given) => {
4762
+ const { scene } = await canvasAtVersion(input, canvasId, expectedVersion, given);
4763
+ return scene;
4764
+ };
4765
+
4766
+ //#endregion
4767
+ //#region src/application/revisioned-canvas-command.composite.ts
4768
+ const CANVAS_COMMAND_PROCEDURES = ["canvas.mutation.get"];
4769
+ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (input) => {
4770
+ const canvasId = input.reference.canvasId;
4771
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_COMMAND_PROCEDURES[0], {
4772
+ canvasId,
4773
+ mutationId: input.clientToken,
4774
+ fingerprint: input.fingerprint
4775
+ }));
4776
+ if (recovered.state === "committed") {
4777
+ input.committed?.(recovered.result);
4778
+ return canvasWriteReceipt(recovered.result, input.fingerprint);
4779
+ }
4780
+ const scene = await sceneAtVersion({ remote }, canvasId, input.baseVersion, input.versionGiven);
4781
+ const operations = await input.plan(scene);
4782
+ if ("outcome" in operations) return operations;
4783
+ assertCanvasReferenceOperations(input.reference, scene, operations);
4784
+ if (operations.length === 0) return {
4785
+ outcome: "no_op",
4786
+ canvasId,
4787
+ version: input.baseVersion,
4788
+ verification: { rendered: false },
4789
+ warnings: []
4790
+ };
4791
+ const request = applyCanvasOperationsInputSchema.safeParse({
4792
+ canvasId,
4793
+ documentFormatVersion: 15,
4794
+ mutationId: input.clientToken,
4795
+ baseVersion: input.baseVersion,
4796
+ operations,
4797
+ requestContext: {
4798
+ fingerprint: input.fingerprint,
4799
+ revisionPolicy: "strict"
4800
+ }
4801
+ });
4802
+ if (!request.success) {
4803
+ const fields = inputProblemFields(request.error);
4804
+ throw new CliError("BAD_REQUEST", "The planned edit exceeds the canonical canvas contract.", `${inputProblemSummary(fields)} Reduce the edit scope.`, {
4805
+ ...fields,
4806
+ outcome: "not_committed"
4807
+ });
4808
+ }
4809
+ const committed = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request.data));
4810
+ input.committed?.(committed);
4811
+ return canvasWriteReceipt(committed, input.fingerprint);
4812
+ } });
4813
+
4814
+ //#endregion
4815
+ //#region src/application/edit-canvas.composite.ts
4816
+ const recoveredStructureWarning = () => `This receipt was recovered from an earlier commit of the same request, so duplicatedNodes and moves are not repeated. The copies are in affected.insertedNodeIds; ${inSurfaceWords({
4817
+ cli: "run canvas tree",
4818
+ mcp: "read the canvas again"
4819
+ })} for the layer order.`;
4820
+ const targetIds = (edit) => {
4821
+ switch (edit.kind) {
4822
+ case "set_text":
4823
+ case "rename": return [edit.nodeId];
4824
+ case "set_styles": return edit.nodeIds;
4825
+ case "duplicate": return [...edit.nodeIds, ...edit.parentId === void 0 ? [] : [edit.parentId]];
4826
+ case "move": return [edit.nodeId, edit.destination.kind === "parent" ? edit.destination.parentId : edit.destination.nodeId];
4827
+ }
4828
+ };
4829
+ const scopeIds = (edit, scene) => {
4830
+ if (edit.kind === "duplicate") return [...edit.nodeIds, ...edit.parentId === void 0 || edit.nodeIds.every((id) => scene.relationships[id]?.parentId === edit.parentId) ? [] : [edit.parentId]];
4831
+ if (edit.kind === "move" && edit.destination.kind === "parent" && scene.relationships[edit.nodeId]?.parentId === edit.destination.parentId) return [edit.nodeId];
4832
+ return targetIds(edit);
4833
+ };
4834
+ const referenceOf = (input) => ({
4835
+ canvasId: input.canvasId,
4836
+ nodeIds: [...input.nodeIds ?? []],
4837
+ ...input.pageId !== void 0 && { pageId: input.pageId }
4838
+ });
4839
+ const planEdits = (input, reference, scene) => {
4840
+ const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
4841
+ for (const id of ids) requireCanvasNode(scene, id);
4455
4842
  for (const edit of input.edits) assertCanvasReferenceNodes(reference, scene, scopeIds(edit, scene));
4843
+ const plan = planCanvasEdits(scene, input.edits, input.idPrefix ?? `copy_${input.mutationId.replaceAll("-", "")}`);
4844
+ assertCanvasReferenceOperations(reference, scene, plan.operations.filter((operation) => "nodeId" in operation && scene.nodes[operation.nodeId] !== void 0));
4845
+ return plan;
4846
+ };
4847
+ const insertedIds = (operation) => {
4848
+ if (operation.op === "insertNode") return [operation.node.id];
4849
+ if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
4850
+ return operation.op === "insertText" || operation.op === "insertPrototype" ? [operation.nodeId] : [];
4851
+ };
4852
+ const requireHeld = (scene, held, id) => {
4853
+ if (held.has(id)) return;
4854
+ throw new CliError("NOT_FOUND", scene.nodes[id] === void 0 ? `Canvas node ${id} does not exist.` : `Canvas node ${id} is removed by an earlier operation of this batch.`, currentNodeIdStep());
4855
+ };
4856
+ /**
4857
+ * Refuses a batch that names a layer the canvas does not hold when the operation runs.
4858
+ * The API answers such a removal as a committed change that removed nothing.
4859
+ */
4860
+ const requireOperationTargets = (scene, operations) => {
4861
+ const held = new Set(Object.keys(scene.nodes));
4862
+ for (const operation of operations) {
4863
+ const inserted = insertedIds(operation);
4864
+ for (const id of inserted) held.add(id);
4865
+ if (inserted.length > 0 || !("nodeId" in operation)) continue;
4866
+ requireHeld(scene, held, operation.nodeId);
4867
+ if (operation.op !== "remove") continue;
4868
+ held.delete(operation.nodeId);
4869
+ if (scene.nodes[operation.nodeId] === void 0) continue;
4870
+ for (const id of canvasDescendantIds(scene, operation.nodeId)) held.delete(id);
4871
+ }
4872
+ };
4873
+ const commitEdit = async (remote, edit) => {
4874
+ const stored = {};
4875
+ const receipt = await createRevisionedCanvasCommandComposite(remote).execute({
4876
+ reference: edit.reference,
4877
+ baseVersion: edit.baseVersion,
4878
+ versionGiven: "flag",
4879
+ clientToken: edit.mutationId,
4880
+ fingerprint: edit.fingerprint,
4881
+ plan: edit.plan,
4882
+ committed: (commit) => {
4883
+ stored.commit = commit;
4884
+ }
4885
+ });
4886
+ if (receipt.outcome === "no_op") return receipt;
4887
+ if (stored.commit === void 0) throw new TypeError("A committed canvas edit came back without what the API stored.");
4888
+ return {
4889
+ ...stored.commit,
4890
+ ...receipt,
4891
+ mutationCommitted: true
4892
+ };
4893
+ };
4894
+ const editReceipt = (receipt, plan, edits) => {
4895
+ if (receipt.outcome === "no_op") return receipt;
4896
+ const next = [`Reuse version ${String(receipt.version)} as ${inputName("baseVersion")} for the next edit; no extra read is required.`, `Render the affected screen at version ${String(receipt.version)} when ready for visual review.`];
4897
+ if (plan === void 0) {
4898
+ const isStructural = edits.some((edit) => edit.kind === "duplicate" || edit.kind === "move");
4899
+ return {
4900
+ ...receipt,
4901
+ next,
4902
+ warnings: [...receipt.warnings, ...isStructural ? [recoveredStructureWarning()] : []]
4903
+ };
4904
+ }
4905
+ return {
4906
+ ...receipt,
4907
+ next,
4908
+ ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
4909
+ ...plan.moves.length > 0 && {
4910
+ moves: plan.moves,
4911
+ affectedParents: plan.affectedParents
4912
+ }
4913
+ };
4914
+ };
4915
+ const createEditCanvasComposite = (remote) => ({
4916
+ execute: async (input) => {
4917
+ const reference = referenceOf(input);
4918
+ const planned = {};
4919
+ const receipt = await commitEdit(remote, {
4920
+ reference: {
4921
+ canvasId: input.canvasId,
4922
+ nodeIds: []
4923
+ },
4924
+ baseVersion: input.baseVersion,
4925
+ mutationId: input.mutationId,
4926
+ fingerprint: canvasExchangeDigest({
4927
+ operation: "canvas.edit/1",
4928
+ reference,
4929
+ baseVersion: input.baseVersion,
4930
+ edits: input.edits,
4931
+ idPrefix: input.idPrefix ?? null
4932
+ }),
4933
+ plan: (scene) => {
4934
+ planned.plan = planEdits(input, reference, scene);
4935
+ return planned.plan.operations;
4936
+ }
4937
+ });
4938
+ return editReceipt(receipt, planned.plan, input.edits);
4939
+ },
4940
+ apply: async (input) => {
4941
+ const reference = referenceOf(input);
4942
+ return commitEdit(remote, {
4943
+ reference,
4944
+ baseVersion: input.baseVersion,
4945
+ mutationId: input.mutationId,
4946
+ fingerprint: canvasExchangeDigest({
4947
+ operation: "canvas.apply/1",
4948
+ reference,
4949
+ baseVersion: input.baseVersion,
4950
+ operations: input.operations
4951
+ }),
4952
+ plan: (scene) => {
4953
+ requireOperationTargets(scene, input.operations);
4954
+ return input.operations;
4955
+ }
4956
+ });
4957
+ }
4958
+ });
4959
+
4960
+ //#endregion
4961
+ //#region src/application/result-page.use-case.ts
4962
+ const TARGET_PAGE_BYTES = 48e3;
4963
+ const boundedResultPage = (entries, offset, limit, maxBytes = TARGET_PAGE_BYTES) => {
4964
+ if (offset > entries.length) throw new CliError("BAD_REQUEST", "The result page offset is out of range.", "Restart pagination at offset 0.");
4965
+ const selected = [];
4966
+ let bytes = 2;
4967
+ const offered = entries.slice(offset, offset + limit);
4968
+ for (const entry of offered) {
4969
+ const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
4970
+ if (selected.length > 0 && bytes + size > maxBytes) break;
4971
+ selected.push(entry);
4972
+ bytes += size;
4973
+ }
4974
+ const nextOffset = offset + selected.length;
4975
+ return {
4976
+ entries: selected,
4977
+ total: entries.length,
4978
+ offset,
4979
+ nextOffset: nextOffset < entries.length ? nextOffset : null,
4980
+ complete: nextOffset === entries.length
4981
+ };
4982
+ };
4983
+
4984
+ //#endregion
4985
+ //#region src/application/canvas-conversion-status.use-case.ts
4986
+ const conversionEntries = (job) => {
4987
+ if (job.state !== "succeeded") return [];
4988
+ return [
4989
+ ...job.result.insertedNodeIds.map((nodeId) => ({
4990
+ kind: "inserted",
4991
+ nodeId
4992
+ })),
4993
+ ...job.result.removedNodeIds.map((nodeId) => ({
4994
+ kind: "removed",
4995
+ nodeId
4996
+ })),
4997
+ ...Object.entries(job.result.idMap).map(([temporaryId, nodeId]) => ({
4998
+ kind: "identity",
4999
+ temporaryId,
5000
+ nodeId
5001
+ })),
5002
+ ...job.result.report.issues.map((issue) => ({
5003
+ kind: "issue",
5004
+ issue
5005
+ }))
5006
+ ];
5007
+ };
5008
+ const conversionSummary = (job) => {
5009
+ if (job.state !== "succeeded") return null;
5010
+ return {
5011
+ mutationId: job.result.mutationId,
5012
+ previousVersion: job.result.previousVersion,
5013
+ version: job.result.version,
5014
+ rootNodeId: job.result.rootNodeId,
5015
+ affectedBounds: job.result.affectedBounds,
5016
+ insertedCount: job.result.insertedNodeIds.length,
5017
+ removedCount: job.result.removedNodeIds.length,
5018
+ identityCount: Object.keys(job.result.idMap).length,
5019
+ issueCount: job.result.report.issues.length
5020
+ };
5021
+ };
5022
+ const canvasConversionStatus = (job, page) => ({
5023
+ kind: "canvas-conversion",
5024
+ operation: {
5025
+ kind: "canvas-conversion",
5026
+ canvasId: job.canvasId,
5027
+ jobId: job.id
5028
+ },
5029
+ state: job.state,
5030
+ phase: job.phase,
5031
+ requestedVersion: job.requestedVersion,
5032
+ destination: job.destination,
5033
+ result: conversionSummary(job),
5034
+ failure: job.failure,
5035
+ details: boundedResultPage(conversionEntries(job), page.offset, page.limit),
5036
+ warnings: job.state === "succeeded" ? ["This receipt does not verify visual fidelity. Render the committed root to inspect it."] : []
5037
+ });
5038
+
5039
+ //#endregion
5040
+ //#region src/application/canvas-conversion.use-case.ts
5041
+ const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
5042
+ const READ_IMPORT_PROCEDURE$1 = "canvas.render.getImport";
5043
+ const POLL_MS$2 = 250;
5044
+ const invalidResponse$2 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
5045
+ const wait$1 = async (milliseconds) => new Promise((resolve) => {
5046
+ globalThis.setTimeout(resolve, milliseconds);
5047
+ });
5048
+ const terminalFailure = (job) => {
5049
+ const failure = job.failure;
5050
+ return new CliError(failure.reason === "VERSION_CHANGED" ? "CONFLICT" : failure.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : failure.reason === "TARGET_INVALID" || failure.reason === "CONVERSION_FAILED" ? "BAD_REQUEST" : "INTERNAL", failure.message, failure.retryable ? `Retry the exact write. If it repeats, ${inSurfaceWords({
5051
+ cli: "run `enhance doctor` and report the job id.",
5052
+ mcp: "the fault is in Enhance, not in this request: tell the person and report the job id."
5053
+ })}` : "Inspect the current canvas and correct the conversion source or destination before retrying.", {
5054
+ jobId: job.id,
5055
+ phase: failure.phase,
5056
+ reason: failure.reason
5057
+ });
5058
+ };
5059
+ const readImport = async (remote, jobId) => {
5060
+ const parsed = getCanvasConversionOutputSchema.safeParse(await remote.query(READ_IMPORT_PROCEDURE$1, { jobId }));
5061
+ if (!parsed.success) throw invalidResponse$2("conversion status");
5062
+ if (parsed.data.job.id !== jobId) throw invalidResponse$2("conversion identity");
5063
+ return parsed.data.job;
5064
+ };
5065
+ const awaitImport = async (remote, initial, timeoutMs) => {
5066
+ const deadline = Date.now() + timeoutMs;
5067
+ let job = initial;
5068
+ while (job.state === "queued" || job.state === "running") {
5069
+ if (Date.now() >= deadline) return job;
5070
+ await wait$1(POLL_MS$2);
5071
+ job = await readImport(remote, job.id);
5072
+ }
5073
+ if (job.state !== "succeeded") throw terminalFailure(job);
5074
+ return job;
5075
+ };
5076
+ const isMatchingDestination = (job, input) => {
5077
+ const actual = job.destination;
5078
+ const expected = input.request.destination;
5079
+ if (actual.kind !== expected.kind) return false;
5080
+ if (actual.kind === "adjacent" || expected.kind === "adjacent") return true;
5081
+ return actual.targetNodeId === expected.targetNodeId && (actual.kind !== "insert-children" || expected.kind !== "insert-children" || actual.pageId === expected.pageId);
5082
+ };
5083
+ const assertConversionIdentity = (job, input) => {
5084
+ const expected = input.request;
5085
+ if (job.canvasId !== expected.canvasId || job.requestedVersion !== expected.expectedVersion || !isMatchingDestination(job, input)) throw invalidResponse$2("conversion destination or revision");
5086
+ const source = job.source;
5087
+ if (source.kind !== expected.source.kind || source.kind === "screen" && expected.source.kind === "screen" && source.nodeId !== expected.source.nodeId || source.kind === "html" && expected.source.kind === "html" && source.label !== expected.source.label) throw invalidResponse$2("conversion source");
5088
+ if (job.state === "succeeded" && (job.result.canvasId !== expected.canvasId || expected.revisionPolicy === "strict" && job.result.previousVersion !== expected.expectedVersion)) throw invalidResponse$2("conversion commitment");
5089
+ };
5090
+ const runCanvasConversion = async (remote, input) => {
5091
+ const made = createCanvasConversionOutputSchema.safeParse(await remote.mutate(CREATE_IMPORT_PROCEDURE, input.request));
5092
+ if (!made.success) throw invalidResponse$2("conversion creation");
5093
+ assertConversionIdentity(made.data.job, input);
5094
+ const job = await awaitImport(remote, made.data.job, input.waitMs);
5095
+ assertConversionIdentity(job, input);
5096
+ return job;
5097
+ };
5098
+ /** The layers the API converts: a screen with a box, directly under the root. */
5099
+ const isConvertibleScreen = (scene, nodeId) => {
5100
+ const node = scene.nodes[nodeId];
5101
+ return node?.component === "screen" && node.box !== void 0 && scene.relationships[nodeId]?.parentId === "root";
5102
+ };
5103
+ const whatLayerIs = (scene, nodeId) => {
5104
+ const node = scene.nodes[nodeId];
5105
+ if (node === void 0) return "is not a layer on this canvas";
5106
+ if (node.component !== "screen") return `is a ${node.component} layer`;
5107
+ if (scene.relationships[nodeId]?.parentId !== "root") return "is a screen layer inside another layer";
5108
+ return "is a screen layer with no box";
5109
+ };
5110
+ const sceneOrNull = async (remote, canvasId) => {
5111
+ try {
5112
+ return readStoredCanvasScene(wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId })).document);
5113
+ } catch {
5114
+ return null;
5115
+ }
5116
+ };
5117
+ /**
5118
+ * The API's refusal of a source layer, said so an agent can choose again: what the command takes,
5119
+ * what the layer given is, and the layers that qualify. The API's own refusal comes back when the
5120
+ * layer does qualify, since it was then refused for another reason, and when the canvas cannot be
5121
+ * read to explain it.
5122
+ */
5123
+ const sourceRefusal = async (remote, source, refusal) => {
5124
+ const scene = await sceneOrNull(remote, source.canvasId);
5125
+ if (scene === null || isConvertibleScreen(scene, source.nodeId)) return refusal;
5126
+ const qualifying = Object.keys(scene.nodes).filter((nodeId) => isConvertibleScreen(scene, nodeId));
5127
+ return new CliError("BAD_REQUEST", `Making a layer editable takes a screen layer at the top of a page, and ${source.nodeId} ${whatLayerIs(scene, source.nodeId)}. ${qualifying.length === 0 ? "No layer on this canvas qualifies." : `The layers on this canvas that qualify: ${qualifying.join(", ")}.`}`, qualifying.length === 0 ? "Only a captured screen is converted. A frame and the layers inside it are edited as they are." : "Give one of those ids as the source. A frame and the layers inside it are edited as they are.");
5128
+ };
5129
+ const makeCanvasEditable = async (remote, offered) => {
5130
+ const input = canvasMakeEditableCapabilityInputSchema.parse(offered);
5131
+ const reference = parseCanvasReference(input.canvasRef);
5132
+ try {
5133
+ return canvasConversionStatus(await runCanvasConversion(remote, {
5134
+ request: {
5135
+ canvasId: reference.canvasId,
5136
+ expectedVersion: input.baseVersion,
5137
+ revisionPolicy: "strict",
5138
+ scope: {
5139
+ pageId: reference.pageId,
5140
+ nodeIds: [...reference.nodeIds]
5141
+ },
5142
+ source: {
5143
+ kind: "screen",
5144
+ nodeId: input.sourceNodeId
5145
+ },
5146
+ destination: input.placement
5147
+ },
5148
+ waitMs: input.waitMs
5149
+ }), {
5150
+ offset: 0,
5151
+ limit: 40
5152
+ });
5153
+ } catch (error) {
5154
+ if (!(error instanceof CliError) || error.code !== "BAD_REQUEST") throw error;
5155
+ throw await sourceRefusal(remote, {
5156
+ canvasId: reference.canvasId,
5157
+ nodeId: input.sourceNodeId
5158
+ }, error);
5159
+ }
5160
+ };
5161
+
5162
+ //#endregion
5163
+ //#region src/application/write-html-canvas.composite.ts
5164
+ const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
5165
+ const MAX_ACTIVITY_NODE_IDS = 100;
5166
+ const MAX_RECEIPT_ENTRIES = 40;
5167
+ const failedReview = (error, input, version) => {
5168
+ return {
5169
+ state: "failed",
5170
+ mutationCommitted: true,
5171
+ requestedVersion: version,
5172
+ ...error instanceof CliError ? {
5173
+ code: error.code,
5174
+ message: error.message,
5175
+ remediation: error.remediation,
5176
+ ...error.fields !== void 0 && { fields: error.fields }
5177
+ } : {
5178
+ code: "INTERNAL",
5179
+ message: "The post-write review render failed.",
5180
+ remediation: "Render the committed version and affected area again; do not replay the write."
5181
+ },
5182
+ next: [callOf("canvas.render", {
5183
+ cli: `--canvas ${input.canvasId} --expected-version ${String(version)}`,
5184
+ mcp: {
5185
+ canvasRef: input.canvasId,
5186
+ expectedVersion: version,
5187
+ target: { kind: "content" }
5188
+ }
5189
+ }), "Do not replay the committed write with a new mutation id."]
5190
+ };
5191
+ };
5192
+ const renderReview = async (render, input, imported) => {
5193
+ try {
5194
+ return await render.execute({
5195
+ canvasId: input.canvasId,
5196
+ expectedVersion: imported.result.version,
5197
+ target: {
5198
+ kind: "node",
5199
+ nodeId: imported.result.rootNodeId
5200
+ },
5201
+ sourceState: null,
5202
+ scale: input.renderScale,
5203
+ outputPath: input.renderOutputPath,
5204
+ overwrite: input.overwriteRender,
5205
+ timeoutMs: input.renderTimeoutMs,
5206
+ retryClientToken: input.renderClientToken
5207
+ });
5208
+ } catch (error) {
5209
+ return failedReview(error, input, imported.result.version);
5210
+ }
5211
+ };
5212
+ const createdNodes = async (remote, imported) => {
5213
+ const scene = await sceneAtVersion({ remote }, imported.canvasId, imported.result.version);
5214
+ return imported.result.insertedNodeIds.map((nodeId) => {
5215
+ const node = scene.nodes[nodeId];
5216
+ return {
5217
+ id: nodeId,
5218
+ name: node?.label ?? "",
5219
+ component: node?.component ?? ""
5220
+ };
5221
+ });
4456
5222
  };
4457
- const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
4458
- const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
4459
- validateTargets(input, scene);
4460
- const plan = planCanvasEdits(scene, input.edits, input.idPrefix ?? `copy_${input.mutationId.replaceAll("-", "")}`);
4461
- assertCanvasReferenceOperations({
5223
+ const committedResponse = (input, imported) => ({
5224
+ canvasId: input.canvasId,
5225
+ mutationCommitted: true,
5226
+ jobId: imported.id,
5227
+ mutationId: imported.result.mutationId,
5228
+ rootNodeId: imported.result.rootNodeId,
5229
+ mode: input.mode,
5230
+ targetNodeId: input.targetNodeId,
5231
+ previousVersion: imported.result.previousVersion,
5232
+ version: imported.result.version,
5233
+ insertedNodeIds: imported.result.insertedNodeIds,
5234
+ removedNodeIds: imported.result.removedNodeIds,
5235
+ affected: {
5236
+ inserted: imported.result.insertedNodeIds.length,
5237
+ changed: 0,
5238
+ removed: imported.result.removedNodeIds.length
5239
+ },
5240
+ affectedBounds: imported.result.affectedBounds
5241
+ });
5242
+ const pendingResponse = (job) => ({
5243
+ state: "pending",
5244
+ canvasId: job.canvasId,
5245
+ jobId: job.id,
5246
+ phase: job.phase,
5247
+ status: {
5248
+ tool: "capability_query",
5249
+ arguments: {
5250
+ capability: READ_IMPORT_PROCEDURE,
5251
+ input: { jobId: job.id }
5252
+ }
5253
+ },
5254
+ next: ["Read the existing import status; do not start another import."]
5255
+ });
5256
+ const conversionInput = (input) => ({
5257
+ waitMs: input.renderTimeoutMs,
5258
+ request: {
4462
5259
  canvasId: input.canvasId,
4463
- nodeIds: input.nodeIds ?? [],
4464
- ...input.pageId !== void 0 && { pageId: input.pageId }
4465
- }, scene, plan.operations.filter((operation) => "nodeId" in operation && scene.nodes[operation.nodeId] !== void 0));
4466
- const parsed = applyCanvasOperationsInputSchema.safeParse({
5260
+ expectedVersion: input.baseVersion,
5261
+ ...input.revisionPolicy !== void 0 && { revisionPolicy: input.revisionPolicy },
5262
+ ...(input.pageId !== void 0 || (input.selectionNodeIds?.length ?? 0) > 0) && { scope: {
5263
+ pageId: input.pageId,
5264
+ nodeIds: [...input.selectionNodeIds ?? []]
5265
+ } },
5266
+ source: {
5267
+ kind: "html",
5268
+ html: input.html,
5269
+ label: "Agent-authored HTML",
5270
+ ...input.idPrefix !== void 0 && { idPrefix: input.idPrefix }
5271
+ },
5272
+ destination: {
5273
+ kind: input.mode,
5274
+ targetNodeId: input.targetNodeId,
5275
+ ...input.mode === "insert-children" && input.pageId !== void 0 && { pageId: input.pageId }
5276
+ }
5277
+ }
5278
+ });
5279
+ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
5280
+ const activity = await createCanvasActivityComposite(remote).begin({
4467
5281
  canvasId: input.canvasId,
4468
- mutationId: input.mutationId,
4469
- documentFormatVersion: 15,
4470
- baseVersion: input.baseVersion,
4471
- operations: plan.operations
5282
+ phase: "creating",
5283
+ nodeIds: [input.targetNodeId],
5284
+ bounds: null
4472
5285
  });
4473
- 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.");
4474
- const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
4475
- return {
4476
- ...result,
4477
- next: [`Reuse version ${String(result.version)} as baseVersion for the next edit; no extra read is required.`, `Render the affected screen at version ${String(result.version)} when ready for visual review.`],
4478
- ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
4479
- ...plan.moves.length > 0 && {
4480
- moves: plan.moves,
4481
- affectedParents: plan.affectedParents
5286
+ try {
5287
+ const imported = await runCanvasConversion(remote, conversionInput(input));
5288
+ if (input.responseMode === "bounded") return canvasConversionStatus(imported, {
5289
+ offset: 0,
5290
+ limit: MAX_RECEIPT_ENTRIES
5291
+ });
5292
+ if (imported.state !== "succeeded") return pendingResponse(imported);
5293
+ if (input.review === "none") return committedResponse(input, imported);
5294
+ await activity?.update({
5295
+ phase: "rendering",
5296
+ nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
5297
+ bounds: imported.result.affectedBounds
5298
+ });
5299
+ const review = await renderReview(render, input, imported);
5300
+ let nodes = [];
5301
+ try {
5302
+ nodes = await createdNodes(remote, imported);
5303
+ } catch {
5304
+ nodes = [];
4482
5305
  }
4483
- };
5306
+ return {
5307
+ ...committedResponse(input, imported),
5308
+ createdNodes: nodes,
5309
+ review,
5310
+ next: ["Inspect the review PNG before continuing."]
5311
+ };
5312
+ } finally {
5313
+ await activity?.finish();
5314
+ }
4484
5315
  } });
4485
5316
 
4486
5317
  //#endregion
4487
- //#region src/infrastructure/capability-reference.mapper.ts
4488
- const fromCapabilityReference = (catalog, id) => {
4489
- const capability = catalog.find((candidate) => candidate.id === id);
4490
- if (capability === void 0) throw new TypeError(`${id} is missing from the capability catalogue`);
4491
- return capability;
4492
- };
4493
-
4494
- //#endregion
4495
- //#region src/application/result-page.use-case.ts
4496
- const TARGET_PAGE_BYTES = 48e3;
4497
- const boundedResultPage = (entries, offset, limit, maxBytes = TARGET_PAGE_BYTES) => {
4498
- if (offset > entries.length) throw new CliError("BAD_REQUEST", "The result page offset is out of range.", "Restart pagination at offset 0.");
4499
- const selected = [];
4500
- let bytes = 2;
4501
- const offered = entries.slice(offset, offset + limit);
4502
- for (const entry of offered) {
4503
- const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
4504
- if (selected.length > 0 && bytes + size > maxBytes) break;
4505
- selected.push(entry);
4506
- bytes += size;
4507
- }
4508
- const nextOffset = offset + selected.length;
5318
+ //#region src/application/read-canvas-reference.use-case.ts
5319
+ const readCanvasReferenceScene = async (remote, input) => {
5320
+ const reference = parseCanvasReference(input.canvas);
5321
+ const held = wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: reference.canvasId }));
5322
+ const document = readStoredCanvasScene(held.document);
5323
+ if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, document);
5324
+ if (input.nodeId !== void 0) assertCanvasReferenceNodes(reference, document, [input.nodeId]);
5325
+ const scope = resolveCanvasReference(input.nodeId === void 0 ? reference : {
5326
+ ...reference,
5327
+ nodeIds: [input.nodeId]
5328
+ }, document);
5329
+ 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.");
5330
+ const children = Object.groupBy(Object.entries(document.relationships), ([, relation]) => relation.parentId);
5331
+ const nodes = Object.values(document.nodes).filter((node) => scope.nodeIds.has(node.id)).map((node) => ({
5332
+ ...node,
5333
+ kind: node.component,
5334
+ parentId: document.relationships[node.id]?.parentId ?? null,
5335
+ children: (children[node.id] ?? []).map(([id]) => id)
5336
+ }));
4509
5337
  return {
4510
- entries: selected,
4511
- total: entries.length,
4512
- offset,
4513
- nextOffset: nextOffset < entries.length ? nextOffset : null,
4514
- complete: nextOffset === entries.length
5338
+ canvasId: reference.canvasId,
5339
+ version: held.version,
5340
+ pageId: scope.pageId,
5341
+ source: reference.nodeIds.length > 0 ? "selection-link" : reference.pageId === void 0 ? "canvas-link" : "page-link",
5342
+ selectedNodeIds: reference.nodeIds,
5343
+ rootNodeIds: scope.rootNodeIds,
5344
+ nodeCount: nodes.length,
5345
+ nodes,
5346
+ next: ["Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants."]
4515
5347
  };
4516
5348
  };
4517
5349
 
4518
5350
  //#endregion
4519
- //#region src/application/canvas-conversion-status.use-case.ts
4520
- const conversionEntries = (job) => {
4521
- if (job.state !== "succeeded") return [];
4522
- return [
4523
- ...job.result.insertedNodeIds.map((nodeId) => ({
4524
- kind: "inserted",
4525
- nodeId
4526
- })),
4527
- ...job.result.removedNodeIds.map((nodeId) => ({
4528
- kind: "removed",
4529
- nodeId
4530
- })),
4531
- ...Object.entries(job.result.idMap).map(([temporaryId, nodeId]) => ({
4532
- kind: "identity",
4533
- temporaryId,
4534
- nodeId
4535
- })),
4536
- ...job.result.report.issues.map((issue) => ({
4537
- kind: "issue",
4538
- issue
4539
- }))
4540
- ];
4541
- };
4542
- const conversionSummary = (job) => {
4543
- if (job.state !== "succeeded") return null;
4544
- return {
4545
- mutationId: job.result.mutationId,
4546
- previousVersion: job.result.previousVersion,
4547
- version: job.result.version,
4548
- rootNodeId: job.result.rootNodeId,
4549
- affectedBounds: job.result.affectedBounds,
4550
- insertedCount: job.result.insertedNodeIds.length,
4551
- removedCount: job.result.removedNodeIds.length,
4552
- identityCount: Object.keys(job.result.idMap).length,
4553
- issueCount: job.result.report.issues.length
4554
- };
5351
+ //#region src/infrastructure/render-file.adapter.ts
5352
+ const DIRECTORY_MODE = 448;
5353
+ const FILE_MODE = 384;
5354
+ const TEMPORARY_TTL_MS = 36e5;
5355
+ const refusalToReplace = (filePath) => new CliError("CONFLICT", `Refusing to replace ${filePath}.`, "Choose another --output path or pass --force deliberately.");
5356
+ const write = (filePath, body, shouldOverwrite) => {
5357
+ try {
5358
+ writeFileSync(filePath, body, {
5359
+ flag: shouldOverwrite ? "w" : "wx",
5360
+ mode: FILE_MODE
5361
+ });
5362
+ chmodSync(filePath, FILE_MODE);
5363
+ } catch (error) {
5364
+ if (typeof error === "object" && error !== null && Reflect.get(error, "code") === "EEXIST") throw refusalToReplace(filePath);
5365
+ throw new CliError("INTERNAL", `Could not write ${filePath}.`, "Create the parent directory and verify it is writable, then retry.");
5366
+ }
4555
5367
  };
4556
- const canvasConversionStatus = (job, page) => ({
4557
- kind: "canvas-conversion",
4558
- operation: {
4559
- kind: "canvas-conversion",
4560
- canvasId: job.canvasId,
4561
- jobId: job.id
5368
+ const createRenderFileAdapter = (configDirectory) => ({
5369
+ refuseExisting: (offeredPath) => {
5370
+ const outputPath = path.resolve(offeredPath);
5371
+ if (existsSync(outputPath)) throw refusalToReplace(outputPath);
4562
5372
  },
4563
- state: job.state,
4564
- phase: job.phase,
4565
- requestedVersion: job.requestedVersion,
4566
- destination: job.destination,
4567
- result: conversionSummary(job),
4568
- failure: job.failure,
4569
- details: boundedResultPage(conversionEntries(job), page.offset, page.limit),
4570
- warnings: job.state === "succeeded" ? ["This receipt does not verify visual fidelity. Render the committed root to inspect it."] : []
5373
+ write: (input) => {
5374
+ if (input.outputPath !== null) {
5375
+ const outputPath = path.resolve(input.outputPath);
5376
+ write(outputPath, input.body, input.overwrite);
5377
+ return {
5378
+ path: outputPath,
5379
+ temporary: false,
5380
+ deleteAfter: null
5381
+ };
5382
+ }
5383
+ const directory = path.join(configDirectory, "sensitive");
5384
+ mkdirSync(directory, {
5385
+ recursive: true,
5386
+ mode: DIRECTORY_MODE
5387
+ });
5388
+ chmodSync(directory, DIRECTORY_MODE);
5389
+ const outputPath = path.join(directory, `render-${globalThis.crypto.randomUUID()}.png`);
5390
+ write(outputPath, input.body, false);
5391
+ return {
5392
+ path: outputPath,
5393
+ temporary: true,
5394
+ deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
5395
+ };
5396
+ }
4571
5397
  });
4572
5398
 
4573
5399
  //#endregion
4574
- //#region src/application/canvas-conversion.use-case.ts
4575
- const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
4576
- const READ_IMPORT_PROCEDURE$1 = "canvas.render.getImport";
4577
- const POLL_MS$2 = 250;
4578
- const invalidResponse$2 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
4579
- const wait$1 = async (milliseconds) => new Promise((resolve) => {
4580
- globalThis.setTimeout(resolve, milliseconds);
4581
- });
4582
- const terminalFailure = (job) => {
4583
- const failure = job.failure;
4584
- return new CliError(failure.reason === "VERSION_CHANGED" ? "CONFLICT" : failure.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : failure.reason === "TARGET_INVALID" || failure.reason === "CONVERSION_FAILED" ? "BAD_REQUEST" : "INTERNAL", failure.message, failure.retryable ? "Retry the exact write. If it repeats, run `enhance doctor` and report the job id." : "Inspect the current canvas and correct the conversion source or destination before retrying.", {
4585
- jobId: job.id,
4586
- phase: failure.phase,
4587
- reason: failure.reason
4588
- });
4589
- };
4590
- const readImport = async (remote, jobId) => {
4591
- const parsed = getCanvasConversionOutputSchema.safeParse(await remote.query(READ_IMPORT_PROCEDURE$1, { jobId }));
4592
- if (!parsed.success) throw invalidResponse$2("conversion status");
4593
- if (parsed.data.job.id !== jobId) throw invalidResponse$2("conversion identity");
4594
- return parsed.data.job;
5400
+ //#region src/application/canvas-preparation.use-case.ts
5401
+ const POLL_MS$1 = 250;
5402
+ const readPreparation = async (remote, jobId) => {
5403
+ try {
5404
+ return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
5405
+ } catch (error) {
5406
+ if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
5407
+ return null;
5408
+ }
4595
5409
  };
4596
- const awaitImport = async (remote, initial, timeoutMs) => {
4597
- const deadline = Date.now() + timeoutMs;
5410
+ const waitForPreparation = async (remote, initial, waitMs) => {
5411
+ const deadline = Date.now() + waitMs;
4598
5412
  let job = initial;
4599
5413
  while (job.state === "queued" || job.state === "running") {
4600
- if (Date.now() >= deadline) return job;
4601
- await wait$1(POLL_MS$2);
4602
- job = await readImport(remote, job.id);
5414
+ const remaining = deadline - Date.now();
5415
+ if (remaining <= 0) break;
5416
+ await setTimeout$1(Math.min(POLL_MS$1, remaining));
5417
+ const status = await readPreparation(remote, initial.id);
5418
+ if (status === null) return job;
5419
+ job = getCanvasPreparationOutputSchema.parse(status.value).job;
5420
+ if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
4603
5421
  }
4604
- if (job.state !== "succeeded") throw terminalFailure(job);
4605
5422
  return job;
4606
5423
  };
4607
- const isMatchingDestination = (job, input) => {
4608
- const actual = job.destination;
4609
- const expected = input.request.destination;
4610
- if (actual.kind !== expected.kind) return false;
4611
- if (actual.kind === "adjacent" || expected.kind === "adjacent") return true;
4612
- return actual.targetNodeId === expected.targetNodeId && (actual.kind !== "insert-children" || expected.kind !== "insert-children" || actual.pageId === expected.pageId);
4613
- };
4614
- const assertConversionIdentity = (job, input) => {
4615
- const expected = input.request;
4616
- if (job.canvasId !== expected.canvasId || job.requestedVersion !== expected.expectedVersion || !isMatchingDestination(job, input)) throw invalidResponse$2("conversion destination or revision");
4617
- const source = job.source;
4618
- if (source.kind !== expected.source.kind || source.kind === "screen" && expected.source.kind === "screen" && source.nodeId !== expected.source.nodeId || source.kind === "html" && expected.source.kind === "html" && source.label !== expected.source.label) throw invalidResponse$2("conversion source");
4619
- if (job.state === "succeeded" && (job.result.canvasId !== expected.canvasId || expected.revisionPolicy === "strict" && job.result.previousVersion !== expected.expectedVersion)) throw invalidResponse$2("conversion commitment");
4620
- };
4621
- const runCanvasConversion = async (remote, input) => {
4622
- const made = createCanvasConversionOutputSchema.safeParse(await remote.mutate(CREATE_IMPORT_PROCEDURE, input.request));
4623
- if (!made.success) throw invalidResponse$2("conversion creation");
4624
- assertConversionIdentity(made.data.job, input);
4625
- const job = await awaitImport(remote, made.data.job, input.waitMs);
4626
- assertConversionIdentity(job, input);
5424
+ const runCanvasPreparation = async (remote, input, waitMs) => {
5425
+ const made = createCanvasPreparationOutputSchema.parse(await remote.mutate("canvas.render.preparation.create", input));
5426
+ const job = await waitForPreparation(remote, made.job, waitMs);
5427
+ if (job.canvasId !== input.canvasId || job.requestedVersion !== input.expectedVersion || !isDeepStrictEqual(job.scope, input.scope) || !isDeepStrictEqual(job.request, input.request)) throw new CliError("CONFLICT", "The native preparation does not match this request.", "Read the canvas and prepare a new intent; do not apply this plan.");
5428
+ if (job.state === "succeeded" && job.result.loadedVersion !== input.expectedVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
4627
5429
  return job;
4628
5430
  };
4629
- const makeCanvasEditable = async (remote, offered) => {
4630
- const input = canvasMakeEditableCapabilityInputSchema.parse(offered);
4631
- const reference = parseCanvasReference(input.canvasRef);
4632
- return canvasConversionStatus(await runCanvasConversion(remote, {
4633
- request: {
4634
- canvasId: reference.canvasId,
4635
- expectedVersion: input.baseVersion,
4636
- revisionPolicy: "strict",
4637
- scope: {
4638
- pageId: reference.pageId,
4639
- nodeIds: [...reference.nodeIds]
4640
- },
4641
- source: {
4642
- kind: "screen",
4643
- nodeId: input.sourceNodeId
4644
- },
4645
- destination: input.placement
4646
- },
4647
- waitMs: input.waitMs
4648
- }), {
4649
- offset: 0,
4650
- limit: 40
4651
- });
4652
- };
4653
5431
 
4654
5432
  //#endregion
4655
- //#region src/application/write-html-canvas.composite.ts
4656
- const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
4657
- const MAX_ACTIVITY_NODE_IDS = 100;
4658
- const MAX_RECEIPT_ENTRIES = 40;
4659
- const failedReview = (error, input, version) => {
5433
+ //#region src/application/captured-frame.use-case.ts
5434
+ /** What to do about a capture that has not finished, naming the command that started it. */
5435
+ const followCapture = (capability) => `Repeat ${commandName(capability)} with identical arguments and ${inputName("clientToken")}, or follow ${commandName("operation.status")}. An unfinished step is not proof that nothing was saved.`;
5436
+ const frameSaveOf = (capture) => ({
5437
+ ...capture,
5438
+ baseVersion: capture.input.baseVersion,
5439
+ command: "canvas.capture"
5440
+ });
5441
+ const mutationOf$1 = (save) => ({
5442
+ kind: "canvas-mutation",
5443
+ canvasId: save.canvasId,
5444
+ mutationId: save.clientToken,
5445
+ fingerprint: save.fingerprint
5446
+ });
5447
+ const attachmentOf = (state) => state === "queued" || state === "running" ? "pending" : "not_confirmed";
5448
+ const captureReceipt = (capture, step) => ({
5449
+ operation: step.operation,
5450
+ state: step.state,
5451
+ requestedVersion: capture.input.baseVersion,
5452
+ source: capture.input.source,
5453
+ attachment: step.frame === void 0 || step.frame === null ? attachmentOf(step.state) : "committed",
5454
+ result: step.result,
5455
+ frame: step.frame ?? null,
5456
+ failure: step.failure,
5457
+ warningCount: 1,
5458
+ warnings: [step.warning]
5459
+ });
5460
+ /** The receipt of a saved capture: the frame, its version, and the change to follow. */
5461
+ const savedCaptureReceipt = (capture, saved, result, frameNodeId) => captureReceipt(capture, {
5462
+ operation: mutationOf$1(frameSaveOf(capture)),
5463
+ state: "succeeded",
5464
+ result,
5465
+ failure: null,
5466
+ frame: {
5467
+ nodeId: frameNodeId,
5468
+ version: saved.version
5469
+ },
5470
+ warning: "The capture is saved as an editable frame. Render the frame at its version to inspect it."
5471
+ });
5472
+ const recordingProvenance = (recording) => ({
5473
+ kind: "recording",
5474
+ recordingId: recording.recordingId,
5475
+ atMs: recording.atMs
5476
+ });
5477
+ /**
5478
+ * The compiled page as a capture's frame: at its place, every layer naming its stored page. A
5479
+ * walkthrough moment also names its walkthrough; a page an agent opened has no walkthrough.
5480
+ */
5481
+ const frameAt = (operation, place, provenance) => {
5482
+ const nodes = Object.fromEntries(Object.entries(operation.nodes).map(([id, node]) => {
5483
+ const props = {
5484
+ ...node.props,
5485
+ capturedResource: { screenId: place.screenId }
5486
+ };
5487
+ if (id !== operation.rootNodeId) return [id, {
5488
+ ...node,
5489
+ props
5490
+ }];
5491
+ const conversion = node.props?.["conversion"];
5492
+ return [id, {
5493
+ ...node,
5494
+ ...node.box !== void 0 && { box: {
5495
+ ...node.box,
5496
+ x: place.x,
5497
+ y: place.y
5498
+ } },
5499
+ props: provenance === void 0 ? props : {
5500
+ ...props,
5501
+ conversion: {
5502
+ ...typeof conversion === "object" && conversion,
5503
+ provenance
5504
+ }
5505
+ }
5506
+ }];
5507
+ }));
4660
5508
  return {
4661
- state: "failed",
4662
- mutationCommitted: true,
4663
- requestedVersion: version,
4664
- ...error instanceof CliError ? {
4665
- code: error.code,
4666
- message: error.message,
4667
- remediation: error.remediation,
4668
- ...error.fields !== void 0 && { fields: error.fields }
4669
- } : {
4670
- code: "INTERNAL",
4671
- message: "The post-write review render failed.",
4672
- remediation: "Render the committed version and affected area again; do not replay the write."
5509
+ ...operation,
5510
+ destination: {
5511
+ kind: "insert-children",
5512
+ targetNodeId: "root",
5513
+ ...place.pageId !== void 0 && { pageId: place.pageId }
4673
5514
  },
4674
- next: [`enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`, "Do not replay the committed write with a new mutation id."]
5515
+ nodes
4675
5516
  };
4676
5517
  };
4677
- const renderReview = async (render, input, imported) => {
5518
+ const notConfirmed = (save, error) => new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The captured frame could not be confirmed.", followCapture(save.command), {
5519
+ ...error instanceof CliError && error.fields,
5520
+ outcome: "not_confirmed",
5521
+ operation: JSON.stringify(mutationOf$1(save))
5522
+ });
5523
+ /** The codes the API refuses a write with: it answered, so nothing was saved under this intent. */
5524
+ const REFUSED_CODES = /* @__PURE__ */ new Set([
5525
+ "BAD_REQUEST",
5526
+ "FORBIDDEN",
5527
+ "UNAUTHORIZED",
5528
+ "NOT_FOUND",
5529
+ "CONFLICT"
5530
+ ]);
5531
+ /** A refusal as the API gave it, marked not committed, with no reference: there is no write to find. */
5532
+ const refusalOf = (error) => error instanceof CliError && REFUSED_CODES.has(error.code) ? new CliError(error.code, error.message, error.remediation, {
5533
+ ...error.fields,
5534
+ outcome: "not_committed"
5535
+ }) : null;
5536
+ /** The one frame a compile made, or a named refusal when it made anything else. */
5537
+ const compiledFrameOf = (job) => {
5538
+ const [compiled] = job.result.operations;
5539
+ if (job.result.operations.length !== 1 || compiled?.op !== "insertConvertedSubtree") throw new CliError("INTERNAL", "The compiled capture is not one editable frame.", "Capture the page again with a new clientToken.");
5540
+ return compiled;
5541
+ };
5542
+ const appliedOrNotConfirmed = async (remote, save, request) => {
4678
5543
  try {
4679
- return await render.execute({
4680
- canvasId: input.canvasId,
4681
- expectedVersion: imported.result.version,
4682
- target: {
4683
- kind: "node",
4684
- nodeId: imported.result.rootNodeId
4685
- },
4686
- sourceState: null,
4687
- scale: input.renderScale,
4688
- outputPath: input.renderOutputPath,
4689
- overwrite: input.overwriteRender,
4690
- timeoutMs: input.renderTimeoutMs,
4691
- retryClientToken: input.renderClientToken
4692
- });
5544
+ return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
4693
5545
  } catch (error) {
4694
- return failedReview(error, input, imported.result.version);
5546
+ if (isFormatRefusalError(error)) throw error;
5547
+ throw refusalOf(error) ?? notConfirmed(save, error);
4695
5548
  }
4696
5549
  };
4697
- const createdNodes = async (remote, imported) => {
4698
- const scene = await sceneAtVersion({ remote }, imported.canvasId, imported.result.version);
4699
- return imported.result.insertedNodeIds.map((nodeId) => {
4700
- const node = scene.nodes[nodeId];
4701
- return {
4702
- id: nodeId,
4703
- name: node?.label ?? "",
4704
- component: node?.component ?? ""
4705
- };
5550
+ /** Saves a capture's frame as one change at the version the agent observed, and confirms it. */
5551
+ const saveFrame = async (remote, save, frame, revisionPolicy = "strict") => {
5552
+ const savedId = frame.op === "insertNode" ? frame.node.id : frame.rootNodeId;
5553
+ const request = applyCanvasOperationsInputSchema.parse({
5554
+ canvasId: save.canvasId,
5555
+ mutationId: save.clientToken,
5556
+ documentFormatVersion: 15,
5557
+ baseVersion: save.baseVersion,
5558
+ operations: [frame],
5559
+ requestContext: {
5560
+ fingerprint: save.fingerprint,
5561
+ revisionPolicy
5562
+ }
4706
5563
  });
5564
+ const saved = await appliedOrNotConfirmed(remote, save, request);
5565
+ if (saved.canvasId !== save.canvasId || saved.mutationId !== save.clientToken || (revisionPolicy === "strict" ? saved.version !== save.baseVersion + 1 : saved.version <= save.baseVersion) || ![...saved.insertedNodeIds, ...saved.changedNodeIds].includes(savedId)) throw notConfirmed(save, null);
5566
+ return saved;
5567
+ };
5568
+ /** Saves the compiled capture as one change at the version the agent observed. */
5569
+ const saveCapturedFrame = async (remote, capture, job, snapshot) => {
5570
+ const compiled = compiledFrameOf(job);
5571
+ const saved = await saveFrame(remote, frameSaveOf(capture), frameAt(compiled, {
5572
+ screenId: snapshot.screenId,
5573
+ x: snapshot.box.x,
5574
+ y: snapshot.box.y,
5575
+ pageId: snapshot.pageId
5576
+ }, recordingProvenance(capture.input.source)));
5577
+ return savedCaptureReceipt(capture, saved, snapshot, compiled.rootNodeId);
4707
5578
  };
4708
- const committedResponse = (input, imported) => ({
4709
- canvasId: input.canvasId,
4710
- mutationCommitted: true,
4711
- jobId: imported.id,
4712
- mutationId: imported.result.mutationId,
4713
- rootNodeId: imported.result.rootNodeId,
4714
- mode: input.mode,
4715
- targetNodeId: input.targetNodeId,
4716
- previousVersion: imported.result.previousVersion,
4717
- version: imported.result.version,
4718
- insertedNodeIds: imported.result.insertedNodeIds,
4719
- removedNodeIds: imported.result.removedNodeIds,
4720
- affected: {
4721
- inserted: imported.result.insertedNodeIds.length,
4722
- changed: 0,
4723
- removed: imported.result.removedNodeIds.length
4724
- },
4725
- affectedBounds: imported.result.affectedBounds
5579
+
5580
+ //#endregion
5581
+ //#region src/application/snapshot-recording.composite.ts
5582
+ const POLL_MS = 250;
5583
+ const PROGRESS_HEARTBEAT_MS = 5e3;
5584
+ const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
5585
+ const wait = async () => new Promise((resolve) => {
5586
+ globalThis.setTimeout(resolve, POLL_MS);
4726
5587
  });
4727
- const pendingResponse = (job) => ({
4728
- state: "pending",
4729
- canvasId: job.canvasId,
5588
+ const failureOf$1 = (job) => new CliError(job.failure?.reason === "VERSION_CHANGED" ? "CONFLICT" : job.failure?.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : job.failure?.reason === "TARGET_INVALID" || job.failure?.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL", job.failure?.message ?? "The snapshot job ended without a result.", `${inSurfaceWords({
5589
+ cli: `Run 'enhance canvas tree --canvas ${job.canvasId}'`,
5590
+ mcp: "Read the canvas again"
5591
+ })} and retry the exact snapshot if its recording node still exists.`, {
4730
5592
  jobId: job.id,
4731
- phase: job.phase,
4732
- status: {
4733
- tool: "capability_query",
4734
- arguments: {
4735
- capability: READ_IMPORT_PROCEDURE,
4736
- input: { jobId: job.id }
4737
- }
4738
- },
4739
- next: ["Read the existing import status; do not start another import."]
5593
+ phase: job.phase
4740
5594
  });
4741
- const conversionInput = (input) => ({
4742
- waitMs: input.renderTimeoutMs,
4743
- request: {
5595
+ const readSnapshotJob = async (remote, jobId) => {
5596
+ const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
5597
+ if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", diagnosisStep(`Run \`enhance doctor\` and report snapshot job ${jobId}.`, `snapshot job ${jobId}`));
5598
+ return read.data.job;
5599
+ };
5600
+ const awaitSnapshot = async (remote, initial, input, progress) => {
5601
+ const deadline = Date.now() + input.timeoutMs;
5602
+ const startedAt = Date.now();
5603
+ let job = initial;
5604
+ let lastReportedAt = 0;
5605
+ let lastReportedState = "";
5606
+ while (job.state === "queued" || job.state === "running") {
5607
+ const currentTime = Date.now();
5608
+ const stateKey = `${job.state}:${job.phase}`;
5609
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
5610
+ progress({
5611
+ event: "snapshot.progress",
5612
+ jobId: job.id,
5613
+ state: job.state,
5614
+ phase: job.phase,
5615
+ elapsedMs: currentTime - startedAt,
5616
+ timeoutMs: input.timeoutMs,
5617
+ retryClientToken: input.retryClientToken
5618
+ });
5619
+ lastReportedAt = currentTime;
5620
+ lastReportedState = stateKey;
5621
+ }
5622
+ if (currentTime >= deadline) {
5623
+ if (input.bounded === true) return job;
5624
+ throw new CliError("INTERNAL", `Snapshot ${job.id} did not finish before the local timeout.`, `Retry this exact ${inSurfaceWords({
5625
+ cli: "command",
5626
+ mcp: "request"
5627
+ })} with ${inputName("clientToken")} ${input.retryClientToken} and a larger ${inputName("timeoutMs")}.`, {
5628
+ jobId: job.id,
5629
+ phase: job.phase
5630
+ });
5631
+ }
5632
+ await wait();
5633
+ const next = await readSnapshotJob(remote, job.id);
5634
+ if (next.id !== initial.id) throw invalidSnapshot();
5635
+ assertSnapshotIdentity(next, input);
5636
+ job = next;
5637
+ }
5638
+ return job;
5639
+ };
5640
+ const invalidSnapshot = () => new CliError("INTERNAL", "The snapshot response does not match the requested source or revision.", diagnosisStep("Run enhance doctor and report the capture job ID.", "the capture job ID"));
5641
+ /** A place-only snapshot adds no layer and no revision; a screen snapshot adds both. */
5642
+ const isPlacedAsExpected = (result, input) => input.context?.request.placement.kind === "editable-below-source" ? result.screenNodeId === null && result.version === input.context.expectedVersion : result.screenNodeId === `scr_${input.recordingId}_${String(input.atMs)}` && (input.context === void 0 || result.version === input.context.expectedVersion + 1);
5643
+ const assertSnapshotIdentity = (job, input) => {
5644
+ if (job.canvasId !== input.canvasId || job.purpose !== "snapshot" || job.sourceState?.recordingId !== input.recordingId || job.sourceState.atMs !== input.atMs || input.context !== void 0 && job.requestedVersion !== input.context.expectedVersion) throw invalidSnapshot();
5645
+ if (job.state !== "succeeded") return;
5646
+ const result = job.result.snapshot;
5647
+ const source = job.result.sourceState;
5648
+ if (job.result.canvasId !== input.canvasId || job.result.loadedVersion !== job.requestedVersion || job.result.requestedVersion !== job.requestedVersion || source?.recordingId !== input.recordingId || source.requestedAtMs !== input.atMs || source.settledAtMs !== input.atMs || result?.recordingId !== input.recordingId || result.atMs !== input.atMs || result.screenId !== job.id || !isPlacedAsExpected(result, input)) throw invalidSnapshot();
5649
+ };
5650
+ /** Creates the snapshot job and follows it until it ends or, when bounded, the wait runs out. */
5651
+ const runSnapshot = async (remote, progress, input) => {
5652
+ const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
4744
5653
  canvasId: input.canvasId,
4745
- expectedVersion: input.baseVersion,
4746
- ...input.revisionPolicy !== void 0 && { revisionPolicy: input.revisionPolicy },
4747
- ...(input.pageId !== void 0 || (input.selectionNodeIds?.length ?? 0) > 0) && { scope: {
4748
- pageId: input.pageId,
4749
- nodeIds: [...input.selectionNodeIds ?? []]
4750
- } },
4751
- source: {
4752
- kind: "html",
4753
- html: input.html,
4754
- label: "Agent-authored HTML",
4755
- ...input.idPrefix !== void 0 && { idPrefix: input.idPrefix }
5654
+ recordingId: input.recordingId,
5655
+ atMs: input.atMs,
5656
+ ...input.context !== void 0 && { context: input.context }
5657
+ }));
5658
+ if (!made.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot creation response.", diagnosisStep("Run `enhance doctor` and report the API and CLI versions."));
5659
+ assertSnapshotIdentity(made.data.job, input);
5660
+ return awaitSnapshot(remote, made.data.job, input, progress);
5661
+ };
5662
+ const executeSnapshot = async (remote, progress, input) => {
5663
+ const held = await runSnapshot(remote, progress, input);
5664
+ if (held.state !== "succeeded" || held.result.snapshot === void 0) throw failureOf$1(held);
5665
+ const job = {
5666
+ ...held,
5667
+ result: {
5668
+ ...held.result,
5669
+ snapshot: held.result.snapshot
5670
+ }
5671
+ };
5672
+ const snapshot = job.result.snapshot;
5673
+ const { screenNodeId } = snapshot;
5674
+ if (screenNodeId === null) throw invalidSnapshot();
5675
+ return {
5676
+ jobId: job.id,
5677
+ canvasId: job.canvasId,
5678
+ ...snapshot,
5679
+ warnings: job.result.warnings,
5680
+ retryClientToken: input.retryClientToken,
5681
+ next: [callOf("canvas.node", {
5682
+ cli: `--canvas ${job.canvasId} --node-id ${screenNodeId}`,
5683
+ mcp: {
5684
+ canvasId: job.canvasId,
5685
+ nodeId: screenNodeId
5686
+ }
5687
+ }), renderNodeCall(job.canvasId, screenNodeId, snapshot.version)]
5688
+ };
5689
+ };
5690
+ const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
5691
+
5692
+ //#endregion
5693
+ //#region src/application/canvas-capture.composite.ts
5694
+ const CANVAS_CAPTURE_PROCEDURES = ["canvas.mutation.get"];
5695
+ const compileAndSave = async (remote, capture, snapshot, waitMs) => {
5696
+ const job = await runCanvasPreparation(remote, {
5697
+ canvasId: capture.canvasId,
5698
+ expectedVersion: capture.input.baseVersion,
5699
+ request: {
5700
+ kind: "compile-screens",
5701
+ landing: "editable-frame",
5702
+ sources: [{
5703
+ screenId: snapshot.screenId,
5704
+ captureId: snapshot.screenId
5705
+ }]
4756
5706
  },
4757
- destination: {
4758
- kind: input.mode,
4759
- targetNodeId: input.targetNodeId,
4760
- ...input.mode === "insert-children" && input.pageId !== void 0 && { pageId: input.pageId }
5707
+ scope: { nodeIds: [] }
5708
+ }, waitMs);
5709
+ if (job.state === "succeeded") return saveCapturedFrame(remote, capture, job, snapshot);
5710
+ return captureReceipt(capture, {
5711
+ operation: {
5712
+ kind: "canvas-preparation",
5713
+ canvasId: capture.canvasId,
5714
+ jobId: job.id,
5715
+ mutationId: capture.clientToken,
5716
+ fingerprint: capture.fingerprint
5717
+ },
5718
+ state: job.state,
5719
+ result: snapshot,
5720
+ failure: job.failure,
5721
+ warning: job.state === "queued" || job.state === "running" ? `The page is stored and still being made editable. ${followCapture("canvas.capture")}` : `The page could not be made editable, and nothing was added to the canvas. Capture the moment again with a new ${inputName("clientToken")}.`
5722
+ });
5723
+ };
5724
+ /** The snapshot stores the page and names the frame's place, adding no layer. */
5725
+ const storeMoment = async (remote, capture, pageId, nodeIds) => runSnapshot(remote, () => null, {
5726
+ canvasId: capture.canvasId,
5727
+ recordingId: capture.input.source.recordingId,
5728
+ atMs: capture.input.source.atMs,
5729
+ retryClientToken: capture.clientToken,
5730
+ timeoutMs: capture.input.waitMs,
5731
+ bounded: true,
5732
+ context: {
5733
+ expectedVersion: capture.input.baseVersion,
5734
+ request: {
5735
+ previewJobId: capture.input.previewJobId,
5736
+ scope: {
5737
+ pageId,
5738
+ nodeIds: [...nodeIds]
5739
+ },
5740
+ placement: { kind: "editable-below-source" }
4761
5741
  }
4762
5742
  }
4763
5743
  });
4764
- const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
4765
- const activity = await createCanvasActivityComposite(remote).begin({
4766
- canvasId: input.canvasId,
4767
- phase: "creating",
4768
- nodeIds: [input.targetNodeId],
4769
- bounds: null
5744
+ /**
5745
+ * Lands a recording moment as an editable frame: the snapshot stores the page and names its
5746
+ * place, the API compiles it, and this saves the frame as one change at the observed version.
5747
+ */
5748
+ const captureCanvasRecording = async (remote, offered, clientToken) => {
5749
+ const input = canvasCaptureCapabilityInputSchema.parse(offered);
5750
+ const reference = parseCanvasReference(input.canvasRef);
5751
+ const capture = {
5752
+ input,
5753
+ canvasId: reference.canvasId,
5754
+ clientToken,
5755
+ fingerprint: canvasExchangeDigest({
5756
+ operation: "canvas.capture/2",
5757
+ reference,
5758
+ baseVersion: input.baseVersion,
5759
+ source: input.source,
5760
+ previewJobId: input.previewJobId
5761
+ })
5762
+ };
5763
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_CAPTURE_PROCEDURES[0], {
5764
+ canvasId: capture.canvasId,
5765
+ mutationId: clientToken,
5766
+ fingerprint: capture.fingerprint
5767
+ }));
5768
+ if (recovered.state === "committed") return savedCaptureReceipt(capture, recovered.result, null, recovered.result.insertedNodeIds[0] ?? "");
5769
+ const startedAt = Date.now();
5770
+ const job = await storeMoment(remote, capture, reference.pageId, reference.nodeIds);
5771
+ const snapshot = job.state === "succeeded" ? job.result.snapshot : void 0;
5772
+ if (snapshot === void 0) return captureReceipt(capture, {
5773
+ operation: {
5774
+ kind: "canvas-render",
5775
+ canvasId: job.canvasId,
5776
+ jobId: job.id
5777
+ },
5778
+ state: job.state,
5779
+ result: null,
5780
+ failure: job.failure,
5781
+ warning: job.state === "queued" || job.state === "running" ? `The moment is still being stored. ${followCapture("canvas.capture")}` : "The moment could not be stored, and nothing was added to the canvas."
4770
5782
  });
5783
+ return compileAndSave(remote, capture, snapshot, Math.max(0, input.waitMs - (Date.now() - startedAt)));
5784
+ };
5785
+
5786
+ //#endregion
5787
+ //#region src/application/capture-page-landing.use-case.ts
5788
+ /** What the picture of a captured page is called when the agent gave no title. */
5789
+ const CAPTURED_PAGE_LABEL = "Captured page";
5790
+ /** The prop that puts a layer on a page of the canvas, as the editor writes it. */
5791
+ const CANVAS_PAGE_ID_PROP = "canvasPageId";
5792
+ /**
5793
+ * The picture's size when the agent gives none. The stored page's own size cannot be read here:
5794
+ * the API lists a stored page only once a layer names it, and this picture is that layer.
5795
+ */
5796
+ const PICTURE_SIZE = {
5797
+ width: 1280,
5798
+ height: 800
5799
+ };
5800
+ const receipt = (step, fields) => ({
5801
+ step,
5802
+ snippet: fields.snippet ?? null,
5803
+ picture: fields.picture ?? null,
5804
+ passExpiresAt: fields.passExpiresAt ?? null,
5805
+ operation: fields.operation ?? null,
5806
+ frame: fields.frame ?? null,
5807
+ url: fields.url ?? null,
5808
+ failure: fields.failure ?? null,
5809
+ warningCount: 1 + (fields.further?.length ?? 0),
5810
+ warnings: [fields.warning, ...fields.further ?? []]
5811
+ });
5812
+ /** A second intent of the same call, derived so a repeat of the call names the same one. */
5813
+ const derivedToken = (clientToken, step) => createHash("sha256").update(`${clientToken}:${step}`).digest("hex").replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u, "$1-$2-4$3-8$4-$5");
5814
+ /** The picture's layer id, which the editable frame keeps when it replaces the picture. */
5815
+ const pictureIdOf = (captureId) => `capture_${captureId.replaceAll("-", "")}`;
5816
+ const saveOf = (placement, step, baseVersion) => ({
5817
+ canvasId: placement.canvasId,
5818
+ command: "canvas.capturePage",
5819
+ clientToken: step === "picture" ? placement.clientToken : derivedToken(placement.clientToken, step),
5820
+ baseVersion,
5821
+ fingerprint: canvasExchangeDigest({
5822
+ operation: `canvas.capturePage/${step}`,
5823
+ reference: placement.reference,
5824
+ baseVersion: placement.baseVersion,
5825
+ captureId: placement.captureId,
5826
+ at: placement.at
5827
+ })
5828
+ });
5829
+ const committedSave = async (remote, save) => {
5830
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query("canvas.mutation.get", {
5831
+ canvasId: save.canvasId,
5832
+ mutationId: save.clientToken,
5833
+ fingerprint: save.fingerprint
5834
+ }));
5835
+ return recovered.state === "committed" ? recovered.result : null;
5836
+ };
5837
+ /** A sort key after every layer on the canvas, so the picture lands in front. */
5838
+ const frontSortKey = (scene) => {
5839
+ let last = "a0";
5840
+ for (const relation of Object.values(scene.relationships)) if (relation.parentId === "root" && relation.sortKey > last) last = relation.sortKey;
5841
+ return `${last}~capture`;
5842
+ };
5843
+ /** The canvas at the agent's version; a stale version is a refusal, and nothing was written. */
5844
+ const canvasAt = async (remote, placement) => {
4771
5845
  try {
4772
- const imported = await runCanvasConversion(remote, conversionInput(input));
4773
- if (input.responseMode === "bounded") return canvasConversionStatus(imported, {
4774
- offset: 0,
4775
- limit: MAX_RECEIPT_ENTRIES
4776
- });
4777
- if (imported.state !== "succeeded") return pendingResponse(imported);
4778
- if (input.review === "none") return committedResponse(input, imported);
4779
- await activity?.update({
4780
- phase: "rendering",
4781
- nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
4782
- bounds: imported.result.affectedBounds
4783
- });
4784
- const review = await renderReview(render, input, imported);
4785
- let nodes = [];
4786
- try {
4787
- nodes = await createdNodes(remote, imported);
4788
- } catch {
4789
- nodes = [];
4790
- }
5846
+ return await canvasAtVersion({ remote }, placement.canvasId, placement.baseVersion, "placed");
5847
+ } catch (error) {
5848
+ throw refusalOf(error) ?? error;
5849
+ }
5850
+ };
5851
+ /** Placing is not moving: a capture that is already a frame stays where it is stored. */
5852
+ const refuseAnotherPosition = (placement, stored) => {
5853
+ if (stored.x === placement.at.x && stored.y === placement.at.y) return;
5854
+ const place = `${String(stored.x)}, ${String(stored.y)}`;
5855
+ throw new CliError("BAD_REQUEST", `This capture is already the frame ${pictureIdOf(placement.captureId)} at ${place}. Placing it again does not move it: use ${commandName("canvas.arrange")}.`, `Move the frame with ${commandName("canvas.arrange")}, or place the capture at ${place} to read its frame.`, { outcome: "not_committed" });
5856
+ };
5857
+ /**
5858
+ * The picture of the page, at the agent's position and in front of everything: it is on the
5859
+ * canvas at once, marked as becoming editable, as every capture lands.
5860
+ */
5861
+ const landPicture = async (remote, placement) => {
5862
+ const save = saveOf(placement, "picture", placement.baseVersion);
5863
+ const prior = await committedSave(remote, save);
5864
+ if (prior !== null) return {
5865
+ kind: "picture",
5866
+ version: prior.version,
5867
+ url: prior.url ?? null
5868
+ };
5869
+ const { scene, url } = await canvasAt(remote, placement);
5870
+ const landed = scene.nodes[pictureIdOf(placement.captureId)];
5871
+ if (landed !== void 0 && landed.component !== "screen") {
5872
+ if (landed.box !== void 0) refuseAnotherPosition(placement, landed.box);
4791
5873
  return {
4792
- ...committedResponse(input, imported),
4793
- createdNodes: nodes,
4794
- review,
4795
- next: ["Inspect the review PNG before continuing."]
5874
+ kind: "frame",
5875
+ version: placement.baseVersion,
5876
+ box: landed.box ?? null,
5877
+ url
4796
5878
  };
4797
- } finally {
4798
- await activity?.finish();
4799
5879
  }
4800
- } });
4801
-
4802
- //#endregion
4803
- //#region src/application/read-canvas-reference.use-case.ts
4804
- const readCanvasReferenceScene = async (remote, input) => {
4805
- const reference = parseCanvasReference(input.canvas);
4806
- const held = wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: reference.canvasId }));
4807
- const document = canvasReadableSceneDocumentSchema.parse(held.document);
4808
- if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, document);
4809
- if (input.nodeId !== void 0) assertCanvasReferenceNodes(reference, document, [input.nodeId]);
4810
- const scope = resolveCanvasReference(input.nodeId === void 0 ? reference : {
4811
- ...reference,
4812
- nodeIds: [input.nodeId]
4813
- }, document);
4814
- 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.");
4815
- const children = Object.groupBy(Object.entries(document.relationships), ([, relation]) => relation.parentId);
4816
- const nodes = Object.values(document.nodes).filter((node) => scope.nodeIds.has(node.id)).map((node) => ({
4817
- ...node,
4818
- kind: node.component,
4819
- parentId: document.relationships[node.id]?.parentId ?? null,
4820
- children: (children[node.id] ?? []).map(([id]) => id)
4821
- }));
5880
+ if (landed !== void 0) return {
5881
+ kind: "picture",
5882
+ version: isFailed(landed) ? await markPicture(remote, placement, CAPTURE_LANDING_CONVERTING, "retry") ?? placement.baseVersion : placement.baseVersion,
5883
+ url
5884
+ };
5885
+ const size = placement.size ?? PICTURE_SIZE;
4822
5886
  return {
4823
- canvasId: reference.canvasId,
4824
- version: held.version,
4825
- pageId: scope.pageId,
4826
- source: reference.nodeIds.length > 0 ? "selection-link" : reference.pageId === void 0 ? "canvas-link" : "page-link",
4827
- selectedNodeIds: reference.nodeIds,
4828
- rootNodeIds: scope.rootNodeIds,
4829
- nodeCount: nodes.length,
4830
- nodes,
4831
- next: ["Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants."]
5887
+ kind: "picture",
5888
+ version: (await saveFrame(remote, save, {
5889
+ op: "insertNode",
5890
+ node: {
5891
+ id: pictureIdOf(placement.captureId),
5892
+ label: placement.title ?? CAPTURED_PAGE_LABEL,
5893
+ component: SCREEN_KIND,
5894
+ styles: {},
5895
+ box: {
5896
+ ...placement.at,
5897
+ ...size
5898
+ },
5899
+ props: {
5900
+ ...placement.pageId !== void 0 && { [CANVAS_PAGE_ID_PROP]: placement.pageId },
5901
+ capture: {
5902
+ screenId: placement.captureId,
5903
+ viewport: size,
5904
+ atMs: 0,
5905
+ landing: CAPTURE_LANDING_CONVERTING
5906
+ }
5907
+ }
5908
+ },
5909
+ parentage: {
5910
+ parentId: "root",
5911
+ sortKey: frontSortKey(scene)
5912
+ }
5913
+ })).version,
5914
+ url
4832
5915
  };
4833
5916
  };
4834
-
4835
- //#endregion
4836
- //#region src/infrastructure/render-file.adapter.ts
4837
- const DIRECTORY_MODE = 448;
4838
- const FILE_MODE = 384;
4839
- const TEMPORARY_TTL_MS = 36e5;
4840
- const write = (filePath, body, shouldOverwrite) => {
5917
+ const isFailed = (node) => {
5918
+ const capture = node.props?.["capture"];
5919
+ const landing = captureLandingSchema.safeParse(typeof capture === "object" && capture !== null ? Reflect.get(capture, "landing") : void 0);
5920
+ return node.component === "screen" && landing.success && landing.data.state === "failed";
5921
+ };
5922
+ /**
5923
+ * Writes the picture's mark, over any edit made meanwhile: failed with its reason, so every viewer
5924
+ * sees the failure, or converting again for Try again. A picture that is no longer one is left.
5925
+ */
5926
+ const markPicture = async (remote, placement, landing, step) => {
5927
+ const pictureId = pictureIdOf(placement.captureId);
5928
+ const current = wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: placement.canvasId }));
5929
+ const scene = canvasReadableSceneDocumentSchema.safeParse(current.document);
5930
+ const picture = scene.success ? scene.data.nodes[pictureId] : void 0;
5931
+ if (picture?.component !== "screen") return null;
5932
+ const capture = picture.props?.["capture"];
5933
+ const save = saveOf(placement, step, current.version);
5934
+ return (await appliedOrNotConfirmed(remote, save, applyCanvasOperationsInputSchema.parse({
5935
+ canvasId: placement.canvasId,
5936
+ mutationId: save.clientToken,
5937
+ documentFormatVersion: 15,
5938
+ baseVersion: current.version,
5939
+ operations: [{
5940
+ op: "setProps",
5941
+ nodeId: pictureId,
5942
+ props: {
5943
+ ...picture.props,
5944
+ capture: {
5945
+ ...typeof capture === "object" && capture,
5946
+ landing
5947
+ }
5948
+ }
5949
+ }],
5950
+ requestContext: {
5951
+ fingerprint: save.fingerprint,
5952
+ revisionPolicy: "rebase"
5953
+ }
5954
+ }))).version;
5955
+ };
5956
+ /**
5957
+ * The editable frame replaces the picture in place, keeping its id, and the answer is the API's
5958
+ * receipt. It applies over edits made meanwhile; if another browser already made the picture
5959
+ * editable, there is nothing to do, and the answer is that frame as the canvas stores it.
5960
+ */
5961
+ const swapIn = async (remote, placement, save, compiled) => {
5962
+ const pictureId = pictureIdOf(placement.captureId);
5963
+ const atPlace = frameAt(compiled, {
5964
+ screenId: placement.captureId,
5965
+ x: placement.at.x,
5966
+ y: placement.at.y,
5967
+ pageId: placement.pageId
5968
+ });
4841
5969
  try {
4842
- writeFileSync(filePath, body, {
4843
- flag: shouldOverwrite ? "w" : "wx",
4844
- mode: FILE_MODE
4845
- });
4846
- chmodSync(filePath, FILE_MODE);
5970
+ return await saveFrame(remote, save, captureSwapOf(atPlace, pictureId), "rebase");
4847
5971
  } catch (error) {
4848
- const code = typeof error === "object" && error !== null && Reflect.get(error, "code") === "EEXIST" ? "CONFLICT" : "INTERNAL";
4849
- throw new CliError(code, code === "CONFLICT" ? `Refusing to replace ${filePath}.` : `Could not write ${filePath}.`, code === "CONFLICT" ? "Choose another --output path or pass --force deliberately." : "Create the parent directory and verify it is writable, then retry.");
5972
+ const current = wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: placement.canvasId }));
5973
+ const scene = canvasReadableSceneDocumentSchema.safeParse(current.document);
5974
+ const picture = scene.success ? scene.data.nodes[pictureId] : void 0;
5975
+ if (picture !== void 0 && picture.component !== "screen") return {
5976
+ version: current.version,
5977
+ boxes: picture.box === void 0 ? {} : { [pictureId]: picture.box }
5978
+ };
5979
+ throw error;
4850
5980
  }
4851
5981
  };
4852
- const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
4853
- if (input.outputPath !== null) {
4854
- const outputPath = path.resolve(input.outputPath);
4855
- write(outputPath, input.body, input.overwrite);
4856
- return {
4857
- path: outputPath,
4858
- temporary: false,
4859
- deleteAfter: null
5982
+
5983
+ //#endregion
5984
+ //#region src/application/capture-page.composite.ts
5985
+ /** The API call this composite makes itself; the landing use-cases declare none. */
5986
+ const CAPTURE_PAGE_PROCEDURES = ["capturePass.create"];
5987
+ /** The longest reason a failed picture shows, as the mark allows. */
5988
+ const MAX_FAILURE_REASON_LENGTH = 200;
5989
+ const NOT_EDITABLE = "The page could not be made editable.";
5990
+ /** A title the agent gave, when it holds anything: otherwise the stored page names its frame. */
5991
+ const givenTitle = (title) => {
5992
+ const own = title?.trim() ?? "";
5993
+ return own === "" ? void 0 : own;
5994
+ };
5995
+ /**
5996
+ * How to get a new script once the pass has ended, which the script says when it refuses. The
5997
+ * command goes without the tool's name: a script's text is never rewritten to the installed name.
5998
+ */
5999
+ const renewWith = () => inSurfaceWords({
6000
+ cli: `Run ${cliPathOf("canvas.capturePage")} again with the canvas alone for a new script.`,
6001
+ mcp: `Call ${commandName("canvas.capturePage")} again without captureId for a new script.`
6002
+ });
6003
+ /** The second call's inputs, which the command-line tool takes inside its JSON input. */
6004
+ const placementInputs = (inputs) => inSurfaceWords({
6005
+ cli: `${inputs} in --input`,
6006
+ mcp: inputs
6007
+ });
6008
+ /**
6009
+ * The snippet an agent runs in its page. It loads the published capture script, which freezes
6010
+ * the page, reads its files as the page would and stores it with the pass; it answers with a few
6011
+ * fields, never the page itself. The script is told when its pass ends and how to renew it.
6012
+ */
6013
+ const captureSnippet = (pass, extent) => {
6014
+ const blocked = `The capture script did not load from ${new URL(pass.scriptUrl).origin}. If this page has a Content Security Policy, run this snippet from Playwright in a context created with bypassCSP: true.`;
6015
+ return [
6016
+ "(async () => {",
6017
+ " if (globalThis.__enhance_capture__ === undefined)",
6018
+ " await new Promise((loaded, failed) => {",
6019
+ " const script = document.createElement('script');",
6020
+ ` script.src = ${JSON.stringify(pass.scriptUrl)};`,
6021
+ " script.onload = loaded;",
6022
+ ` script.onerror = () => failed(new Error(${JSON.stringify(blocked)}));`,
6023
+ " document.head.append(script);",
6024
+ " });",
6025
+ " return globalThis.__enhance_capture__.captureToEnhance({",
6026
+ ` apiUrl: ${JSON.stringify(pass.apiUrl)},`,
6027
+ ` pass: ${JSON.stringify(pass.pass)},`,
6028
+ ` extent: ${JSON.stringify(extent)},`,
6029
+ ` passExpiresAt: ${JSON.stringify(pass.expiresAt)},`,
6030
+ ` renewWith: ${JSON.stringify(renewWith())},`,
6031
+ " });",
6032
+ "})()"
6033
+ ].join("\n");
6034
+ };
6035
+ const askForSnippet = async (remote, canvasId, extent) => {
6036
+ const pass = createCapturePassOutputSchema.parse(await remote.mutate(CAPTURE_PAGE_PROCEDURES[0], { canvasId }));
6037
+ return receipt("run-snippet", {
6038
+ snippet: captureSnippet(pass, extent),
6039
+ passExpiresAt: pass.expiresAt,
6040
+ warning: `Run snippet in the page you opened, with Playwright's page.evaluate or your browser's JavaScript tool. It answers with captureId; ${inSurfaceWords({
6041
+ cli: "run",
6042
+ mcp: "call"
6043
+ })} ${commandName("canvas.capturePage")} again with ${placementInputs("that captureId, at and baseVersion")}. The pass works for 15 minutes and for any number of pages, and the snippet holds it: keep the snippet out of what you print. To send the fonts installed on this machine with the page, grant the page the "local-fonts" permission before you run the snippet: in Playwright, await context.grantPermissions(["local-fonts"]).`
6044
+ });
6045
+ };
6046
+ /**
6047
+ * The picture is on the canvas and is not editable yet: still converting, or failed, in which case
6048
+ * the picture is marked failed with the reason, for every viewer to see.
6049
+ */
6050
+ const notYetEditable = async (remote, placement, landed, job) => {
6051
+ const { picture, save, url } = landed;
6052
+ const isRunning = ["queued", "running"].includes(job.state);
6053
+ if (!isRunning) await markPicture(remote, placement, {
6054
+ state: "failed",
6055
+ reason: (job.failure?.message ?? NOT_EDITABLE).slice(0, MAX_FAILURE_REASON_LENGTH)
6056
+ }, "failed");
6057
+ return receipt(isRunning ? "converting" : "failed", {
6058
+ picture,
6059
+ url,
6060
+ operation: {
6061
+ kind: "canvas-preparation",
6062
+ canvasId: placement.canvasId,
6063
+ jobId: job.id,
6064
+ mutationId: save.clientToken,
6065
+ fingerprint: save.fingerprint
6066
+ },
6067
+ failure: job.failure,
6068
+ warning: isRunning ? `The picture is on the canvas and is being made editable. ${followCapture("canvas.capturePage")}` : `The picture is on the canvas, marked as not editable with the reason. Repeat the call with a new ${inputName("clientToken")} to try again.`
6069
+ });
6070
+ };
6071
+ const mutationOf = (save) => ({
6072
+ kind: "canvas-mutation",
6073
+ canvasId: save.canvasId,
6074
+ mutationId: save.clientToken,
6075
+ fingerprint: save.fingerprint
6076
+ });
6077
+ const placed$1 = (save, on, further = []) => receipt("placed", {
6078
+ operation: mutationOf(save),
6079
+ ...on,
6080
+ further,
6081
+ warning: "The picture has become an editable frame in place. Render the frame at its version to inspect it. For the next capture, frame.version is the baseVersion and frame.box says where this one sits."
6082
+ });
6083
+ /** The frame as the API stored it: a receipt's boxes are the stored ones, the request's are not. */
6084
+ const storedFrame = (nodeId, saved) => ({
6085
+ nodeId,
6086
+ version: saved.version,
6087
+ box: saved.boxes[nodeId] ?? null
6088
+ });
6089
+ /** The size an agent gave sizes only the interim picture, so a frame of another size is said. */
6090
+ const sizeWarnings = (given, frame) => given === void 0 || frame.box === null || given.width === frame.box.width && given.height === frame.box.height ? [] : [`The size given was ${String(given.width)} by ${String(given.height)}; the frame is ${String(frame.box.width)} by ${String(frame.box.height)}. A size only sizes the picture shown while the page converts.`];
6091
+ const place$1 = async (remote, placement) => {
6092
+ const landed = await landPicture(remote, placement);
6093
+ const nodeId = pictureIdOf(placement.captureId);
6094
+ if (landed.kind === "frame") {
6095
+ const frame = {
6096
+ nodeId,
6097
+ version: landed.version,
6098
+ box: landed.box
4860
6099
  };
6100
+ return receipt("placed", {
6101
+ frame,
6102
+ url: landed.url,
6103
+ further: sizeWarnings(placement.size, frame),
6104
+ warning: `This capture was already an editable frame, so nothing was converted or saved. Its box is where the canvas stores it; move it with ${commandName("canvas.arrange")}.`
6105
+ });
6106
+ }
6107
+ const picture = {
6108
+ nodeId,
6109
+ version: landed.version
6110
+ };
6111
+ const save = saveOf(placement, "frame", landed.version);
6112
+ const swapped = await committedSave(remote, save);
6113
+ if (swapped !== null) {
6114
+ const frame = storedFrame(nodeId, swapped);
6115
+ return placed$1(save, {
6116
+ frame,
6117
+ picture,
6118
+ url: landed.url
6119
+ }, sizeWarnings(placement.size, frame));
4861
6120
  }
4862
- const directory = path.join(configDirectory, "sensitive");
4863
- mkdirSync(directory, {
4864
- recursive: true,
4865
- mode: DIRECTORY_MODE
6121
+ const job = await runCanvasPreparation(remote, {
6122
+ canvasId: placement.canvasId,
6123
+ expectedVersion: landed.version,
6124
+ request: {
6125
+ kind: "compile-screens",
6126
+ landing: "editable-frame",
6127
+ sources: [{
6128
+ screenId: placement.captureId,
6129
+ captureId: placement.captureId,
6130
+ ...placement.title !== void 0 && { label: placement.title }
6131
+ }]
6132
+ },
6133
+ scope: { nodeIds: [] }
6134
+ }, placement.waitMs);
6135
+ if (job.state !== "succeeded") return notYetEditable(remote, placement, {
6136
+ picture,
6137
+ save,
6138
+ url: landed.url
6139
+ }, job);
6140
+ const frame = storedFrame(nodeId, await swapIn(remote, placement, save, compiledFrameOf(job)));
6141
+ return placed$1(save, {
6142
+ frame,
6143
+ picture,
6144
+ url: landed.url
6145
+ }, [...sizeWarnings(placement.size, frame), ...(job.result.warnings ?? []).map(({ code, message }) => `${code}: ${message}`)]);
6146
+ };
6147
+ /**
6148
+ * @justified intent
6149
+ * An agent's page capture, in two calls. The first gives a snippet with a capture pass; the agent
6150
+ * runs it in the page it opened, which stores the page. The second places that capture: the API
6151
+ * lands it as a picture at the agent's position at once, as every capture lands, then the API
6152
+ * compiles it and the editable frame replaces the picture in place.
6153
+ */
6154
+ const captureCanvasPage = async (remote, offered, clientToken) => {
6155
+ const input = canvasCapturePageCapabilityInputSchema.parse(offered);
6156
+ const reference = parseCanvasReference(input.canvasRef);
6157
+ if (input.captureId === void 0) return askForSnippet(remote, reference.canvasId, input.extent);
6158
+ if (input.at === void 0 || input.baseVersion === void 0) throw new CliError("BAD_REQUEST", "A placement needs a position, x and y in at, and the baseVersion you read.", `${inSurfaceWords({
6159
+ cli: "Run",
6160
+ mcp: "Call"
6161
+ })} ${commandName("canvas.capturePage")} again with ${placementInputs("captureId, at: { x, y } and baseVersion")}.`);
6162
+ return place$1(remote, {
6163
+ canvasId: reference.canvasId,
6164
+ clientToken,
6165
+ reference,
6166
+ baseVersion: input.baseVersion,
6167
+ captureId: input.captureId,
6168
+ title: givenTitle(input.title),
6169
+ at: input.at,
6170
+ size: input.size,
6171
+ pageId: reference.pageId,
6172
+ waitMs: input.waitMs
4866
6173
  });
4867
- chmodSync(directory, DIRECTORY_MODE);
4868
- const outputPath = path.join(directory, `render-${globalThis.crypto.randomUUID()}.png`);
4869
- write(outputPath, input.body, false);
4870
- return {
4871
- path: outputPath,
4872
- temporary: true,
4873
- deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
4874
- };
4875
- } });
6174
+ };
4876
6175
 
4877
6176
  //#endregion
4878
6177
  //#region src/application/import-canvas-asset.composite.ts
@@ -4881,7 +6180,7 @@ const ASSET_PROCEDURES = [
4881
6180
  "canvas.asset.complete",
4882
6181
  "canvas.document.get"
4883
6182
  ];
4884
- const importFailure = (error, operation) => new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The asset import did not return a confirmed result.", error instanceof CliError ? error.remediation : "Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.", {
6183
+ const importFailure = (error, operation) => new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The asset import did not return a confirmed result.", error instanceof CliError ? error.remediation : `Read ${commandName("operation.status")} for this import or retry the same file and ${inputName("clientToken")}. No canvas placement was requested.`, {
4885
6184
  ...error instanceof CliError && error.fields,
4886
6185
  operation: JSON.stringify(operation),
4887
6186
  outcome: "not_confirmed"
@@ -4891,10 +6190,7 @@ const assertIdentity = (asset, intent) => {
4891
6190
  };
4892
6191
  const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (input) => {
4893
6192
  const reference = parseCanvasReference(input.canvasRef);
4894
- if (hasCanvasReferenceScope(reference)) {
4895
- const held = wholeCanvasDocumentOutputSchema.parse(await remote.query(ASSET_PROCEDURES[2], { canvasId: reference.canvasId }));
4896
- canvasReferenceNodeIds(reference, canvasReadableSceneDocumentSchema.parse(held.document));
4897
- }
6193
+ if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, readStoredCanvasScene(wholeCanvasDocumentOutputSchema.parse(await remote.query(ASSET_PROCEDURES[2], { canvasId: reference.canvasId })).document));
4898
6194
  const { body, ...file } = await files.read();
4899
6195
  const intent = reserveCanvasAssetInputSchema.parse({
4900
6196
  ...file,
@@ -4918,7 +6214,7 @@ const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (i
4918
6214
  clientToken: input.clientToken
4919
6215
  }));
4920
6216
  assertIdentity(completed, intent);
4921
- if (completed.assetId !== reserved.assetId || completed.path !== reserved.path) throw new CliError("INTERNAL", "The completed asset identity changed.", "Read operation_status and do not place an unconfirmed resource.");
6217
+ if (completed.assetId !== reserved.assetId || completed.path !== reserved.path) throw new CliError("INTERNAL", "The completed asset identity changed.", `Read ${commandName("operation.status")} and do not place an unconfirmed resource.`);
4922
6218
  return canvasAssetImportOutputSchema.parse({
4923
6219
  operation,
4924
6220
  resource: completed,
@@ -4965,7 +6261,7 @@ const reserveAndUpload = async (remote, input, artifact, reserved) => {
4965
6261
  if (created.data.state === "uploading") await remote.upload({
4966
6262
  url: created.data.upload.url,
4967
6263
  headers: created.data.upload.headers,
4968
- body: artifact.open()
6264
+ body: await artifact.open()
4969
6265
  });
4970
6266
  if (created.data.state === "uploading" || created.data.state === "queued") {
4971
6267
  const submitted = submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLICATION_PROCEDURES[2], {
@@ -5056,7 +6352,7 @@ const toPrototypePublicationFailure = (publication) => {
5056
6352
  failure: {
5057
6353
  code: failure.code,
5058
6354
  message: failure.message,
5059
- 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."
6355
+ remediation: isBuildFailure ? `Correct the named build problem and publish a new artifact with a new ${inputName("clientToken")}.` : `This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new ${inputName("clientToken")}. Do not change the source to repair a service failure.`
5060
6356
  }
5061
6357
  };
5062
6358
  };
@@ -5075,14 +6371,14 @@ const requireScopedAttachment = async (remote) => {
5075
6371
  const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PROCEDURES[0], {}));
5076
6372
  if (!capabilities.success || capabilities.data.attachmentProtocolVersion !== 1) throw new CliError("BAD_REQUEST", "This API does not advertise revision-checked prototype attachment.", "Upgrade the API before publishing through the canvas profile. No artifact was created or attached.");
5077
6373
  };
5078
- const failureOf$1 = (error) => error instanceof CliError ? {
6374
+ const failureOf = (error) => error instanceof CliError ? {
5079
6375
  code: error.code,
5080
6376
  message: error.message,
5081
6377
  remediation: error.remediation
5082
6378
  } : {
5083
6379
  code: "INTERNAL",
5084
6380
  message: "The publication request did not return a confirmed outcome.",
5085
- remediation: "Retry the identical request with its original clientToken; do not assume the canvas is unchanged."
6381
+ remediation: `Retry the identical request with its original ${inputName("clientToken")}; do not assume the canvas is unchanged.`
5086
6382
  };
5087
6383
  const attach = async (remote, input, publication) => {
5088
6384
  const reference = parseCanvasReference(input.canvasRef);
@@ -5118,7 +6414,7 @@ const attachReady = async (remote, input, base, publication) => {
5118
6414
  nextAction: "inspect_result"
5119
6415
  };
5120
6416
  } catch (error) {
5121
- const failure = failureOf$1(error);
6417
+ const failure = failureOf(error);
5122
6418
  const isConflict = failure.code === "CONFLICT";
5123
6419
  const isRejected = REJECTED_CODES.has(failure.code);
5124
6420
  return {
@@ -5126,7 +6422,7 @@ const attachReady = async (remote, input, base, publication) => {
5126
6422
  attachmentStatus: isConflict ? "conflict" : isRejected ? "not_attempted" : "not_confirmed",
5127
6423
  failure,
5128
6424
  nextAction: failure.code === "UNAUTHORIZED" || failure.code === "FORBIDDEN" ? "restore_access" : isConflict || isRejected ? "replan_attachment" : "retry_same_request",
5129
- 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."]
6425
+ 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 ${inputName("clientToken")}. A changed scope or destination requires a new attachment intent.`]
5130
6426
  };
5131
6427
  }
5132
6428
  };
@@ -5161,7 +6457,7 @@ const finishPublication = async (remote, input, canvasId, publication) => {
5161
6457
  failure: {
5162
6458
  code: "NOT_FOUND",
5163
6459
  message: "The deployment was abandoned.",
5164
- remediation: "Publish the same build explicitly with a new clientToken if it is still needed."
6460
+ remediation: `Publish the same build explicitly with a new ${inputName("clientToken")} if it is still needed.`
5165
6461
  }
5166
6462
  };
5167
6463
  if (publication.state !== "ready") return base;
@@ -5198,9 +6494,9 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
5198
6494
  publication: null,
5199
6495
  attachmentStatus: "not_attempted",
5200
6496
  attachment: null,
5201
- failure: failureOf$1(error),
6497
+ failure: failureOf(error),
5202
6498
  nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
5203
- 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."]
6499
+ warnings: [`An existing deployment may still be processing. Retry the same source and ${inputName("clientToken")} to recover or finish upload; do not reserve a new publication.`]
5204
6500
  };
5205
6501
  }
5206
6502
  } });
@@ -5209,7 +6505,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
5209
6505
  //#region src/application/publish-prototype.composite.ts
5210
6506
  const PUBLISH_WAIT_MS = 3e5;
5211
6507
  const PUBLISH_PROTOTYPE_PROCEDURES = ["prototype.attach"];
5212
- 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.");
6508
+ const invalidResponse = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
5213
6509
  const requireReadyPublication = (status) => {
5214
6510
  if (status.state === "failed") {
5215
6511
  const failure = toPrototypePublicationFailure(status);
@@ -5251,90 +6547,50 @@ const executePublish = async (remote, artifacts, input) => {
5251
6547
  totalBytes: status.totalBytes,
5252
6548
  alreadyExists: created.alreadyExists,
5253
6549
  warnings: prototypePublicationWarnings(status),
5254
- next: [attached.data.canvasUrl ?? attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
6550
+ next: [attached.data.canvasUrl ?? attached.data.openUrl, renderNodeCall(input.canvasId, attached.data.nodeId, attached.data.version)]
5255
6551
  };
5256
6552
  } catch (error) {
5257
6553
  if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
5258
6554
  if (progress.deploymentId === null) throw error;
5259
- 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}.`, {
6555
+ throw new PartialBatchError(error instanceof CliError ? error.message : `Prototype deployment ${progress.deploymentId} has no confirmed completion.`, `${error instanceof CliError ? `${error.remediation} ` : ""}Retry ${inSurfaceWords({
6556
+ cli: `'${commandName("prototype.publish")}'`,
6557
+ mcp: commandName("prototype.publish")
6558
+ })} with the same ${inputName("clientToken")} ${input.clientToken}.`, {
5260
6559
  code: error instanceof CliError ? error.code : "INTERNAL",
5261
6560
  fields: {
5262
6561
  ...error instanceof CliError && error.fields,
5263
- canvasId: input.canvasId,
5264
- deploymentId: progress.deploymentId,
5265
- clientToken: input.clientToken
5266
- }
5267
- });
5268
- }
5269
- };
5270
- const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
5271
-
5272
- //#endregion
5273
- //#region src/application/canvas-preparation-status.use-case.ts
5274
- const canvasPreparationStatus = (job, operation) => {
5275
- if (job.id !== operation.jobId || job.canvasId !== operation.canvasId) throw new CliError("NOT_FOUND", "The preparation does not belong to this operation.", "Use the complete operation reference returned by the original action.");
5276
- return {
5277
- kind: "canvas-preparation",
5278
- operation,
5279
- state: job.state,
5280
- phase: job.phase,
5281
- requestedVersion: job.requestedVersion,
5282
- failure: job.failure,
5283
- outcome: "not_confirmed",
5284
- prepared: job.state === "succeeded",
5285
- warnings: ["Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit."]
5286
- };
5287
- };
5288
- const readCanvasPreparationStatus = async (remote, operation) => {
5289
- const { job } = getCanvasPreparationOutputSchema.parse(await remote.query("canvas.render.preparation.get", { jobId: operation.jobId }));
5290
- return canvasPreparationStatus(job, operation);
5291
- };
5292
-
5293
- //#endregion
5294
- //#region src/application/canvas-receipt.use-case.ts
5295
- const MAX_RECEIPT_NODE_IDS = 40;
5296
- const canvasWriteReceipt = (commit, fingerprint) => {
5297
- let remaining = MAX_RECEIPT_NODE_IDS;
5298
- const take = (ids) => {
5299
- const selected = ids.slice(0, remaining);
5300
- remaining -= selected.length;
5301
- return selected;
5302
- };
5303
- const insertedNodeIds = take(commit.insertedNodeIds);
5304
- const changedNodeIds = take(commit.changedNodeIds);
5305
- const removedNodeIds = take(commit.removedNodeIds);
5306
- const total = commit.insertedNodeIds.length + commit.changedNodeIds.length + commit.removedNodeIds.length;
5307
- return {
5308
- outcome: "committed",
5309
- canvasId: commit.canvasId,
5310
- mutationId: commit.mutationId,
5311
- previousVersion: commit.previousVersion,
5312
- version: commit.version,
5313
- operation: {
5314
- kind: "canvas-mutation",
5315
- canvasId: commit.canvasId,
5316
- mutationId: commit.mutationId,
5317
- fingerprint
5318
- },
5319
- affected: {
5320
- insertedNodeIds,
5321
- changedNodeIds,
5322
- removedNodeIds,
5323
- complete: total <= MAX_RECEIPT_NODE_IDS,
5324
- total
5325
- },
5326
- ...commit.copiedNodeIds !== void 0 && { identities: {
5327
- entries: Object.entries(commit.copiedNodeIds).toSorted(([left], [right]) => left.localeCompare(right, "en")).slice(0, MAX_RECEIPT_NODE_IDS).map(([sourceNodeId, nodeId]) => ({
5328
- sourceNodeId,
5329
- nodeId
5330
- })),
5331
- complete: Object.keys(commit.copiedNodeIds).length <= MAX_RECEIPT_NODE_IDS,
5332
- total: Object.keys(commit.copiedNodeIds).length
5333
- } },
5334
- verification: { rendered: false },
5335
- warnings: []
6562
+ canvasId: input.canvasId,
6563
+ deploymentId: progress.deploymentId,
6564
+ clientToken: input.clientToken
6565
+ }
6566
+ });
6567
+ }
6568
+ };
6569
+ const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
6570
+
6571
+ //#endregion
6572
+ //#region src/application/canvas-preparation-status.use-case.ts
6573
+ const canvasPreparationStatus = (job, operation) => {
6574
+ if (job.id !== operation.jobId || job.canvasId !== operation.canvasId) throw new CliError("NOT_FOUND", "The preparation does not belong to this operation.", "Use the complete operation reference returned by the original action.");
6575
+ return {
6576
+ kind: "canvas-preparation",
6577
+ operation,
6578
+ state: job.state,
6579
+ phase: job.phase,
6580
+ requestedVersion: job.requestedVersion,
6581
+ failure: job.failure,
6582
+ outcome: "not_confirmed",
6583
+ prepared: job.state === "succeeded",
6584
+ warnings: [`Preparation is not a canvas commit. Repeat the original ${inSurfaceWords({
6585
+ cli: "command",
6586
+ mcp: "tool"
6587
+ })} with identical arguments and ${inputName("clientToken")} to finish; status reads never commit.`]
5336
6588
  };
5337
6589
  };
6590
+ const readCanvasPreparationStatus = async (remote, operation) => {
6591
+ const { job } = getCanvasPreparationOutputSchema.parse(await remote.query("canvas.render.preparation.get", { jobId: operation.jobId }));
6592
+ return canvasPreparationStatus(job, operation);
6593
+ };
5338
6594
 
5339
6595
  //#endregion
5340
6596
  //#region src/application/operation-image.use-case.ts
@@ -5520,10 +6776,24 @@ const createReadOperationStatusComposite = (remote, files) => ({ execute: async
5520
6776
  //#region src/application/read-transcript.composite.ts
5521
6777
  const MAX_PREVIEW_COMMANDS = 3;
5522
6778
  const READ_TRANSCRIPT_PROCEDURES = ["transcript.get"];
5523
- const previewCommands = (canvasId, recordingId, cueTimes) => [...new Set(cueTimes)].slice(0, MAX_PREVIEW_COMMANDS).map((atMs) => `enhance canvas render --canvas ${canvasId} --node-id rec_${recordingId} --at-ms ${String(atMs)}`);
6779
+ const previewCommands = (canvasId, recordingId, cueTimes) => [...new Set(cueTimes)].slice(0, MAX_PREVIEW_COMMANDS).map((atMs) => callOf("canvas.render", {
6780
+ cli: `--canvas ${canvasId} --node-id rec_${recordingId} --at-ms ${String(atMs)}`,
6781
+ mcp: {
6782
+ canvasRef: canvasId,
6783
+ target: {
6784
+ kind: "node",
6785
+ nodeId: `rec_${recordingId}`
6786
+ },
6787
+ sourceState: {
6788
+ kind: "recording",
6789
+ recordingId,
6790
+ atMs
6791
+ }
6792
+ }
6793
+ }));
5524
6794
  const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
5525
6795
  const parsed = transcriptOutputSchema.safeParse(await remote.query(READ_TRANSCRIPT_PROCEDURES[0], input));
5526
- if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid transcript response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
6796
+ if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid transcript response.", diagnosisStep("Run `enhance doctor`; report the API and CLI versions if they differ."));
5527
6797
  if (parsed.data.state !== "ready") return parsed.data;
5528
6798
  return {
5529
6799
  ...parsed.data,
@@ -5532,141 +6802,6 @@ const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
5532
6802
  };
5533
6803
  } });
5534
6804
 
5535
- //#endregion
5536
- //#region src/application/snapshot-recording.composite.ts
5537
- const POLL_MS$1 = 250;
5538
- const PROGRESS_HEARTBEAT_MS = 5e3;
5539
- const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
5540
- const wait = async () => new Promise((resolve) => {
5541
- globalThis.setTimeout(resolve, POLL_MS$1);
5542
- });
5543
- const failureOf = (job) => new CliError(job.failure?.reason === "VERSION_CHANGED" ? "CONFLICT" : job.failure?.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : job.failure?.reason === "TARGET_INVALID" || job.failure?.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL", job.failure?.message ?? "The snapshot job ended without a result.", `Run 'enhance canvas tree --canvas ${job.canvasId}' and retry the exact snapshot if its recording node still exists.`, {
5544
- jobId: job.id,
5545
- phase: job.phase
5546
- });
5547
- const readSnapshotJob = async (remote, jobId) => {
5548
- const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
5549
- if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${jobId}.`);
5550
- return read.data.job;
5551
- };
5552
- const awaitSnapshot = async (remote, initial, input, progress) => {
5553
- const deadline = Date.now() + input.timeoutMs;
5554
- const startedAt = Date.now();
5555
- let job = initial;
5556
- let lastReportedAt = 0;
5557
- let lastReportedState = "";
5558
- while (job.state === "queued" || job.state === "running") {
5559
- const currentTime = Date.now();
5560
- const stateKey = `${job.state}:${job.phase}`;
5561
- if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
5562
- progress({
5563
- event: "snapshot.progress",
5564
- jobId: job.id,
5565
- state: job.state,
5566
- phase: job.phase,
5567
- elapsedMs: currentTime - startedAt,
5568
- timeoutMs: input.timeoutMs,
5569
- retryClientToken: input.retryClientToken
5570
- });
5571
- lastReportedAt = currentTime;
5572
- lastReportedState = stateKey;
5573
- }
5574
- if (currentTime >= deadline) {
5575
- if (input.bounded === true) return job;
5576
- throw new CliError("INTERNAL", `Snapshot ${job.id} did not finish before the local timeout.`, `Retry this exact command with --client-token ${input.retryClientToken} and a larger --timeout-ms.`, {
5577
- jobId: job.id,
5578
- phase: job.phase
5579
- });
5580
- }
5581
- await wait();
5582
- const next = await readSnapshotJob(remote, job.id);
5583
- if (next.id !== initial.id) throw invalidSnapshot();
5584
- assertSnapshotIdentity(next, input);
5585
- job = next;
5586
- }
5587
- return job;
5588
- };
5589
- const invalidSnapshot = () => new CliError("INTERNAL", "The snapshot response does not match the requested source or revision.", "Run enhance doctor and report the capture job ID.");
5590
- const assertSnapshotIdentity = (job, input) => {
5591
- if (job.canvasId !== input.canvasId || job.purpose !== "snapshot" || job.sourceState?.recordingId !== input.recordingId || job.sourceState.atMs !== input.atMs || input.context !== void 0 && job.requestedVersion !== input.context.expectedVersion) throw invalidSnapshot();
5592
- if (job.state !== "succeeded") return;
5593
- const result = job.result.snapshot;
5594
- const source = job.result.sourceState;
5595
- if (job.result.canvasId !== input.canvasId || job.result.loadedVersion !== job.requestedVersion || job.result.requestedVersion !== job.requestedVersion || source?.recordingId !== input.recordingId || source.requestedAtMs !== input.atMs || source.settledAtMs !== input.atMs || result?.recordingId !== input.recordingId || result.atMs !== input.atMs || result.screenId !== job.id || result.screenNodeId !== `scr_${input.recordingId}_${String(input.atMs)}` || input.context !== void 0 && result.version !== input.context.expectedVersion + 1) throw invalidSnapshot();
5596
- };
5597
- const captureReceipt = (job, input) => ({
5598
- operation: {
5599
- kind: "canvas-render",
5600
- canvasId: job.canvasId,
5601
- jobId: job.id
5602
- },
5603
- state: job.state,
5604
- requestedVersion: job.requestedVersion,
5605
- source: {
5606
- kind: "recording",
5607
- recordingId: input.recordingId,
5608
- atMs: input.atMs
5609
- },
5610
- attachment: job.state === "succeeded" ? "committed" : job.state === "queued" || job.state === "running" ? "pending" : "not_confirmed",
5611
- result: job.result?.snapshot ?? null,
5612
- failure: job.failure,
5613
- warningCount: job.result?.warnings.length ?? 0,
5614
- warnings: [job.state === "succeeded" ? "The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings." : "Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created."]
5615
- });
5616
- const captureCanvasRecording = async (remote, offered, clientToken) => {
5617
- const input = canvasCaptureCapabilityInputSchema.parse(offered);
5618
- const reference = parseCanvasReference(input.canvasRef);
5619
- return createSnapshotRecordingComposite(remote, () => null).execute({
5620
- canvasId: reference.canvasId,
5621
- recordingId: input.source.recordingId,
5622
- atMs: input.source.atMs,
5623
- retryClientToken: clientToken,
5624
- timeoutMs: input.waitMs,
5625
- bounded: true,
5626
- context: {
5627
- expectedVersion: input.baseVersion,
5628
- request: {
5629
- previewJobId: input.previewJobId,
5630
- scope: {
5631
- pageId: reference.pageId,
5632
- nodeIds: [...reference.nodeIds]
5633
- },
5634
- placement: input.placement
5635
- }
5636
- }
5637
- });
5638
- };
5639
- const executeSnapshot = async (remote, progress, input) => {
5640
- const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
5641
- canvasId: input.canvasId,
5642
- recordingId: input.recordingId,
5643
- atMs: input.atMs,
5644
- ...input.context !== void 0 && { context: input.context }
5645
- }));
5646
- if (!made.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot creation response.", "Run `enhance doctor` and report the API and CLI versions.");
5647
- assertSnapshotIdentity(made.data.job, input);
5648
- const held = await awaitSnapshot(remote, made.data.job, input, progress);
5649
- if (input.bounded === true) return captureReceipt(held, input);
5650
- if (held.state !== "succeeded" || held.result.snapshot === void 0) throw failureOf(held);
5651
- const job = {
5652
- ...held,
5653
- result: {
5654
- ...held.result,
5655
- snapshot: held.result.snapshot
5656
- }
5657
- };
5658
- const snapshot = job.result.snapshot;
5659
- return {
5660
- jobId: job.id,
5661
- canvasId: job.canvasId,
5662
- ...snapshot,
5663
- warnings: job.result.warnings,
5664
- retryClientToken: input.retryClientToken,
5665
- next: [`enhance canvas node --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId}`, `enhance canvas render --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId} --expected-version ${String(snapshot.version)}`]
5666
- };
5667
- };
5668
- const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
5669
-
5670
6805
  //#endregion
5671
6806
  //#region src/infrastructure/canvas-asset-file.adapter.ts
5672
6807
  const CONTENT_TYPES$1 = {
@@ -5733,7 +6868,7 @@ const readItems = async (remote, input) => {
5733
6868
  items: [],
5734
6869
  truncated: false
5735
6870
  }]);
5736
- const canvases = listCanvasesOutputSchema.parse(canvasValue);
6871
+ const canvases = listedCanvasesAnswerSchema.parse(canvasValue);
5737
6872
  const teams = listOrganisationsOutputSchema.parse(teamValue);
5738
6873
  const items = canvases.items.map((canvas) => ({
5739
6874
  kind: "canvas",
@@ -5742,7 +6877,8 @@ const readItems = async (remote, input) => {
5742
6877
  organisationId: canvas.organisationId,
5743
6878
  accessState: canvas.accessState,
5744
6879
  viewerCan: canvas.viewerCan,
5745
- openPath: `/c/${canvas.id}`
6880
+ openPath: `/c/${canvas.id}`,
6881
+ url: canvas.url ?? null
5746
6882
  }));
5747
6883
  if (input.includeDestinations) items.push({
5748
6884
  kind: "destination",
@@ -5808,39 +6944,6 @@ const createFindCanvasComposite = (remote) => ({ execute: async (input) => {
5808
6944
  };
5809
6945
  } });
5810
6946
 
5811
- //#endregion
5812
- //#region src/application/canvas-preparation.use-case.ts
5813
- const POLL_MS = 250;
5814
- const readPreparation = async (remote, jobId) => {
5815
- try {
5816
- return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
5817
- } catch (error) {
5818
- if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
5819
- return null;
5820
- }
5821
- };
5822
- const waitForPreparation = async (remote, initial, waitMs) => {
5823
- const deadline = Date.now() + waitMs;
5824
- let job = initial;
5825
- while (job.state === "queued" || job.state === "running") {
5826
- const remaining = deadline - Date.now();
5827
- if (remaining <= 0) break;
5828
- await setTimeout$1(Math.min(POLL_MS, remaining));
5829
- const status = await readPreparation(remote, initial.id);
5830
- if (status === null) return job;
5831
- job = getCanvasPreparationOutputSchema.parse(status.value).job;
5832
- if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
5833
- }
5834
- return job;
5835
- };
5836
- const runCanvasPreparation = async (remote, input, waitMs) => {
5837
- const made = createCanvasPreparationOutputSchema.parse(await remote.mutate("canvas.render.preparation.create", input));
5838
- const job = await waitForPreparation(remote, made.job, waitMs);
5839
- if (job.canvasId !== input.canvasId || job.requestedVersion !== input.expectedVersion || !isDeepStrictEqual(job.scope, input.scope) || !isDeepStrictEqual(job.request, input.request)) throw new CliError("CONFLICT", "The native preparation does not match this request.", "Read the canvas and prepare a new intent; do not apply this plan.");
5840
- if (job.state === "succeeded" && job.result.loadedVersion !== input.expectedVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
5841
- return job;
5842
- };
5843
-
5844
6947
  //#endregion
5845
6948
  //#region src/application/prepare-canvas-command.composite.ts
5846
6949
  const RECOVER_MUTATION = "canvas.mutation.get";
@@ -5848,7 +6951,8 @@ const applyPreparedOperations = async (remote, request) => {
5848
6951
  try {
5849
6952
  return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
5850
6953
  } catch (error) {
5851
- throw new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The canvas commit could not be confirmed.", "Read operation_status or repeat the original action with identical arguments and clientToken.", {
6954
+ if (isFormatRefusalError(error)) throw error;
6955
+ throw new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The canvas commit could not be confirmed.", `Read ${commandName("operation.status")} or repeat the original action with identical arguments and ${inputName("clientToken")}.`, {
5852
6956
  ...error instanceof CliError && error.fields,
5853
6957
  outcome: "not_confirmed",
5854
6958
  operation: JSON.stringify({
@@ -5882,7 +6986,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
5882
6986
  }
5883
6987
  });
5884
6988
  const result = await applyPreparedOperations(remote, request);
5885
- if (result.canvasId !== job.canvasId || result.mutationId !== input.clientToken || result.previousVersion !== input.baseVersion || result.version !== input.baseVersion + 1 || input.request.kind === "duplicate" && !isDeepStrictEqual(result.copiedNodeIds, job.result.idMap)) throw new CliError("INTERNAL", "The canvas commit receipt could not be verified.", "Check operation_status using the original mutation reference before retrying.", {
6989
+ if (result.canvasId !== job.canvasId || result.mutationId !== input.clientToken || result.previousVersion !== input.baseVersion || result.version !== input.baseVersion + 1 || input.request.kind === "duplicate" && !isDeepStrictEqual(result.copiedNodeIds, job.result.idMap)) throw new CliError("INTERNAL", "The canvas commit receipt could not be verified.", `Check ${commandName("operation.status")} using the original mutation reference before retrying.`, {
5886
6990
  outcome: "not_confirmed",
5887
6991
  operation: JSON.stringify({
5888
6992
  kind: "canvas-mutation",
@@ -6876,6 +7980,7 @@ const outlineNodes = (scene, roots, depth, isCurrent) => {
6876
7980
  const node = requireCanvasNode(scene, id);
6877
7981
  const children = childrenByParent.get(id) ?? [];
6878
7982
  const isLocked = isCanvasNodeLocked(scene, id);
7983
+ const boxSource = canvasBoxSourceOf(node);
6879
7984
  nodes.push({
6880
7985
  id,
6881
7986
  label: node.label,
@@ -6893,7 +7998,8 @@ const outlineNodes = (scene, roots, depth, isCurrent) => {
6893
7998
  "group",
6894
7999
  "text"
6895
8000
  ].includes(node.component),
6896
- bounds: node.box ?? null
8001
+ bounds: node.box ?? null,
8002
+ ...boxSource !== void 0 && { boxSource }
6897
8003
  });
6898
8004
  if (at < depth) for (const child of children) visit(child, at + 1);
6899
8005
  };
@@ -6937,6 +8043,7 @@ const readCanvasOutline = (input, snapshot) => {
6937
8043
  total: all.length,
6938
8044
  nodes,
6939
8045
  omittedDescendants: hasOmittedDescendants,
8046
+ ...canvasRecordedBoxNoteFor(nodes),
6940
8047
  nextCursor: nextOffset < all.length ? encodeCanvasExchangeToken({
6941
8048
  protocol: "enhance-canvas-outline/1",
6942
8049
  canvasId: reference.canvasId,
@@ -7238,8 +8345,8 @@ const createReadCanvasComposite = (remote) => ({ execute: async (input) => {
7238
8345
  const reference = parseCanvasReference(input.canvasRef);
7239
8346
  const held = wholeCanvasDocumentOutputSchema.parse(await remote.query(READ_CANVAS_PROCEDURES[0], { canvasId: reference.canvasId }));
7240
8347
  if (input.expectedVersion !== void 0 && input.expectedVersion !== held.version) return stale(held.version);
8348
+ const scene = readStoredCanvasScene(held.document);
7241
8349
  const current = canvasSceneDocumentSchema.safeParse(held.document);
7242
- const scene = current.success ? current.data : canvasReadableSceneDocumentSchema.parse(held.document);
7243
8350
  if (input.view === "resources") return readCanvasResources(input, {
7244
8351
  reference,
7245
8352
  scene,
@@ -7270,43 +8377,6 @@ const createReadCanvasComposite = (remote) => ({ execute: async (input) => {
7270
8377
  });
7271
8378
  } });
7272
8379
 
7273
- //#endregion
7274
- //#region src/application/revisioned-canvas-command.composite.ts
7275
- const CANVAS_COMMAND_PROCEDURES = ["canvas.mutation.get"];
7276
- const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (input) => {
7277
- const canvasId = input.reference.canvasId;
7278
- const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_COMMAND_PROCEDURES[0], {
7279
- canvasId,
7280
- mutationId: input.clientToken,
7281
- fingerprint: input.fingerprint
7282
- }));
7283
- if (recovered.state === "committed") return canvasWriteReceipt(recovered.result, input.fingerprint);
7284
- const scene = await sceneAtVersion({ remote }, canvasId, input.baseVersion);
7285
- const operations = await input.plan(scene);
7286
- if ("outcome" in operations) return operations;
7287
- assertCanvasReferenceOperations(input.reference, scene, operations);
7288
- if (operations.length === 0) return {
7289
- outcome: "no_op",
7290
- canvasId,
7291
- version: input.baseVersion,
7292
- verification: { rendered: false },
7293
- warnings: []
7294
- };
7295
- const request = applyCanvasOperationsInputSchema.safeParse({
7296
- canvasId,
7297
- documentFormatVersion: 15,
7298
- mutationId: input.clientToken,
7299
- baseVersion: input.baseVersion,
7300
- operations,
7301
- requestContext: {
7302
- fingerprint: input.fingerprint,
7303
- revisionPolicy: "strict"
7304
- }
7305
- });
7306
- if (!request.success) throw new CliError("BAD_REQUEST", "The planned edit exceeds the canonical canvas contract.", request.error.issues[0]?.message ?? "Reduce the edit scope.", { outcome: "not_committed" });
7307
- return canvasWriteReceipt(applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request.data)), input.fingerprint);
7308
- } });
7309
-
7310
8380
  //#endregion
7311
8381
  //#region src/application/remove-canvas-nodes.composite.ts
7312
8382
  const removalPlan = (scene, rootNodeIds) => {
@@ -7342,6 +8412,7 @@ const createRemoveCanvasNodesComposite = (remote) => ({ execute: async ({ client
7342
8412
  return createRevisionedCanvasCommandComposite(remote).execute({
7343
8413
  reference,
7344
8414
  baseVersion: input.baseVersion,
8415
+ versionGiven: "input",
7345
8416
  clientToken,
7346
8417
  fingerprint: canvasExchangeDigest({
7347
8418
  operation: "canvas.remove/1",
@@ -7463,7 +8534,7 @@ const parseCanvasHtmlUpdate = (html) => {
7463
8534
  childNodes: element.childNodes.map((child) => "tagName" in child && !isPaintElement(child) ? visit(child, id) : child)
7464
8535
  };
7465
8536
  if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
7466
- 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.");
8537
+ 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 ${commandName("canvas.arrange")} to move retained content into it.`);
7467
8538
  let key = `new_${String(fragments.length)}`;
7468
8539
  while (reservedIds.has(key)) key = `_${key}`;
7469
8540
  reservedIds.add(key);
@@ -7542,7 +8613,7 @@ const styleChangeOperations = (document, node, before, after) => {
7542
8613
  geometry: "default"
7543
8614
  }] : [],
7544
8615
  ...canvasEditableImageOperations(node, before.styles, after.styles),
7545
- ...Object.keys(styles).length === 0 ? [] : canvasStyleOperations(document, [{
8616
+ ...Object.keys(styles).length === 0 ? [] : canvasStoredStyleOperations(document, [{
7546
8617
  nodeIds: [node.id],
7547
8618
  styles
7548
8619
  }])
@@ -7665,6 +8736,7 @@ const createUpdateCanvasHtmlComposite = (remote) => ({ execute: async (offered)
7665
8736
  return createRevisionedCanvasCommandComposite(remote).execute({
7666
8737
  reference,
7667
8738
  baseVersion: binding.version,
8739
+ versionGiven: "snapshot",
7668
8740
  clientToken: input.clientToken,
7669
8741
  fingerprint,
7670
8742
  plan: async (scene) => prepareUpdate(remote, input, {
@@ -7773,7 +8845,7 @@ const targetFailure = (error, target) => {
7773
8845
  } : {
7774
8846
  code: "INTERNAL",
7775
8847
  message: "This render outcome could not be confirmed.",
7776
- remediation: "Retry the identical batch and clientToken to recover its native render jobs."
8848
+ remediation: `Retry the identical batch and ${inputName("clientToken")} to recover its native render jobs.`
7777
8849
  }
7778
8850
  };
7779
8851
  };
@@ -7830,7 +8902,7 @@ const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered,
7830
8902
  complete: results.every((result) => "jobId" in result.outcome),
7831
8903
  renderedPixels,
7832
8904
  results,
7833
- 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."]
8905
+ next: [`Inspect each delivered image alongside its target id. Collect pending images with ${commandName("operation.status")} and ${inputName("includeImage", "input")} true. Retry uncertain outcomes with the identical batch and ${inputName("clientToken")}.`]
7834
8906
  };
7835
8907
  } });
7836
8908
 
@@ -8170,7 +9242,7 @@ const packageArtifact = async (input) => {
8170
9242
  expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
8171
9243
  },
8172
9244
  manifest: packaged.manifest,
8173
- open: () => createReadStream(artifactPath),
9245
+ open: async () => openAsBlob(artifactPath),
8174
9246
  dispose: async () => rm(tempDirectory, { recursive: true })
8175
9247
  };
8176
9248
  } catch (error) {
@@ -8190,8 +9262,10 @@ const createPrototypeArtifactAdapter = (directory) => ({ package: async (input)
8190
9262
  //#region src/infrastructure/capability-invocation.adapter.ts
8191
9263
  const applyCanvas = async (dependencies, offered) => {
8192
9264
  const input = canvasApplyCapabilityInputSchema.parse(offered);
8193
- return createApplyCanvasComposite(dependencies.remote).execute({
8194
- ...input,
9265
+ return createEditCanvasComposite(dependencies.remote).apply({
9266
+ canvasId: input.canvasId,
9267
+ baseVersion: input.baseVersion,
9268
+ operations: input.operations,
8195
9269
  mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
8196
9270
  });
8197
9271
  };
@@ -8277,6 +9351,7 @@ const invokeComposite = async (dependencies, capabilityId, offered, retryClientT
8277
9351
  "canvas.writeHtml": async () => writeCanvasHtml(dependencies, offered),
8278
9352
  "canvas.insertHtml": async () => insertCanvasHtml(dependencies, offered, retryClientToken),
8279
9353
  "canvas.capture": async () => captureCanvasRecording(dependencies.remote, offered, retryClientToken),
9354
+ "canvas.capturePage": async () => captureCanvasPage(dependencies.remote, offered, retryClientToken),
8280
9355
  "canvas.makeEditable": async () => makeCanvasEditable(dependencies.remote, offered),
8281
9356
  "comment.attention": async () => readCommentAttention(dependencies, offered),
8282
9357
  "prototype.publishCanvas": async () => {
@@ -8305,10 +9380,273 @@ const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capabil
8305
9380
  return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
8306
9381
  } });
8307
9382
 
9383
+ //#endregion
9384
+ //#region src/infrastructure/input-shape.lib.ts
9385
+ const DISCRIMINATOR_PREFERENCE = [
9386
+ "kind",
9387
+ "op",
9388
+ "type",
9389
+ "view",
9390
+ "on"
9391
+ ];
9392
+ const MAX_REFERENCE_DEPTH = 8;
9393
+ const recordOf = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : null;
9394
+ const stringsOf = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
9395
+ const readerOf = (root) => {
9396
+ const definitions = recordOf(recordOf(root)?.["$defs"]) ?? {};
9397
+ const resolved = (value, depth = 0) => {
9398
+ const schema = recordOf(value);
9399
+ const reference = schema?.["$ref"];
9400
+ if (schema === null || typeof reference !== "string") return schema;
9401
+ if (depth > MAX_REFERENCE_DEPTH) return null;
9402
+ if (reference === "#") return resolved(root, depth + 1);
9403
+ return resolved(definitions[reference.replace("#/$defs/", "")], depth + 1);
9404
+ };
9405
+ return resolved;
9406
+ };
9407
+ /** The schemas a value may match, however its unions nest, with `null` taken out and noted. */
9408
+ const alternativesOf = (schema, read) => {
9409
+ const listed = schema["anyOf"] ?? schema["oneOf"];
9410
+ if (!Array.isArray(listed)) return {
9411
+ members: [schema],
9412
+ isNullable: false
9413
+ };
9414
+ const nested = listed.flatMap((member) => {
9415
+ const held = read(member);
9416
+ return held === null ? [] : [alternativesOf(held, read)];
9417
+ });
9418
+ const members = nested.flatMap((alternatives) => alternatives.members);
9419
+ const present = members.filter((member) => member["type"] !== "null");
9420
+ return {
9421
+ members: present,
9422
+ isNullable: present.length < members.length || nested.some((alternatives) => alternatives.isNullable)
9423
+ };
9424
+ };
9425
+ const propertiesOf = (schema) => recordOf(schema["properties"]);
9426
+ const discriminatorOf = (shapes) => {
9427
+ const names = Object.keys(propertiesOf(shapes[0] ?? {}) ?? {}).filter((name) => shapes.every((shape) => {
9428
+ const property = recordOf(propertiesOf(shape)?.[name]);
9429
+ return property !== null && "const" in property;
9430
+ }));
9431
+ return DISCRIMINATOR_PREFERENCE.find((name) => names.includes(name)) ?? names[0] ?? null;
9432
+ };
9433
+ /** The object shapes a value, or each entry of a list, may take, when it may take several. */
9434
+ const kindsOf = (schema, read) => {
9435
+ const outer = alternativesOf(schema, read);
9436
+ const single = outer.members.length === 1 ? outer.members[0] : void 0;
9437
+ const isList = single?.["type"] === "array";
9438
+ const entry = isList ? read(single["items"]) : null;
9439
+ const { members } = entry === null ? outer : alternativesOf(entry, read);
9440
+ if (members.length < 2 || members.some((member) => propertiesOf(member) === null)) return null;
9441
+ return {
9442
+ shapes: members,
9443
+ discriminator: discriminatorOf(members),
9444
+ isList,
9445
+ isNullable: outer.isNullable
9446
+ };
9447
+ };
9448
+ const unionTypeOf = (schema, read) => {
9449
+ const { members, isNullable } = alternativesOf(schema, read);
9450
+ const discriminator = kindsOf(schema, read)?.discriminator ?? null;
9451
+ const written = discriminator === null ? [...new Set(members.map((member) => typeOf(member, read)))].join(" | ") : `{${discriminator}: ${members.map((member) => typeOf(propertiesOf(member)?.[discriminator], read)).join(" | ")}, …}`;
9452
+ return isNullable ? `${written} | null` : written;
9453
+ };
9454
+ /** A value's type in a few words: a primitive, its literal values, or an object's field names. */
9455
+ const typeOf = (value, read) => {
9456
+ const schema = read(value);
9457
+ if (schema === null) return "JSON";
9458
+ if ("const" in schema) return JSON.stringify(schema["const"]);
9459
+ if (Array.isArray(schema["enum"])) return schema["enum"].map((entry) => JSON.stringify(entry)).join(" | ");
9460
+ if (Array.isArray(schema["anyOf"] ?? schema["oneOf"])) return unionTypeOf(schema, read);
9461
+ if (schema["type"] === "array") return `array of ${typeOf(schema["items"], read)}`;
9462
+ const properties = propertiesOf(schema);
9463
+ if (properties === null) return typeof schema["type"] === "string" ? schema["type"] : "JSON";
9464
+ const required = new Set(stringsOf(schema["required"]));
9465
+ return `{${Object.keys(properties).map((name) => required.has(name) ? name : `${name}?`).join(", ")}}`;
9466
+ };
9467
+ /** Whether a type is one word that needs no telling apart from the field's name. */
9468
+ const isPlainType = (type) => /^(?:string|number|integer|boolean|JSON|object)$/u.test(type);
9469
+ const isObject = (shape) => shape["type"] === "object" || propertiesOf(shape) !== null;
9470
+ /** Whether a value is a JSON object, or a list of them, which a flag takes as JSON text. */
9471
+ const isJsonValued = (schema) => {
9472
+ const read = readerOf(schema);
9473
+ const root = read(schema);
9474
+ if (root === null) return false;
9475
+ return alternativesOf(root, read).members.some((member) => {
9476
+ const entry = member["type"] === "array" ? read(member["items"]) : member;
9477
+ return entry !== null && alternativesOf(entry, read).members.some((shape) => isObject(shape));
9478
+ });
9479
+ };
9480
+
9481
+ //#endregion
9482
+ //#region src/infrastructure/input-fields.lib.ts
9483
+ const UNGUIDED_MEANING = /^Input field \w+\.$/u;
9484
+ /** A field as one kind names it: bare when primitive, with its own fields or values otherwise. */
9485
+ const fieldOfKind = (name, value, read, isTyped) => {
9486
+ const written = typeOf(value, read);
9487
+ if (!isTyped || isPlainType(written.replace(/^array of /u, ""))) return name;
9488
+ return written.startsWith("{") ? `${name} ${written}` : `${name} (${written})`;
9489
+ };
9490
+ const kindLine = (shape, discriminator, read, detail) => {
9491
+ const properties = propertiesOf(shape) ?? {};
9492
+ const required = new Set(stringsOf(shape["required"]));
9493
+ const names = Object.keys(properties).filter((name) => name !== discriminator);
9494
+ const needed = names.filter((name) => required.has(name)).map((name) => fieldOfKind(name, properties[name], read, detail.isTyped));
9495
+ const optional = detail.hasOptional ? names.filter((name) => !required.has(name)) : [];
9496
+ const fields = [needed.join(", "), ...optional.length > 0 ? [`optional ${optional.join(", ")}`] : []].filter((part) => part !== "").join("; ");
9497
+ if (discriminator === null) return ` ${fields}`;
9498
+ const label = ` ${discriminator} ${typeOf(properties[discriminator], read)}`;
9499
+ return fields === "" ? label : `${label}: ${fields}`;
9500
+ };
9501
+ const meaningOf = (name, schema, guide) => {
9502
+ const guided = guide.find((field) => field.name === name)?.meaning;
9503
+ if (guided !== void 0 && !UNGUIDED_MEANING.test(guided)) return guided;
9504
+ const described = schema?.["description"];
9505
+ return typeof described === "string" ? described : "";
9506
+ };
9507
+ const fieldRow = (name, value, requirement, context) => {
9508
+ const { read, guide, detail } = context;
9509
+ const schema = read(value);
9510
+ const kinds = schema === null ? null : kindsOf(schema, read);
9511
+ const meaning = detail === "required" || detail === "bare" ? "" : meaningOf(name, schema, guide);
9512
+ if (kinds === null || detail === "required") return {
9513
+ name,
9514
+ requirement,
9515
+ type: typeOf(value, read),
9516
+ meaning,
9517
+ kinds: []
9518
+ };
9519
+ const noun = kinds.discriminator === null ? "shapes" : "kinds";
9520
+ return {
9521
+ name,
9522
+ requirement,
9523
+ type: `${kinds.isNullable ? "null, or " : ""}${kinds.isList ? "array, each entry " : ""}one of the ${noun} below`,
9524
+ meaning,
9525
+ kinds: kinds.shapes.map((shape) => kindLine(shape, kinds.discriminator, read, {
9526
+ isTyped: detail === "full",
9527
+ hasOptional: detail === "full"
9528
+ }))
9529
+ };
9530
+ };
9531
+ const tableOf = (rows) => {
9532
+ const nameWidth = Math.max(...rows.map((row) => row.name.length));
9533
+ const requirementWidth = Math.max(...rows.map((row) => row.requirement?.length ?? 0));
9534
+ return rows.flatMap((row) => [[
9535
+ ` ${row.name.padEnd(nameWidth)}`,
9536
+ ...row.requirement === null ? [] : [row.requirement.padEnd(requirementWidth)],
9537
+ row.meaning === "" ? row.type : `${row.type}. ${row.meaning}`
9538
+ ].join(" ").trimEnd(), ...row.kinds]);
9539
+ };
9540
+ /** The fields of an object, each marked required or optional. */
9541
+ const objectRows = (schema, context) => {
9542
+ const required = new Set(stringsOf(schema["required"]));
9543
+ return Object.entries(propertiesOf(schema) ?? {}).filter(([name]) => context.detail !== "required" || required.has(name)).map(([name, value]) => fieldRow(name, value, required.has(name) ? "required" : "optional", context));
9544
+ };
9545
+ /**
9546
+ * The fields of every shape, once each, that have more to say than their name: what the field
9547
+ * means, the kinds it takes, or a type that is not a plain value.
9548
+ */
9549
+ const sharedRows = (kinds, context) => {
9550
+ if (context.detail === "required") return [];
9551
+ const merged = Object.fromEntries(kinds.shapes.flatMap((shape) => Object.entries(propertiesOf(shape) ?? {})));
9552
+ return Object.entries(merged).filter(([name]) => name !== kinds.discriminator).map(([name, value]) => fieldRow(name, value, null, context)).filter((row) => row.meaning !== "" || row.kinds.length > 0 || !isPlainType(row.type));
9553
+ };
9554
+
9555
+ //#endregion
9556
+ //#region src/infrastructure/input-help.lib.ts
9557
+ const DETAILS = [
9558
+ "full",
9559
+ "brief",
9560
+ "bare",
9561
+ "required",
9562
+ "none"
9563
+ ];
9564
+ /** A value that is one of several shapes: each shape, then the fields that need explaining. */
9565
+ const shapeLines = (input, kinds, read, detail) => {
9566
+ const fields = sharedRows(kinds, {
9567
+ read,
9568
+ guide: input.fields,
9569
+ detail
9570
+ });
9571
+ return [
9572
+ kinds.isList ? `${input.flag} takes a JSON array. Each entry is one of:` : `${input.flag} takes a JSON object in one of these shapes:`,
9573
+ ...kinds.shapes.map((shape) => kindLine(shape, kinds.discriminator, read, {
9574
+ isTyped: false,
9575
+ hasOptional: detail === "full"
9576
+ })),
9577
+ ...fields.length > 0 ? ["Their fields:", ...tableOf(fields)] : []
9578
+ ];
9579
+ };
9580
+ /** An object, or a list of objects: one line when no field needs explaining, else a table. */
9581
+ const objectLines = (input, fielded, noun, context) => {
9582
+ const rows = objectRows(fielded, {
9583
+ ...context,
9584
+ guide: input.fields
9585
+ });
9586
+ if (!rows.every((row) => row.kinds.length === 0 && row.meaning === "")) return [noun === "object" ? `${input.flag} takes a JSON object with these fields:` : `${input.flag} takes a JSON array. Each entry has these fields:`, ...tableOf(rows)];
9587
+ const fields = rows.map((row) => row.requirement === "required" ? `${row.name} (${row.type})` : `${row.name}? (${row.type})`);
9588
+ return [`${input.flag} takes a JSON ${noun === "object" ? "object" : "array of objects"}: {${fields.join(", ")}}`];
9589
+ };
9590
+ const flagLines = (input, detail) => {
9591
+ const read = readerOf(input.schema);
9592
+ const root = read(input.schema);
9593
+ if (root === null || detail === "none") return [];
9594
+ const kinds = kindsOf(root, read);
9595
+ if (kinds !== null) return shapeLines(input, kinds, read, detail);
9596
+ const { members } = alternativesOf(root, read);
9597
+ const value = members.length === 1 ? members[0] ?? root : root;
9598
+ const entry = value["type"] === "array" ? read(value["items"]) : null;
9599
+ if (entry !== null && propertiesOf(entry) !== null) return objectLines(input, entry, "array", {
9600
+ read,
9601
+ detail
9602
+ });
9603
+ if (propertiesOf(value) !== null) return objectLines(input, value, "object", {
9604
+ read,
9605
+ detail
9606
+ });
9607
+ return [`${input.flag} takes JSON: ${typeOf(root, read)}`];
9608
+ };
9609
+ const earlierLines = (earlier) => {
9610
+ if (earlier.length === 0) return [];
9611
+ const [only] = earlier;
9612
+ return ["Where the input comes from:", ...earlier.length === 1 ? [` ${only ?? ""}`] : earlier.map((step, index) => ` ${String(index + 1)}. ${step}`)];
9613
+ };
9614
+ /** The line that says what was left out, and the command that prints all of it. */
9615
+ const restLines = (input, detail) => {
9616
+ if (input.flags.length === 0) return [];
9617
+ if (detail === "required") return [`Only required fields are listed. Every field: ${input.rest}`];
9618
+ return detail === "none" ? [`The fields of ${input.flags.map(({ flag }) => flag).join(" and ")} are listed by: ${input.rest}`] : [];
9619
+ };
9620
+ const written = (input, detail) => {
9621
+ const sections = [
9622
+ earlierLines(input.earlier),
9623
+ ...input.flags.map((flag) => flagLines(flag, detail)),
9624
+ restLines(input, detail),
9625
+ input.example === null ? [] : [
9626
+ "Example:",
9627
+ ` ${input.example}`,
9628
+ ...input.placeholders === null ? [] : [` ${input.placeholders}`]
9629
+ ]
9630
+ ].filter((section) => section.length > 0);
9631
+ return sections.length === 0 ? "" : `\n${sections.map((section) => section.join("\n")).join("\n\n")}`;
9632
+ };
9633
+ /**
9634
+ * The text help prints after a command's options: where its input comes from, the fields of each
9635
+ * JSON flag with the kinds a field may take, and one example. When the whole text is longer than
9636
+ * the limit, it is written with less: first without the detail of each kind, then without what
9637
+ * each field means, then with the required fields alone and the command that prints the rest,
9638
+ * and last with that command alone.
9639
+ */
9640
+ const toInputHelp = (input) => {
9641
+ const texts = DETAILS.map((detail) => written(input, detail));
9642
+ return texts.find((text) => text.length <= input.limit) ?? texts.at(-1) ?? "";
9643
+ };
9644
+ /** Writes each `{capability.id}` of a text as the surface that prints it names that capability. */
9645
+ const withCapabilityNames = (text, nameOf) => text.replaceAll(/\{([\w.]+)\}/gu, (_, id) => nameOf(id));
9646
+
8308
9647
  //#endregion
8309
9648
  //#region src/infrastructure/oauth-loopback.adapter.ts
8310
9649
  const CALLBACK_PATH = "/callback";
8311
- const AUTHORIZATION_TIMEOUT_MS = 12e4;
8312
9650
  const ENTROPY_BYTES = 32;
8313
9651
  const HTTP_OK = 200;
8314
9652
  const HTTP_BAD_REQUEST = 400;
@@ -8393,9 +9731,6 @@ const authorizationCode = async (input) => {
8393
9731
  completion.reject(/* @__PURE__ */ new Error("browser authorization cancelled"));
8394
9732
  };
8395
9733
  input.signal?.addEventListener("abort", abort, { once: true });
8396
- const timeout = setTimeout(() => {
8397
- completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
8398
- }, AUTHORIZATION_TIMEOUT_MS);
8399
9734
  try {
8400
9735
  input.signal?.throwIfAborted();
8401
9736
  input.onReady(url);
@@ -8405,7 +9740,6 @@ const authorizationCode = async (input) => {
8405
9740
  redirectUri
8406
9741
  };
8407
9742
  } finally {
8408
- clearTimeout(timeout);
8409
9743
  input.signal?.removeEventListener("abort", abort);
8410
9744
  await new Promise((resolve) => {
8411
9745
  server.close(() => {
@@ -8442,6 +9776,7 @@ const CLI_DEVELOPMENT_PROFILE = {
8442
9776
  apiUrl: "https://api.enhance3.karunalabs.ai",
8443
9777
  commandName: "enhance-dev",
8444
9778
  configDirectoryName: "enhance-development",
9779
+ macConfigDirectoryName: "Enhance Development",
8445
9780
  environment: "development",
8446
9781
  mcpServiceName: "enhance-dev-mcp"
8447
9782
  };
@@ -8449,31 +9784,42 @@ const CLI_PRODUCTION_PROFILE = {
8449
9784
  apiUrl: "https://api.enhancelabs.ai",
8450
9785
  commandName: "enhance",
8451
9786
  configDirectoryName: "enhance",
9787
+ macConfigDirectoryName: "Enhance",
8452
9788
  environment: "production",
8453
9789
  mcpServiceName: "enhance-mcp"
8454
9790
  };
8455
9791
  const normalizedApi = (value) => URL.canParse(value) ? new URL(value).href.replace(/\/+$/u, "") : value;
9792
+ /** ~/.config, where the tool keeps its sign-in off a Mac, and kept it on a Mac before. */
9793
+ const configFolder = (homeDirectory, release) => path.join(homeDirectory, ".config", release.configDirectoryName);
9794
+ /**
9795
+ * On a Mac, the person's own Application Support folder, which macOS makes for them and which
9796
+ * they always own; ~/.config can belong to root when some tool once ran with sudo.
9797
+ */
9798
+ const macFolder = (homeDirectory, release) => path.join(homeDirectory, "Library", "Application Support", release.macConfigDirectoryName);
9799
+ const foldersOf = (homeDirectory, release) => [configFolder(homeDirectory, release), macFolder(homeDirectory, release)].map((folder) => path.resolve(folder));
8456
9800
  const rejectCredentialCollision = (apiUrl, directory, homeDirectory, production) => {
8457
9801
  const origin = URL.canParse(apiUrl) ? new URL(apiUrl).origin : null;
8458
9802
  const resolved = path.resolve(directory);
8459
9803
  const development = CLI_DEVELOPMENT_PROFILE;
8460
- 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.");
9804
+ if (origin === new URL(development.apiUrl).origin && foldersOf(homeDirectory, production).includes(resolved) || origin === new URL(production.apiUrl).origin && foldersOf(homeDirectory, development).includes(resolved)) 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.");
8461
9805
  };
8462
9806
  const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
8463
- const resolveCliConfig = (variables, homeDirectory, release) => {
9807
+ const resolveCliConfig = (variables, homeDirectory, release, isMac = false) => {
8464
9808
  const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
8465
9809
  if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
8466
9810
  const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
8467
- const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
9811
+ const earlierConfigDirectory = configFolder(homeDirectory, release);
9812
+ const expectedConfigDirectory = isMac ? macFolder(homeDirectory, release) : earlierConfigDirectory;
8468
9813
  const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
8469
9814
  if (release.environment === "development") {
8470
9815
  if (requestedApi !== void 0 && normalizedApi(requestedApi) !== normalizedApi(release.apiUrl)) throw new TypeError("Enhance development cannot use this API. Use the bundled development endpoint.");
8471
- if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
9816
+ if (requestedConfigDirectory !== void 0 && !foldersOf(homeDirectory, release).includes(path.resolve(requestedConfigDirectory))) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
8472
9817
  } else rejectCredentialCollision(requestedApi ?? release.apiUrl, requestedConfigDirectory ?? expectedConfigDirectory, homeDirectory, release);
8473
9818
  return {
8474
9819
  apiUrl: requestedApi ?? release.apiUrl,
8475
9820
  commandName: release.commandName,
8476
9821
  configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
9822
+ ...isMac && requestedConfigDirectory === void 0 && { earlierConfigDirectory },
8477
9823
  mcpServiceName: release.mcpServiceName
8478
9824
  };
8479
9825
  };
@@ -8493,6 +9839,7 @@ const remoteMcpConfigSchema = z.object({
8493
9839
  MCP_SERVICE_DOCUMENTATION_URL: z.url().default("https://enhancelabs.ai"),
8494
9840
  MCP_ALLOWED_HOSTS: z.string().min(1),
8495
9841
  MCP_FILE_ORIGINS: z.string().default(""),
9842
+ MCP_STAGED_UPLOAD_ORIGIN: z.url().optional(),
8496
9843
  MCP_UI_URL: z.url().optional(),
8497
9844
  MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
8498
9845
  });
@@ -8500,7 +9847,13 @@ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables
8500
9847
 
8501
9848
  //#endregion
8502
9849
  //#region src/infrastructure/environment.config.ts
8503
- const readCliEnvironment = () => resolveCliConfig(process.env, homedir(), CLI_PRODUCTION_PROFILE);
9850
+ const readCliEnvironment = () => resolveCliConfig(process.env, homedir(), CLI_PRODUCTION_PROFILE, process.platform === "darwin");
9851
+ /** The machine `setup` works on: whose home, and how its shells find the tool. */
9852
+ const readToolMachine = () => ({
9853
+ homeDirectory: homedir(),
9854
+ searchPath: process.env["PATH"] ?? "",
9855
+ entry: process.argv[1]
9856
+ });
8504
9857
  const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
8505
9858
  const readLocalMcpEnvironment = () => {
8506
9859
  const profile = z.enum(["legacy", "canvas"]).default("legacy").parse(process.env["ENHANCE_MCP_PROFILE"]);
@@ -8615,15 +9968,11 @@ const health = async (apiUrl) => {
8615
9968
  }
8616
9969
  };
8617
9970
  const upload = async (input) => {
8618
- const isStreaming = !(input.body instanceof Uint8Array);
8619
- const body = isStreaming ? Readable.toWeb(input.body) : input.body;
8620
- const request = {
9971
+ const response = await fetch(input.url, {
8621
9972
  method: "PUT",
8622
9973
  headers: input.headers,
8623
- body,
8624
- ...isStreaming && { duplex: "half" }
8625
- };
8626
- const response = await fetch(input.url, request);
9974
+ body: input.body
9975
+ });
8627
9976
  if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
8628
9977
  const etag = response.headers.get("etag");
8629
9978
  if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
@@ -8668,4 +10017,14 @@ const createMutationKeyAdapter = () => {
8668
10017
  };
8669
10018
 
8670
10019
  //#endregion
8671
- export { canvasRadialGradientSvg as C, canvasAngularGradientSvg as D, canvasDiamondGradientSvg as E, canvasColorCss as O, createAuthUseCase as S, canvasFilterListCss as T, 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, compareCanvasSortKeys as k, 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, canvasLinearGradientSvg as w, createRenderCanvasComposite as x, createApplyCanvasComposite as y };
10020
+ //#region src/infrastructure/zod-messages.lib.ts
10021
+ /**
10022
+ * Installs zod's English messages. zod installs them as a side effect of loading, but it declares
10023
+ * no side effects, so a bundle drops them and every schema failure says only "Invalid input".
10024
+ */
10025
+ const installZodMessages = () => {
10026
+ z.config(z.locales.en());
10027
+ };
10028
+
10029
+ //#endregion
10030
+ export { canvasAngularGradientSvg as A, assertCanvasReferenceOperations as C, canvasLinearGradientSvg as D, canvasRadialGradientSvg as E, compareCanvasSortKeys as M, canvasFilterListCss as O, createCanvasActivityComposite as S, createAuthUseCase as T, readCanvasReferenceScene as _, readLocalMcpEnvironment as a, createEditCanvasComposite as b, createOauthLoopbackAdapter as c, isJsonValued as d, createCapabilityInvocationAdapter as f, createRenderFileAdapter as g, createImportCanvasAssetComposite as h, readCliEnvironment as i, canvasColorCss as j, canvasDiamondGradientSvg as k, toInputHelp as l, createPublishCanvasPrototypeComposite as m, createMutationKeyAdapter as n, readRemoteMcpEnvironment as o, createPrototypeArtifactAdapter as p, createHttpRemoteAdapter as r, readToolMachine as s, installZodMessages as t, withCapabilityNames as u, createWriteHtmlCanvasComposite as v, createRenderCanvasComposite as w, sceneAtVersion as x, boundedResultPage as y };