@enhance-eng/enhance 0.1.5 → 0.1.7

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.
@@ -0,0 +1,1322 @@
1
+ #!/usr/bin/env node
2
+ import { $ as createCanvasConversionOutputSchema, B as getMeOutputSchema, C as CliError, F as getPrototypeArtifactCapabilitiesOutputSchema, G as beginCanvasActivityOutputSchema, H as cliAuthConfigurationSchema, I as getPrototypePublishStatusOutputSchema, J as applyCanvasOperationsOutputSchema, L as prototypeArtifactManifestSchema, M as attachPrototypeArtifactOutputSchema, N as createPrototypeArtifactOutputSchema, P as foldPrototypeArtifactPath, R as prototypeArtifactPathSchema, S as PartialBatchError, U as createAgentTokenOutputSchema, Z as getCanvasDocumentOutputSchema, _ as canvasWriteHtmlCapabilityInputSchema, at as downloadCanvasRenderOutputSchema, b as recordingSnapshotCapabilityInputSchema, et as getCanvasConversionOutputSchema, g as canvasRenderCapabilityInputSchema, h as canvasApplyCapabilityInputSchema, it as createRecordingSnapshotOutputSchema, j as PROTOTYPE_ARTIFACT_MANIFEST_PATH, ot as getCanvasRenderOutputSchema, rt as createCanvasRenderOutputSchema, st as canvasSceneDocumentSchema, v as commentAttentionCapabilityInputSchema, w as transcriptOutputSchema, x as transcriptReadCapabilityInputSchema, y as prototypePublishCapabilityInputSchema, z as submitPrototypeArtifactOutputSchema } from "./cli-output-identity.lib-BSUBcRJm.mjs";
3
+ import { z } from "zod";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import process from "node:process";
6
+ import { chmodSync, createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ import { mkdtemp, realpath, rm, stat } from "node:fs/promises";
11
+ import { Readable, Transform } from "node:stream";
12
+ import { pipeline } from "node:stream/promises";
13
+ import { ZipFile } from "yazl";
14
+ import { createTRPCUntypedClient, httpLink } from "@trpc/client";
15
+ import { spawn } from "node:child_process";
16
+ import { createServer } from "node:http";
17
+
18
+ //#region src/application/auth.use-case.ts
19
+ const TOKEN = /^enh_[\w-]{43}$/;
20
+ const authenticated = (value) => {
21
+ const parsed = getMeOutputSchema.parse(value);
22
+ if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "Run 'enhance auth login' and complete authentication in the browser.");
23
+ return {
24
+ authenticated: true,
25
+ personId: parsed.person.id,
26
+ displayName: parsed.person.displayName,
27
+ tokenId: parsed.authentication.tokenId,
28
+ tokenLabel: parsed.authentication.tokenLabel,
29
+ expiresAt: parsed.authentication.expiresAt
30
+ };
31
+ };
32
+ const createAuthUseCase = (credentials, remote, browser) => ({
33
+ loginWithToken: async (token) => {
34
+ if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass a manual token from Settings to 'enhance auth login' through stdin.");
35
+ const status = authenticated(await remote.queryWithToken("person.me", {}, token));
36
+ await credentials.write(token);
37
+ return status;
38
+ },
39
+ loginWithBrowser: async (input) => {
40
+ const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
41
+ if (configuration.method === "token") throw new CliError("BAD_REQUEST", "Browser authentication is not configured for this Enhance environment.", "Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.");
42
+ const accessToken = await browser.authorize({
43
+ issuer: configuration.issuer,
44
+ clientId: configuration.clientId,
45
+ scope: configuration.scope,
46
+ openBrowser: input.openBrowser,
47
+ onReady: input.onReady
48
+ });
49
+ const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
50
+ label: input.label,
51
+ expiresAt: null
52
+ }, accessToken));
53
+ const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
54
+ await credentials.write(created.token);
55
+ return status;
56
+ },
57
+ status: async () => {
58
+ if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
59
+ return authenticated(await remote.query("person.me", {}));
60
+ },
61
+ logout: async () => ({ loggedOut: await credentials.remove() })
62
+ });
63
+
64
+ //#endregion
65
+ //#region src/application/render-png.use-case.ts
66
+ const PNG_SIGNATURE = Uint8Array.from(globalThis.atob("iVBORw0KGgo="), (character) => character.codePointAt(0) ?? 0);
67
+ const PNG_HEADER_BYTE_LENGTH = 24;
68
+ const PNG_WIDTH_OFFSET = 16;
69
+ const PNG_HEIGHT_OFFSET = 20;
70
+ const pngDimensions = (body) => {
71
+ if (body.byteLength < PNG_HEADER_BYTE_LENGTH || PNG_SIGNATURE.some((byte, index) => body[index] !== byte)) return null;
72
+ const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
73
+ return {
74
+ width: view.getUint32(PNG_WIDTH_OFFSET),
75
+ height: view.getUint32(PNG_HEIGHT_OFFSET)
76
+ };
77
+ };
78
+ const downloadVerifiedRenderPng = async (remote, job) => {
79
+ const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
80
+ if (!signed.success) throw new CliError("INTERNAL", "The API returned an invalid render download response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
81
+ const body = await remote.download(signed.data.download.url);
82
+ const dimensions = pngDimensions(body);
83
+ 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}.`);
84
+ return body;
85
+ };
86
+
87
+ //#endregion
88
+ //#region src/application/render-canvas.composite.ts
89
+ const POLL_MS$2 = 250;
90
+ const PROGRESS_HEARTBEAT_MS$1 = 5e3;
91
+ const RENDER_CANVAS_PROCEDURES = ["canvas.render.create", "canvas.render.get"];
92
+ 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.");
93
+ const terminalFailure$1 = (job) => {
94
+ const failure = job.failure;
95
+ if (failure === null) return invalidResponse$2("render job");
96
+ 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";
97
+ 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.";
98
+ return new CliError(code, failure.message, remediation, {
99
+ jobId: job.id,
100
+ reason: failure.reason,
101
+ phase: failure.phase
102
+ });
103
+ };
104
+ const wait$2 = async (milliseconds) => new Promise((resolve) => {
105
+ globalThis.setTimeout(resolve, milliseconds);
106
+ });
107
+ const readJob = async (remote, jobId) => {
108
+ const parsed = getCanvasRenderOutputSchema.safeParse(await remote.query(RENDER_CANVAS_PROCEDURES[1], { jobId }));
109
+ if (!parsed.success) throw invalidResponse$2("render status");
110
+ return parsed.data.job;
111
+ };
112
+ const awaitJob = async (remote, input) => {
113
+ const startedAt = Date.now();
114
+ let lastReportedAt = 0;
115
+ let lastReportedState = "";
116
+ let job = input.initial;
117
+ while (job.state === "queued" || job.state === "running") {
118
+ const currentTime = Date.now();
119
+ const stateKey = `${job.state}:${job.phase}`;
120
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS$1) {
121
+ input.progress({
122
+ event: "render.progress",
123
+ jobId: job.id,
124
+ state: job.state,
125
+ phase: job.phase,
126
+ elapsedMs: currentTime - startedAt,
127
+ timeoutMs: input.timeoutMs,
128
+ retryClientToken: input.retryClientToken
129
+ });
130
+ lastReportedAt = currentTime;
131
+ lastReportedState = stateKey;
132
+ }
133
+ if (currentTime >= input.deadline) 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.`, {
134
+ jobId: job.id,
135
+ phase: job.phase
136
+ });
137
+ await wait$2(POLL_MS$2);
138
+ job = await readJob(remote, job.id);
139
+ }
140
+ if (job.state !== "succeeded") throw terminalFailure$1(job);
141
+ return job;
142
+ };
143
+ const nextCommands = (job) => {
144
+ const inspect = `enhance canvas inspect --canvas ${job.canvasId}`;
145
+ if (job.result.sourceState !== void 0) return [
146
+ "Inspect the PNG at path before persisting this moment.",
147
+ `enhance recording snapshot --canvas ${job.canvasId} --recording-id ${job.result.sourceState.recordingId} --at-ms ${String(job.result.sourceState.settledAtMs)}`,
148
+ inspect
149
+ ];
150
+ if (job.target.kind !== "node") return [inspect];
151
+ return [inspect, `enhance canvas node --canvas ${job.canvasId} --node-id ${job.target.nodeId}`];
152
+ };
153
+ const resultFrom = (job, written) => ({
154
+ jobId: job.id,
155
+ canvasId: job.canvasId,
156
+ requestedVersion: job.requestedVersion,
157
+ loadedVersion: job.result.loadedVersion,
158
+ target: job.target,
159
+ sourceState: job.result.sourceState ?? null,
160
+ bounds: job.result.bounds,
161
+ width: job.result.width,
162
+ height: job.result.height,
163
+ scale: job.result.scale,
164
+ contentType: job.result.contentType,
165
+ bytes: job.result.bytes,
166
+ warnings: job.result.warnings,
167
+ path: written.path,
168
+ sensitive: true,
169
+ cleanup: written.temporary ? "unlink-after-use" : "caller-owned",
170
+ ...written.deleteAfter !== null && { deleteAfter: written.deleteAfter.toISOString() },
171
+ next: nextCommands(job)
172
+ });
173
+ const executeRender = async (dependencies, input) => {
174
+ const made = createCanvasRenderOutputSchema.safeParse(await dependencies.remote.mutate(RENDER_CANVAS_PROCEDURES[0], {
175
+ canvasId: input.canvasId,
176
+ ...input.expectedVersion !== null && { expectedVersion: input.expectedVersion },
177
+ target: input.target,
178
+ ...input.sourceState !== null && { sourceState: input.sourceState },
179
+ scale: input.scale,
180
+ format: "png"
181
+ }));
182
+ if (!made.success) throw invalidResponse$2("render creation");
183
+ const job = await awaitJob(dependencies.remote, {
184
+ initial: made.data.job,
185
+ deadline: Date.now() + input.timeoutMs,
186
+ timeoutMs: input.timeoutMs,
187
+ retryClientToken: input.retryClientToken,
188
+ progress: dependencies.progress
189
+ });
190
+ const body = await downloadVerifiedRenderPng(dependencies.remote, job);
191
+ const written = dependencies.files.write({
192
+ body,
193
+ outputPath: input.outputPath,
194
+ overwrite: input.overwrite,
195
+ at: dependencies.now()
196
+ });
197
+ return resultFrom(job, written);
198
+ };
199
+ const createRenderCanvasComposite = (remote, files, now, progress = () => null) => ({ execute: async (input) => executeRender({
200
+ remote,
201
+ files,
202
+ now,
203
+ progress
204
+ }, input) });
205
+
206
+ //#endregion
207
+ //#region src/application/canvas-activity.composite.ts
208
+ const PROCEDURES = {
209
+ begin: "canvas.realtime.activity.begin",
210
+ renew: "canvas.realtime.activity.renew",
211
+ end: "canvas.realtime.activity.end"
212
+ };
213
+ const ignoreFailure = async (operation) => {
214
+ try {
215
+ await operation();
216
+ return true;
217
+ } catch {
218
+ return false;
219
+ }
220
+ };
221
+ const liveHandle = (remote, initial, activityId, renewAfterMs) => {
222
+ let target = initial;
223
+ let isFinished = false;
224
+ let isRenewing = false;
225
+ const renew = async () => {
226
+ if (isFinished || isRenewing) return;
227
+ isRenewing = true;
228
+ await ignoreFailure(async () => remote.mutate(PROCEDURES.renew, {
229
+ ...target,
230
+ nodeIds: [...target.nodeIds],
231
+ activityId
232
+ }));
233
+ isRenewing = false;
234
+ };
235
+ const timer = setInterval(() => void renew(), renewAfterMs);
236
+ return {
237
+ activityId,
238
+ update: async (next) => {
239
+ if (isFinished) return;
240
+ target = {
241
+ ...target,
242
+ ...next
243
+ };
244
+ await renew();
245
+ },
246
+ finish: async () => {
247
+ if (isFinished) return;
248
+ isFinished = true;
249
+ clearInterval(timer);
250
+ await ignoreFailure(async () => remote.mutate(PROCEDURES.end, {
251
+ canvasId: target.canvasId,
252
+ activityId
253
+ }));
254
+ }
255
+ };
256
+ };
257
+ const createCanvasActivityComposite = (remote) => ({
258
+ begin: async (target) => {
259
+ try {
260
+ const parsed = beginCanvasActivityOutputSchema.safeParse(await remote.mutate(PROCEDURES.begin, {
261
+ ...target,
262
+ nodeIds: [...target.nodeIds]
263
+ }));
264
+ return parsed.success ? liveHandle(remote, target, parsed.data.activityId, parsed.data.renewAfterMs) : null;
265
+ } catch {
266
+ return null;
267
+ }
268
+ },
269
+ finish: async (canvasId, activityId) => ignoreFailure(async () => remote.mutate(PROCEDURES.end, {
270
+ canvasId,
271
+ activityId
272
+ }))
273
+ });
274
+
275
+ //#endregion
276
+ //#region src/application/apply-canvas.composite.ts
277
+ const APPLY_PROCEDURE = "canvas.applyOperations";
278
+ const MAX_ACTIVITY_NODE_IDS$1 = 100;
279
+ const BOX_OPERATION_TYPES = /* @__PURE__ */ new Set([
280
+ "insertPrototype",
281
+ "insertText",
282
+ "setBox"
283
+ ]);
284
+ const hasOperationBox = (operation) => BOX_OPERATION_TYPES.has(operation.op);
285
+ const activityPhase = (input) => {
286
+ if (input.operations.some((operation) => operation.op === "insertNode" || operation.op === "insertText")) return "creating";
287
+ if (input.operations.some((operation) => operation.op === "remove")) return "deleting";
288
+ return "writing";
289
+ };
290
+ const operationNodeIds = (operation) => {
291
+ if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
292
+ if (operation.op === "insertNode") return [operation.node.id];
293
+ return [operation.nodeId];
294
+ };
295
+ const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operation) => operationNodeIds(operation)))].slice(0, MAX_ACTIVITY_NODE_IDS$1);
296
+ const operationBox = (operation) => {
297
+ if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
298
+ if (operation.op === "insertNode") return operation.node.box ?? null;
299
+ if (hasOperationBox(operation)) return operation.box;
300
+ return null;
301
+ };
302
+ const union = (boxes) => {
303
+ const first = boxes[0];
304
+ if (first === void 0) return null;
305
+ let x1 = first.x;
306
+ let y1 = first.y;
307
+ let x2 = first.x + first.width;
308
+ let y2 = first.y + first.height;
309
+ for (const box of boxes.slice(1)) {
310
+ x1 = Math.min(x1, box.x);
311
+ y1 = Math.min(y1, box.y);
312
+ x2 = Math.max(x2, box.x + box.width);
313
+ y2 = Math.max(y2, box.y + box.height);
314
+ }
315
+ return {
316
+ x: x1,
317
+ y: y1,
318
+ width: x2 - x1,
319
+ height: y2 - y1
320
+ };
321
+ };
322
+ const apply = async (remote, input) => {
323
+ const response = await remote.mutate(APPLY_PROCEDURE, input);
324
+ const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
325
+ 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.");
326
+ return parsed.data;
327
+ };
328
+ const createApplyCanvasComposite = (remote) => ({ execute: async (input, options) => {
329
+ if (options?.activity === false) return apply(remote, input);
330
+ const activity = await createCanvasActivityComposite(remote).begin({
331
+ canvasId: input.canvasId,
332
+ phase: activityPhase(input),
333
+ nodeIds: activityNodeIds(input),
334
+ bounds: union(input.operations.flatMap((operation) => {
335
+ const box = operationBox(operation);
336
+ return box === null ? [] : [box];
337
+ }))
338
+ });
339
+ try {
340
+ return await apply(remote, input);
341
+ } finally {
342
+ await activity?.finish();
343
+ }
344
+ } });
345
+
346
+ //#endregion
347
+ //#region src/application/write-html-canvas.composite.ts
348
+ const READ_DOCUMENT_PROCEDURE = "canvas.document.get";
349
+ const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
350
+ const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
351
+ const POLL_MS$1 = 250;
352
+ const MAX_ACTIVITY_NODE_IDS = 100;
353
+ const invalidResponse$1 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
354
+ const wait$1 = async (milliseconds) => new Promise((resolve) => {
355
+ globalThis.setTimeout(resolve, milliseconds);
356
+ });
357
+ const terminalFailure = (job) => {
358
+ const failure = job.failure;
359
+ 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 tree and correct the HTML or destination before retrying.", {
360
+ jobId: job.id,
361
+ phase: failure.phase,
362
+ reason: failure.reason
363
+ });
364
+ };
365
+ const readImport = async (remote, jobId) => {
366
+ const parsed = getCanvasConversionOutputSchema.safeParse(await remote.query(READ_IMPORT_PROCEDURE, { jobId }));
367
+ if (!parsed.success) throw invalidResponse$1("HTML import status");
368
+ return parsed.data.job;
369
+ };
370
+ const awaitImport = async (remote, initial, timeoutMs) => {
371
+ const deadline = Date.now() + timeoutMs;
372
+ let job = initial;
373
+ while (job.state === "queued" || job.state === "running") {
374
+ if (Date.now() >= deadline) throw new CliError("INTERNAL", `HTML import ${job.id} did not finish before the local timeout.`, "Retry the exact command with a larger --timeout-ms. If the queue remains stuck, run `enhance doctor`.", {
375
+ jobId: job.id,
376
+ phase: job.phase
377
+ });
378
+ await wait$1(POLL_MS$1);
379
+ job = await readImport(remote, job.id);
380
+ }
381
+ if (job.state !== "succeeded") throw terminalFailure(job);
382
+ return job;
383
+ };
384
+ const createImport = async (remote, input) => {
385
+ const made = createCanvasConversionOutputSchema.safeParse(await remote.mutate(CREATE_IMPORT_PROCEDURE, {
386
+ canvasId: input.canvasId,
387
+ expectedVersion: input.baseVersion,
388
+ source: {
389
+ kind: "html",
390
+ html: input.html,
391
+ label: "Agent-authored HTML",
392
+ ...input.idPrefix !== void 0 && { idPrefix: input.idPrefix }
393
+ },
394
+ destination: {
395
+ kind: input.mode,
396
+ targetNodeId: input.targetNodeId
397
+ }
398
+ }));
399
+ if (!made.success) throw invalidResponse$1("HTML import creation");
400
+ return awaitImport(remote, made.data.job, input.renderTimeoutMs);
401
+ };
402
+ const failedReview = (error, input, version) => {
403
+ return {
404
+ state: "failed",
405
+ mutationCommitted: true,
406
+ requestedVersion: version,
407
+ ...error instanceof CliError ? {
408
+ code: error.code,
409
+ message: error.message,
410
+ remediation: error.remediation,
411
+ ...error.fields !== void 0 && { fields: error.fields }
412
+ } : {
413
+ code: "INTERNAL",
414
+ message: "The post-write review render failed.",
415
+ remediation: "Read the current canvas version, then render the affected area again."
416
+ },
417
+ next: [
418
+ `enhance canvas inspect --canvas ${input.canvasId}`,
419
+ `enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`,
420
+ "Do not replay the committed write with a new mutation id."
421
+ ]
422
+ };
423
+ };
424
+ const renderReview = async (render, input, imported) => {
425
+ try {
426
+ return await render.execute({
427
+ canvasId: input.canvasId,
428
+ expectedVersion: imported.result.version,
429
+ target: {
430
+ kind: "node",
431
+ nodeId: imported.result.rootNodeId
432
+ },
433
+ sourceState: null,
434
+ scale: input.renderScale,
435
+ outputPath: input.renderOutputPath,
436
+ overwrite: input.overwriteRender,
437
+ timeoutMs: input.renderTimeoutMs,
438
+ retryClientToken: input.renderClientToken
439
+ });
440
+ } catch (error) {
441
+ return failedReview(error, input, imported.result.version);
442
+ }
443
+ };
444
+ const createdNodes = async (remote, imported) => {
445
+ const held = getCanvasDocumentOutputSchema.safeParse(await remote.query(READ_DOCUMENT_PROCEDURE, { canvasId: imported.canvasId }));
446
+ if (!held.success) throw invalidResponse$1("canvas document");
447
+ const scene = canvasSceneDocumentSchema.safeParse(held.data.document);
448
+ if (!scene.success) throw invalidResponse$1("editable canvas document");
449
+ return imported.result.insertedNodeIds.map((nodeId) => {
450
+ const node = scene.data.nodes[nodeId];
451
+ return {
452
+ id: nodeId,
453
+ name: node?.label ?? "",
454
+ component: node?.component ?? ""
455
+ };
456
+ });
457
+ };
458
+ const writeResponse = async (remote, input, imported, review) => ({
459
+ canvasId: input.canvasId,
460
+ mutationCommitted: true,
461
+ mode: input.mode,
462
+ targetNodeId: input.targetNodeId,
463
+ previousVersion: imported.result.previousVersion,
464
+ version: imported.result.version,
465
+ createdNodes: await createdNodes(remote, imported),
466
+ removedNodeIds: imported.result.removedNodeIds,
467
+ affectedBounds: imported.result.affectedBounds,
468
+ review,
469
+ next: [`enhance canvas tree --canvas ${input.canvasId}`, "Inspect the review PNG before continuing."]
470
+ });
471
+ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
472
+ const activity = await createCanvasActivityComposite(remote).begin({
473
+ canvasId: input.canvasId,
474
+ phase: "creating",
475
+ nodeIds: [input.targetNodeId],
476
+ bounds: null
477
+ });
478
+ try {
479
+ const imported = await createImport(remote, input);
480
+ await activity?.update({
481
+ phase: "rendering",
482
+ nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
483
+ bounds: imported.result.affectedBounds
484
+ });
485
+ const review = await renderReview(render, input, imported);
486
+ return await writeResponse(remote, input, imported, review);
487
+ } finally {
488
+ await activity?.finish();
489
+ }
490
+ } });
491
+
492
+ //#endregion
493
+ //#region src/infrastructure/render-file.adapter.ts
494
+ const DIRECTORY_MODE = 448;
495
+ const FILE_MODE = 384;
496
+ const TEMPORARY_TTL_MS = 36e5;
497
+ const write = (filePath, body, shouldOverwrite) => {
498
+ try {
499
+ writeFileSync(filePath, body, {
500
+ flag: shouldOverwrite ? "w" : "wx",
501
+ mode: FILE_MODE
502
+ });
503
+ chmodSync(filePath, FILE_MODE);
504
+ } catch (error) {
505
+ const code = typeof error === "object" && error !== null && Reflect.get(error, "code") === "EEXIST" ? "CONFLICT" : "INTERNAL";
506
+ 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.");
507
+ }
508
+ };
509
+ const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
510
+ if (input.outputPath !== null) {
511
+ const outputPath = path.resolve(input.outputPath);
512
+ write(outputPath, input.body, input.overwrite);
513
+ return {
514
+ path: outputPath,
515
+ temporary: false,
516
+ deleteAfter: null
517
+ };
518
+ }
519
+ const directory = path.join(configDirectory, "sensitive");
520
+ mkdirSync(directory, {
521
+ recursive: true,
522
+ mode: DIRECTORY_MODE
523
+ });
524
+ chmodSync(directory, DIRECTORY_MODE);
525
+ const outputPath = path.join(directory, `render-${globalThis.crypto.randomUUID()}.png`);
526
+ write(outputPath, input.body, false);
527
+ return {
528
+ path: outputPath,
529
+ temporary: true,
530
+ deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
531
+ };
532
+ } });
533
+
534
+ //#endregion
535
+ //#region src/application/publish-prototype.composite.ts
536
+ const PUBLISH_WAIT_MS = 3e5;
537
+ const INITIAL_POLL_MS = 50;
538
+ const MAX_POLL_MS = 1e3;
539
+ const PUBLISH_PROTOTYPE_PROCEDURES = [
540
+ "prototype.getArtifactCapabilities",
541
+ "prototype.createArtifact",
542
+ "prototype.submitArtifact",
543
+ "prototype.getPublishStatus",
544
+ "prototype.attach"
545
+ ];
546
+ 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.");
547
+ const waitUntilSettled = async (remote, input) => {
548
+ const deadline = Date.now() + PUBLISH_WAIT_MS;
549
+ let pollMs = INITIAL_POLL_MS;
550
+ while (Date.now() < deadline) {
551
+ const parsed = getPrototypePublishStatusOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[3], input));
552
+ if (!parsed.success) throw invalidResponse("status");
553
+ if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
554
+ if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
555
+ await setTimeout$1(pollMs);
556
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
557
+ }
558
+ throw new Error("prototype ingestion is still running");
559
+ };
560
+ const reserveAndUpload = async (remote, input, artifact, reserved) => {
561
+ const created = createPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[1], {
562
+ canvasId: input.canvasId,
563
+ ...input.prototypeId !== null && { prototypeId: input.prototypeId },
564
+ clientToken: input.clientToken,
565
+ nodeId: input.nodeId,
566
+ title: input.title,
567
+ entryPath: artifact.manifest.entryPath,
568
+ artifact: artifact.identity,
569
+ box: input.box
570
+ }));
571
+ if (!created.success) throw invalidResponse("artifact creation");
572
+ reserved(created.data.deploymentId);
573
+ if (created.data.state === "uploading") await remote.upload({
574
+ url: created.data.upload.url,
575
+ headers: created.data.upload.headers,
576
+ body: artifact.open()
577
+ });
578
+ if (created.data.state === "uploading" || created.data.state === "queued") {
579
+ if (!submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[2], {
580
+ canvasId: input.canvasId,
581
+ deploymentId: created.data.deploymentId
582
+ })).success) throw invalidResponse("artifact submission");
583
+ }
584
+ return created.data;
585
+ };
586
+ const requireSuccessfulIngestion = (status) => {
587
+ if (status.state !== "failed") return;
588
+ const { failure } = status;
589
+ throw new CliError("BAD_REQUEST", failure.message, "Fix the build and publish it with a new client token.", failure.path === void 0 ? void 0 : { path: failure.path });
590
+ };
591
+ const executePublish = async (remote, artifacts, input) => {
592
+ const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[0], {}));
593
+ if (!capabilities.success) throw invalidResponse("capabilities");
594
+ const artifact = await artifacts.package({
595
+ directory: input.directory,
596
+ entryPath: input.entryPath,
597
+ limits: capabilities.data.limits
598
+ });
599
+ const progress = { deploymentId: null };
600
+ try {
601
+ const created = await reserveAndUpload(remote, input, artifact, (reservedId) => {
602
+ progress.deploymentId = reservedId;
603
+ });
604
+ const status = await waitUntilSettled(remote, {
605
+ canvasId: input.canvasId,
606
+ deploymentId: created.deploymentId
607
+ });
608
+ requireSuccessfulIngestion(status);
609
+ const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[4], {
610
+ canvasId: input.canvasId,
611
+ deploymentId: created.deploymentId,
612
+ baseVersion: input.baseVersion
613
+ }));
614
+ if (!attached.success) throw invalidResponse("attachment");
615
+ return {
616
+ ...attached.data,
617
+ fileCount: status.fileCount,
618
+ totalBytes: status.totalBytes,
619
+ alreadyExists: created.alreadyExists,
620
+ next: [attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
621
+ };
622
+ } catch (error) {
623
+ if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
624
+ if (progress.deploymentId === null) throw error;
625
+ throw new PartialBatchError(`Prototype deployment ${progress.deploymentId} was created, but publishing did not complete.`, `Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`);
626
+ } finally {
627
+ await artifact.dispose();
628
+ }
629
+ };
630
+ const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
631
+
632
+ //#endregion
633
+ //#region src/application/read-transcript.composite.ts
634
+ const MAX_PREVIEW_COMMANDS = 3;
635
+ const READ_TRANSCRIPT_PROCEDURES = ["transcript.get"];
636
+ 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)}`);
637
+ const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
638
+ const parsed = transcriptOutputSchema.safeParse(await remote.query(READ_TRANSCRIPT_PROCEDURES[0], input));
639
+ 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.");
640
+ if (parsed.data.state !== "ready") return parsed.data;
641
+ return {
642
+ ...parsed.data,
643
+ guidance: "Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.",
644
+ next: previewCommands(input.canvasId, input.recordingId, parsed.data.cues.map((cue) => cue.startMs))
645
+ };
646
+ } });
647
+
648
+ //#endregion
649
+ //#region src/application/snapshot-recording.composite.ts
650
+ const POLL_MS = 250;
651
+ const PROGRESS_HEARTBEAT_MS = 5e3;
652
+ const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
653
+ const wait = async () => new Promise((resolve) => {
654
+ globalThis.setTimeout(resolve, POLL_MS);
655
+ });
656
+ 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.`, {
657
+ jobId: job.id,
658
+ phase: job.phase
659
+ });
660
+ const readSnapshotJob = async (remote, jobId) => {
661
+ const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
662
+ if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${jobId}.`);
663
+ return read.data.job;
664
+ };
665
+ const awaitSnapshot = async (remote, initial, input, progress) => {
666
+ const deadline = Date.now() + input.timeoutMs;
667
+ const startedAt = Date.now();
668
+ let job = initial;
669
+ let lastReportedAt = 0;
670
+ let lastReportedState = "";
671
+ while (job.state === "queued" || job.state === "running") {
672
+ const currentTime = Date.now();
673
+ const stateKey = `${job.state}:${job.phase}`;
674
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
675
+ progress({
676
+ event: "snapshot.progress",
677
+ jobId: job.id,
678
+ state: job.state,
679
+ phase: job.phase,
680
+ elapsedMs: currentTime - startedAt,
681
+ timeoutMs: input.timeoutMs,
682
+ retryClientToken: input.retryClientToken
683
+ });
684
+ lastReportedAt = currentTime;
685
+ lastReportedState = stateKey;
686
+ }
687
+ if (currentTime >= deadline) 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.`, {
688
+ jobId: job.id,
689
+ phase: job.phase
690
+ });
691
+ await wait();
692
+ job = await readSnapshotJob(remote, job.id);
693
+ }
694
+ if (job.state !== "succeeded" || job.result.snapshot === void 0) throw failureOf(job);
695
+ return {
696
+ ...job,
697
+ result: {
698
+ ...job.result,
699
+ snapshot: job.result.snapshot
700
+ }
701
+ };
702
+ };
703
+ const executeSnapshot = async (remote, progress, input) => {
704
+ const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
705
+ canvasId: input.canvasId,
706
+ recordingId: input.recordingId,
707
+ atMs: input.atMs
708
+ }));
709
+ 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.");
710
+ const job = await awaitSnapshot(remote, made.data.job, input, progress);
711
+ const snapshot = job.result.snapshot;
712
+ return {
713
+ jobId: job.id,
714
+ canvasId: job.canvasId,
715
+ ...snapshot,
716
+ warnings: job.result.warnings,
717
+ retryClientToken: input.retryClientToken,
718
+ 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)}`]
719
+ };
720
+ };
721
+ const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
722
+
723
+ //#endregion
724
+ //#region src/infrastructure/prototype-zip.adapter.ts
725
+ const NORMALIZED_MTIME = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
726
+ const REGULAR_FILE_MODE = 33188;
727
+ const ZIP64_ENTRY_FLOOR = 65535;
728
+ const badRequest$1 = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
729
+ const hashingTransform = (source, completed) => {
730
+ const hash = createHash("sha256");
731
+ let bytes = 0;
732
+ return new Transform({
733
+ transform: (chunk, _encoding, callback) => {
734
+ bytes += chunk.byteLength;
735
+ hash.update(chunk);
736
+ callback(null, chunk);
737
+ },
738
+ flush: (callback) => {
739
+ if (bytes !== source.bytes) {
740
+ callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
741
+ return;
742
+ }
743
+ completed({
744
+ path: source.path,
745
+ contentType: source.contentType,
746
+ bytes,
747
+ sha256: hash.digest("hex")
748
+ });
749
+ callback();
750
+ }
751
+ });
752
+ };
753
+ const addManifest = (input) => {
754
+ const manifest = prototypeArtifactManifestSchema.parse({
755
+ version: 1,
756
+ entryPath: input.entryPath,
757
+ files: input.files.map((file) => input.completed.get(file.path))
758
+ });
759
+ const body = Buffer.from(JSON.stringify(manifest), "utf8");
760
+ if (body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
761
+ input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
762
+ mtime: NORMALIZED_MTIME,
763
+ mode: REGULAR_FILE_MODE,
764
+ compress: true,
765
+ forceDosTimestamp: true
766
+ });
767
+ input.zip.end({
768
+ forceZip64Format: input.files.length >= ZIP64_ENTRY_FLOOR,
769
+ comment: ""
770
+ });
771
+ return manifest;
772
+ };
773
+ const createPrototypeZipAdapter = async (input) => {
774
+ const zip = new ZipFile();
775
+ const hash = createHash("sha256");
776
+ const hashing = new Transform({ transform: (chunk, _encoding, callback) => {
777
+ hash.update(chunk);
778
+ callback(null, chunk);
779
+ } });
780
+ const completed = /* @__PURE__ */ new Map();
781
+ const packaged = { manifest: null };
782
+ const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
783
+ zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
784
+ const complete = (file) => {
785
+ completed.set(file.path, file);
786
+ if (packaged.manifest === null && completed.size === input.files.length) packaged.manifest = addManifest({
787
+ zip,
788
+ completed,
789
+ ...input
790
+ });
791
+ };
792
+ for (const source of input.files) zip.addReadStreamLazy(source.path, {
793
+ size: source.bytes,
794
+ mtime: NORMALIZED_MTIME,
795
+ mode: REGULAR_FILE_MODE,
796
+ compress: true,
797
+ forceDosTimestamp: true
798
+ }, (callback) => {
799
+ callback(null, createReadStream(source.absolutePath).pipe(hashingTransform(source, complete)));
800
+ });
801
+ await output;
802
+ if (packaged.manifest === null) throw new Error("prototype ZIP completed without a manifest");
803
+ const artifactStats = await stat(input.artifactPath);
804
+ if (artifactStats.size > input.limits.artifactBytes) throw badRequest$1("The packaged prototype artifact is too large.", `This environment accepts ${String(input.limits.artifactBytes)} compressed bytes.`);
805
+ return {
806
+ manifest: packaged.manifest,
807
+ bytes: artifactStats.size,
808
+ sha256: hash.digest("hex")
809
+ };
810
+ };
811
+
812
+ //#endregion
813
+ //#region src/infrastructure/prototype-artifact.adapter.ts
814
+ const CONTENT_TYPES = {
815
+ ".avif": "image/avif",
816
+ ".css": "text/css; charset=utf-8",
817
+ ".gif": "image/gif",
818
+ ".html": "text/html; charset=utf-8",
819
+ ".ico": "image/x-icon",
820
+ ".jpeg": "image/jpeg",
821
+ ".jpg": "image/jpeg",
822
+ ".js": "text/javascript; charset=utf-8",
823
+ ".json": "application/json; charset=utf-8",
824
+ ".map": "application/json; charset=utf-8",
825
+ ".mjs": "text/javascript; charset=utf-8",
826
+ ".mp3": "audio/mpeg",
827
+ ".mp4": "video/mp4",
828
+ ".ogg": "audio/ogg",
829
+ ".otf": "font/otf",
830
+ ".png": "image/png",
831
+ ".svg": "image/svg+xml",
832
+ ".ttf": "font/ttf",
833
+ ".txt": "text/plain; charset=utf-8",
834
+ ".wasm": "application/wasm",
835
+ ".webm": "video/webm",
836
+ ".webp": "image/webp",
837
+ ".woff": "font/woff",
838
+ ".woff2": "font/woff2",
839
+ ".xml": "application/xml"
840
+ };
841
+ const contentTypeOf = (filePath) => CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
842
+ const statsFor = async (filePath) => {
843
+ try {
844
+ return await stat(filePath);
845
+ } catch {
846
+ return null;
847
+ }
848
+ };
849
+ const byteLength = (value) => Buffer.byteLength(value, "utf8");
850
+ const badRequest = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
851
+ const validatePath = (relativePath, limits) => {
852
+ if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
853
+ if (byteLength(relativePath) > limits.pathBytes) throw badRequest(`The prototype path ${relativePath} is too long.`, `Shorten it to at most ${String(limits.pathBytes)} UTF-8 bytes.`);
854
+ };
855
+ const walk = async (root, directory, ancestors, limits) => {
856
+ const resolvedDirectory = await realpath(directory);
857
+ if (ancestors.has(resolvedDirectory)) throw badRequest(`Cannot package the circular directory link at ${directory}.`, "Pass a directory tree that can be read once from top to bottom.");
858
+ const nextAncestors = new Set(ancestors).add(resolvedDirectory);
859
+ const { readdir } = await import("node:fs/promises");
860
+ const entries = await readdir(directory, { withFileTypes: true });
861
+ const files = [];
862
+ const orderedEntries = entries.toSorted((left, right) => left.name.localeCompare(right.name));
863
+ for (const entry of orderedEntries) {
864
+ const absolutePath = path.join(directory, entry.name);
865
+ const stats = await statsFor(absolutePath);
866
+ if (stats?.isDirectory() === true) {
867
+ files.push(...await walk(root, absolutePath, nextAncestors, limits));
868
+ continue;
869
+ }
870
+ if (stats?.isFile() !== true) throw badRequest(`Cannot read ${absolutePath} as a prototype file.`, "Pass a directory containing only regular files and directory links.");
871
+ const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
872
+ validatePath(relativePath, limits);
873
+ files.push({
874
+ absolutePath,
875
+ path: relativePath,
876
+ bytes: Number(stats.size),
877
+ contentType: contentTypeOf(absolutePath)
878
+ });
879
+ }
880
+ return files;
881
+ };
882
+ const validateSources = (files, entryPath, limits) => {
883
+ if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
884
+ if (files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
885
+ const folded = /* @__PURE__ */ new Set();
886
+ let totalBytes = 0;
887
+ for (const file of files) {
888
+ const key = foldPrototypeArtifactPath(file.path);
889
+ if (folded.has(key)) throw badRequest(`The prototype path ${file.path} collides by case or Unicode normalization.`, "Rename one of the colliding files so the build is portable.");
890
+ folded.add(key);
891
+ if (file.bytes > limits.fileBytes) throw badRequest(`The prototype file ${file.path} is too large.`, `This environment accepts ${String(limits.fileBytes)} bytes in one runtime file.`);
892
+ totalBytes += file.bytes;
893
+ if (totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
894
+ }
895
+ const entry = files.find((file) => file.path === entryPath);
896
+ if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
897
+ if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
898
+ };
899
+ const packageArtifact = async (input) => {
900
+ const root = path.resolve(input.directory);
901
+ const rootStats = await statsFor(root);
902
+ if (rootStats === null) throw new CliError("NOT_FOUND", `The prototype directory ${root} does not exist.`, "Build the app or pass the correct unpacked build directory.");
903
+ if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
904
+ const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
905
+ validatePath(entryPath, input.limits);
906
+ const files = await walk(root, root, /* @__PURE__ */ new Set(), input.limits);
907
+ validateSources(files, entryPath, input.limits);
908
+ const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
909
+ const artifactPath = path.join(tempDirectory, "artifact.zip");
910
+ try {
911
+ const packaged = await createPrototypeZipAdapter({
912
+ artifactPath,
913
+ files,
914
+ entryPath,
915
+ limits: input.limits
916
+ });
917
+ return {
918
+ identity: {
919
+ protocolVersion: 1,
920
+ format: "zip",
921
+ bytes: packaged.bytes,
922
+ sha256: packaged.sha256,
923
+ fileCount: packaged.manifest.files.length,
924
+ expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
925
+ },
926
+ manifest: packaged.manifest,
927
+ open: () => createReadStream(artifactPath),
928
+ dispose: async () => rm(tempDirectory, { recursive: true })
929
+ };
930
+ } catch (error) {
931
+ await rm(tempDirectory, { recursive: true });
932
+ throw error;
933
+ }
934
+ };
935
+ const createPrototypeArtifactAdapter = () => ({ package: packageArtifact });
936
+
937
+ //#endregion
938
+ //#region src/infrastructure/capability-invocation.adapter.ts
939
+ const renderFor = (input) => createRenderCanvasComposite(input.remote, createRenderFileAdapter(input.configDirectory), input.now ?? (() => /* @__PURE__ */ new Date()), input.progress ?? (() => null));
940
+ const applyCanvas = async (dependencies, offered) => {
941
+ const input = canvasApplyCapabilityInputSchema.parse(offered);
942
+ return createApplyCanvasComposite(dependencies.remote).execute({
943
+ ...input,
944
+ mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
945
+ });
946
+ };
947
+ const renderCanvas = async (dependencies, offered, retryClientToken) => {
948
+ const input = canvasRenderCapabilityInputSchema.parse(offered);
949
+ return renderFor(dependencies).execute({
950
+ ...input,
951
+ retryClientToken
952
+ });
953
+ };
954
+ const writeCanvasHtml = async (dependencies, offered) => {
955
+ const input = canvasWriteHtmlCapabilityInputSchema.parse(offered);
956
+ return createWriteHtmlCanvasComposite(dependencies.remote, renderFor(dependencies)).execute({
957
+ ...input,
958
+ renderClientToken: dependencies.mutationKey.current("canvas.render.create", { purpose: "write-html-review" })
959
+ });
960
+ };
961
+ const readCommentAttention = async (dependencies, offered) => {
962
+ const input = commentAttentionCapabilityInputSchema.parse(offered);
963
+ return dependencies.remote.query("comment.list", {
964
+ canvasId: input.canvasId,
965
+ filter: "open",
966
+ agentActionable: false
967
+ });
968
+ };
969
+ const publishPrototype = async (dependencies, offered, retryClientToken) => {
970
+ const input = prototypePublishCapabilityInputSchema.parse(offered);
971
+ return createPublishPrototypeComposite(dependencies.remote, createPrototypeArtifactAdapter()).execute({
972
+ ...input,
973
+ clientToken: retryClientToken
974
+ });
975
+ };
976
+ const snapshotRecording = async (dependencies, offered, retryClientToken) => {
977
+ const input = recordingSnapshotCapabilityInputSchema.parse(offered);
978
+ return createSnapshotRecordingComposite(dependencies.remote, dependencies.progress ?? (() => null)).execute({
979
+ ...input,
980
+ retryClientToken
981
+ });
982
+ };
983
+ const readTranscript = async (dependencies, offered) => {
984
+ const input = transcriptReadCapabilityInputSchema.parse(offered);
985
+ return createReadTranscriptComposite(dependencies.remote).execute(input);
986
+ };
987
+ const invokeComposite = async (dependencies, capabilityId, offered, retryClientToken) => {
988
+ switch (capabilityId) {
989
+ case "canvas.apply": return applyCanvas(dependencies, offered);
990
+ case "canvas.render": return renderCanvas(dependencies, offered, retryClientToken);
991
+ case "canvas.writeHtml": return writeCanvasHtml(dependencies, offered);
992
+ case "comment.attention": return readCommentAttention(dependencies, offered);
993
+ case "prototype.publish": return publishPrototype(dependencies, offered, retryClientToken);
994
+ case "recording.snapshot": return snapshotRecording(dependencies, offered, retryClientToken);
995
+ case "transcript.read": return readTranscript(dependencies, offered);
996
+ default: throw new TypeError(`${capabilityId} has no composite execution`);
997
+ }
998
+ };
999
+ const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capability, arguments: offered, clientToken }) => {
1000
+ const parsed = capability.inputSchema.parse(offered);
1001
+ const selectedClientToken = clientToken ?? randomUUID();
1002
+ input.mutationKey.select(selectedClientToken, capability.idempotency === "composite");
1003
+ if (capability.execution.kind === "composite") return invokeComposite(input, capability.id, parsed, selectedClientToken);
1004
+ return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
1005
+ } });
1006
+
1007
+ //#endregion
1008
+ //#region src/infrastructure/oauth-loopback.adapter.ts
1009
+ const CALLBACK_PATH = "/callback";
1010
+ const AUTHORIZATION_TIMEOUT_MS = 12e4;
1011
+ const ENTROPY_BYTES = 32;
1012
+ const HTTP_OK = 200;
1013
+ const HTTP_BAD_REQUEST = 400;
1014
+ const HTTP_NOT_FOUND = 404;
1015
+ const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
1016
+ const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
1017
+ const launchBrowser = (url) => {
1018
+ const command = process.platform === "darwin" ? {
1019
+ executable: "open",
1020
+ arguments: [url]
1021
+ } : process.platform === "win32" ? {
1022
+ executable: "rundll32.exe",
1023
+ arguments: ["url.dll,FileProtocolHandler", url]
1024
+ } : {
1025
+ executable: "xdg-open",
1026
+ arguments: [url]
1027
+ };
1028
+ const child = spawn(command.executable, command.arguments, {
1029
+ detached: true,
1030
+ stdio: "ignore"
1031
+ });
1032
+ child.once("error", () => false);
1033
+ child.unref();
1034
+ };
1035
+ const handleCallback = (input, request, response) => {
1036
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
1037
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
1038
+ response.writeHead(HTTP_NOT_FOUND).end();
1039
+ return;
1040
+ }
1041
+ if (url.searchParams.get("state") !== input.state) {
1042
+ response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
1043
+ return;
1044
+ }
1045
+ const error = url.searchParams.get("error");
1046
+ const received = url.searchParams.get("code");
1047
+ if (error !== null || received === null || received === "") {
1048
+ response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
1049
+ input.completion.reject(new Error(error ?? "the authorization response carried no code"));
1050
+ return;
1051
+ }
1052
+ response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
1053
+ input.completion.resolve(received);
1054
+ };
1055
+ const authorizeUrl = (input) => {
1056
+ const authorize = endpoint(input.issuer, "oauth/authorize");
1057
+ authorize.search = new URLSearchParams({
1058
+ response_type: "code",
1059
+ client_id: input.clientId,
1060
+ redirect_uri: input.redirectUri,
1061
+ scope: input.scope,
1062
+ state: input.state,
1063
+ code_challenge: input.challenge,
1064
+ code_challenge_method: "S256"
1065
+ }).toString();
1066
+ return authorize.href;
1067
+ };
1068
+ const authorizationCode = async (input) => {
1069
+ const completion = Promise.withResolvers();
1070
+ const server = createServer((request, response) => {
1071
+ handleCallback({
1072
+ state: input.state,
1073
+ completion
1074
+ }, request, response);
1075
+ });
1076
+ await new Promise((resolve, reject) => {
1077
+ server.once("error", reject);
1078
+ server.listen(0, "127.0.0.1", resolve);
1079
+ });
1080
+ const address = server.address();
1081
+ if (address === null || typeof address === "string") {
1082
+ server.close();
1083
+ throw new Error("the OAuth callback listener has no TCP port");
1084
+ }
1085
+ const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
1086
+ const url = authorizeUrl({
1087
+ ...input,
1088
+ redirectUri
1089
+ });
1090
+ input.onReady(url);
1091
+ if (input.openBrowser) launchBrowser(url);
1092
+ const timeout = setTimeout(() => {
1093
+ completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
1094
+ }, AUTHORIZATION_TIMEOUT_MS);
1095
+ try {
1096
+ return {
1097
+ code: await completion.promise,
1098
+ redirectUri
1099
+ };
1100
+ } finally {
1101
+ clearTimeout(timeout);
1102
+ await new Promise((resolve) => {
1103
+ server.close(() => {
1104
+ resolve();
1105
+ });
1106
+ });
1107
+ }
1108
+ };
1109
+ const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
1110
+ try {
1111
+ const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
1112
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
1113
+ const state = randomBytes(ENTROPY_BYTES).toString("base64url");
1114
+ const authorized = await authorizationCode({
1115
+ ...input,
1116
+ challenge,
1117
+ state
1118
+ });
1119
+ return await remote.exchangeOauthCode({
1120
+ issuer: input.issuer,
1121
+ clientId: input.clientId,
1122
+ code: authorized.code,
1123
+ redirectUri: authorized.redirectUri,
1124
+ verifier
1125
+ });
1126
+ } catch (error) {
1127
+ throw new CliError("UNAUTHORIZED", error instanceof Error ? `Browser authentication failed: ${error.message}.` : "Browser authentication failed.", "Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.");
1128
+ }
1129
+ } });
1130
+
1131
+ //#endregion
1132
+ //#region src/infrastructure/environment-profile.lib.ts
1133
+ const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
1134
+ const resolveCliConfig = (variables, homeDirectory, release) => {
1135
+ const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
1136
+ if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
1137
+ const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
1138
+ const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
1139
+ const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
1140
+ if (release.environment === "development") {
1141
+ if (requestedApi !== void 0 && requestedApi !== release.apiUrl) throw new TypeError(`Enhance development cannot use ${requestedApi}`);
1142
+ if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
1143
+ }
1144
+ return {
1145
+ apiUrl: requestedApi ?? release.apiUrl,
1146
+ commandName: release.commandName,
1147
+ configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
1148
+ mcpServiceName: release.mcpServiceName
1149
+ };
1150
+ };
1151
+
1152
+ //#endregion
1153
+ //#region src/infrastructure/remote-mcp.config.ts
1154
+ const remoteMcpConfigSchema = z.object({
1155
+ PORT: z.coerce.number().int().min(1).max(65535).default(3e3),
1156
+ MCP_HOST: z.string().min(1).default("0.0.0.0"),
1157
+ ENHANCE_API_URL: z.url(),
1158
+ MCP_AUTH_ISSUER: z.url(),
1159
+ MCP_RESOURCE_URL: z.url(),
1160
+ MCP_SERVICE_DOCUMENTATION_URL: z.url().default("https://enhancelabs.ai"),
1161
+ MCP_ALLOWED_HOSTS: z.string().min(1),
1162
+ MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
1163
+ });
1164
+ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables);
1165
+
1166
+ //#endregion
1167
+ //#region src/infrastructure/environment.config.ts
1168
+ const releaseProfile = {
1169
+ apiUrl: "https://api.enhancelabs.ai",
1170
+ commandName: "enhance",
1171
+ configDirectoryName: "enhance",
1172
+ environment: "production",
1173
+ mcpServiceName: "enhance-mcp"
1174
+ };
1175
+ const CLI_CONFIG = resolveCliConfig(process.env, homedir(), releaseProfile);
1176
+ const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
1177
+
1178
+ //#endregion
1179
+ //#region src/infrastructure/http-remote.adapter.ts
1180
+ const HEALTH_TIMEOUT_MS = 4e3;
1181
+ const NOT_FOUND_STATUS = 404;
1182
+ const FORBIDDEN_STATUS = 403;
1183
+ const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
1184
+ const networkCodeSchema = z.object({ code: z.string().regex(/^[A-Z][A-Z_0-9]+$/u) });
1185
+ const NETWORK_REMEDIATION = "Check network access and proxy settings for this API, then run enhance doctor again.";
1186
+ const originOf = (input) => new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
1187
+ const networkReason = (error) => {
1188
+ const parsed = networkCodeSchema.safeParse(error);
1189
+ if (parsed.success) return parsed.data.code;
1190
+ if (error instanceof Error && error.cause !== void 0) return networkReason(error.cause);
1191
+ return error instanceof Error ? error.name : "Network request failed";
1192
+ };
1193
+ const httpFailure = (url, status) => new CliError("INTERNAL", `${originOf(url)} answered HTTP ${String(status)}.`, NETWORK_REMEDIATION);
1194
+ const fetchNetwork = async (input, init) => {
1195
+ try {
1196
+ return await fetch(input, init);
1197
+ } catch (error) {
1198
+ throw new CliError("INTERNAL", `Could not reach ${originOf(input)}: ${networkReason(error)}.`, NETWORK_REMEDIATION);
1199
+ }
1200
+ };
1201
+ const fetchApi = async (input, init) => {
1202
+ const response = await fetchNetwork(input, init);
1203
+ if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
1204
+ return response;
1205
+ };
1206
+ const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
1207
+ url: `${apiUrl}/trpc`,
1208
+ fetch: async (input, init) => fetchApi(input, {
1209
+ ...init,
1210
+ signal: init?.signal ?? null
1211
+ }),
1212
+ headers: {
1213
+ ...token !== null && { authorization: `Bearer ${token}` },
1214
+ ...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
1215
+ }
1216
+ })] });
1217
+ const download = async (url) => {
1218
+ const response = await fetch(url);
1219
+ if (!response.ok) throw new CliError(response.status === NOT_FOUND_STATUS || response.status === FORBIDDEN_STATUS ? "NOT_FOUND" : "INTERNAL", `Render download answered HTTP ${String(response.status)}.`, "The result may have expired. Request a new render.");
1220
+ return new Uint8Array(await response.arrayBuffer());
1221
+ };
1222
+ const authenticationConfig = async (apiUrl) => {
1223
+ const response = await fetchNetwork(`${apiUrl}/v1/cli-auth`);
1224
+ if (!response.ok) {
1225
+ if (response.status === NOT_FOUND_STATUS) throw new CliError("BAD_REQUEST", "This Enhance API does not support browser authentication.", "Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.");
1226
+ throw new CliError("INTERNAL", `${originOf(apiUrl)} CLI authentication discovery answered HTTP ${String(response.status)}.`, NETWORK_REMEDIATION);
1227
+ }
1228
+ return response.json();
1229
+ };
1230
+ const oauthMetadata = async (issuer) => {
1231
+ const base = issuer.endsWith("/") ? issuer : `${issuer}/`;
1232
+ const response = await fetchNetwork(new URL(".well-known/oauth-authorization-server", base));
1233
+ if (!response.ok) throw httpFailure(issuer, response.status);
1234
+ return response.json();
1235
+ };
1236
+ const exchangeOauthCode = async (input) => {
1237
+ const response = await fetchNetwork(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
1238
+ method: "POST",
1239
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1240
+ body: new URLSearchParams({
1241
+ grant_type: "authorization_code",
1242
+ client_id: input.clientId,
1243
+ code: input.code,
1244
+ redirect_uri: input.redirectUri,
1245
+ code_verifier: input.verifier
1246
+ })
1247
+ });
1248
+ if (!response.ok) throw new CliError("INTERNAL", `${originOf(input.issuer)} token exchange answered HTTP ${String(response.status)}`, NETWORK_REMEDIATION);
1249
+ return oauthTokenResponseSchema.parse(await response.json()).access_token;
1250
+ };
1251
+ const health = async (apiUrl) => {
1252
+ try {
1253
+ const response = await fetchNetwork(`${apiUrl}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
1254
+ return {
1255
+ url: apiUrl,
1256
+ reachable: response.ok,
1257
+ status: response.status,
1258
+ ...!response.ok && { error: httpFailure(apiUrl, response.status).message }
1259
+ };
1260
+ } catch (error) {
1261
+ return {
1262
+ url: apiUrl,
1263
+ reachable: false,
1264
+ status: null,
1265
+ error: error instanceof Error ? error.message : `Could not reach ${originOf(apiUrl)}.`
1266
+ };
1267
+ }
1268
+ };
1269
+ const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
1270
+ const normalized = apiUrl.replace(/\/$/, "");
1271
+ return {
1272
+ authenticationConfig: async () => authenticationConfig(normalized),
1273
+ oauthMetadata,
1274
+ exchangeOauthCode,
1275
+ query: async (path, input) => clientFor(normalized, await credentials.read()).query(path, input),
1276
+ queryWithToken: async (path, input, token) => clientFor(normalized, token).query(path, input),
1277
+ mutate: async (procedure, input) => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input),
1278
+ mutateWithToken: async (procedure, input, token) => clientFor(normalized, token).mutation(procedure, input),
1279
+ download,
1280
+ upload: async (input) => {
1281
+ const isStreaming = !(input.body instanceof Uint8Array);
1282
+ const body = isStreaming ? Readable.toWeb(input.body) : input.body;
1283
+ const request = {
1284
+ method: "PUT",
1285
+ headers: input.headers,
1286
+ body,
1287
+ ...isStreaming && { duplex: "half" }
1288
+ };
1289
+ const response = await fetch(input.url, request);
1290
+ if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
1291
+ const etag = response.headers.get("etag");
1292
+ if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
1293
+ return etag.replaceAll("\"", "");
1294
+ },
1295
+ health: async () => health(normalized)
1296
+ };
1297
+ };
1298
+
1299
+ //#endregion
1300
+ //#region src/infrastructure/mutation-key.adapter.ts
1301
+ const ordered = (value) => {
1302
+ if (Array.isArray(value)) return value.map((entry) => ordered(entry));
1303
+ if (typeof value !== "object" || value === null) return value;
1304
+ return Object.fromEntries(Object.entries(value).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, held]) => [key, ordered(held)]));
1305
+ };
1306
+ const childKey = (selected, procedure, input) => {
1307
+ return createHash("sha256").update(`${selected}\0${procedure}\0${JSON.stringify(ordered(input))}`).digest("hex").replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u, "$1-$2-5$3-8$4-$5");
1308
+ };
1309
+ const createMutationKeyAdapter = () => {
1310
+ let selected = randomUUID();
1311
+ let isComposite = false;
1312
+ return {
1313
+ current: (procedure, input) => isComposite ? childKey(selected, procedure, input) : selected,
1314
+ select: (clientToken, selectedForComposite) => {
1315
+ selected = clientToken ?? randomUUID();
1316
+ isComposite = selectedForComposite;
1317
+ }
1318
+ };
1319
+ };
1320
+
1321
+ //#endregion
1322
+ export { createOauthLoopbackAdapter as a, createWriteHtmlCanvasComposite as c, createRenderCanvasComposite as d, createAuthUseCase as f, readRemoteMcpEnvironment as i, createApplyCanvasComposite as l, createHttpRemoteAdapter as n, createCapabilityInvocationAdapter as o, CLI_CONFIG as r, createRenderFileAdapter as s, createMutationKeyAdapter as t, createCanvasActivityComposite as u };