@enhance-eng/enhance 0.1.14 → 0.1.16

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,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { B as getMeOutputSchema, C as CliError, F as getPrototypeArtifactCapabilitiesOutputSchema, H as cliAuthConfigurationSchema, I as getPrototypePublishStatusOutputSchema, L as prototypeArtifactManifestSchema, M as attachPrototypeArtifactOutputSchema, N as createPrototypeArtifactOutputSchema, P as foldPrototypeArtifactPath, R as prototypeArtifactPathSchema, S as PartialBatchError, U as createAgentTokenOutputSchema, X as applyCanvasOperationsOutputSchema, _ as canvasWriteHtmlCapabilityInputSchema, b as recordingSnapshotCapabilityInputSchema, ct as downloadCanvasRenderOutputSchema, et as getCanvasDocumentOutputSchema, g as canvasRenderCapabilityInputSchema, h as canvasApplyCapabilityInputSchema, j as PROTOTYPE_ARTIFACT_MANIFEST_PATH, lt as getCanvasRenderOutputSchema, nt as createCanvasConversionOutputSchema, ot as createCanvasRenderOutputSchema, q as beginCanvasActivityOutputSchema, rt as getCanvasConversionOutputSchema, st as createRecordingSnapshotOutputSchema, ut as canvasReadableSceneDocumentSchema, v as commentAttentionCapabilityInputSchema, w as transcriptOutputSchema, x as transcriptReadCapabilityInputSchema, y as prototypePublishCapabilityInputSchema, z as submitPrototypeArtifactOutputSchema } from "./cli-output-identity.lib-bX6NwZjd.mjs";
2
+ import { A as parseCanvasReference, B as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as transcriptReadCapabilityInputSchema, Ct as canvasAdditionalStyleSchema, D as assertCanvasReferenceOperations, Dt as canvasAxisStyleProperties, E as assertCanvasReferenceNodes, G as getPrototypePublishStatusOutputSchema, H as createPrototypeArtifactOutputSchema, J as submitPrototypeArtifactOutputSchema, K as prototypeArtifactManifestSchema, M as CliError, N as transcriptOutputSchema, Q as createAgentTokenOutputSchema, S as recordingSnapshotCapabilityInputSchema, St as canvasReadableSceneDocumentSchema, U as foldPrototypeArtifactPath, V as attachPrototypeArtifactOutputSchema, W as getPrototypeArtifactCapabilitiesOutputSchema, Y as getMeOutputSchema, Z as cliAuthConfigurationSchema, _ as canvasApplyCapabilityInputSchema, at as applyCanvasOperationsInputSchema, b as commentAttentionCapabilityInputSchema, bt as downloadCanvasRenderOutputSchema, ct as canvasNodeStylePatchSchema, ft as createCanvasConversionOutputSchema, it as MAX_CANVAS_OPERATIONS, j as PartialBatchError, lt as canvasLayoutWithoutCssProperties, nt as beginCanvasActivityOutputSchema, ot as applyCanvasOperationsOutputSchema, pt as getCanvasConversionOutputSchema, q as prototypeArtifactPathSchema, ut as getCanvasDocumentOutputSchema, v as canvasRenderCapabilityInputSchema, vt as createCanvasRenderOutputSchema, w as canvasEditCapabilityInputSchema, wt as canvasTypographySchema, x as prototypePublishCapabilityInputSchema, xt as getCanvasRenderOutputSchema, y as canvasWriteHtmlCapabilityInputSchema, yt as createRecordingSnapshotOutputSchema } from "./cli-output-identity.lib-F9-nlguI.mjs";
3
3
  import { z } from "zod";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import process from "node:process";
6
+ import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";
6
7
  import { chmodSync, createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
7
8
  import path from "node:path";
8
9
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -349,9 +350,663 @@ const createApplyCanvasComposite = (remote) => ({ execute: async (input, options
349
350
  }
350
351
  } });
351
352
 
353
+ //#endregion
354
+ //#region src/application/canvas-scene-at-version.use-case.ts
355
+ const sceneAtVersion = async (input, canvasId, expectedVersion) => {
356
+ const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
357
+ if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
358
+ if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(held.data.version)} before submitting a new edit.`);
359
+ const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
360
+ if (scene.success) return scene.data;
361
+ throw new CliError("INTERNAL", "The stored canvas is not an editable scene.", "Open the canvas in the editor and repair or recreate the invalid document.");
362
+ };
363
+
364
+ //#endregion
365
+ //#region src/application/canvas-structure-document.use-case.ts
366
+ const ROOT_CANVAS_NODE_ID = "root";
367
+ const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey.localeCompare(right.sortKey)).map(([nodeId]) => nodeId);
368
+ const canCanvasNodeContainChildren = (node) => node !== void 0 && [
369
+ "root",
370
+ "frame",
371
+ "group"
372
+ ].includes(node.component);
373
+ const requireCanvasNode = (document, nodeId) => {
374
+ const node = document.nodes[nodeId];
375
+ if (node !== void 0) return node;
376
+ throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
377
+ };
378
+ const canvasDescendantIds = (document, nodeId) => {
379
+ const found = /* @__PURE__ */ new Set();
380
+ const visit = (parentId) => {
381
+ for (const childId of canvasChildIds(document, parentId)) {
382
+ found.add(childId);
383
+ visit(childId);
384
+ }
385
+ };
386
+ visit(nodeId);
387
+ return found;
388
+ };
389
+
390
+ //#endregion
391
+ //#region src/application/canvas-duplicate-operations.use-case.ts
392
+ const SLUG_LENGTH = 60;
393
+ const ID_LENGTH = 200;
394
+ const ID_SEQUENCE_LENGTH = 4;
395
+ const SORT_KEY_LENGTH = 500;
396
+ const FALLBACK_SORT_SEQUENCE_LENGTH = 6;
397
+ const slug = (source) => {
398
+ const held = source.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9_-]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, SLUG_LENGTH);
399
+ return held === "" ? "copy" : held;
400
+ };
401
+ const createDuplicateId = (prefix) => {
402
+ let sequence = 0;
403
+ return (label) => {
404
+ sequence += 1;
405
+ return `${slug(prefix)}_${slug(label)}_${String(sequence).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, ID_LENGTH);
406
+ };
407
+ };
408
+ const subtreeIds = (document, rootId) => {
409
+ const ordered = [];
410
+ const visit = (nodeId) => {
411
+ ordered.push(nodeId);
412
+ for (const childId of canvasChildIds(document, nodeId)) visit(childId);
413
+ };
414
+ visit(rootId);
415
+ return ordered;
416
+ };
417
+ const duplicateMap = (document, rootId, nextId) => Object.fromEntries(subtreeIds(document, rootId).map((nodeId) => [nodeId, nextId(requireCanvasNode(document, nodeId).label)]));
418
+ const duplicateInsertOperation = (context, oldId) => {
419
+ const { document, rootId, parentId, inputIndex, sourceSortKey, map } = context;
420
+ const node = requireCanvasNode(document, oldId);
421
+ const newId = map[oldId];
422
+ if (newId === void 0) throw new Error(`Missing duplicate id for ${oldId}`);
423
+ const oldParentage = document.relationships[oldId];
424
+ const isRoot = oldId === rootId;
425
+ const clonedParentId = isRoot ? parentId : map[oldParentage?.parentId ?? ""];
426
+ if (clonedParentId === void 0) throw new Error(`Missing duplicate parent for ${oldId}`);
427
+ const fallbackSort = `agent:${String(inputIndex + 1).padStart(FALLBACK_SORT_SEQUENCE_LENGTH, "0")}`;
428
+ return {
429
+ op: "insertNode",
430
+ node: {
431
+ ...structuredClone(node),
432
+ id: newId
433
+ },
434
+ parentage: {
435
+ parentId: clonedParentId,
436
+ sortKey: isRoot ? `${sourceSortKey}~agent-copy-${String(inputIndex + 1).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, SORT_KEY_LENGTH) : oldParentage?.sortKey ?? fallbackSort
437
+ }
438
+ };
439
+ };
440
+ const duplicateOne = (context) => {
441
+ const { document, input, inputIndex, nextId } = context;
442
+ const source = requireCanvasNode(document, input.id);
443
+ if (input.id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be duplicated.", "Duplicate one or more root children instead.");
444
+ const sourceParentage = document.relationships[input.id];
445
+ if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, "Choose a reachable node from canvas tree.");
446
+ const parentId = input.parentId ?? sourceParentage.parentId;
447
+ if (!canCanvasNodeContainChildren(document.nodes[parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${parentId} cannot contain duplicates.`, "Choose a frame, group, or root as the destination.");
448
+ const map = duplicateMap(document, input.id, nextId);
449
+ const treeContext = {
450
+ document,
451
+ rootId: input.id,
452
+ parentId,
453
+ inputIndex,
454
+ sourceSortKey: sourceParentage.sortKey,
455
+ map
456
+ };
457
+ const operations = subtreeIds(document, input.id).map((oldId) => duplicateInsertOperation(treeContext, oldId));
458
+ const newId = map[input.id];
459
+ if (newId === void 0) throw new Error(`Missing duplicate root id for ${input.id}`);
460
+ return {
461
+ operations,
462
+ summary: {
463
+ sourceId: input.id,
464
+ newId,
465
+ name: source.label,
466
+ component: source.component,
467
+ descendantIdMap: Object.fromEntries(Object.entries(map).filter(([oldId]) => oldId !== input.id))
468
+ }
469
+ };
470
+ };
471
+ const duplicateCanvasNodeOperations = (document, inputs, idPrefix) => {
472
+ if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No nodes were provided to duplicate.", "Pass at least one stable node id.");
473
+ const nextId = createDuplicateId(idPrefix);
474
+ const duplicates = inputs.map((input, inputIndex) => duplicateOne({
475
+ document,
476
+ input,
477
+ inputIndex,
478
+ nextId
479
+ }));
480
+ return {
481
+ operations: duplicates.flatMap((duplicate) => duplicate.operations),
482
+ duplicatedNodes: duplicates.map((duplicate) => duplicate.summary)
483
+ };
484
+ };
485
+
486
+ //#endregion
487
+ //#region src/application/canvas-move-operations.use-case.ts
488
+ const moveState = (document) => ({
489
+ document,
490
+ children: new Map(Object.keys(document.nodes).map((nodeId) => [nodeId, canvasChildIds(document, nodeId)])),
491
+ parentOf: new Map(Object.entries(document.relationships).map(([nodeId, relationship]) => [nodeId, relationship.parentId])),
492
+ affected: /* @__PURE__ */ new Set()
493
+ });
494
+ const directDestination = (input, state) => {
495
+ const destination = (state.children.get(input.parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId);
496
+ return {
497
+ parentId: input.parentId,
498
+ index: Math.max(0, Math.min(input.index ?? destination.length, destination.length))
499
+ };
500
+ };
501
+ const siblingDestination = (input, state) => {
502
+ const siblingId = "before" in input ? input.before : input.after;
503
+ if (siblingId === input.nodeId || state.document.nodes[siblingId] === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is not a valid move target.`, "Choose another current sibling node.");
504
+ const parentId = state.parentOf.get(siblingId);
505
+ if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, "Choose a reachable sibling from canvas tree.");
506
+ const siblingIndex = (state.children.get(parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId).indexOf(siblingId);
507
+ return {
508
+ parentId,
509
+ index: "before" in input ? siblingIndex : siblingIndex + 1
510
+ };
511
+ };
512
+ const destinationFor = (input, state) => "parentId" in input ? directDestination(input, state) : siblingDestination(input, state);
513
+ const validateMove = (input, destination, state) => {
514
+ if (input.nodeId === "root" || state.document.nodes[input.nodeId] === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.nodeId} cannot be moved.`, "Choose a current non-root node.");
515
+ if (canvasDescendantIds(state.document, input.nodeId).has(destination.parentId) || destination.parentId === input.nodeId || !canCanvasNodeContainChildren(state.document.nodes[destination.parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${destination.parentId} is not a valid parent for ${input.nodeId}.`, "Choose a frame, group, or root outside the moving subtree.");
516
+ };
517
+ const applyMove = (input, destination, state) => {
518
+ const oldParentId = state.parentOf.get(input.nodeId);
519
+ if (oldParentId !== void 0) {
520
+ state.children.set(oldParentId, (state.children.get(oldParentId) ?? []).filter((id) => id !== input.nodeId));
521
+ state.affected.add(oldParentId);
522
+ }
523
+ const children = [...state.children.get(destination.parentId) ?? []];
524
+ const operations = [];
525
+ const relationships = { ...state.document.relationships };
526
+ const keyAt = (index) => {
527
+ const id = children[index];
528
+ return id === void 0 ? null : relationships[id]?.sortKey ?? null;
529
+ };
530
+ let sortKey = null;
531
+ try {
532
+ const before = keyAt(destination.index - 1);
533
+ const after = keyAt(destination.index);
534
+ const candidate = generateKeyBetween(before, after);
535
+ if ((before === null || before.localeCompare(candidate) < 0) && (after === null || candidate.localeCompare(after) < 0)) sortKey = candidate;
536
+ } catch {
537
+ sortKey = null;
538
+ }
539
+ if (sortKey === null) {
540
+ const ordered = [...children];
541
+ ordered.splice(destination.index, 0, input.nodeId);
542
+ const keys = generateNKeysBetween(null, null, ordered.length).toSorted((left, right) => left.localeCompare(right));
543
+ for (const [index, id] of ordered.entries()) {
544
+ const key = keys[index];
545
+ if (key === void 0) throw new Error("Missing generated move sort key.");
546
+ const parentage = {
547
+ parentId: destination.parentId,
548
+ sortKey: key
549
+ };
550
+ relationships[id] = parentage;
551
+ operations.push({
552
+ op: "setParentage",
553
+ nodeId: id,
554
+ parentage
555
+ });
556
+ }
557
+ } else {
558
+ const parentage = {
559
+ parentId: destination.parentId,
560
+ sortKey
561
+ };
562
+ relationships[input.nodeId] = parentage;
563
+ operations.push({
564
+ op: "setParentage",
565
+ nodeId: input.nodeId,
566
+ parentage
567
+ });
568
+ }
569
+ children.splice(destination.index, 0, input.nodeId);
570
+ state.children.set(destination.parentId, children);
571
+ state.parentOf.set(input.nodeId, destination.parentId);
572
+ state.affected.add(destination.parentId);
573
+ return {
574
+ operations,
575
+ document: {
576
+ ...state.document,
577
+ relationships
578
+ }
579
+ };
580
+ };
581
+ const moveCanvasNodeOperations = (document, inputs) => {
582
+ if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
583
+ const state = moveState(document);
584
+ const moves = [];
585
+ return {
586
+ operations: inputs.flatMap((input) => {
587
+ const destination = destinationFor(input, state);
588
+ validateMove(input, destination, state);
589
+ moves.push({
590
+ nodeId: input.nodeId,
591
+ ...destination
592
+ });
593
+ const applied = applyMove(input, destination, state);
594
+ state.document = applied.document;
595
+ return applied.operations;
596
+ }),
597
+ moves,
598
+ affectedParents: Array.from(state.affected, (parentId) => ({
599
+ parentId,
600
+ children: [...state.children.get(parentId) ?? []]
601
+ }))
602
+ };
603
+ };
604
+
605
+ //#endregion
606
+ //#region src/application/canvas-typography-operations.use-case.ts
607
+ const NORMAL_FONT_WEIGHT = 400;
608
+ const BOLD_FONT_WEIGHT = 700;
609
+ const fontSize = (value) => {
610
+ if (typeof value === "number") return value;
611
+ return /^(?:\d+(?:\.\d+)?|\.\d+)px$/u.test(String(value)) ? Number(String(value).replace("px", "")) : NaN;
612
+ };
613
+ const fontWeight = (value) => {
614
+ if (value === "normal") return NORMAL_FONT_WEIGHT;
615
+ return value === "bold" ? BOLD_FONT_WEIGHT : Number(value);
616
+ };
617
+ const canvasTypographyOperation = (node, styles) => {
618
+ if (node.typography === void 0) return null;
619
+ const keys = [
620
+ "font-family",
621
+ "font-size",
622
+ "font-weight",
623
+ "font-style"
624
+ ];
625
+ if (keys.every((key) => !Object.hasOwn(styles, key))) return null;
626
+ if (keys.some((key) => styles[key] === null)) throw new CliError("BAD_REQUEST", "Imported typography needs an explicit font value.", "Replace the font family, pixel size, weight or style instead of clearing that field.");
627
+ const next = { ...node.typography };
628
+ const family = styles["font-family"];
629
+ if (family !== void 0) {
630
+ const families = String(family).split(",").map((held) => held.trim().replaceAll(/^(?:"|')|(?:"|')$/gu, "")).filter((held) => held !== "");
631
+ next.family = families[0] ?? "";
632
+ next.fallbackFamilies = families.slice(1);
633
+ }
634
+ if (styles["font-size"] !== void 0) next.size = fontSize(styles["font-size"]);
635
+ if (styles["font-weight"] !== void 0) next.weight = fontWeight(styles["font-weight"]);
636
+ const typography = canvasTypographySchema.safeParse({
637
+ ...next,
638
+ ...styles["font-style"] !== void 0 && { style: styles["font-style"] }
639
+ });
640
+ if (!typography.success) throw new CliError("BAD_REQUEST", "The font edit cannot be represented by editable typography.", "Use a font family list, numeric or pixel size, weight from 1 to 1000, and normal, italic or oblique style.");
641
+ return {
642
+ op: "setTypography",
643
+ nodeId: node.id,
644
+ typography: typography.data
645
+ };
646
+ };
647
+
648
+ //#endregion
649
+ //#region src/application/canvas-style-operations.use-case.ts
650
+ const ADDITIONAL_STYLE_ID_LENGTH = 200;
651
+ const camelToKebab = (property) => property.startsWith("--") ? property : property.replace(/^Webkit/u, "-webkit-").replace(/^Moz/u, "-moz-").replaceAll(/([a-z\d])([A-Z])/gu, "$1-$2").toLowerCase();
652
+ const additionalOperation = (node, styles) => {
653
+ const held = new Map((node.additionalStyles?.declarations ?? []).map((declaration) => [declaration.property, declaration]));
654
+ for (const [property, value] of Object.entries(styles)) {
655
+ if (value === null || canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) {
656
+ held.delete(property);
657
+ continue;
658
+ }
659
+ const result = canvasAdditionalStyleSchema.safeParse({
660
+ id: held.get(property)?.id ?? `css-${property}`.slice(0, ADDITIONAL_STYLE_ID_LENGTH),
661
+ property,
662
+ value: String(value),
663
+ enabled: true
664
+ });
665
+ if (!result.success) throw new CliError("BAD_REQUEST", `Style ${property} is not safe CSS.`, "Use a valid CSS property without imports, expressions, or executable URLs.");
666
+ held.set(property, result.data);
667
+ }
668
+ const declarations = [];
669
+ for (const declaration of held.values()) {
670
+ if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
671
+ declarations.push(declaration);
672
+ }
673
+ return JSON.stringify(declarations) === JSON.stringify(node.additionalStyles?.declarations ?? []) ? null : {
674
+ op: "setAdditionalStyles",
675
+ nodeId: node.id,
676
+ additionalStyles: { declarations }
677
+ };
678
+ };
679
+ const layoutOperation = (document, node, next, styles) => {
680
+ const changed = new Set(Object.keys(styles));
681
+ const properties = (axis) => [...canvasAxisStyleProperties(node, axis, document), ...canvasAxisStyleProperties(next, axis, document)];
682
+ const layout = canvasLayoutWithoutCssProperties(node.layout ?? {}, changed, {
683
+ horizontal: properties("horizontal"),
684
+ vertical: properties("vertical")
685
+ });
686
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
687
+ const value = styles[property];
688
+ if (value === "fill" || value === "hug") layout[axis] = { mode: value };
689
+ }
690
+ return JSON.stringify(layout) === JSON.stringify(node.layout ?? {}) ? null : {
691
+ op: "setLayout",
692
+ nodeId: node.id,
693
+ layout: Object.keys(layout).length === 0 ? "default" : layout
694
+ };
695
+ };
696
+ const cssValues = (document, node, styles) => {
697
+ const result = { ...styles };
698
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
699
+ if (styles[property] !== "fill" && styles[property] !== "hug") continue;
700
+ result[property] = null;
701
+ for (const related of canvasAxisStyleProperties(node, axis, document)) if (node.styles[related] !== void 0 || node.additionalStyles?.declarations.some((declaration) => declaration.property === related) === true) result[related] = null;
702
+ }
703
+ return result;
704
+ };
705
+ const operationsForNode = (document, node, source) => {
706
+ const styles = cssValues(document, node, source);
707
+ const additional = additionalOperation(node, styles);
708
+ const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
709
+ const next = {
710
+ ...node,
711
+ styles: { ...node.styles },
712
+ ...additional !== null && additional.additionalStyles !== "default" && { additionalStyles: additional.additionalStyles }
713
+ };
714
+ for (const [property, value] of Object.entries(stylePatch)) if (value === null) Reflect.deleteProperty(next.styles, property);
715
+ else next.styles[property] = value;
716
+ const layout = layoutOperation(document, node, next, source);
717
+ const typography = canvasTypographyOperation(node, styles);
718
+ const clearFill = (node.component === "text" ? ["color"] : [
719
+ "background",
720
+ "background-color",
721
+ "background-image"
722
+ ]).some((property) => Object.hasOwn(styles, property)) && node.appearance?.fills !== void 0 ? [{
723
+ op: "setAppearance",
724
+ nodeId: node.id,
725
+ appearance: { clear: ["fills"] }
726
+ }] : [];
727
+ return [
728
+ ...Object.keys(stylePatch).length > 0 ? [{
729
+ op: "setStyles",
730
+ nodeId: node.id,
731
+ styles: canvasNodeStylePatchSchema.parse(stylePatch)
732
+ }] : [],
733
+ ...clearFill,
734
+ ...typography === null ? [] : [typography],
735
+ ...layout === null ? [] : [layout],
736
+ ...additional === null ? [] : [additional]
737
+ ];
738
+ };
739
+ const mergedUpdates = (updates) => {
740
+ const merged = /* @__PURE__ */ new Map();
741
+ for (const update of updates) for (const nodeId of update.nodeIds) {
742
+ const styles = merged.get(nodeId) ?? {};
743
+ for (const [property, value] of Object.entries(update.styles)) {
744
+ const normalized = camelToKebab(property);
745
+ Reflect.deleteProperty(styles, normalized);
746
+ styles[normalized] = value;
747
+ }
748
+ merged.set(nodeId, styles);
749
+ }
750
+ return merged;
751
+ };
752
+ const canvasStyleOperations = (document, updates) => {
753
+ const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
754
+ const node = document.nodes[nodeId];
755
+ if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
756
+ return operationsForNode(document, node, styles);
757
+ });
758
+ if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
759
+ return operations;
760
+ };
761
+
762
+ //#endregion
763
+ //#region src/application/canvas-edit-operations.use-case.ts
764
+ const TEXT_LEADING = 1.35;
765
+ const projectStyles = (node, operation) => {
766
+ const styles = { ...node.styles };
767
+ for (const [name, value] of Object.entries(operation.styles)) if (value === null || value === void 0) Reflect.deleteProperty(styles, name);
768
+ else styles[name] = value;
769
+ const cleared = operation.clear ?? [];
770
+ for (const name of cleared) Reflect.deleteProperty(styles, name);
771
+ if (node.component === "text" && operation.styles["line-height"] === void 0) {
772
+ const size = operation.styles["font-size"];
773
+ if (typeof size === "number") styles["line-height"] = `${String(Math.round(size * TEXT_LEADING))}px`;
774
+ else if (size === null) Reflect.deleteProperty(styles, "line-height");
775
+ }
776
+ return {
777
+ ...node,
778
+ styles
779
+ };
780
+ };
781
+ const PLANNED_OPERATIONS = /* @__PURE__ */ new Set([
782
+ "insertNode",
783
+ "setText",
784
+ "setLabel",
785
+ "setStyles",
786
+ "setAppearance",
787
+ "setTypography",
788
+ "setLayout",
789
+ "setAdditionalStyles",
790
+ "setParentage"
791
+ ]);
792
+ const isPlannedOperation = (operation) => PLANNED_OPERATIONS.has(operation.op);
793
+ const projectTypography = (node, typography) => {
794
+ const next = { ...node };
795
+ if (typography === "default") Reflect.deleteProperty(next, "typography");
796
+ else next.typography = typography;
797
+ return next;
798
+ };
799
+ const projectNode = (node, operation) => {
800
+ switch (operation.op) {
801
+ case "setText":
802
+ if (node.component !== "text") throw new CliError("BAD_REQUEST", `Canvas node ${node.id} is not editable text.`, "Use the text node id from canvas tree.");
803
+ return {
804
+ ...node,
805
+ props: {
806
+ ...node.props,
807
+ text: operation.text
808
+ }
809
+ };
810
+ case "setLabel": return {
811
+ ...node,
812
+ label: operation.label,
813
+ labelOrigin: "user"
814
+ };
815
+ case "setStyles": return projectStyles(node, operation);
816
+ case "setAppearance": {
817
+ const appearance = { ...node.appearance };
818
+ const cleared = operation.appearance.clear ?? [];
819
+ for (const property of cleared) Reflect.deleteProperty(appearance, property);
820
+ const next = {
821
+ ...node,
822
+ appearance
823
+ };
824
+ if (Object.keys(appearance).length === 0) Reflect.deleteProperty(next, "appearance");
825
+ return next;
826
+ }
827
+ case "setTypography": return projectTypography(node, operation.typography);
828
+ case "setLayout": {
829
+ const next = { ...node };
830
+ if (operation.layout === "default") Reflect.deleteProperty(next, "layout");
831
+ else next.layout = operation.layout;
832
+ return next;
833
+ }
834
+ case "setAdditionalStyles": {
835
+ const next = { ...node };
836
+ if (operation.additionalStyles === "default") Reflect.deleteProperty(next, "additionalStyles");
837
+ else next.additionalStyles = operation.additionalStyles;
838
+ return next;
839
+ }
840
+ }
841
+ };
842
+ const projectOperation = (scene, operation) => {
843
+ if (!isPlannedOperation(operation)) throw new Error(`Unexpected focused edit operation: ${operation.op}`);
844
+ if (operation.op === "insertNode") {
845
+ if (scene.nodes[operation.node.id] !== void 0) throw new CliError("BAD_REQUEST", `Duplicate id ${operation.node.id} already exists.`, "Use a new client token for a new duplication.");
846
+ return {
847
+ ...scene,
848
+ nodes: {
849
+ ...scene.nodes,
850
+ [operation.node.id]: operation.node
851
+ },
852
+ relationships: {
853
+ ...scene.relationships,
854
+ [operation.node.id]: operation.parentage
855
+ }
856
+ };
857
+ }
858
+ const node = requireCanvasNode(scene, operation.nodeId);
859
+ if (operation.op === "setParentage") return {
860
+ ...scene,
861
+ relationships: {
862
+ ...scene.relationships,
863
+ [node.id]: operation.parentage
864
+ }
865
+ };
866
+ return {
867
+ ...scene,
868
+ nodes: {
869
+ ...scene.nodes,
870
+ [node.id]: projectNode(node, operation)
871
+ }
872
+ };
873
+ };
874
+ const moveInput = (edit) => {
875
+ const { nodeId, destination } = edit;
876
+ switch (destination.kind) {
877
+ case "before": return {
878
+ nodeId,
879
+ before: destination.nodeId
880
+ };
881
+ case "after": return {
882
+ nodeId,
883
+ after: destination.nodeId
884
+ };
885
+ case "parent": return {
886
+ nodeId,
887
+ parentId: destination.parentId,
888
+ ...destination.index !== void 0 && { index: destination.index }
889
+ };
890
+ }
891
+ };
892
+ const operationsForEdit = (edit, plan, prefix, duplicateIndex) => {
893
+ switch (edit.kind) {
894
+ case "set_text": return [{
895
+ op: "setText",
896
+ nodeId: edit.nodeId,
897
+ text: edit.text
898
+ }];
899
+ case "rename": return [{
900
+ op: "setLabel",
901
+ nodeId: edit.nodeId,
902
+ label: edit.name,
903
+ labelOrigin: "user"
904
+ }];
905
+ case "set_styles": return canvasStyleOperations(plan.scene, [{
906
+ nodeIds: edit.nodeIds,
907
+ styles: edit.styles
908
+ }]);
909
+ case "duplicate": {
910
+ const idPrefix = duplicateIndex === 0 ? prefix : `${String(duplicateIndex + 1)}_${prefix}`;
911
+ const duplicate = duplicateCanvasNodeOperations(plan.scene, edit.nodeIds.map((id) => ({
912
+ id,
913
+ ...edit.parentId !== void 0 && { parentId: edit.parentId }
914
+ })), idPrefix);
915
+ plan.duplicatedNodes.push(...duplicate.duplicatedNodes);
916
+ return duplicate.operations;
917
+ }
918
+ case "move": {
919
+ const move = moveCanvasNodeOperations(plan.scene, [moveInput(edit)]);
920
+ plan.moves.push(...move.moves);
921
+ for (const parent of move.affectedParents) plan.affectedParents.add(parent.parentId);
922
+ return move.operations;
923
+ }
924
+ }
925
+ };
926
+ const planCanvasEdits = (scene, edits, prefix) => {
927
+ const plan = {
928
+ scene,
929
+ operations: [],
930
+ duplicatedNodes: [],
931
+ moves: [],
932
+ affectedParents: /* @__PURE__ */ new Set()
933
+ };
934
+ let duplicateIndex = 0;
935
+ for (const edit of edits) {
936
+ const operations = operationsForEdit(edit, plan, prefix, duplicateIndex);
937
+ if (edit.kind === "duplicate") duplicateIndex += 1;
938
+ for (const operation of operations) plan.scene = projectOperation(plan.scene, operation);
939
+ plan.operations.push(...operations);
940
+ }
941
+ return {
942
+ operations: plan.operations,
943
+ duplicatedNodes: plan.duplicatedNodes,
944
+ moves: plan.moves,
945
+ affectedParents: [...plan.affectedParents].map((parentId) => ({
946
+ parentId,
947
+ children: canvasChildIds(plan.scene, parentId)
948
+ }))
949
+ };
950
+ };
951
+
952
+ //#endregion
953
+ //#region src/application/edit-canvas.composite.ts
954
+ const MAX_EDIT_TARGETS = 1e3;
955
+ const targetIds = (edit) => {
956
+ switch (edit.kind) {
957
+ case "set_text":
958
+ case "rename": return [edit.nodeId];
959
+ case "set_styles": return edit.nodeIds;
960
+ case "duplicate": return [...edit.nodeIds, ...edit.parentId === void 0 ? [] : [edit.parentId]];
961
+ case "move": return [edit.nodeId, edit.destination.kind === "parent" ? edit.destination.parentId : edit.destination.nodeId];
962
+ }
963
+ };
964
+ const scopeIds = (edit, scene) => {
965
+ if (edit.kind === "duplicate") return [...edit.nodeIds, ...edit.parentId === void 0 || edit.nodeIds.every((id) => scene.relationships[id]?.parentId === edit.parentId) ? [] : [edit.parentId]];
966
+ if (edit.kind === "move" && edit.destination.kind === "parent" && scene.relationships[edit.nodeId]?.parentId === edit.destination.parentId) return [edit.nodeId];
967
+ return targetIds(edit);
968
+ };
969
+ const validateTargets = (input, scene) => {
970
+ if (input.edits.length === 0 || input.edits.length > 1e3) throw new CliError("BAD_REQUEST", "The edit batch exceeds the canonical operation limit.", "Split larger changes into bounded batches.");
971
+ const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
972
+ if (ids.size > MAX_EDIT_TARGETS) throw new CliError("BAD_REQUEST", "A batch may target at most 1,000 nodes.", "Split the edit into smaller batches.");
973
+ for (const id of ids) requireCanvasNode(scene, id);
974
+ const reference = {
975
+ canvasId: input.canvasId,
976
+ nodeIds: input.nodeIds ?? []
977
+ };
978
+ for (const edit of input.edits) assertCanvasReferenceNodes(reference, scene, scopeIds(edit, scene));
979
+ };
980
+ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
981
+ const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
982
+ validateTargets(input, scene);
983
+ const plan = planCanvasEdits(scene, input.edits, input.idPrefix ?? `copy_${input.mutationId.replaceAll("-", "")}`);
984
+ assertCanvasReferenceOperations({
985
+ canvasId: input.canvasId,
986
+ nodeIds: input.nodeIds ?? []
987
+ }, scene, plan.operations.filter((operation) => "nodeId" in operation && scene.nodes[operation.nodeId] !== void 0));
988
+ const parsed = applyCanvasOperationsInputSchema.safeParse({
989
+ canvasId: input.canvasId,
990
+ mutationId: input.mutationId,
991
+ documentFormatVersion: 3,
992
+ baseVersion: input.baseVersion,
993
+ operations: plan.operations
994
+ });
995
+ if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit exceeds canonical canvas limits.", parsed.error.issues[0]?.message ?? "Reduce the edit batch.");
996
+ const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
997
+ return {
998
+ ...result,
999
+ next: [`Reuse version ${String(result.version)} as baseVersion for the next edit; no extra read is required.`, `Render the affected screen at version ${String(result.version)} when ready for visual review.`],
1000
+ ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
1001
+ ...plan.moves.length > 0 && {
1002
+ moves: plan.moves,
1003
+ affectedParents: plan.affectedParents
1004
+ }
1005
+ };
1006
+ } });
1007
+
352
1008
  //#endregion
353
1009
  //#region src/application/write-html-canvas.composite.ts
354
- const READ_DOCUMENT_PROCEDURE = "canvas.document.get";
355
1010
  const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
356
1011
  const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
357
1012
  const POLL_MS$1 = 250;
@@ -377,10 +1032,7 @@ const awaitImport = async (remote, initial, timeoutMs) => {
377
1032
  const deadline = Date.now() + timeoutMs;
378
1033
  let job = initial;
379
1034
  while (job.state === "queued" || job.state === "running") {
380
- 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`.", {
381
- jobId: job.id,
382
- phase: job.phase
383
- });
1035
+ if (Date.now() >= deadline) return job;
384
1036
  await wait$1(POLL_MS$1);
385
1037
  job = await readImport(remote, job.id);
386
1038
  }
@@ -418,13 +1070,9 @@ const failedReview = (error, input, version) => {
418
1070
  } : {
419
1071
  code: "INTERNAL",
420
1072
  message: "The post-write review render failed.",
421
- remediation: "Read the current canvas version, then render the affected area again."
1073
+ remediation: "Render the committed version and affected area again; do not replay the write."
422
1074
  },
423
- next: [
424
- `enhance canvas inspect --canvas ${input.canvasId}`,
425
- `enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`,
426
- "Do not replay the committed write with a new mutation id."
427
- ]
1075
+ next: [`enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`, "Do not replay the committed write with a new mutation id."]
428
1076
  };
429
1077
  };
430
1078
  const renderReview = async (render, input, imported) => {
@@ -448,12 +1096,9 @@ const renderReview = async (render, input, imported) => {
448
1096
  }
449
1097
  };
450
1098
  const createdNodes = async (remote, imported) => {
451
- const held = getCanvasDocumentOutputSchema.safeParse(await remote.query(READ_DOCUMENT_PROCEDURE, { canvasId: imported.canvasId }));
452
- if (!held.success) throw invalidResponse$1("canvas document");
453
- const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
454
- if (!scene.success) throw invalidResponse$1("editable canvas document");
1099
+ const scene = await sceneAtVersion({ remote }, imported.canvasId, imported.result.version);
455
1100
  return imported.result.insertedNodeIds.map((nodeId) => {
456
- const node = scene.data.nodes[nodeId];
1101
+ const node = scene.nodes[nodeId];
457
1102
  return {
458
1103
  id: nodeId,
459
1104
  name: node?.label ?? "",
@@ -461,20 +1106,47 @@ const createdNodes = async (remote, imported) => {
461
1106
  };
462
1107
  });
463
1108
  };
464
- const writeResponse = async (remote, input, imported, review) => ({
1109
+ const committedResponse = (input, imported) => ({
465
1110
  canvasId: input.canvasId,
466
1111
  mutationCommitted: true,
1112
+ jobId: imported.id,
1113
+ mutationId: imported.result.mutationId,
1114
+ rootNodeId: imported.result.rootNodeId,
467
1115
  mode: input.mode,
468
1116
  targetNodeId: input.targetNodeId,
469
1117
  previousVersion: imported.result.previousVersion,
470
1118
  version: imported.result.version,
471
- createdNodes: await createdNodes(remote, imported),
1119
+ insertedNodeIds: imported.result.insertedNodeIds,
472
1120
  removedNodeIds: imported.result.removedNodeIds,
473
- affectedBounds: imported.result.affectedBounds,
474
- review,
475
- next: [`enhance canvas tree --canvas ${input.canvasId}`, "Inspect the review PNG before continuing."]
1121
+ affected: {
1122
+ inserted: imported.result.insertedNodeIds.length,
1123
+ changed: 0,
1124
+ removed: imported.result.removedNodeIds.length
1125
+ },
1126
+ affectedBounds: imported.result.affectedBounds
1127
+ });
1128
+ const pendingResponse = (job) => ({
1129
+ state: "pending",
1130
+ canvasId: job.canvasId,
1131
+ jobId: job.id,
1132
+ phase: job.phase,
1133
+ status: {
1134
+ tool: "capability_query",
1135
+ arguments: {
1136
+ capability: READ_IMPORT_PROCEDURE,
1137
+ input: { jobId: job.id }
1138
+ }
1139
+ },
1140
+ next: ["Read the existing import status; do not start another import."]
476
1141
  });
477
1142
  const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
1143
+ if (input.selectionNodeIds !== void 0 && input.selectionNodeIds.length > 0) {
1144
+ const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
1145
+ assertCanvasReferenceNodes({
1146
+ canvasId: input.canvasId,
1147
+ nodeIds: input.selectionNodeIds
1148
+ }, scene, [input.targetNodeId]);
1149
+ }
478
1150
  const activity = await createCanvasActivityComposite(remote).begin({
479
1151
  canvasId: input.canvasId,
480
1152
  phase: "creating",
@@ -483,13 +1155,26 @@ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (in
483
1155
  });
484
1156
  try {
485
1157
  const imported = await createImport(remote, input);
1158
+ if (imported.state !== "succeeded") return pendingResponse(imported);
1159
+ if (input.review === "none") return committedResponse(input, imported);
486
1160
  await activity?.update({
487
1161
  phase: "rendering",
488
1162
  nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
489
1163
  bounds: imported.result.affectedBounds
490
1164
  });
491
1165
  const review = await renderReview(render, input, imported);
492
- return await writeResponse(remote, input, imported, review);
1166
+ let nodes = [];
1167
+ try {
1168
+ nodes = await createdNodes(remote, imported);
1169
+ } catch {
1170
+ nodes = [];
1171
+ }
1172
+ return {
1173
+ ...committedResponse(input, imported),
1174
+ createdNodes: nodes,
1175
+ review,
1176
+ next: ["Inspect the review PNG before continuing."]
1177
+ };
493
1178
  } finally {
494
1179
  await activity?.finish();
495
1180
  }
@@ -992,6 +1677,17 @@ const readTranscript = async (dependencies, offered) => {
992
1677
  };
993
1678
  const invokeComposite = async (dependencies, capabilityId, offered, retryClientToken) => {
994
1679
  switch (capabilityId) {
1680
+ case "canvas.edit": {
1681
+ const input = canvasEditCapabilityInputSchema.parse(offered);
1682
+ const reference = parseCanvasReference(input.canvas);
1683
+ return createEditCanvasComposite(dependencies.remote).execute({
1684
+ canvasId: reference.canvasId,
1685
+ nodeIds: reference.nodeIds,
1686
+ baseVersion: input.baseVersion,
1687
+ edits: input.edits,
1688
+ mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
1689
+ });
1690
+ }
995
1691
  case "canvas.apply": return applyCanvas(dependencies, offered);
996
1692
  case "canvas.render": return renderCanvas(dependencies, offered, retryClientToken);
997
1693
  case "canvas.writeHtml": return writeCanvasHtml(dependencies, offered);
@@ -1332,4 +2028,4 @@ const createMutationKeyAdapter = () => {
1332
2028
  };
1333
2029
 
1334
2030
  //#endregion
1335
- 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 };
2031
+ export { createOauthLoopbackAdapter as a, createWriteHtmlCanvasComposite as c, createApplyCanvasComposite as d, createCanvasActivityComposite as f, readRemoteMcpEnvironment as i, createEditCanvasComposite as l, createAuthUseCase as m, createHttpRemoteAdapter as n, createCapabilityInvocationAdapter as o, createRenderCanvasComposite as p, CLI_CONFIG as r, createRenderFileAdapter as s, createMutationKeyAdapter as t, sceneAtVersion as u };