@enhance-eng/enhance 0.1.160 → 0.1.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as canvasRenderBatchRequestSchema, $n as wholeCanvasDocumentOutputSchema, $t as cliAuthConfigurationSchema, An as canvasRecordingPropsSchema, Ar as canvasAdditionalStyleSchema, At as hasCanvasReferenceScope, Bn as FRAME_KIND, Bt as getRecordingOutputSchema, Cn as canvasCssTypographyOwners, Cr as reserveCanvasAssetOutputSchema, D as encodeCanvasExchangeToken, Dn as canvasCaptureSchema, Dr as canvasRichTextValueOf, Dt as canvasReferenceNodeIds, E as decodeCanvasExchangeToken, Er as canvasRichTextOf, Et as assertCanvasReferenceNodes, F as canvasAssetImportOutputSchema, G as canvasApplyCapabilityInputSchema, Gn as TEXT_KIND, Gt as foldPrototypeArtifactPath, H as canvasCaptureCapabilityInputSchema, Hn as IMAGE_KIND, Ht as PROTOTYPE_ARTIFACT_MANIFEST_PATH, I as canvasArrangeCapabilityInputSchema, In as AGENT_CLIENT_HEADER, Ir as listCanvasesOutputSchema, J as canvasWriteHtmlCapabilityInputSchema, Jn as getCanvasMutationOutputSchema, Jt as prototypeArtifactManifestSchema, K as canvasReadCapabilityInputSchema, Kn as applyCanvasOperationsInputSchema, Kt as getPrototypeArtifactCapabilitiesOutputSchema, Mn as canvasReferencePageOf, Mr as canvasBlendModeSchema, Mt as PartialBatchError, N as canvasAssetImportCapabilityInputSchema, Nn as resolveCanvasReference, Nr as canvasPaintSchema, Nt as CliError, O as resolveCanvasSnapshot, On as canvasConversionMetadataSchema, Or as hasCanvasRichTextPaints, Pn as beginCanvasActivityOutputSchema, Pt as transcriptOutputSchema, Q as transcriptReadCapabilityInputSchema, R as canvasDuplicateCapabilityInputSchema, Rn as createCanvasPreparationOutputSchema, Sn as applyCanvasTypographyPatch, Sr as reserveCanvasAssetInputSchema, St as canvasMakeEditableCapabilityInputSchema, T as canvasSnapshotToken, Tn as canvasTextPropsWithContent, Tr as canvasImageAssetIdentityFromPath, Un as PAGE_KIND, Ut as attachPrototypeArtifactOutputSchema, Vn as GROUP_KIND, Wn as RECTANGLE_KIND, Wt as createPrototypeArtifactOutputSchema, X as prototypePublishCapabilityInputSchema, Xn as textOf, Xt as submitPrototypeArtifactOutputSchema, Y as commentAttentionCapabilityInputSchema, Yn as canvasLayoutWithoutCssProperties, Yt as prototypeArtifactPathSchema, Z as recordingSnapshotCapabilityInputSchema, Zn as mapCanvasFontSources, Zt as getMeOutputSchema, _t as canvasFindCursorSchema, ar as canvasRenderStateSchema, at as canvasRenderFileSchema, b as canvasPrototypeCapabilityInputSchema, br as canvasCssValue, bt as canvasInsertHtmlCapabilityInputSchema, cr as createCanvasRenderOutputSchema, ct as canvasOutlineCursorSchema, d as toRemoteError, dr as getCanvasRenderOutputSchema, dt as canvasUpdateHtmlCapabilityInputSchema, en as createAgentTokenOutputSchema, fr as canvasReadableSceneDocumentSchema, ft as canvasUpdateHtmlInputSchema, gr as canvasAxisStyleProperties, hr as canvasAuthoredStyleDeclarations, it as canvasRenderRequestSchema, j as operationStatusInputSchema, jn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, jr as CANVAS_BLEND_MODES, jt as parseCanvasReference, kn as canvasPrototypePropsSchema, kr as CANVAS_RICH_TEXT_STYLE_PROPERTIES, lr as createRecordingSnapshotOutputSchema, lt as canvasReadInputSchema, mt as canvasResourcesCursorSchema, nn as listOrganisationsOutputSchema, nr as createCanvasConversionOutputSchema, ot as canvasRemoveCapabilityInputSchema, pr as canvasSceneDocumentSchema, pt as canvasTranscriptCursorSchema, q as canvasRenderCapabilityInputSchema, qn as applyCanvasOperationsOutputSchema, qt as getPrototypePublishStatusOutputSchema, rr as getCanvasConversionOutputSchema, tr as canvasNodeStylePatchSchema, tt as canvasRenderPendingSchema, ur as downloadCanvasRenderOutputSchema, vt as canvasFindInputSchema, w as canvasExchangeDigest, wn as canvasTextChangeBetween, wr as canvasFontAssetIdentityFromPath, wt as canvasEditCapabilityInputSchema, xr as canvasAssetUploadOutputSchema, yr as canvasCssTokens, zn as getCanvasPreparationOutputSchema } from "./cli-output-identity.lib-DrfKWcGw.mjs";
2
+ import { $ 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";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
5
5
  import { homedir, tmpdir } from "node:os";
@@ -8,8 +8,8 @@ import { chmodSync, constants, createReadStream, createWriteStream, mkdirSync, w
8
8
  import path from "node:path";
9
9
  import { createHash, randomBytes, randomUUID } from "node:crypto";
10
10
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
- import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
12
11
  import { isDeepStrictEqual } from "node:util";
12
+ import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
13
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";
@@ -4874,6 +4874,343 @@ const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
4874
4874
  };
4875
4875
  } });
4876
4876
 
4877
+ //#endregion
4878
+ //#region src/application/canvas-preparation.use-case.ts
4879
+ const POLL_MS$1 = 250;
4880
+ const readPreparation = async (remote, jobId) => {
4881
+ try {
4882
+ return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
4883
+ } catch (error) {
4884
+ if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
4885
+ return null;
4886
+ }
4887
+ };
4888
+ const waitForPreparation = async (remote, initial, waitMs) => {
4889
+ const deadline = Date.now() + waitMs;
4890
+ let job = initial;
4891
+ while (job.state === "queued" || job.state === "running") {
4892
+ const remaining = deadline - Date.now();
4893
+ if (remaining <= 0) break;
4894
+ await setTimeout$1(Math.min(POLL_MS$1, remaining));
4895
+ const status = await readPreparation(remote, initial.id);
4896
+ if (status === null) return job;
4897
+ job = getCanvasPreparationOutputSchema.parse(status.value).job;
4898
+ if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
4899
+ }
4900
+ return job;
4901
+ };
4902
+ const runCanvasPreparation = async (remote, input, waitMs) => {
4903
+ const made = createCanvasPreparationOutputSchema.parse(await remote.mutate("canvas.render.preparation.create", input));
4904
+ const job = await waitForPreparation(remote, made.job, waitMs);
4905
+ if (job.canvasId !== input.canvasId || job.requestedVersion !== input.expectedVersion || !isDeepStrictEqual(job.scope, input.scope) || !isDeepStrictEqual(job.request, input.request)) throw new CliError("CONFLICT", "The native preparation does not match this request.", "Read the canvas and prepare a new intent; do not apply this plan.");
4906
+ if (job.state === "succeeded" && job.result.loadedVersion !== input.expectedVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
4907
+ return job;
4908
+ };
4909
+
4910
+ //#endregion
4911
+ //#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.";
4913
+ const attachmentOf = (state) => state === "queued" || state === "running" ? "pending" : "not_confirmed";
4914
+ const captureReceipt = (capture, step) => ({
4915
+ operation: step.operation,
4916
+ state: step.state,
4917
+ requestedVersion: capture.input.baseVersion,
4918
+ source: capture.input.source,
4919
+ attachment: step.frame === void 0 || step.frame === null ? attachmentOf(step.state) : "committed",
4920
+ result: step.result,
4921
+ frame: step.frame ?? null,
4922
+ failure: step.failure,
4923
+ warningCount: 1,
4924
+ warnings: [step.warning]
4925
+ });
4926
+ const mutationReference = (capture) => ({
4927
+ kind: "canvas-mutation",
4928
+ canvasId: capture.canvasId,
4929
+ mutationId: capture.clientToken,
4930
+ fingerprint: capture.fingerprint
4931
+ });
4932
+ /** The receipt of a saved capture: the frame, its version, and the change to follow. */
4933
+ const savedCaptureReceipt = (capture, saved, result, frameNodeId) => captureReceipt(capture, {
4934
+ operation: mutationReference(capture),
4935
+ state: "succeeded",
4936
+ result,
4937
+ failure: null,
4938
+ frame: {
4939
+ nodeId: frameNodeId,
4940
+ version: saved.version
4941
+ },
4942
+ warning: "The capture is saved as an editable frame. Render the frame at its version to inspect it."
4943
+ });
4944
+ const recordingProvenance = (recording) => ({
4945
+ kind: "recording",
4946
+ recordingId: recording.recordingId,
4947
+ atMs: recording.atMs
4948
+ });
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) => {
4951
+ const nodes = Object.fromEntries(Object.entries(operation.nodes).map(([id, node]) => {
4952
+ const props = {
4953
+ ...node.props,
4954
+ capturedResource: { screenId: snapshot.screenId }
4955
+ };
4956
+ if (id !== operation.rootNodeId) return [id, {
4957
+ ...node,
4958
+ props
4959
+ }];
4960
+ const conversion = node.props?.["conversion"];
4961
+ return [id, {
4962
+ ...node,
4963
+ ...node.box !== void 0 && { box: {
4964
+ ...node.box,
4965
+ x: snapshot.box.x,
4966
+ y: snapshot.box.y
4967
+ } },
4968
+ props: {
4969
+ ...props,
4970
+ conversion: {
4971
+ ...typeof conversion === "object" && conversion,
4972
+ provenance: recordingProvenance(recording)
4973
+ }
4974
+ }
4975
+ }];
4976
+ }));
4977
+ return {
4978
+ ...operation,
4979
+ destination: {
4980
+ kind: "insert-children",
4981
+ targetNodeId: "root",
4982
+ ...snapshot.pageId !== void 0 && { pageId: snapshot.pageId }
4983
+ },
4984
+ nodes
4985
+ };
4986
+ };
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) => {
4993
+ const request = applyCanvasOperationsInputSchema.parse({
4994
+ canvasId: capture.canvasId,
4995
+ mutationId: capture.clientToken,
4996
+ documentFormatVersion: 15,
4997
+ baseVersion: capture.input.baseVersion,
4998
+ operations: [frame],
4999
+ requestContext: {
5000
+ fingerprint: capture.fingerprint,
5001
+ revisionPolicy: "strict"
5002
+ }
5003
+ });
5004
+ try {
5005
+ return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
5006
+ } catch (error) {
5007
+ throw notConfirmed(capture, error);
5008
+ }
5009
+ };
5010
+ /** Saves the compiled capture as one change at the version the agent observed. */
5011
+ 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);
5016
+ return savedCaptureReceipt(capture, saved, snapshot, compiled.rootNodeId);
5017
+ };
5018
+
5019
+ //#endregion
5020
+ //#region src/application/snapshot-recording.composite.ts
5021
+ const POLL_MS = 250;
5022
+ const PROGRESS_HEARTBEAT_MS = 5e3;
5023
+ const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
5024
+ const wait = async () => new Promise((resolve) => {
5025
+ globalThis.setTimeout(resolve, POLL_MS);
5026
+ });
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.`, {
5028
+ jobId: job.id,
5029
+ phase: job.phase
5030
+ });
5031
+ const readSnapshotJob = async (remote, jobId) => {
5032
+ 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}.`);
5034
+ return read.data.job;
5035
+ };
5036
+ const awaitSnapshot = async (remote, initial, input, progress) => {
5037
+ const deadline = Date.now() + input.timeoutMs;
5038
+ const startedAt = Date.now();
5039
+ let job = initial;
5040
+ let lastReportedAt = 0;
5041
+ let lastReportedState = "";
5042
+ while (job.state === "queued" || job.state === "running") {
5043
+ const currentTime = Date.now();
5044
+ const stateKey = `${job.state}:${job.phase}`;
5045
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
5046
+ progress({
5047
+ event: "snapshot.progress",
5048
+ jobId: job.id,
5049
+ state: job.state,
5050
+ phase: job.phase,
5051
+ elapsedMs: currentTime - startedAt,
5052
+ timeoutMs: input.timeoutMs,
5053
+ retryClientToken: input.retryClientToken
5054
+ });
5055
+ lastReportedAt = currentTime;
5056
+ lastReportedState = stateKey;
5057
+ }
5058
+ if (currentTime >= deadline) {
5059
+ 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.`, {
5061
+ jobId: job.id,
5062
+ phase: job.phase
5063
+ });
5064
+ }
5065
+ await wait();
5066
+ const next = await readSnapshotJob(remote, job.id);
5067
+ if (next.id !== initial.id) throw invalidSnapshot();
5068
+ assertSnapshotIdentity(next, input);
5069
+ job = next;
5070
+ }
5071
+ return job;
5072
+ };
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.");
5074
+ /** A place-only snapshot adds no layer and no revision; a screen snapshot adds both. */
5075
+ 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
+ const assertSnapshotIdentity = (job, input) => {
5077
+ if (job.canvasId !== input.canvasId || job.purpose !== "snapshot" || job.sourceState?.recordingId !== input.recordingId || job.sourceState.atMs !== input.atMs || input.context !== void 0 && job.requestedVersion !== input.context.expectedVersion) throw invalidSnapshot();
5078
+ if (job.state !== "succeeded") return;
5079
+ const result = job.result.snapshot;
5080
+ const source = job.result.sourceState;
5081
+ if (job.result.canvasId !== input.canvasId || job.result.loadedVersion !== job.requestedVersion || job.result.requestedVersion !== job.requestedVersion || source?.recordingId !== input.recordingId || source.requestedAtMs !== input.atMs || source.settledAtMs !== input.atMs || result?.recordingId !== input.recordingId || result.atMs !== input.atMs || result.screenId !== job.id || !isPlacedAsExpected(result, input)) throw invalidSnapshot();
5082
+ };
5083
+ /** Creates the snapshot job and follows it until it ends or, when bounded, the wait runs out. */
5084
+ const runSnapshot = async (remote, progress, input) => {
5085
+ const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
5086
+ canvasId: input.canvasId,
5087
+ recordingId: input.recordingId,
5088
+ atMs: input.atMs,
5089
+ ...input.context !== void 0 && { context: input.context }
5090
+ }));
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.");
5092
+ assertSnapshotIdentity(made.data.job, input);
5093
+ return awaitSnapshot(remote, made.data.job, input, progress);
5094
+ };
5095
+ const executeSnapshot = async (remote, progress, input) => {
5096
+ const held = await runSnapshot(remote, progress, input);
5097
+ if (held.state !== "succeeded" || held.result.snapshot === void 0) throw failureOf$1(held);
5098
+ const job = {
5099
+ ...held,
5100
+ result: {
5101
+ ...held.result,
5102
+ snapshot: held.result.snapshot
5103
+ }
5104
+ };
5105
+ const snapshot = job.result.snapshot;
5106
+ const { screenNodeId } = snapshot;
5107
+ if (screenNodeId === null) throw invalidSnapshot();
5108
+ return {
5109
+ jobId: job.id,
5110
+ canvasId: job.canvasId,
5111
+ ...snapshot,
5112
+ warnings: job.result.warnings,
5113
+ 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)}`]
5115
+ };
5116
+ };
5117
+ const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
5118
+
5119
+ //#endregion
5120
+ //#region src/application/canvas-capture.composite.ts
5121
+ const CAPTURED_PAGE_LABEL = "Captured page";
5122
+ const CANVAS_CAPTURE_PROCEDURES = ["canvas.mutation.get"];
5123
+ const compileAndSave = async (remote, capture, snapshot, waitMs) => {
5124
+ const job = await runCanvasPreparation(remote, {
5125
+ canvasId: capture.canvasId,
5126
+ expectedVersion: capture.input.baseVersion,
5127
+ request: {
5128
+ kind: "compile-screens",
5129
+ sources: [{
5130
+ screenId: snapshot.screenId,
5131
+ captureId: snapshot.screenId,
5132
+ label: CAPTURED_PAGE_LABEL
5133
+ }]
5134
+ },
5135
+ scope: { nodeIds: [] }
5136
+ }, waitMs);
5137
+ if (job.state === "succeeded") return saveCapturedFrame(remote, capture, job, snapshot);
5138
+ return captureReceipt(capture, {
5139
+ operation: {
5140
+ kind: "canvas-preparation",
5141
+ canvasId: capture.canvasId,
5142
+ jobId: job.id,
5143
+ mutationId: capture.clientToken,
5144
+ fingerprint: capture.fingerprint
5145
+ },
5146
+ state: job.state,
5147
+ result: snapshot,
5148
+ 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."
5150
+ });
5151
+ };
5152
+ /** The snapshot stores the page and names the frame's place, adding no layer. */
5153
+ const storeMoment = async (remote, capture, pageId, nodeIds) => runSnapshot(remote, () => null, {
5154
+ canvasId: capture.canvasId,
5155
+ recordingId: capture.input.source.recordingId,
5156
+ atMs: capture.input.source.atMs,
5157
+ retryClientToken: capture.clientToken,
5158
+ timeoutMs: capture.input.waitMs,
5159
+ bounded: true,
5160
+ context: {
5161
+ expectedVersion: capture.input.baseVersion,
5162
+ request: {
5163
+ previewJobId: capture.input.previewJobId,
5164
+ scope: {
5165
+ pageId,
5166
+ nodeIds: [...nodeIds]
5167
+ },
5168
+ placement: { kind: "editable-below-source" }
5169
+ }
5170
+ }
5171
+ });
5172
+ /**
5173
+ * Lands a recording moment as an editable frame: the snapshot stores the page and names its
5174
+ * place, the API compiles it, and this saves the frame as one change at the observed version.
5175
+ */
5176
+ const captureCanvasRecording = async (remote, offered, clientToken) => {
5177
+ const input = canvasCaptureCapabilityInputSchema.parse(offered);
5178
+ const reference = parseCanvasReference(input.canvasRef);
5179
+ const capture = {
5180
+ input,
5181
+ canvasId: reference.canvasId,
5182
+ clientToken,
5183
+ fingerprint: canvasExchangeDigest({
5184
+ operation: "canvas.capture/2",
5185
+ reference,
5186
+ baseVersion: input.baseVersion,
5187
+ source: input.source,
5188
+ previewJobId: input.previewJobId
5189
+ })
5190
+ };
5191
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_CAPTURE_PROCEDURES[0], {
5192
+ canvasId: capture.canvasId,
5193
+ mutationId: clientToken,
5194
+ fingerprint: capture.fingerprint
5195
+ }));
5196
+ if (recovered.state === "committed") return savedCaptureReceipt(capture, recovered.result, null, recovered.result.insertedNodeIds[0] ?? "");
5197
+ const startedAt = Date.now();
5198
+ const job = await storeMoment(remote, capture, reference.pageId, reference.nodeIds);
5199
+ const snapshot = job.state === "succeeded" ? job.result.snapshot : void 0;
5200
+ if (snapshot === void 0) return captureReceipt(capture, {
5201
+ operation: {
5202
+ kind: "canvas-render",
5203
+ canvasId: job.canvasId,
5204
+ jobId: job.id
5205
+ },
5206
+ state: job.state,
5207
+ result: null,
5208
+ 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."
5210
+ });
5211
+ return compileAndSave(remote, capture, snapshot, Math.max(0, input.waitMs - (Date.now() - startedAt)));
5212
+ };
5213
+
4877
5214
  //#endregion
4878
5215
  //#region src/application/import-canvas-asset.composite.ts
4879
5216
  const ASSET_PROCEDURES = [
@@ -5075,7 +5412,7 @@ const requireScopedAttachment = async (remote) => {
5075
5412
  const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PROCEDURES[0], {}));
5076
5413
  if (!capabilities.success || capabilities.data.attachmentProtocolVersion !== 1) throw new CliError("BAD_REQUEST", "This API does not advertise revision-checked prototype attachment.", "Upgrade the API before publishing through the canvas profile. No artifact was created or attached.");
5077
5414
  };
5078
- const failureOf$1 = (error) => error instanceof CliError ? {
5415
+ const failureOf = (error) => error instanceof CliError ? {
5079
5416
  code: error.code,
5080
5417
  message: error.message,
5081
5418
  remediation: error.remediation
@@ -5118,7 +5455,7 @@ const attachReady = async (remote, input, base, publication) => {
5118
5455
  nextAction: "inspect_result"
5119
5456
  };
5120
5457
  } catch (error) {
5121
- const failure = failureOf$1(error);
5458
+ const failure = failureOf(error);
5122
5459
  const isConflict = failure.code === "CONFLICT";
5123
5460
  const isRejected = REJECTED_CODES.has(failure.code);
5124
5461
  return {
@@ -5198,7 +5535,7 @@ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute:
5198
5535
  publication: null,
5199
5536
  attachmentStatus: "not_attempted",
5200
5537
  attachment: null,
5201
- failure: failureOf$1(error),
5538
+ failure: failureOf(error),
5202
5539
  nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
5203
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."]
5204
5541
  };
@@ -5532,141 +5869,6 @@ const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
5532
5869
  };
5533
5870
  } });
5534
5871
 
5535
- //#endregion
5536
- //#region src/application/snapshot-recording.composite.ts
5537
- const POLL_MS$1 = 250;
5538
- const PROGRESS_HEARTBEAT_MS = 5e3;
5539
- const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
5540
- const wait = async () => new Promise((resolve) => {
5541
- globalThis.setTimeout(resolve, POLL_MS$1);
5542
- });
5543
- const failureOf = (job) => new CliError(job.failure?.reason === "VERSION_CHANGED" ? "CONFLICT" : job.failure?.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : job.failure?.reason === "TARGET_INVALID" || job.failure?.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL", job.failure?.message ?? "The snapshot job ended without a result.", `Run 'enhance canvas tree --canvas ${job.canvasId}' and retry the exact snapshot if its recording node still exists.`, {
5544
- jobId: job.id,
5545
- phase: job.phase
5546
- });
5547
- const readSnapshotJob = async (remote, jobId) => {
5548
- const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
5549
- if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${jobId}.`);
5550
- return read.data.job;
5551
- };
5552
- const awaitSnapshot = async (remote, initial, input, progress) => {
5553
- const deadline = Date.now() + input.timeoutMs;
5554
- const startedAt = Date.now();
5555
- let job = initial;
5556
- let lastReportedAt = 0;
5557
- let lastReportedState = "";
5558
- while (job.state === "queued" || job.state === "running") {
5559
- const currentTime = Date.now();
5560
- const stateKey = `${job.state}:${job.phase}`;
5561
- if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
5562
- progress({
5563
- event: "snapshot.progress",
5564
- jobId: job.id,
5565
- state: job.state,
5566
- phase: job.phase,
5567
- elapsedMs: currentTime - startedAt,
5568
- timeoutMs: input.timeoutMs,
5569
- retryClientToken: input.retryClientToken
5570
- });
5571
- lastReportedAt = currentTime;
5572
- lastReportedState = stateKey;
5573
- }
5574
- if (currentTime >= deadline) {
5575
- if (input.bounded === true) return job;
5576
- throw new CliError("INTERNAL", `Snapshot ${job.id} did not finish before the local timeout.`, `Retry this exact command with --client-token ${input.retryClientToken} and a larger --timeout-ms.`, {
5577
- jobId: job.id,
5578
- phase: job.phase
5579
- });
5580
- }
5581
- await wait();
5582
- const next = await readSnapshotJob(remote, job.id);
5583
- if (next.id !== initial.id) throw invalidSnapshot();
5584
- assertSnapshotIdentity(next, input);
5585
- job = next;
5586
- }
5587
- return job;
5588
- };
5589
- const invalidSnapshot = () => new CliError("INTERNAL", "The snapshot response does not match the requested source or revision.", "Run enhance doctor and report the capture job ID.");
5590
- const assertSnapshotIdentity = (job, input) => {
5591
- if (job.canvasId !== input.canvasId || job.purpose !== "snapshot" || job.sourceState?.recordingId !== input.recordingId || job.sourceState.atMs !== input.atMs || input.context !== void 0 && job.requestedVersion !== input.context.expectedVersion) throw invalidSnapshot();
5592
- if (job.state !== "succeeded") return;
5593
- const result = job.result.snapshot;
5594
- const source = job.result.sourceState;
5595
- if (job.result.canvasId !== input.canvasId || job.result.loadedVersion !== job.requestedVersion || job.result.requestedVersion !== job.requestedVersion || source?.recordingId !== input.recordingId || source.requestedAtMs !== input.atMs || source.settledAtMs !== input.atMs || result?.recordingId !== input.recordingId || result.atMs !== input.atMs || result.screenId !== job.id || result.screenNodeId !== `scr_${input.recordingId}_${String(input.atMs)}` || input.context !== void 0 && result.version !== input.context.expectedVersion + 1) throw invalidSnapshot();
5596
- };
5597
- const captureReceipt = (job, input) => ({
5598
- operation: {
5599
- kind: "canvas-render",
5600
- canvasId: job.canvasId,
5601
- jobId: job.id
5602
- },
5603
- state: job.state,
5604
- requestedVersion: job.requestedVersion,
5605
- source: {
5606
- kind: "recording",
5607
- recordingId: input.recordingId,
5608
- atMs: input.atMs
5609
- },
5610
- attachment: job.state === "succeeded" ? "committed" : job.state === "queued" || job.state === "running" ? "pending" : "not_confirmed",
5611
- result: job.result?.snapshot ?? null,
5612
- failure: job.failure,
5613
- warningCount: job.result?.warnings.length ?? 0,
5614
- warnings: [job.state === "succeeded" ? "The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings." : "Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created."]
5615
- });
5616
- const captureCanvasRecording = async (remote, offered, clientToken) => {
5617
- const input = canvasCaptureCapabilityInputSchema.parse(offered);
5618
- const reference = parseCanvasReference(input.canvasRef);
5619
- return createSnapshotRecordingComposite(remote, () => null).execute({
5620
- canvasId: reference.canvasId,
5621
- recordingId: input.source.recordingId,
5622
- atMs: input.source.atMs,
5623
- retryClientToken: clientToken,
5624
- timeoutMs: input.waitMs,
5625
- bounded: true,
5626
- context: {
5627
- expectedVersion: input.baseVersion,
5628
- request: {
5629
- previewJobId: input.previewJobId,
5630
- scope: {
5631
- pageId: reference.pageId,
5632
- nodeIds: [...reference.nodeIds]
5633
- },
5634
- placement: input.placement
5635
- }
5636
- }
5637
- });
5638
- };
5639
- const executeSnapshot = async (remote, progress, input) => {
5640
- const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
5641
- canvasId: input.canvasId,
5642
- recordingId: input.recordingId,
5643
- atMs: input.atMs,
5644
- ...input.context !== void 0 && { context: input.context }
5645
- }));
5646
- if (!made.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot creation response.", "Run `enhance doctor` and report the API and CLI versions.");
5647
- assertSnapshotIdentity(made.data.job, input);
5648
- const held = await awaitSnapshot(remote, made.data.job, input, progress);
5649
- if (input.bounded === true) return captureReceipt(held, input);
5650
- if (held.state !== "succeeded" || held.result.snapshot === void 0) throw failureOf(held);
5651
- const job = {
5652
- ...held,
5653
- result: {
5654
- ...held.result,
5655
- snapshot: held.result.snapshot
5656
- }
5657
- };
5658
- const snapshot = job.result.snapshot;
5659
- return {
5660
- jobId: job.id,
5661
- canvasId: job.canvasId,
5662
- ...snapshot,
5663
- warnings: job.result.warnings,
5664
- retryClientToken: input.retryClientToken,
5665
- next: [`enhance canvas node --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId}`, `enhance canvas render --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId} --expected-version ${String(snapshot.version)}`]
5666
- };
5667
- };
5668
- const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
5669
-
5670
5872
  //#endregion
5671
5873
  //#region src/infrastructure/canvas-asset-file.adapter.ts
5672
5874
  const CONTENT_TYPES$1 = {
@@ -5808,39 +6010,6 @@ const createFindCanvasComposite = (remote) => ({ execute: async (input) => {
5808
6010
  };
5809
6011
  } });
5810
6012
 
5811
- //#endregion
5812
- //#region src/application/canvas-preparation.use-case.ts
5813
- const POLL_MS = 250;
5814
- const readPreparation = async (remote, jobId) => {
5815
- try {
5816
- return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
5817
- } catch (error) {
5818
- if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
5819
- return null;
5820
- }
5821
- };
5822
- const waitForPreparation = async (remote, initial, waitMs) => {
5823
- const deadline = Date.now() + waitMs;
5824
- let job = initial;
5825
- while (job.state === "queued" || job.state === "running") {
5826
- const remaining = deadline - Date.now();
5827
- if (remaining <= 0) break;
5828
- await setTimeout$1(Math.min(POLL_MS, remaining));
5829
- const status = await readPreparation(remote, initial.id);
5830
- if (status === null) return job;
5831
- job = getCanvasPreparationOutputSchema.parse(status.value).job;
5832
- if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
5833
- }
5834
- return job;
5835
- };
5836
- const runCanvasPreparation = async (remote, input, waitMs) => {
5837
- const made = createCanvasPreparationOutputSchema.parse(await remote.mutate("canvas.render.preparation.create", input));
5838
- const job = await waitForPreparation(remote, made.job, waitMs);
5839
- if (job.canvasId !== input.canvasId || job.requestedVersion !== input.expectedVersion || !isDeepStrictEqual(job.scope, input.scope) || !isDeepStrictEqual(job.request, input.request)) throw new CliError("CONFLICT", "The native preparation does not match this request.", "Read the canvas and prepare a new intent; do not apply this plan.");
5840
- if (job.state === "succeeded" && job.result.loadedVersion !== input.expectedVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
5841
- return job;
5842
- };
5843
-
5844
6013
  //#endregion
5845
6014
  //#region src/application/prepare-canvas-command.composite.ts
5846
6015
  const RECOVER_MUTATION = "canvas.mutation.get";
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { C as canvasPrototypeOutputSchema, F as canvasAssetImportOutputSchema, Gt as foldPrototypeArtifactPath, Nt as CliError, P as canvasAssetImportInputSchema, Qt as MCP_AUTH_SCOPE, S as canvasPrototypeIntentSchema, Yt as prototypeArtifactPathSchema, Zt as getMeOutputSchema, p as createCapabilityCatalogAdapter, v as PROTOTYPE_UPDATE_GUIDANCE } from "./cli-output-identity.lib-DrfKWcGw.mjs";
3
- import { a as readRemoteMcpEnvironment, c as createPrototypeArtifactAdapter, l as createPublishCanvasPrototypeComposite, n as createHttpRemoteAdapter, t as createMutationKeyAdapter, u as createImportCanvasAssetComposite } from "./mutation-key.adapter-DFjvJyX6.mjs";
4
- import { n as createMcpCanvasProfileAdapter, t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-DrEm-z3C.mjs";
5
- import { a as createMcpResultAdapter, o as createMcpClientContextAdapter, t as createMcpServerAdapter } from "./mcp-server.adapter-YQLl2Wec.mjs";
2
+ import { C as canvasPrototypeOutputSchema, F as canvasAssetImportOutputSchema, Gt as foldPrototypeArtifactPath, Nt as CliError, P as canvasAssetImportInputSchema, Qt as MCP_AUTH_SCOPE, S as canvasPrototypeIntentSchema, Yt as prototypeArtifactPathSchema, Zt as getMeOutputSchema, p as createCapabilityCatalogAdapter, v as PROTOTYPE_UPDATE_GUIDANCE } from "./cli-output-identity.lib-BfvrkZX5.mjs";
3
+ import { a as readRemoteMcpEnvironment, c as createPrototypeArtifactAdapter, l as createPublishCanvasPrototypeComposite, n as createHttpRemoteAdapter, t as createMutationKeyAdapter, u as createImportCanvasAssetComposite } from "./mutation-key.adapter-TMLqYILu.mjs";
4
+ import { n as createMcpCanvasProfileAdapter, t as createMcpInvocationAdapter } from "./mcp-invocation.adapter-DtgErzi9.mjs";
5
+ import { a as createMcpResultAdapter, o as createMcpClientContextAdapter, t as createMcpServerAdapter } from "./mcp-server.adapter-DJeyBKo7.mjs";
6
6
  import process from "node:process";
7
7
  import { z } from "zod";
8
8
  import os, { tmpdir } from "node:os";
@@ -729,7 +729,7 @@ const server = await createRemoteMcpHttpAdapter({
729
729
  fileOrigins: config.MCP_FILE_ORIGINS.split(",").map((value) => value.trim()).filter(Boolean),
730
730
  allowedHosts: config.MCP_ALLOWED_HOSTS.split(",").map((value) => value.trim()),
731
731
  allowedOrigins: config.MCP_ALLOWED_ORIGINS.split(",").map((value) => value.trim()),
732
- version: "0.1.160",
732
+ version: "0.1.161",
733
733
  ...config.MCP_UI_URL !== void 0 && { uiUrl: config.MCP_UI_URL },
734
734
  onerror: (error) => process.stderr.write(`${error.message}\n`)
735
735
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enhance-eng/enhance",
3
- "version": "0.1.160",
3
+ "version": "0.1.161",
4
4
  "private": false,
5
5
  "description": "Agent-first command-line interface for Enhance.",
6
6
  "keywords": [