@enhance-eng/enhance 0.1.161 → 0.1.166

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, Hn as IMAGE_KIND, Ht as PROTOTYPE_ARTIFACT_MANIFEST_PATH, I as canvasCaptureCapabilityInputSchema, 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, 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, V as canvasDuplicateCapabilityInputSchema, 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, z as canvasArrangeCapabilityInputSchema, zn as getCanvasPreparationOutputSchema } from "./cli-output-identity.lib-BfvrkZX5.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-DTdmAFNC.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
13
  import { isDeepStrictEqual } from "node:util";
12
- import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
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,67 +4541,421 @@ 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 }
4454
- };
4455
- for (const edit of input.edits) assertCanvasReferenceNodes(reference, scene, scopeIds(edit, scene));
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
+ };
4456
4593
  };
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({
4462
- 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({
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
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({
4467
4671
  canvasId: input.canvasId,
4468
- mutationId: input.mutationId,
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,
4469
4793
  documentFormatVersion: 15,
4794
+ mutationId: input.clientToken,
4470
4795
  baseVersion: input.baseVersion,
4471
- operations: plan.operations
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);
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
+ }
4472
4885
  });
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));
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.");
4475
4888
  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.`],
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,
4478
4908
  ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
4479
4909
  ...plan.moves.length > 0 && {
4480
4910
  moves: plan.moves,
4481
4911
  affectedParents: plan.affectedParents
4482
4912
  }
4483
4913
  };
4484
- } });
4485
-
4486
- //#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
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
+ });
4493
4959
 
4494
4960
  //#endregion
4495
4961
  //#region src/application/result-page.use-case.ts
@@ -4575,13 +5041,16 @@ const canvasConversionStatus = (job, page) => ({
4575
5041
  const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
4576
5042
  const READ_IMPORT_PROCEDURE$1 = "canvas.render.getImport";
4577
5043
  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.");
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."));
4579
5045
  const wait$1 = async (milliseconds) => new Promise((resolve) => {
4580
5046
  globalThis.setTimeout(resolve, milliseconds);
4581
5047
  });
4582
5048
  const terminalFailure = (job) => {
4583
5049
  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.", {
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.", {
4585
5054
  jobId: job.id,
4586
5055
  phase: failure.phase,
4587
5056
  reason: failure.reason
@@ -4626,29 +5095,68 @@ const runCanvasConversion = async (remote, input) => {
4626
5095
  assertConversionIdentity(job, input);
4627
5096
  return job;
4628
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
+ };
4629
5129
  const makeCanvasEditable = async (remote, offered) => {
4630
5130
  const input = canvasMakeEditableCapabilityInputSchema.parse(offered);
4631
5131
  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
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
4644
5147
  },
4645
- destination: input.placement
4646
- },
4647
- waitMs: input.waitMs
4648
- }), {
4649
- offset: 0,
4650
- limit: 40
4651
- });
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
+ }
4652
5160
  };
4653
5161
 
4654
5162
  //#endregion
@@ -4671,7 +5179,14 @@ const failedReview = (error, input, version) => {
4671
5179
  message: "The post-write review render failed.",
4672
5180
  remediation: "Render the committed version and affected area again; do not replay the write."
4673
5181
  },
4674
- next: [`enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`, "Do not replay the committed write with a new mutation id."]
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."]
4675
5190
  };
4676
5191
  };
4677
5192
  const renderReview = async (render, input, imported) => {
@@ -4804,7 +5319,7 @@ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (in
4804
5319
  const readCanvasReferenceScene = async (remote, input) => {
4805
5320
  const reference = parseCanvasReference(input.canvas);
4806
5321
  const held = wholeCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: reference.canvasId }));
4807
- const document = canvasReadableSceneDocumentSchema.parse(held.document);
5322
+ const document = readStoredCanvasScene(held.document);
4808
5323
  if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, document);
4809
5324
  if (input.nodeId !== void 0) assertCanvasReferenceNodes(reference, document, [input.nodeId]);
4810
5325
  const scope = resolveCanvasReference(input.nodeId === void 0 ? reference : {
@@ -4837,6 +5352,7 @@ const readCanvasReferenceScene = async (remote, input) => {
4837
5352
  const DIRECTORY_MODE = 448;
4838
5353
  const FILE_MODE = 384;
4839
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.");
4840
5356
  const write = (filePath, body, shouldOverwrite) => {
4841
5357
  try {
4842
5358
  writeFileSync(filePath, body, {
@@ -4845,34 +5361,40 @@ const write = (filePath, body, shouldOverwrite) => {
4845
5361
  });
4846
5362
  chmodSync(filePath, FILE_MODE);
4847
5363
  } 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.");
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.");
4850
5366
  }
4851
5367
  };
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);
5368
+ const createRenderFileAdapter = (configDirectory) => ({
5369
+ refuseExisting: (offeredPath) => {
5370
+ const outputPath = path.resolve(offeredPath);
5371
+ if (existsSync(outputPath)) throw refusalToReplace(outputPath);
5372
+ },
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);
4856
5391
  return {
4857
5392
  path: outputPath,
4858
- temporary: false,
4859
- deleteAfter: null
5393
+ temporary: true,
5394
+ deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
4860
5395
  };
4861
5396
  }
4862
- const directory = path.join(configDirectory, "sensitive");
4863
- mkdirSync(directory, {
4864
- recursive: true,
4865
- mode: DIRECTORY_MODE
4866
- });
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
- } });
5397
+ });
4876
5398
 
4877
5399
  //#endregion
4878
5400
  //#region src/application/canvas-preparation.use-case.ts
@@ -4909,7 +5431,19 @@ const runCanvasPreparation = async (remote, input, waitMs) => {
4909
5431
 
4910
5432
  //#endregion
4911
5433
  //#region src/application/captured-frame.use-case.ts
4912
- const FOLLOW_CAPTURE = "Repeat canvas_capture with identical arguments and clientToken, or follow operation_status. An unfinished step is not proof that nothing was saved.";
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
+ });
4913
5447
  const attachmentOf = (state) => state === "queued" || state === "running" ? "pending" : "not_confirmed";
4914
5448
  const captureReceipt = (capture, step) => ({
4915
5449
  operation: step.operation,
@@ -4923,15 +5457,9 @@ const captureReceipt = (capture, step) => ({
4923
5457
  warningCount: 1,
4924
5458
  warnings: [step.warning]
4925
5459
  });
4926
- const mutationReference = (capture) => ({
4927
- kind: "canvas-mutation",
4928
- canvasId: capture.canvasId,
4929
- mutationId: capture.clientToken,
4930
- fingerprint: capture.fingerprint
4931
- });
4932
5460
  /** The receipt of a saved capture: the frame, its version, and the change to follow. */
4933
5461
  const savedCaptureReceipt = (capture, saved, result, frameNodeId) => captureReceipt(capture, {
4934
- operation: mutationReference(capture),
5462
+ operation: mutationOf$1(frameSaveOf(capture)),
4935
5463
  state: "succeeded",
4936
5464
  result,
4937
5465
  failure: null,
@@ -4946,12 +5474,15 @@ const recordingProvenance = (recording) => ({
4946
5474
  recordingId: recording.recordingId,
4947
5475
  atMs: recording.atMs
4948
5476
  });
4949
- /** The compiled page as the capture's frame: at the snapshot's place, every layer naming its page. */
4950
- const capturedFrame = (operation, snapshot, recording) => {
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) => {
4951
5482
  const nodes = Object.fromEntries(Object.entries(operation.nodes).map(([id, node]) => {
4952
5483
  const props = {
4953
5484
  ...node.props,
4954
- capturedResource: { screenId: snapshot.screenId }
5485
+ capturedResource: { screenId: place.screenId }
4955
5486
  };
4956
5487
  if (id !== operation.rootNodeId) return [id, {
4957
5488
  ...node,
@@ -4962,14 +5493,14 @@ const capturedFrame = (operation, snapshot, recording) => {
4962
5493
  ...node,
4963
5494
  ...node.box !== void 0 && { box: {
4964
5495
  ...node.box,
4965
- x: snapshot.box.x,
4966
- y: snapshot.box.y
5496
+ x: place.x,
5497
+ y: place.y
4967
5498
  } },
4968
- props: {
5499
+ props: provenance === void 0 ? props : {
4969
5500
  ...props,
4970
5501
  conversion: {
4971
5502
  ...typeof conversion === "object" && conversion,
4972
- provenance: recordingProvenance(recording)
5503
+ provenance
4973
5504
  }
4974
5505
  }
4975
5506
  }];
@@ -4979,40 +5510,70 @@ const capturedFrame = (operation, snapshot, recording) => {
4979
5510
  destination: {
4980
5511
  kind: "insert-children",
4981
5512
  targetNodeId: "root",
4982
- ...snapshot.pageId !== void 0 && { pageId: snapshot.pageId }
5513
+ ...place.pageId !== void 0 && { pageId: place.pageId }
4983
5514
  },
4984
5515
  nodes
4985
5516
  };
4986
5517
  };
4987
- const notConfirmed = (capture, error) => new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The captured frame could not be confirmed.", FOLLOW_CAPTURE, {
4988
- ...error instanceof CliError && error.fields,
4989
- outcome: "not_confirmed",
4990
- operation: JSON.stringify(mutationReference(capture))
4991
- });
4992
- const applyFrame = async (remote, capture, frame) => {
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) => {
5543
+ try {
5544
+ return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
5545
+ } catch (error) {
5546
+ if (isFormatRefusalError(error)) throw error;
5547
+ throw refusalOf(error) ?? notConfirmed(save, error);
5548
+ }
5549
+ };
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;
4993
5553
  const request = applyCanvasOperationsInputSchema.parse({
4994
- canvasId: capture.canvasId,
4995
- mutationId: capture.clientToken,
5554
+ canvasId: save.canvasId,
5555
+ mutationId: save.clientToken,
4996
5556
  documentFormatVersion: 15,
4997
- baseVersion: capture.input.baseVersion,
5557
+ baseVersion: save.baseVersion,
4998
5558
  operations: [frame],
4999
5559
  requestContext: {
5000
- fingerprint: capture.fingerprint,
5001
- revisionPolicy: "strict"
5560
+ fingerprint: save.fingerprint,
5561
+ revisionPolicy
5002
5562
  }
5003
5563
  });
5004
- try {
5005
- return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
5006
- } catch (error) {
5007
- throw notConfirmed(capture, error);
5008
- }
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;
5009
5567
  };
5010
5568
  /** Saves the compiled capture as one change at the version the agent observed. */
5011
5569
  const saveCapturedFrame = async (remote, capture, job, snapshot) => {
5012
- const [compiled] = job.result.operations;
5013
- if (job.result.operations.length !== 1 || compiled?.op !== "insertConvertedSubtree") throw new CliError("INTERNAL", "The compiled capture is not one editable frame.", "Capture the moment again with a new clientToken.");
5014
- const saved = await applyFrame(remote, capture, capturedFrame(compiled, snapshot, capture.input.source));
5015
- if (saved.canvasId !== capture.canvasId || saved.mutationId !== capture.clientToken || saved.version !== capture.input.baseVersion + 1 || !saved.insertedNodeIds.includes(compiled.rootNodeId)) throw notConfirmed(capture, null);
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)));
5016
5577
  return savedCaptureReceipt(capture, saved, snapshot, compiled.rootNodeId);
5017
5578
  };
5018
5579
 
@@ -5024,13 +5585,16 @@ const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snaps
5024
5585
  const wait = async () => new Promise((resolve) => {
5025
5586
  globalThis.setTimeout(resolve, POLL_MS);
5026
5587
  });
5027
- 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.", `Run 'enhance canvas tree --canvas ${job.canvasId}' and retry the exact snapshot if its recording node still exists.`, {
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.`, {
5028
5592
  jobId: job.id,
5029
5593
  phase: job.phase
5030
5594
  });
5031
5595
  const readSnapshotJob = async (remote, jobId) => {
5032
5596
  const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
5033
- if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${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}`));
5034
5598
  return read.data.job;
5035
5599
  };
5036
5600
  const awaitSnapshot = async (remote, initial, input, progress) => {
@@ -5057,7 +5621,10 @@ const awaitSnapshot = async (remote, initial, input, progress) => {
5057
5621
  }
5058
5622
  if (currentTime >= deadline) {
5059
5623
  if (input.bounded === true) return job;
5060
- 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.`, {
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")}.`, {
5061
5628
  jobId: job.id,
5062
5629
  phase: job.phase
5063
5630
  });
@@ -5070,7 +5637,7 @@ const awaitSnapshot = async (remote, initial, input, progress) => {
5070
5637
  }
5071
5638
  return job;
5072
5639
  };
5073
- 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.");
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"));
5074
5641
  /** A place-only snapshot adds no layer and no revision; a screen snapshot adds both. */
5075
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);
5076
5643
  const assertSnapshotIdentity = (job, input) => {
@@ -5088,7 +5655,7 @@ const runSnapshot = async (remote, progress, input) => {
5088
5655
  atMs: input.atMs,
5089
5656
  ...input.context !== void 0 && { context: input.context }
5090
5657
  }));
5091
- 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.");
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."));
5092
5659
  assertSnapshotIdentity(made.data.job, input);
5093
5660
  return awaitSnapshot(remote, made.data.job, input, progress);
5094
5661
  };
@@ -5111,14 +5678,19 @@ const executeSnapshot = async (remote, progress, input) => {
5111
5678
  ...snapshot,
5112
5679
  warnings: job.result.warnings,
5113
5680
  retryClientToken: input.retryClientToken,
5114
- next: [`enhance canvas node --canvas ${job.canvasId} --node-id ${screenNodeId}`, `enhance canvas render --canvas ${job.canvasId} --node-id ${screenNodeId} --expected-version ${String(snapshot.version)}`]
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)]
5115
5688
  };
5116
5689
  };
5117
5690
  const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
5118
5691
 
5119
5692
  //#endregion
5120
5693
  //#region src/application/canvas-capture.composite.ts
5121
- const CAPTURED_PAGE_LABEL = "Captured page";
5122
5694
  const CANVAS_CAPTURE_PROCEDURES = ["canvas.mutation.get"];
5123
5695
  const compileAndSave = async (remote, capture, snapshot, waitMs) => {
5124
5696
  const job = await runCanvasPreparation(remote, {
@@ -5126,10 +5698,10 @@ const compileAndSave = async (remote, capture, snapshot, waitMs) => {
5126
5698
  expectedVersion: capture.input.baseVersion,
5127
5699
  request: {
5128
5700
  kind: "compile-screens",
5701
+ landing: "editable-frame",
5129
5702
  sources: [{
5130
5703
  screenId: snapshot.screenId,
5131
- captureId: snapshot.screenId,
5132
- label: CAPTURED_PAGE_LABEL
5704
+ captureId: snapshot.screenId
5133
5705
  }]
5134
5706
  },
5135
5707
  scope: { nodeIds: [] }
@@ -5146,7 +5718,7 @@ const compileAndSave = async (remote, capture, snapshot, waitMs) => {
5146
5718
  state: job.state,
5147
5719
  result: snapshot,
5148
5720
  failure: job.failure,
5149
- warning: job.state === "queued" || job.state === "running" ? `The page is stored and still being made editable. ${FOLLOW_CAPTURE}` : "The page could not be made editable, and nothing was added to the canvas. Capture the moment again with a new clientToken."
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")}.`
5150
5722
  });
5151
5723
  };
5152
5724
  /** The snapshot stores the page and names the frame's place, adding no layer. */
@@ -5206,11 +5778,401 @@ const captureCanvasRecording = async (remote, offered, clientToken) => {
5206
5778
  state: job.state,
5207
5779
  result: null,
5208
5780
  failure: job.failure,
5209
- warning: job.state === "queued" || job.state === "running" ? `The moment is still being stored. ${FOLLOW_CAPTURE}` : "The moment could not be stored, and nothing was added to the canvas."
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."
5210
5782
  });
5211
5783
  return compileAndSave(remote, capture, snapshot, Math.max(0, input.waitMs - (Date.now() - startedAt)));
5212
5784
  };
5213
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) => {
5845
+ try {
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);
5873
+ return {
5874
+ kind: "frame",
5875
+ version: placement.baseVersion,
5876
+ box: landed.box ?? null,
5877
+ url
5878
+ };
5879
+ }
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;
5886
+ return {
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
5915
+ };
5916
+ };
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
+ });
5969
+ try {
5970
+ return await saveFrame(remote, save, captureSwapOf(atPlace, pictureId), "rebase");
5971
+ } catch (error) {
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;
5980
+ }
5981
+ };
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 a Content Security Policy blocked it, run this snippet from Playwright in a context 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 (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 lasts 15 minutes for any number of pages, and the snippet holds it: keep the snippet out of what you print. To send this machine's installed fonts, first grant the page local-fonts: 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
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));
6120
+ }
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
6173
+ });
6174
+ };
6175
+
5214
6176
  //#endregion
5215
6177
  //#region src/application/import-canvas-asset.composite.ts
5216
6178
  const ASSET_PROCEDURES = [
@@ -5218,7 +6180,7 @@ const ASSET_PROCEDURES = [
5218
6180
  "canvas.asset.complete",
5219
6181
  "canvas.document.get"
5220
6182
  ];
5221
- 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.`, {
5222
6184
  ...error instanceof CliError && error.fields,
5223
6185
  operation: JSON.stringify(operation),
5224
6186
  outcome: "not_confirmed"
@@ -5228,10 +6190,7 @@ const assertIdentity = (asset, intent) => {
5228
6190
  };
5229
6191
  const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (input) => {
5230
6192
  const reference = parseCanvasReference(input.canvasRef);
5231
- if (hasCanvasReferenceScope(reference)) {
5232
- const held = wholeCanvasDocumentOutputSchema.parse(await remote.query(ASSET_PROCEDURES[2], { canvasId: reference.canvasId }));
5233
- canvasReferenceNodeIds(reference, canvasReadableSceneDocumentSchema.parse(held.document));
5234
- }
6193
+ if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, readStoredCanvasScene(wholeCanvasDocumentOutputSchema.parse(await remote.query(ASSET_PROCEDURES[2], { canvasId: reference.canvasId })).document));
5235
6194
  const { body, ...file } = await files.read();
5236
6195
  const intent = reserveCanvasAssetInputSchema.parse({
5237
6196
  ...file,
@@ -5255,7 +6214,7 @@ const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (i
5255
6214
  clientToken: input.clientToken
5256
6215
  }));
5257
6216
  assertIdentity(completed, intent);
5258
- 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.`);
5259
6218
  return canvasAssetImportOutputSchema.parse({
5260
6219
  operation,
5261
6220
  resource: completed,
@@ -5302,7 +6261,7 @@ const reserveAndUpload = async (remote, input, artifact, reserved) => {
5302
6261
  if (created.data.state === "uploading") await remote.upload({
5303
6262
  url: created.data.upload.url,
5304
6263
  headers: created.data.upload.headers,
5305
- body: artifact.open()
6264
+ body: await artifact.open()
5306
6265
  });
5307
6266
  if (created.data.state === "uploading" || created.data.state === "queued") {
5308
6267
  const submitted = submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLICATION_PROCEDURES[2], {
@@ -5393,7 +6352,7 @@ const toPrototypePublicationFailure = (publication) => {
5393
6352
  failure: {
5394
6353
  code: failure.code,
5395
6354
  message: failure.message,
5396
- 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.`
5397
6356
  }
5398
6357
  };
5399
6358
  };
@@ -5419,7 +6378,7 @@ const failureOf = (error) => error instanceof CliError ? {
5419
6378
  } : {
5420
6379
  code: "INTERNAL",
5421
6380
  message: "The publication request did not return a confirmed outcome.",
5422
- 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.`
5423
6382
  };
5424
6383
  const attach = async (remote, input, publication) => {
5425
6384
  const reference = parseCanvasReference(input.canvasRef);
@@ -5463,7 +6422,7 @@ const attachReady = async (remote, input, base, publication) => {
5463
6422
  attachmentStatus: isConflict ? "conflict" : isRejected ? "not_attempted" : "not_confirmed",
5464
6423
  failure,
5465
6424
  nextAction: failure.code === "UNAUTHORIZED" || failure.code === "FORBIDDEN" ? "restore_access" : isConflict || isRejected ? "replan_attachment" : "retry_same_request",
5466
- 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.`]
5467
6426
  };
5468
6427
  }
5469
6428
  };
@@ -5498,7 +6457,7 @@ const finishPublication = async (remote, input, canvasId, publication) => {
5498
6457
  failure: {
5499
6458
  code: "NOT_FOUND",
5500
6459
  message: "The deployment was abandoned.",
5501
- 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.`
5502
6461
  }
5503
6462
  };
5504
6463
  if (publication.state !== "ready") return base;
@@ -5537,7 +6496,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
5537
6496
  attachment: null,
5538
6497
  failure: failureOf(error),
5539
6498
  nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
5540
- 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.`]
5541
6500
  };
5542
6501
  }
5543
6502
  } });
@@ -5546,7 +6505,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
5546
6505
  //#region src/application/publish-prototype.composite.ts
5547
6506
  const PUBLISH_WAIT_MS = 3e5;
5548
6507
  const PUBLISH_PROTOTYPE_PROCEDURES = ["prototype.attach"];
5549
- 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."));
5550
6509
  const requireReadyPublication = (status) => {
5551
6510
  if (status.state === "failed") {
5552
6511
  const failure = toPrototypePublicationFailure(status);
@@ -5588,12 +6547,15 @@ const executePublish = async (remote, artifacts, input) => {
5588
6547
  totalBytes: status.totalBytes,
5589
6548
  alreadyExists: created.alreadyExists,
5590
6549
  warnings: prototypePublicationWarnings(status),
5591
- 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)]
5592
6551
  };
5593
6552
  } catch (error) {
5594
6553
  if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
5595
6554
  if (progress.deploymentId === null) throw error;
5596
- 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}.`, {
5597
6559
  code: error instanceof CliError ? error.code : "INTERNAL",
5598
6560
  fields: {
5599
6561
  ...error instanceof CliError && error.fields,
@@ -5619,7 +6581,10 @@ const canvasPreparationStatus = (job, operation) => {
5619
6581
  failure: job.failure,
5620
6582
  outcome: "not_confirmed",
5621
6583
  prepared: job.state === "succeeded",
5622
- warnings: ["Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit."]
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.`]
5623
6588
  };
5624
6589
  };
5625
6590
  const readCanvasPreparationStatus = async (remote, operation) => {
@@ -5627,52 +6592,6 @@ const readCanvasPreparationStatus = async (remote, operation) => {
5627
6592
  return canvasPreparationStatus(job, operation);
5628
6593
  };
5629
6594
 
5630
- //#endregion
5631
- //#region src/application/canvas-receipt.use-case.ts
5632
- const MAX_RECEIPT_NODE_IDS = 40;
5633
- const canvasWriteReceipt = (commit, fingerprint) => {
5634
- let remaining = MAX_RECEIPT_NODE_IDS;
5635
- const take = (ids) => {
5636
- const selected = ids.slice(0, remaining);
5637
- remaining -= selected.length;
5638
- return selected;
5639
- };
5640
- const insertedNodeIds = take(commit.insertedNodeIds);
5641
- const changedNodeIds = take(commit.changedNodeIds);
5642
- const removedNodeIds = take(commit.removedNodeIds);
5643
- const total = commit.insertedNodeIds.length + commit.changedNodeIds.length + commit.removedNodeIds.length;
5644
- return {
5645
- outcome: "committed",
5646
- canvasId: commit.canvasId,
5647
- mutationId: commit.mutationId,
5648
- previousVersion: commit.previousVersion,
5649
- version: commit.version,
5650
- operation: {
5651
- kind: "canvas-mutation",
5652
- canvasId: commit.canvasId,
5653
- mutationId: commit.mutationId,
5654
- fingerprint
5655
- },
5656
- affected: {
5657
- insertedNodeIds,
5658
- changedNodeIds,
5659
- removedNodeIds,
5660
- complete: total <= MAX_RECEIPT_NODE_IDS,
5661
- total
5662
- },
5663
- ...commit.copiedNodeIds !== void 0 && { identities: {
5664
- entries: Object.entries(commit.copiedNodeIds).toSorted(([left], [right]) => left.localeCompare(right, "en")).slice(0, MAX_RECEIPT_NODE_IDS).map(([sourceNodeId, nodeId]) => ({
5665
- sourceNodeId,
5666
- nodeId
5667
- })),
5668
- complete: Object.keys(commit.copiedNodeIds).length <= MAX_RECEIPT_NODE_IDS,
5669
- total: Object.keys(commit.copiedNodeIds).length
5670
- } },
5671
- verification: { rendered: false },
5672
- warnings: []
5673
- };
5674
- };
5675
-
5676
6595
  //#endregion
5677
6596
  //#region src/application/operation-image.use-case.ts
5678
6597
  const deliverOperationImage = async (remote, files, status) => {
@@ -5857,10 +6776,24 @@ const createReadOperationStatusComposite = (remote, files) => ({ execute: async
5857
6776
  //#region src/application/read-transcript.composite.ts
5858
6777
  const MAX_PREVIEW_COMMANDS = 3;
5859
6778
  const READ_TRANSCRIPT_PROCEDURES = ["transcript.get"];
5860
- 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
+ }));
5861
6794
  const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
5862
6795
  const parsed = transcriptOutputSchema.safeParse(await remote.query(READ_TRANSCRIPT_PROCEDURES[0], input));
5863
- 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."));
5864
6797
  if (parsed.data.state !== "ready") return parsed.data;
5865
6798
  return {
5866
6799
  ...parsed.data,
@@ -5935,7 +6868,7 @@ const readItems = async (remote, input) => {
5935
6868
  items: [],
5936
6869
  truncated: false
5937
6870
  }]);
5938
- const canvases = listCanvasesOutputSchema.parse(canvasValue);
6871
+ const canvases = listedCanvasesAnswerSchema.parse(canvasValue);
5939
6872
  const teams = listOrganisationsOutputSchema.parse(teamValue);
5940
6873
  const items = canvases.items.map((canvas) => ({
5941
6874
  kind: "canvas",
@@ -5944,7 +6877,8 @@ const readItems = async (remote, input) => {
5944
6877
  organisationId: canvas.organisationId,
5945
6878
  accessState: canvas.accessState,
5946
6879
  viewerCan: canvas.viewerCan,
5947
- openPath: `/c/${canvas.id}`
6880
+ openPath: `/c/${canvas.id}`,
6881
+ url: canvas.url ?? null
5948
6882
  }));
5949
6883
  if (input.includeDestinations) items.push({
5950
6884
  kind: "destination",
@@ -6017,7 +6951,8 @@ const applyPreparedOperations = async (remote, request) => {
6017
6951
  try {
6018
6952
  return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
6019
6953
  } catch (error) {
6020
- 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")}.`, {
6021
6956
  ...error instanceof CliError && error.fields,
6022
6957
  outcome: "not_confirmed",
6023
6958
  operation: JSON.stringify({
@@ -6051,7 +6986,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
6051
6986
  }
6052
6987
  });
6053
6988
  const result = await applyPreparedOperations(remote, request);
6054
- 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.`, {
6055
6990
  outcome: "not_confirmed",
6056
6991
  operation: JSON.stringify({
6057
6992
  kind: "canvas-mutation",
@@ -7045,6 +7980,7 @@ const outlineNodes = (scene, roots, depth, isCurrent) => {
7045
7980
  const node = requireCanvasNode(scene, id);
7046
7981
  const children = childrenByParent.get(id) ?? [];
7047
7982
  const isLocked = isCanvasNodeLocked(scene, id);
7983
+ const boxSource = canvasBoxSourceOf(node);
7048
7984
  nodes.push({
7049
7985
  id,
7050
7986
  label: node.label,
@@ -7062,7 +7998,8 @@ const outlineNodes = (scene, roots, depth, isCurrent) => {
7062
7998
  "group",
7063
7999
  "text"
7064
8000
  ].includes(node.component),
7065
- bounds: node.box ?? null
8001
+ bounds: node.box ?? null,
8002
+ ...boxSource !== void 0 && { boxSource }
7066
8003
  });
7067
8004
  if (at < depth) for (const child of children) visit(child, at + 1);
7068
8005
  };
@@ -7106,6 +8043,7 @@ const readCanvasOutline = (input, snapshot) => {
7106
8043
  total: all.length,
7107
8044
  nodes,
7108
8045
  omittedDescendants: hasOmittedDescendants,
8046
+ ...canvasRecordedBoxNoteFor(nodes),
7109
8047
  nextCursor: nextOffset < all.length ? encodeCanvasExchangeToken({
7110
8048
  protocol: "enhance-canvas-outline/1",
7111
8049
  canvasId: reference.canvasId,
@@ -7407,8 +8345,8 @@ const createReadCanvasComposite = (remote) => ({ execute: async (input) => {
7407
8345
  const reference = parseCanvasReference(input.canvasRef);
7408
8346
  const held = wholeCanvasDocumentOutputSchema.parse(await remote.query(READ_CANVAS_PROCEDURES[0], { canvasId: reference.canvasId }));
7409
8347
  if (input.expectedVersion !== void 0 && input.expectedVersion !== held.version) return stale(held.version);
8348
+ const scene = readStoredCanvasScene(held.document);
7410
8349
  const current = canvasSceneDocumentSchema.safeParse(held.document);
7411
- const scene = current.success ? current.data : canvasReadableSceneDocumentSchema.parse(held.document);
7412
8350
  if (input.view === "resources") return readCanvasResources(input, {
7413
8351
  reference,
7414
8352
  scene,
@@ -7439,43 +8377,6 @@ const createReadCanvasComposite = (remote) => ({ execute: async (input) => {
7439
8377
  });
7440
8378
  } });
7441
8379
 
7442
- //#endregion
7443
- //#region src/application/revisioned-canvas-command.composite.ts
7444
- const CANVAS_COMMAND_PROCEDURES = ["canvas.mutation.get"];
7445
- const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (input) => {
7446
- const canvasId = input.reference.canvasId;
7447
- const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_COMMAND_PROCEDURES[0], {
7448
- canvasId,
7449
- mutationId: input.clientToken,
7450
- fingerprint: input.fingerprint
7451
- }));
7452
- if (recovered.state === "committed") return canvasWriteReceipt(recovered.result, input.fingerprint);
7453
- const scene = await sceneAtVersion({ remote }, canvasId, input.baseVersion);
7454
- const operations = await input.plan(scene);
7455
- if ("outcome" in operations) return operations;
7456
- assertCanvasReferenceOperations(input.reference, scene, operations);
7457
- if (operations.length === 0) return {
7458
- outcome: "no_op",
7459
- canvasId,
7460
- version: input.baseVersion,
7461
- verification: { rendered: false },
7462
- warnings: []
7463
- };
7464
- const request = applyCanvasOperationsInputSchema.safeParse({
7465
- canvasId,
7466
- documentFormatVersion: 15,
7467
- mutationId: input.clientToken,
7468
- baseVersion: input.baseVersion,
7469
- operations,
7470
- requestContext: {
7471
- fingerprint: input.fingerprint,
7472
- revisionPolicy: "strict"
7473
- }
7474
- });
7475
- 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" });
7476
- return canvasWriteReceipt(applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request.data)), input.fingerprint);
7477
- } });
7478
-
7479
8380
  //#endregion
7480
8381
  //#region src/application/remove-canvas-nodes.composite.ts
7481
8382
  const removalPlan = (scene, rootNodeIds) => {
@@ -7511,6 +8412,7 @@ const createRemoveCanvasNodesComposite = (remote) => ({ execute: async ({ client
7511
8412
  return createRevisionedCanvasCommandComposite(remote).execute({
7512
8413
  reference,
7513
8414
  baseVersion: input.baseVersion,
8415
+ versionGiven: "input",
7514
8416
  clientToken,
7515
8417
  fingerprint: canvasExchangeDigest({
7516
8418
  operation: "canvas.remove/1",
@@ -7632,7 +8534,7 @@ const parseCanvasHtmlUpdate = (html) => {
7632
8534
  childNodes: element.childNodes.map((child) => "tagName" in child && !isPaintElement(child) ? visit(child, id) : child)
7633
8535
  };
7634
8536
  if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
7635
- 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.`);
7636
8538
  let key = `new_${String(fragments.length)}`;
7637
8539
  while (reservedIds.has(key)) key = `_${key}`;
7638
8540
  reservedIds.add(key);
@@ -7711,7 +8613,7 @@ const styleChangeOperations = (document, node, before, after) => {
7711
8613
  geometry: "default"
7712
8614
  }] : [],
7713
8615
  ...canvasEditableImageOperations(node, before.styles, after.styles),
7714
- ...Object.keys(styles).length === 0 ? [] : canvasStyleOperations(document, [{
8616
+ ...Object.keys(styles).length === 0 ? [] : canvasStoredStyleOperations(document, [{
7715
8617
  nodeIds: [node.id],
7716
8618
  styles
7717
8619
  }])
@@ -7834,6 +8736,7 @@ const createUpdateCanvasHtmlComposite = (remote) => ({ execute: async (offered)
7834
8736
  return createRevisionedCanvasCommandComposite(remote).execute({
7835
8737
  reference,
7836
8738
  baseVersion: binding.version,
8739
+ versionGiven: "snapshot",
7837
8740
  clientToken: input.clientToken,
7838
8741
  fingerprint,
7839
8742
  plan: async (scene) => prepareUpdate(remote, input, {
@@ -7942,7 +8845,7 @@ const targetFailure = (error, target) => {
7942
8845
  } : {
7943
8846
  code: "INTERNAL",
7944
8847
  message: "This render outcome could not be confirmed.",
7945
- 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.`
7946
8849
  }
7947
8850
  };
7948
8851
  };
@@ -7999,7 +8902,7 @@ const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered,
7999
8902
  complete: results.every((result) => "jobId" in result.outcome),
8000
8903
  renderedPixels,
8001
8904
  results,
8002
- 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")}.`]
8003
8906
  };
8004
8907
  } });
8005
8908
 
@@ -8339,7 +9242,7 @@ const packageArtifact = async (input) => {
8339
9242
  expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
8340
9243
  },
8341
9244
  manifest: packaged.manifest,
8342
- open: () => createReadStream(artifactPath),
9245
+ open: async () => openAsBlob(artifactPath),
8343
9246
  dispose: async () => rm(tempDirectory, { recursive: true })
8344
9247
  };
8345
9248
  } catch (error) {
@@ -8359,8 +9262,10 @@ const createPrototypeArtifactAdapter = (directory) => ({ package: async (input)
8359
9262
  //#region src/infrastructure/capability-invocation.adapter.ts
8360
9263
  const applyCanvas = async (dependencies, offered) => {
8361
9264
  const input = canvasApplyCapabilityInputSchema.parse(offered);
8362
- return createApplyCanvasComposite(dependencies.remote).execute({
8363
- ...input,
9265
+ return createEditCanvasComposite(dependencies.remote).apply({
9266
+ canvasId: input.canvasId,
9267
+ baseVersion: input.baseVersion,
9268
+ operations: input.operations,
8364
9269
  mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
8365
9270
  });
8366
9271
  };
@@ -8446,6 +9351,7 @@ const invokeComposite = async (dependencies, capabilityId, offered, retryClientT
8446
9351
  "canvas.writeHtml": async () => writeCanvasHtml(dependencies, offered),
8447
9352
  "canvas.insertHtml": async () => insertCanvasHtml(dependencies, offered, retryClientToken),
8448
9353
  "canvas.capture": async () => captureCanvasRecording(dependencies.remote, offered, retryClientToken),
9354
+ "canvas.capturePage": async () => captureCanvasPage(dependencies.remote, offered, retryClientToken),
8449
9355
  "canvas.makeEditable": async () => makeCanvasEditable(dependencies.remote, offered),
8450
9356
  "comment.attention": async () => readCommentAttention(dependencies, offered),
8451
9357
  "prototype.publishCanvas": async () => {
@@ -8474,10 +9380,273 @@ const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capabil
8474
9380
  return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
8475
9381
  } });
8476
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
+
8477
9647
  //#endregion
8478
9648
  //#region src/infrastructure/oauth-loopback.adapter.ts
8479
9649
  const CALLBACK_PATH = "/callback";
8480
- const AUTHORIZATION_TIMEOUT_MS = 12e4;
8481
9650
  const ENTROPY_BYTES = 32;
8482
9651
  const HTTP_OK = 200;
8483
9652
  const HTTP_BAD_REQUEST = 400;
@@ -8562,9 +9731,6 @@ const authorizationCode = async (input) => {
8562
9731
  completion.reject(/* @__PURE__ */ new Error("browser authorization cancelled"));
8563
9732
  };
8564
9733
  input.signal?.addEventListener("abort", abort, { once: true });
8565
- const timeout = setTimeout(() => {
8566
- completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
8567
- }, AUTHORIZATION_TIMEOUT_MS);
8568
9734
  try {
8569
9735
  input.signal?.throwIfAborted();
8570
9736
  input.onReady(url);
@@ -8574,7 +9740,6 @@ const authorizationCode = async (input) => {
8574
9740
  redirectUri
8575
9741
  };
8576
9742
  } finally {
8577
- clearTimeout(timeout);
8578
9743
  input.signal?.removeEventListener("abort", abort);
8579
9744
  await new Promise((resolve) => {
8580
9745
  server.close(() => {
@@ -8611,6 +9776,7 @@ const CLI_DEVELOPMENT_PROFILE = {
8611
9776
  apiUrl: "https://api.enhance3.karunalabs.ai",
8612
9777
  commandName: "enhance-dev",
8613
9778
  configDirectoryName: "enhance-development",
9779
+ macConfigDirectoryName: "Enhance Development",
8614
9780
  environment: "development",
8615
9781
  mcpServiceName: "enhance-dev-mcp"
8616
9782
  };
@@ -8618,31 +9784,42 @@ const CLI_PRODUCTION_PROFILE = {
8618
9784
  apiUrl: "https://api.enhancelabs.ai",
8619
9785
  commandName: "enhance",
8620
9786
  configDirectoryName: "enhance",
9787
+ macConfigDirectoryName: "Enhance",
8621
9788
  environment: "production",
8622
9789
  mcpServiceName: "enhance-mcp"
8623
9790
  };
8624
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));
8625
9800
  const rejectCredentialCollision = (apiUrl, directory, homeDirectory, production) => {
8626
9801
  const origin = URL.canParse(apiUrl) ? new URL(apiUrl).origin : null;
8627
9802
  const resolved = path.resolve(directory);
8628
9803
  const development = CLI_DEVELOPMENT_PROFILE;
8629
- 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.");
8630
9805
  };
8631
9806
  const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
8632
- const resolveCliConfig = (variables, homeDirectory, release) => {
9807
+ const resolveCliConfig = (variables, homeDirectory, release, isMac = false) => {
8633
9808
  const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
8634
9809
  if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
8635
9810
  const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
8636
- const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
9811
+ const earlierConfigDirectory = configFolder(homeDirectory, release);
9812
+ const expectedConfigDirectory = isMac ? macFolder(homeDirectory, release) : earlierConfigDirectory;
8637
9813
  const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
8638
9814
  if (release.environment === "development") {
8639
9815
  if (requestedApi !== void 0 && normalizedApi(requestedApi) !== normalizedApi(release.apiUrl)) throw new TypeError("Enhance development cannot use this API. Use the bundled development endpoint.");
8640
- 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}`);
8641
9817
  } else rejectCredentialCollision(requestedApi ?? release.apiUrl, requestedConfigDirectory ?? expectedConfigDirectory, homeDirectory, release);
8642
9818
  return {
8643
9819
  apiUrl: requestedApi ?? release.apiUrl,
8644
9820
  commandName: release.commandName,
8645
9821
  configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
9822
+ ...isMac && requestedConfigDirectory === void 0 && { earlierConfigDirectory },
8646
9823
  mcpServiceName: release.mcpServiceName
8647
9824
  };
8648
9825
  };
@@ -8662,6 +9839,7 @@ const remoteMcpConfigSchema = z.object({
8662
9839
  MCP_SERVICE_DOCUMENTATION_URL: z.url().default("https://enhancelabs.ai"),
8663
9840
  MCP_ALLOWED_HOSTS: z.string().min(1),
8664
9841
  MCP_FILE_ORIGINS: z.string().default(""),
9842
+ MCP_STAGED_UPLOAD_ORIGIN: z.url().optional(),
8665
9843
  MCP_UI_URL: z.url().optional(),
8666
9844
  MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
8667
9845
  });
@@ -8669,7 +9847,13 @@ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables
8669
9847
 
8670
9848
  //#endregion
8671
9849
  //#region src/infrastructure/environment.config.ts
8672
- 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
+ });
8673
9857
  const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
8674
9858
  const readLocalMcpEnvironment = () => {
8675
9859
  const profile = z.enum(["legacy", "canvas"]).default("legacy").parse(process.env["ENHANCE_MCP_PROFILE"]);
@@ -8784,15 +9968,11 @@ const health = async (apiUrl) => {
8784
9968
  }
8785
9969
  };
8786
9970
  const upload = async (input) => {
8787
- const isStreaming = !(input.body instanceof Uint8Array);
8788
- const body = isStreaming ? Readable.toWeb(input.body) : input.body;
8789
- const request = {
9971
+ const response = await fetch(input.url, {
8790
9972
  method: "PUT",
8791
9973
  headers: input.headers,
8792
- body,
8793
- ...isStreaming && { duplex: "half" }
8794
- };
8795
- const response = await fetch(input.url, request);
9974
+ body: input.body
9975
+ });
8796
9976
  if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
8797
9977
  const etag = response.headers.get("etag");
8798
9978
  if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
@@ -8837,4 +10017,14 @@ const createMutationKeyAdapter = () => {
8837
10017
  };
8838
10018
 
8839
10019
  //#endregion
8840
- 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 };