unsys-canvas 0.1.2 → 0.2.0

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.
package/dist/core.js CHANGED
@@ -67,8 +67,8 @@ function unsysCanvasPositiveAreaOverlap(a, b) {
67
67
  var SESSION_FORMAT_WRAPPER = /^(in (one|this|a) (multi-turn |topic-horizon )?guided (conversation|dialogue)[,:.]?\s+|through (a |one )?(multi-turn |topic-horizon )?guided (conversation|dialogue)[,:.]?\s+|in (one|this|a) topic-horizon (conversation|dialogue)[,:.]?\s+|this (chapter|session) is a (topic-horizon |guided |multi-turn )?(conversation|dialogue)[,:.]?\s+|as your (practice )?coach[,:.]?\s+)/i;
68
68
  var COMMAND_META_WRAPPERS = [
69
69
  /^your (question|reply|answer|prompt) sits in the right place(?:\s*\([^)]+\))?[.!]?\s*/i,
70
- /^\(after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|declutter|answer|draw|do\/?run|run|focus)\)[.!]?\s*/i,
71
- /^after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|declutter|answer|draw|do\/?run|run|focus)[,:.]?\s*/i
70
+ /^\(after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|pretty|declutter|answer|draw|do\/?run|run|focus)\)[.!]?\s*/i,
71
+ /^after\s+(?:check\/?\s*ask|simplify|split|breakdown|subdivide|concepts|define|refactor|pretty|declutter|answer|draw|do\/?run|run|focus)[,:.]?\s*/i
72
72
  ];
73
73
  function capitalizeIfStripped(original, stripped) {
74
74
  if (!stripped) return "";
@@ -744,6 +744,22 @@ function buildUnsysCanvasSimplifyUserMessage(input) {
744
744
  ].join("\n");
745
745
  return unsysCanvasWithDomainPrefix(body, input.workspace);
746
746
  }
747
+ function buildUnsysCanvasPrettyUserMessage(input) {
748
+ const live = (input.selectedElements ?? []).filter((el) => el && !el.isDeleted);
749
+ const body = [
750
+ "Pretty the selected marks into a tidied, well-made Excalidraw note.",
751
+ "Keep the same meaning. Do not drop claims. The original marks stay; your result is placed beside them.",
752
+ "Give the note a clear title or header. Group related bits, align them, and use even spacing.",
753
+ "Wrap the composition in a container or frame. Use bullets when the content is a list of points.",
754
+ "Use the board palette: stroke #1e1e1e, header fill #ffffff, body fill #f4f4f5. Tasteful, not noisy.",
755
+ 'Prefer JSON "elements" (frame or rectangle, title text, body text or bullets). If a diagram is unnecessary, put the formatted note in "text" with a title on the first line, then a blank line, then the body.',
756
+ "Do not mention commands or placement.",
757
+ "",
758
+ "Selected elements:",
759
+ unsysCanvasCommandSelectionListing(live)
760
+ ].join("\n");
761
+ return unsysCanvasWithDomainPrefix(body, input.workspace);
762
+ }
747
763
  function buildUnsysCanvasClearOverlapsUserMessage(input) {
748
764
  const live = (input.selectedElements ?? []).filter((el) => el && !el.isDeleted);
749
765
  const body = [
@@ -768,6 +784,7 @@ function buildUnsysCanvasCommandUserMessage(input) {
768
784
  if (kind === "declutter" || kind === "clear-overlaps") return buildUnsysCanvasClearOverlapsUserMessage(input);
769
785
  if (kind === "draw") return buildUnsysCanvasDrawUserMessage(input);
770
786
  if (kind === "simplify") return buildUnsysCanvasSimplifyUserMessage(input);
787
+ if (kind === "pretty") return buildUnsysCanvasPrettyUserMessage(input);
771
788
  if (kind === "concepts") return buildUnsysCanvasConceptsUserMessage(input);
772
789
  if (kind === "check") return buildUnsysCanvasCheckUserMessage(input);
773
790
  return buildUnsysCanvasAskUserMessage({
@@ -1289,6 +1306,8 @@ function unsysCanvasNoteLabel(kind) {
1289
1306
  return "Do/run";
1290
1307
  case "simplify":
1291
1308
  return "Simplify";
1309
+ case "pretty":
1310
+ return "Pretty";
1292
1311
  case "concepts":
1293
1312
  return "Concepts";
1294
1313
  case "define":
@@ -2376,6 +2395,8 @@ var UNSYS_CANVAS_COMMANDS = [
2376
2395
  label: "Simplify",
2377
2396
  tooltip: "Keep the original marks and place a shorter, plainer rewrite next to them. If the selection is a term, make the meaning plain.",
2378
2397
  shortcut: "s",
2398
+ gesture: "question-mark",
2399
+ gestureHint: "Laser: question mark over a mark.",
2379
2400
  needsSelection: true,
2380
2401
  boardOnly: false,
2381
2402
  replacesSelection: false
@@ -2385,6 +2406,8 @@ var UNSYS_CANVAS_COMMANDS = [
2385
2406
  label: "Subdivide",
2386
2407
  tooltip: "Keep the original mark and fan its parts into smaller nodes, linked with arrows.",
2387
2408
  shortcut: "b",
2409
+ gesture: "double-line",
2410
+ gestureHint: "Laser: two quick lines from a mark into empty space.",
2388
2411
  needsSelection: true,
2389
2412
  boardOnly: false,
2390
2413
  replacesSelection: false
@@ -2394,6 +2417,8 @@ var UNSYS_CANVAS_COMMANDS = [
2394
2417
  label: "Concepts",
2395
2418
  tooltip: "Keep the original and fan its named concepts into linked nodes.",
2396
2419
  shortcut: "c",
2420
+ gesture: "line",
2421
+ gestureHint: "Laser: line from a mark into empty space.",
2397
2422
  needsSelection: true,
2398
2423
  boardOnly: false,
2399
2424
  replacesSelection: false
@@ -2404,6 +2429,8 @@ var UNSYS_CANVAS_COMMANDS = [
2404
2429
  slash: "run",
2405
2430
  tooltip: "Work the highlighted problem: carry it out, compute it, or show the result.",
2406
2431
  shortcut: "d",
2432
+ gesture: "loop",
2433
+ gestureHint: "Laser: circle or loop over a mark.",
2407
2434
  needsSelection: true,
2408
2435
  boardOnly: false,
2409
2436
  replacesSelection: false
@@ -2413,9 +2440,22 @@ var UNSYS_CANVAS_COMMANDS = [
2413
2440
  label: "Refactor",
2414
2441
  tooltip: "Delete the selected marks and replace them with a clearer rewrite.",
2415
2442
  shortcut: "r",
2443
+ gesture: "zigzag",
2444
+ gestureHint: "Laser: zigzag over a mark.",
2416
2445
  needsSelection: true,
2417
2446
  boardOnly: false,
2418
2447
  replacesSelection: true
2448
+ },
2449
+ {
2450
+ id: "pretty",
2451
+ label: "Pretty",
2452
+ tooltip: "Keep the original marks and place a tidied, well-formatted Excalidraw note next to them.",
2453
+ shortcut: "p",
2454
+ gesture: "check",
2455
+ gestureHint: "Laser: check mark over a mark.",
2456
+ needsSelection: true,
2457
+ boardOnly: false,
2458
+ replacesSelection: false
2419
2459
  }
2420
2460
  ];
2421
2461
  function unsysCanvasCommandsFor(_guide, extras = []) {
@@ -2434,6 +2474,8 @@ function unsysCanvasCommandsFor(_guide, extras = []) {
2434
2474
  boardOnly: false,
2435
2475
  replacesSelection: false,
2436
2476
  slash: extra.slash,
2477
+ gesture: extra.gesture,
2478
+ gestureHint: extra.gestureHint,
2437
2479
  run: extra.run
2438
2480
  });
2439
2481
  }
@@ -2536,6 +2578,7 @@ function unsysCanvasBindFanArrow(arrow, start, end, hostBounds) {
2536
2578
  function unsysCanvasFanNoteKind(mark) {
2537
2579
  if (mark === "ileConcepts") return "concepts";
2538
2580
  if (mark === "ileSimplify") return "simplify";
2581
+ if (mark === "ilePretty") return "pretty";
2539
2582
  return "breakdown";
2540
2583
  }
2541
2584
  function unsysCanvasFanStem(host, hostRect, end, toX, toY, mark, hostBounds) {
@@ -2695,6 +2738,80 @@ function fanUnsysCanvasLabeledNodes(scene, selectedElements, chunks, mark) {
2695
2738
  parts
2696
2739
  };
2697
2740
  }
2741
+ function placeUnsysCanvasPrettyReply(scene, selectedElements, payload) {
2742
+ const current = serializeUnsysCanvasScene(scene);
2743
+ const extra = normalizeExtraSkeletons(payload.elements);
2744
+ const text = String(payload.text || "").trim();
2745
+ if (extra.length) {
2746
+ const found = unsysCanvasFanHost(current, selectedElements);
2747
+ if (!found) return { scene: current, placed: false, parts: [] };
2748
+ const { host, expanded } = found;
2749
+ const hostRect = unsysCanvasNormalizedRect(host) ?? {
2750
+ minX: Number(host.x) || 0,
2751
+ minY: Number(host.y) || 0,
2752
+ maxX: (Number(host.x) || 0) + Math.max(1, Number(host.width) || 0),
2753
+ maxY: (Number(host.y) || 0) + Math.max(1, Number(host.height) || 0)
2754
+ };
2755
+ const created = [];
2756
+ for (const item of extra) {
2757
+ const converted = convertToExcalidrawElements([
2758
+ {
2759
+ ...item,
2760
+ customData: { ...item.customData ?? {}, ilePretty: true }
2761
+ }
2762
+ ]);
2763
+ created.push(...converted);
2764
+ }
2765
+ if (!created.length) return { scene: current, placed: false, parts: [] };
2766
+ const box = unsysCanvasContentBounds(created);
2767
+ const gapX = UNSYS_CANVAS_OVERLAP_GAP + 48;
2768
+ const dx = hostRect.maxX + gapX - (box?.minX ?? 0);
2769
+ const dy = hostRect.minY - (box?.minY ?? 0);
2770
+ for (const el of created) {
2771
+ el.x = Number(el.x) + dx;
2772
+ el.y = Number(el.y) + dy;
2773
+ }
2774
+ const settledNodes = settleUnsysCanvasIncoming(
2775
+ created,
2776
+ current.elements.filter((el) => !el.isDeleted)
2777
+ );
2778
+ const bind = settledNodes.find((el) => el.type === "frame" || el.type === "rectangle") ?? settledNodes.find((el) => el.type !== "arrow" && el.type !== "line") ?? settledNodes[0];
2779
+ const nodeHosts = bind ? [bind] : [];
2780
+ const { connectors, hostBounds } = unsysCanvasFanConnectors(
2781
+ host,
2782
+ hostRect,
2783
+ settledNodes,
2784
+ nodeHosts,
2785
+ "ilePretty"
2786
+ );
2787
+ const hostNext = {
2788
+ ...host,
2789
+ boundElements: hostBounds,
2790
+ version: (Number(host.version) || 1) + 1
2791
+ };
2792
+ const parts = [...settledNodes, ...connectors];
2793
+ return {
2794
+ scene: {
2795
+ ...current,
2796
+ elements: [
2797
+ ...current.elements.map((el) => el.id === host.id ? hostNext : el),
2798
+ ...parts
2799
+ ],
2800
+ appState: {
2801
+ ...current.appState,
2802
+ selectedElementIds: Object.fromEntries(
2803
+ expanded.filter((el) => el.id && !el.isDeleted).map((el) => [el.id, true])
2804
+ )
2805
+ }
2806
+ },
2807
+ placed: true,
2808
+ parts
2809
+ };
2810
+ }
2811
+ if (!text) return { scene: current, placed: false, parts: [] };
2812
+ const fanned = fanUnsysCanvasLabeledNodes(current, selectedElements, [text], "ilePretty");
2813
+ return { scene: fanned.scene, placed: fanned.split, parts: fanned.parts };
2814
+ }
2698
2815
  function breakdownUnsysCanvasSelection(scene, selectedElements) {
2699
2816
  const current = serializeUnsysCanvasScene(scene);
2700
2817
  const expanded = expandUnsysCanvasCommandSelection(current, selectedElements);
@@ -2711,6 +2828,7 @@ function unsysCanvasCommandPrompt(action) {
2711
2828
  if (action === "draw") return "Do/run";
2712
2829
  if (action === "breakdown") return "Subdivide";
2713
2830
  if (action === "concepts") return "Concepts";
2831
+ if (action === "pretty") return "Pretty";
2714
2832
  return action;
2715
2833
  }
2716
2834
  function removeUnsysCanvasSelection(scene, selectedElements) {
@@ -2812,566 +2930,1091 @@ function runUnsysCanvasCommand(input) {
2812
2930
  if (input.action === "draw") {
2813
2931
  return idle(null, { kind: "draw", prompt });
2814
2932
  }
2933
+ if (input.action === "pretty") {
2934
+ return idle(null, { kind: "pretty", prompt });
2935
+ }
2815
2936
  return idle(null);
2816
2937
  }
2817
2938
 
2818
- // src/lib/events.ts
2819
- var UNSYS_CANVAS_EVENT_TYPES = [
2820
- "element:added",
2821
- "element:updated",
2822
- "element:deleted",
2823
- "element:moved",
2824
- "element:resized",
2825
- "text:edited",
2826
- "selection:changed",
2827
- "tool:changed",
2828
- "viewport:changed",
2829
- "command:run",
2830
- "prompt:submit",
2831
- "dictate:start",
2832
- "dictate:stop",
2833
- "dictate:text",
2834
- "laser:gesture",
2835
- "latex:render",
2836
- "undo",
2837
- "redo"
2838
- ];
2839
- var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
2840
- var HIGH_FREQ = /* @__PURE__ */ new Set([
2841
- "viewport:changed",
2842
- "element:moved",
2843
- "element:resized",
2844
- "element:updated",
2845
- "text:edited"
2846
- ]);
2847
- function asRecord2(value) {
2848
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
2849
- return value;
2939
+ // src/lib/work-canvas/work-canvas-xai.ts
2940
+ var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
2941
+ var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
2942
+ function unsysCanvasXaiNeedsBoardContext(kind) {
2943
+ return !kind || kind === "ask" || kind === "draw";
2850
2944
  }
2851
- function elementMap(elements) {
2852
- const map = /* @__PURE__ */ new Map();
2853
- for (const el of elements) {
2854
- if (el && typeof el.id === "string") map.set(el.id, el);
2855
- }
2856
- return map;
2945
+ function unsysCanvasXaiMaxTokens(kind) {
2946
+ if (kind === "concepts") return 220;
2947
+ if (kind === "simplify") return 280;
2948
+ if (kind === "pretty") return 520;
2949
+ if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
2950
+ if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
2951
+ return 800;
2857
2952
  }
2858
- function changedProps(prev, next) {
2859
- const changed = {};
2860
- const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
2861
- for (const key of keys) {
2862
- if (SKIP_KEYS.has(key)) continue;
2863
- const from = prev?.[key];
2864
- const to = next[key];
2865
- if (JSON.stringify(from) !== JSON.stringify(to)) {
2866
- changed[key] = { from, to };
2867
- }
2868
- }
2869
- return changed;
2953
+ function unsysCanvasXaiFetchTimeout(kind) {
2954
+ return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
2870
2955
  }
2871
- function selectedIds(appState) {
2872
- const raw = asRecord2(appState.selectedElementIds);
2873
- return Object.keys(raw).filter((id) => raw[id]);
2956
+ function unsysCanvasContextSkipChrome(el) {
2957
+ const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
2958
+ return part === "header" || part === "label" || part === "body";
2874
2959
  }
2875
- function zoomValue(appState) {
2876
- const zoom = appState.zoom;
2877
- if (zoom && typeof zoom === "object" && "value" in zoom) {
2878
- return Number(zoom.value) || 1;
2960
+ function unsysCanvasCompactListing(scene, options) {
2961
+ const live = serializeUnsysCanvasScene(scene).elements.filter(
2962
+ (el) => !el.isDeleted && el.type !== "cursor" && !unsysCanvasContextSkipChrome(el)
2963
+ );
2964
+ if (!live.length) return "(no live elements)";
2965
+ const cap = Math.max(1, UNSYS_CANVAS_CONTEXT_MAX_MARKS);
2966
+ const shown = live.slice(0, cap);
2967
+ const lines = shown.map((el) => {
2968
+ const text = String(el.originalText || el.text || "").replace(/\s+/g, " ").trim().slice(0, UNSYS_CANVAS_CONTEXT_TEXT_MAX);
2969
+ return text ? `[${el.type}] ${JSON.stringify(text)}` : `[${el.type}]`;
2970
+ });
2971
+ if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
2972
+ return lines.join("\n");
2973
+ }
2974
+ function unsysCanvasTurnContextMessage(scene, input) {
2975
+ const board = String(input?.boardLabel || "CHAPTER").trim() || "CHAPTER";
2976
+ const listing = unsysCanvasCompactListing(scene);
2977
+ const body = `CURRENT ${board} WORK CANVAS (compact: type and text of live marks; positions omitted). Co-author this board: your reply is placed as a Work note the learner can move and edit. ${unsysCanvasXaiToolsInstruction()}
2978
+ ${listing}`;
2979
+ return unsysCanvasWithDomainPrefix(body, input?.workspace);
2980
+ }
2981
+ var UNSYS_CONCEPT_LABEL_MAX = 8;
2982
+ var UNSYS_CONCEPT_LABEL_MAX_CHARS = 72;
2983
+ function unsysCanvasCleanConceptLabel(raw) {
2984
+ return String(raw || "").replace(/^\s*(?:[-*•]+|\d+[.)])\s+/, "").replace(/\s+/g, " ").trim();
2985
+ }
2986
+ function unsysCanvasTakeConceptLabels(items) {
2987
+ const out = [];
2988
+ const seen = /* @__PURE__ */ new Set();
2989
+ for (const item of items) {
2990
+ const label = unsysCanvasCleanConceptLabel(item);
2991
+ if (label.length < 2 || label.length > UNSYS_CONCEPT_LABEL_MAX_CHARS) continue;
2992
+ const key = label.toLowerCase();
2993
+ if (seen.has(key)) continue;
2994
+ seen.add(key);
2995
+ out.push(label);
2996
+ if (out.length >= UNSYS_CONCEPT_LABEL_MAX) break;
2879
2997
  }
2880
- return Number(zoom) || 1;
2998
+ return out;
2881
2999
  }
2882
- function toolName(appState) {
2883
- const tool = appState.activeTool;
2884
- if (typeof tool === "string") return tool;
2885
- if (tool && typeof tool === "object" && "type" in tool) {
2886
- return String(tool.type || "") || null;
3000
+ function unsysCanvasConceptLabels(raw, payload) {
3001
+ const source = String(raw || "").trim();
3002
+ const parsed = extractJsonObject(source);
3003
+ const fromJson = parsed?.concepts ?? parsed?.labels;
3004
+ if (Array.isArray(fromJson)) {
3005
+ const labels = unsysCanvasTakeConceptLabels(fromJson.map((item) => String(item ?? "")));
3006
+ if (labels.length) return labels;
2887
3007
  }
2888
- return null;
3008
+ const fromElements = unsysCanvasTakeConceptLabels(
3009
+ (payload?.elements ?? []).map((el) => String(el?.label?.text || el?.text || ""))
3010
+ );
3011
+ if (fromElements.length) return fromElements;
3012
+ const prose = stripLearnerFacingWrappers(String(payload?.text || parsed?.text || source).trim());
3013
+ const lines = prose.split(/\n+/).map((line) => line.trim()).filter(Boolean);
3014
+ const fromLines = unsysCanvasTakeConceptLabels(lines);
3015
+ if (fromLines.length >= 2) return fromLines;
3016
+ if (fromLines.length === 1 && lines.length === 1) {
3017
+ const parts = fromLines[0].split(/\s*(?:,|;|•)\s+|\s+and\s+/i);
3018
+ const fromParts = unsysCanvasTakeConceptLabels(parts);
3019
+ if (fromParts.length >= 2) return fromParts;
3020
+ }
3021
+ return fromLines;
2889
3022
  }
2890
- function snapshot(scene) {
2891
- const rec = asRecord2(scene);
2892
- const elements = Array.isArray(rec.elements) ? rec.elements : [];
3023
+ function compressUnsysCanvasSelection(scene, selectedElements, summary) {
3024
+ const current = serializeUnsysCanvasScene(scene);
3025
+ const text = unsysCanvasCommandProse(String(summary ?? ""));
3026
+ const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3027
+ if (!text || !liveSelected.length) return current;
3028
+ const bounds = unsysCanvasContentBounds(liveSelected);
3029
+ const created = unsysCanvasXaiNoteElements({
3030
+ text,
3031
+ x: bounds?.minX ?? TEXT_ORIGIN_X,
3032
+ y: bounds?.minY ?? TEXT_ORIGIN_Y,
3033
+ label: unsysCanvasNoteLabel("selective-compress"),
3034
+ customData: {
3035
+ [UNSYS_CANVAS_COMPRESS_WORK_CUSTOM_DATA_KEY]: true,
3036
+ ileSelectiveCompression: true,
3037
+ author: "xai"
3038
+ }
3039
+ }).elements;
3040
+ if (!created.length) return current;
3041
+ const remove = new Set(liveSelected.map((el) => el.id));
3042
+ const kept = current.elements.filter((el) => !remove.has(el.id));
3043
+ const settled = settleUnsysCanvasIncoming(
3044
+ created,
3045
+ kept.filter((el) => !el.isDeleted)
3046
+ );
2893
3047
  return {
2894
- elements,
2895
- appState: asRecord2(rec.appState),
2896
- files: asRecord2(rec.files)
3048
+ ...current,
3049
+ elements: [...kept, ...settled],
3050
+ appState: {
3051
+ ...current.appState,
3052
+ selectedElementIds: {}
3053
+ }
2897
3054
  };
2898
3055
  }
2899
- function eventKey(event) {
2900
- const id = typeof event.payload.id === "string" ? event.payload.id : "";
2901
- return `${event.type}:${id}`;
2902
- }
2903
- function mergePayload(prev, next) {
2904
- const merged = { ...prev, ...next };
2905
- if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
2906
- if ("to" in next) merged.to = next.to;
2907
- if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
2908
- const a = prev.changed;
2909
- const b = next.changed;
2910
- const changed = { ...a };
2911
- for (const [key, value] of Object.entries(b)) {
2912
- const earlier = a[key];
2913
- changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
2914
- }
2915
- merged.changed = changed;
3056
+ function parseUnsysCanvasLayoutEdits(raw) {
3057
+ let record = null;
3058
+ if (typeof raw === "string") {
3059
+ record = extractJsonObject(raw);
3060
+ } else if (raw && typeof raw === "object" && !Array.isArray(raw)) {
3061
+ record = raw;
2916
3062
  }
2917
- return merged;
2918
- }
2919
- var UnsysCanvasEventCollector = class {
2920
- constructor(options) {
2921
- this.seq = 0;
2922
- this.prev = null;
2923
- this.buffer = [];
2924
- this.lastFlush = 0;
2925
- this.batchMs = options?.batchMs ?? 0;
3063
+ const list = record && Array.isArray(record.elements) ? record.elements : Array.isArray(raw) ? raw : [];
3064
+ const edits = [];
3065
+ for (const item of list) {
3066
+ if (!item || typeof item !== "object") continue;
3067
+ const rec = item;
3068
+ const id = typeof rec.id === "string" ? rec.id.trim() : "";
3069
+ const text = typeof rec.text === "string" ? rec.text.trim() : "";
3070
+ const x = Number(rec.x);
3071
+ const y = Number(rec.y);
3072
+ edits.push({
3073
+ id,
3074
+ text: text || null,
3075
+ x: Number.isFinite(x) ? x : null,
3076
+ y: Number.isFinite(y) ? y : null
3077
+ });
2926
3078
  }
2927
- reset(scene) {
2928
- this.prev = snapshot(scene);
2929
- this.seq = 0;
2930
- this.buffer = [];
2931
- this.lastFlush = 0;
2932
- }
2933
- syncWithoutEmit(scene) {
2934
- this.prev = snapshot(scene);
2935
- }
2936
- push(type, payload) {
2937
- this.seq += 1;
2938
- return { seq: this.seq, ts: Date.now(), type, payload };
2939
- }
2940
- observeScene(scene, _opts) {
2941
- const next = snapshot(scene);
2942
- const prev = this.prev ?? { elements: [], appState: {}};
2943
- const events = [];
2944
- const prevEls = elementMap(prev.elements);
2945
- const nextEls = elementMap(next.elements);
2946
- for (const [id, el] of nextEls) {
2947
- const before = prevEls.get(id);
2948
- const deleted = Boolean(el.isDeleted);
2949
- const wasDeleted = Boolean(before?.isDeleted);
2950
- if (!before || wasDeleted && !deleted) {
2951
- if (!deleted) {
2952
- events.push(
2953
- this.push("element:added", {
2954
- id,
2955
- type: el.type,
2956
- element: el
2957
- })
2958
- );
2959
- }
2960
- continue;
2961
- }
2962
- if (!wasDeleted && deleted) {
2963
- events.push(this.push("element:deleted", { id, type: el.type, element: el }));
2964
- continue;
2965
- }
2966
- if (deleted) continue;
2967
- const changed = changedProps(before, el);
2968
- if (!Object.keys(changed).length) continue;
2969
- events.push(
2970
- this.push("element:updated", {
2971
- id,
2972
- type: el.type,
2973
- changed
2974
- })
2975
- );
2976
- if ("x" in changed || "y" in changed) {
2977
- events.push(
2978
- this.push("element:moved", {
2979
- id,
2980
- type: el.type,
2981
- from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
2982
- to: { x: el.x, y: el.y }
2983
- })
2984
- );
2985
- }
2986
- if ("width" in changed || "height" in changed) {
2987
- events.push(
2988
- this.push("element:resized", {
2989
- id,
2990
- type: el.type,
2991
- from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
2992
- to: { width: el.width, height: el.height }
2993
- })
2994
- );
2995
- }
2996
- if ("text" in changed || "originalText" in changed) {
2997
- events.push(
2998
- this.push("text:edited", {
2999
- id,
3000
- type: el.type,
3001
- from: changed.text?.from ?? changed.originalText?.from ?? before.text,
3002
- to: el.text ?? el.originalText
3003
- })
3004
- );
3005
- }
3006
- }
3007
- for (const [id, el] of prevEls) {
3008
- if (nextEls.has(id)) continue;
3009
- if (el.isDeleted) continue;
3010
- events.push(this.push("element:deleted", { id, type: el.type, element: el }));
3079
+ return edits;
3080
+ }
3081
+ function unsysCanvasEditForElement(edits, el, indexAmongSelected, matchById) {
3082
+ if (matchById) return edits.find((edit) => edit.id === el.id) ?? null;
3083
+ return edits[indexAmongSelected] ?? null;
3084
+ }
3085
+ function unsysCanvasLayoutReply(raw, elements) {
3086
+ const source = String(raw || "");
3087
+ if (parseUnsysCanvasLayoutEdits(source).length) return source;
3088
+ const list = (elements ?? []).filter((el) => el && typeof el === "object");
3089
+ if (list.length) return { elements: list };
3090
+ return source;
3091
+ }
3092
+ function applyUnsysCanvasSuggestInsight(scene, selectedElements, suggestion) {
3093
+ const current = serializeUnsysCanvasScene(scene);
3094
+ const text = unsysCanvasCommandProse(String(suggestion ?? ""));
3095
+ const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3096
+ if (!text || !liveSelected.length) return current;
3097
+ const origin = unsysCanvasEmptyNearbyOrigin({
3098
+ elements: current.elements,
3099
+ near: liveSelected,
3100
+ box: { width: UNSYS_CANVAS_TEXT_BOX_WIDTH, height: 80 }
3101
+ });
3102
+ const created = unsysCanvasXaiNoteElements({
3103
+ text,
3104
+ x: origin.x,
3105
+ y: origin.y,
3106
+ label: unsysCanvasNoteLabel("suggest-insight"),
3107
+ customData: {
3108
+ author: "xai",
3109
+ ileSuggestedInsight: true
3011
3110
  }
3012
- const prevSel = selectedIds(prev.appState);
3013
- const nextSel = selectedIds(next.appState);
3014
- if (prevSel.join(",") !== nextSel.join(",")) {
3015
- events.push(this.push("selection:changed", { from: prevSel, to: nextSel }));
3111
+ }).elements;
3112
+ if (!created.length) return current;
3113
+ const settled = settleUnsysCanvasIncoming(
3114
+ created,
3115
+ current.elements.filter((el) => !el.isDeleted)
3116
+ );
3117
+ return {
3118
+ ...current,
3119
+ elements: [...current.elements, ...settled]
3120
+ };
3121
+ }
3122
+ function unsysCanvasSceneVisiblyChanged(before, after) {
3123
+ const previous = serializeUnsysCanvasScene(before).elements.filter((el) => !el.isDeleted);
3124
+ const next = serializeUnsysCanvasScene(after).elements.filter((el) => !el.isDeleted);
3125
+ if (previous.length !== next.length) return true;
3126
+ const byId = new Map(previous.map((el) => [el.id, el]));
3127
+ for (const el of next) {
3128
+ const prior = byId.get(el.id);
3129
+ if (!prior) return true;
3130
+ if (prior.x !== el.x || prior.y !== el.y || prior.width !== el.width || prior.height !== el.height || String(prior.text || "") !== String(el.text || "") || String(prior.originalText || "") !== String(el.originalText || "")) {
3131
+ return true;
3016
3132
  }
3017
- const prevTool = toolName(prev.appState);
3018
- const nextTool = toolName(next.appState);
3019
- if (prevTool !== nextTool) {
3020
- events.push(this.push("tool:changed", { from: prevTool, to: nextTool }));
3133
+ }
3134
+ return false;
3135
+ }
3136
+ function unsysCanvasAskFallback(kind) {
3137
+ if (!kind || kind === "ask") return "Learn more failed. Try again.";
3138
+ return `${kind} failed. Try again.`;
3139
+ }
3140
+ function applyUnsysCanvasAskReply(input) {
3141
+ const live = serializeUnsysCanvasScene(input.live);
3142
+ const selected = expandUnsysCanvasCommandSelection(live, input.selectedElements);
3143
+ const kind = input.kind ?? null;
3144
+ const noteLabel = unsysCanvasNoteLabel(kind);
3145
+ const source = kind && kind !== "ask" ? String(input.payload.raw || "") : String(input.payload.text || "");
3146
+ const layoutReply = unsysCanvasLayoutReply(input.payload.raw, input.payload.elements);
3147
+ const merge = (text, extra) => mergeUnsysCanvasTurnOntoLiveWorkCanvas(
3148
+ live,
3149
+ {
3150
+ text,
3151
+ elements: input.payload.elements,
3152
+ turnId: input.payload.turnId,
3153
+ origin: input.payload.origin,
3154
+ label: noteLabel
3155
+ },
3156
+ {
3157
+ fallbackOrigin: input.fallbackOrigin,
3158
+ reserved: input.reserved
3021
3159
  }
3022
- const prevView = {
3023
- zoom: zoomValue(prev.appState),
3024
- scrollX: Number(prev.appState.scrollX) || 0,
3025
- scrollY: Number(prev.appState.scrollY) || 0
3026
- };
3027
- const nextView = {
3028
- zoom: zoomValue(next.appState),
3029
- scrollX: Number(next.appState.scrollX) || 0,
3030
- scrollY: Number(next.appState.scrollY) || 0
3031
- };
3032
- if (prevView.zoom !== nextView.zoom || prevView.scrollX !== nextView.scrollX || prevView.scrollY !== nextView.scrollY) {
3033
- events.push(this.push("viewport:changed", { from: prevView, to: nextView }));
3160
+ );
3161
+ let next = live;
3162
+ if (kind === "selective-compress") {
3163
+ next = compressUnsysCanvasSelection(live, selected, source);
3164
+ } else if (kind === "refactor") {
3165
+ next = replaceUnsysCanvasSelection(live, selected, {
3166
+ text: input.payload.text,
3167
+ elements: input.payload.elements,
3168
+ turnId: input.payload.turnId,
3169
+ label: noteLabel
3170
+ });
3171
+ } else if (kind === "simplify") {
3172
+ const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
3173
+ if (text) {
3174
+ next = fanUnsysCanvasLabeledNodes(live, selected, [text], "ileSimplify").scene;
3034
3175
  }
3035
- this.prev = next;
3036
- return this.batch(events);
3176
+ } else if (kind === "pretty") {
3177
+ const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
3178
+ const placed = placeUnsysCanvasPrettyReply(live, selected, {
3179
+ text,
3180
+ elements: input.payload.elements
3181
+ });
3182
+ if (placed.placed) next = placed.scene;
3183
+ } else if (kind === "concepts") {
3184
+ const labels = unsysCanvasConceptLabels(source, {
3185
+ text: input.payload.text,
3186
+ elements: input.payload.elements
3187
+ });
3188
+ next = fanUnsysCanvasLabeledNodes(live, selected, labels, "ileConcepts").scene;
3189
+ } else if (kind === "suggest-insight") {
3190
+ next = applyUnsysCanvasSuggestInsight(live, selected, source);
3191
+ } else if (kind === "declutter" || kind === "clear-overlaps") {
3192
+ next = applyUnsysCanvasPositionEdits(live, selected, layoutReply);
3193
+ } else {
3194
+ next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
3037
3195
  }
3038
- command(id, meta) {
3039
- return [
3040
- this.push("command:run", {
3041
- id: id ?? null,
3042
- args: meta ?? {}
3043
- })
3044
- ];
3196
+ if (unsysCanvasSceneVisiblyChanged(live, next)) return withUnsysCanvasAutoLayout(next);
3197
+ const fallback = stripLearnerFacingWrappers(String(input.payload.text || "").trim()) || unsysCanvasAskFallback(kind);
3198
+ return withUnsysCanvasAutoLayout(merge(fallback));
3199
+ }
3200
+ function applyUnsysCanvasPositionEdits(scene, selectedElements, reply) {
3201
+ const current = serializeUnsysCanvasScene(scene);
3202
+ const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3203
+ if (!liveSelected.length) return current;
3204
+ const edits = parseUnsysCanvasLayoutEdits(reply);
3205
+ if (!edits.length) return current;
3206
+ const selectedIds2 = new Set(liveSelected.map((el) => el.id));
3207
+ const matchById = edits.some((edit) => edit.id && selectedIds2.has(edit.id));
3208
+ let ordinal = 0;
3209
+ return {
3210
+ ...current,
3211
+ elements: current.elements.map((el) => {
3212
+ if (!selectedIds2.has(el.id) || el.isDeleted) return el;
3213
+ const edit = unsysCanvasEditForElement(edits, el, ordinal, matchById);
3214
+ ordinal += 1;
3215
+ if (!edit || edit.x == null && edit.y == null) return el;
3216
+ return {
3217
+ ...el,
3218
+ x: edit.x == null ? el.x : edit.x,
3219
+ y: edit.y == null ? el.y : edit.y,
3220
+ version: (Number(el.version) || 1) + 1
3221
+ };
3222
+ })
3223
+ };
3224
+ }
3225
+
3226
+ // src/lib/work-canvas/command-registry.ts
3227
+ var UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT = [
3228
+ "You sit beside the learner on a work canvas. Speak in complete, unhurried sentences. Be eloquent and plain.",
3229
+ "Answer the topic directly. Never mention canvas commands, origin, or placement.",
3230
+ "Never mention the host product, event names, or platform jargon.",
3231
+ "Write mathematics as LaTeX: $...$ inline and $$...$$ on its own line.",
3232
+ 'Reply as JSON with a "text" field. Do not put JSON or code fences inside "text".'
3233
+ ].join(" ");
3234
+ var UNSYS_CANVAS_MODEL_COMMAND_IDS = [
3235
+ "ask",
3236
+ "draw",
3237
+ "simplify",
3238
+ "concepts",
3239
+ "check",
3240
+ "selective-compress",
3241
+ "refactor",
3242
+ "suggest-insight",
3243
+ "clear-overlaps",
3244
+ "declutter"
3245
+ ];
3246
+ var CONTEXT_TEXT_MAX = 2e3;
3247
+ var CONTEXT_PROMPT_MAX = 4e3;
3248
+ var CONTEXT_SELECTED_MAX = 64;
3249
+ var CONTEXT_LIVE_MAX = 48;
3250
+ var CONTEXT_ID_MAX = 80;
3251
+ var ELEMENT_TYPES = /* @__PURE__ */ new Set([
3252
+ "text",
3253
+ "freedraw",
3254
+ "rectangle",
3255
+ "diamond",
3256
+ "ellipse",
3257
+ "arrow",
3258
+ "line",
3259
+ "image",
3260
+ "frame",
3261
+ "embeddable"
3262
+ ]);
3263
+ function finiteNumber(value) {
3264
+ const n = Number(value);
3265
+ return Number.isFinite(n) ? n : 0;
3266
+ }
3267
+ function clipText(value, max) {
3268
+ return String(value ?? "").replace(/\s+/g, " ").trim().slice(0, max);
3269
+ }
3270
+ function compactUnsysCanvasContextElement(el) {
3271
+ if (!el || typeof el !== "object") return null;
3272
+ const id = String(el.id || "").trim().slice(0, CONTEXT_ID_MAX);
3273
+ const type = String(el.type || "").trim().slice(0, 32);
3274
+ if (!id || !type || !ELEMENT_TYPES.has(type)) return null;
3275
+ const text = clipText(
3276
+ "originalText" in el ? el.originalText || el.text : el.text,
3277
+ CONTEXT_TEXT_MAX
3278
+ );
3279
+ const compact = {
3280
+ id,
3281
+ type,
3282
+ x: finiteNumber(el.x),
3283
+ y: finiteNumber(el.y)
3284
+ };
3285
+ if (el.width != null) compact.width = finiteNumber(el.width);
3286
+ if (el.height != null) compact.height = finiteNumber(el.height);
3287
+ if (text) compact.text = text;
3288
+ return compact;
3289
+ }
3290
+ function compactList(elements, max) {
3291
+ const out = [];
3292
+ for (const item of elements ?? []) {
3293
+ const compact = compactUnsysCanvasContextElement(item);
3294
+ if (!compact) continue;
3295
+ out.push(compact);
3296
+ if (out.length >= max) break;
3045
3297
  }
3046
- dictate(meta) {
3047
- const rec = asRecord2(meta);
3048
- const type = rec.phase === "start" ? "dictate:start" : rec.phase === "stop" ? "dictate:stop" : "dictate:text";
3049
- return [this.push(type, rec)];
3298
+ return out;
3299
+ }
3300
+ function asSceneFromContext(context) {
3301
+ const live = context.liveElements?.length ? context.liveElements : context.selectedElements;
3302
+ return {
3303
+ elements: live,
3304
+ appState: {},
3305
+ files: {}
3306
+ };
3307
+ }
3308
+ function asSelectedFromContext(context) {
3309
+ return context.selectedElements;
3310
+ }
3311
+ function extractUnsysCanvasCommandContext(input) {
3312
+ const scene = input.scene ?? { elements: [], appState: {}, files: {} };
3313
+ const selected = expandUnsysCanvasCommandSelection(scene, input.selectedElements);
3314
+ const payload = {
3315
+ selectedElements: compactList(selected, CONTEXT_SELECTED_MAX)
3316
+ };
3317
+ if (unsysCanvasXaiNeedsBoardContext(input.commandId)) {
3318
+ payload.liveElements = compactList(
3319
+ (scene.elements ?? []).filter((el) => el && !el.isDeleted),
3320
+ CONTEXT_LIVE_MAX
3321
+ );
3050
3322
  }
3051
- prompt(text, meta) {
3052
- return [this.push("prompt:submit", { text: text ?? "", ...asRecord2(meta) })];
3323
+ const prompt = clipText(input.prompt, CONTEXT_PROMPT_MAX);
3324
+ if (prompt) payload.prompt = prompt;
3325
+ if (input.workspace) payload.workspace = input.workspace;
3326
+ return payload;
3327
+ }
3328
+ function defaultParse(raw) {
3329
+ const parsed = parseUnsysCanvasAskReply(raw);
3330
+ const turn = parseUnsysCanvasCanvasTurn(raw);
3331
+ return {
3332
+ text: parsed.message,
3333
+ elements: parsed.canvasElements,
3334
+ origin: turn.origin ?? null,
3335
+ raw: parsed.raw
3336
+ };
3337
+ }
3338
+ function defaultBuildPrompt(commandId, context) {
3339
+ const kind = commandId;
3340
+ const scene = asSceneFromContext(context);
3341
+ const selected = asSelectedFromContext(context);
3342
+ const userText = [
3343
+ buildUnsysCanvasCommandUserMessage({
3344
+ kind,
3345
+ prompt: context.prompt,
3346
+ selectedElements: selected,
3347
+ workspace: context.workspace
3348
+ }),
3349
+ unsysCanvasXaiNeedsBoardContext(kind) ? unsysCanvasTurnContextMessage(scene, {
3350
+ boardLabel: context.boardLabel,
3351
+ workspace: context.workspace
3352
+ }) : ""
3353
+ ].filter(Boolean).join("\n\n");
3354
+ return {
3355
+ messages: [
3356
+ { role: "system", content: `${UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT} ${unsysCanvasXaiToolsInstruction()}` },
3357
+ { role: "user", content: userText }
3358
+ ],
3359
+ responseFormat: "json",
3360
+ maxTokens: unsysCanvasXaiMaxTokens(kind),
3361
+ timeoutMs: unsysCanvasXaiFetchTimeout(kind)
3362
+ };
3363
+ }
3364
+ var MODEL_KIND_LABEL = {
3365
+ ask: "Ask",
3366
+ check: "Check",
3367
+ "selective-compress": "Compress",
3368
+ "suggest-insight": "Suggest insight",
3369
+ "clear-overlaps": "Clear overlaps",
3370
+ declutter: "Declutter"
3371
+ };
3372
+ function hiddenModelDef(id) {
3373
+ return {
3374
+ id,
3375
+ label: MODEL_KIND_LABEL[id] ?? id,
3376
+ tooltip: MODEL_KIND_LABEL[id] ?? id,
3377
+ shortcut: "",
3378
+ needsSelection: id !== "ask",
3379
+ boardOnly: false,
3380
+ replacesSelection: id === "refactor" || id === "selective-compress",
3381
+ catalog: false,
3382
+ needsModel: true,
3383
+ placement: id === "refactor" || id === "selective-compress" ? "replace" : "beside",
3384
+ extractContext: (input) => extractUnsysCanvasCommandContext({
3385
+ commandId: id,
3386
+ scene: input.scene,
3387
+ selectedElements: input.selectedElements,
3388
+ prompt: input.prompt,
3389
+ workspace: input.workspace
3390
+ }),
3391
+ buildPrompt: (context) => defaultBuildPrompt(id, context),
3392
+ parseResponse: defaultParse
3393
+ };
3394
+ }
3395
+ function catalogDef(command) {
3396
+ const needsModel = command.id !== "breakdown";
3397
+ return {
3398
+ ...command,
3399
+ catalog: true,
3400
+ needsModel,
3401
+ placement: command.replacesSelection ? "replace" : "beside",
3402
+ extractContext: (input) => extractUnsysCanvasCommandContext({
3403
+ commandId: command.id,
3404
+ scene: input.scene,
3405
+ selectedElements: input.selectedElements,
3406
+ prompt: input.prompt,
3407
+ workspace: input.workspace
3408
+ }),
3409
+ buildPrompt: needsModel ? (context) => defaultBuildPrompt(command.id, context) : void 0,
3410
+ parseResponse: defaultParse
3411
+ };
3412
+ }
3413
+ var BUILTIN_BY_ID = /* @__PURE__ */ new Map();
3414
+ for (const command of UNSYS_CANVAS_COMMANDS) {
3415
+ BUILTIN_BY_ID.set(command.id, catalogDef(command));
3416
+ }
3417
+ for (const id of UNSYS_CANVAS_MODEL_COMMAND_IDS) {
3418
+ if (!BUILTIN_BY_ID.has(id)) BUILTIN_BY_ID.set(id, hiddenModelDef(id));
3419
+ }
3420
+ function extraToDefinition(extra) {
3421
+ const id = String(extra.id || "").trim();
3422
+ const needsModel = Boolean(extra.buildPrompt) || extra.needsModel === true;
3423
+ return {
3424
+ id,
3425
+ label: extra.label,
3426
+ tooltip: extra.tooltip ?? extra.label,
3427
+ shortcut: extra.shortcut ?? "",
3428
+ needsSelection: extra.needsSelection ?? false,
3429
+ boardOnly: false,
3430
+ replacesSelection: false,
3431
+ slash: extra.slash,
3432
+ run: extra.run,
3433
+ catalog: extra.catalog !== false,
3434
+ needsModel,
3435
+ placement: extra.placement ?? "beside",
3436
+ gesture: extra.gesture,
3437
+ gestureHint: extra.gestureHint,
3438
+ extractContext: extra.extractContext ?? ((input) => extractUnsysCanvasCommandContext({
3439
+ commandId: id,
3440
+ scene: input.scene,
3441
+ selectedElements: input.selectedElements,
3442
+ prompt: input.prompt,
3443
+ workspace: input.workspace
3444
+ })),
3445
+ buildPrompt: extra.buildPrompt,
3446
+ parseResponse: extra.parseResponse ?? defaultParse
3447
+ };
3448
+ }
3449
+ function listUnsysCanvasCommandDefinitions(extras = []) {
3450
+ const out = [...BUILTIN_BY_ID.values()];
3451
+ const seen = new Set(out.map((command) => command.id));
3452
+ for (const extra of extras) {
3453
+ const id = String(extra?.id || "").trim();
3454
+ if (!id || seen.has(id)) continue;
3455
+ seen.add(id);
3456
+ out.push(extraToDefinition(extra));
3053
3457
  }
3054
- laser(meta) {
3055
- return [this.push("laser:gesture", asRecord2(meta))];
3458
+ return out;
3459
+ }
3460
+ function getUnsysCanvasCommand(id, extras = []) {
3461
+ const key = String(id || "").trim();
3462
+ if (!key) return null;
3463
+ const extra = extras.find((command) => String(command?.id || "").trim() === key);
3464
+ if (extra) return extraToDefinition(extra);
3465
+ return BUILTIN_BY_ID.get(key) ?? null;
3466
+ }
3467
+ function isUnsysCanvasKnownCommandId(id, extras = []) {
3468
+ return getUnsysCanvasCommand(id, extras) != null;
3469
+ }
3470
+ function buildUnsysCanvasCommandPrompt(commandId, context, extras = []) {
3471
+ const command = getUnsysCanvasCommand(commandId, extras);
3472
+ if (!command) {
3473
+ throw new Error(`Unknown canvas command: ${commandId}`);
3056
3474
  }
3057
- latex(meta) {
3058
- return [this.push("latex:render", asRecord2(meta))];
3475
+ if (command.buildPrompt) return command.buildPrompt(context);
3476
+ return defaultBuildPrompt(commandId, context);
3477
+ }
3478
+ function parseUnsysCanvasCommandResponse(commandId, raw, extras = []) {
3479
+ const command = getUnsysCanvasCommand(commandId, extras);
3480
+ const parse = command?.parseResponse ?? defaultParse;
3481
+ return parse(raw);
3482
+ }
3483
+ function unsysCanvasCommandPlacement(id) {
3484
+ return String(id || "").trim() === "refactor" ? "replace" : "beside";
3485
+ }
3486
+ function unsysCanvasGestureCommandId(gesture) {
3487
+ const kind = String(gesture || "").trim();
3488
+ if (!kind) return null;
3489
+ for (const command of UNSYS_CANVAS_COMMANDS) {
3490
+ if (command.gesture === kind) return command.id;
3059
3491
  }
3060
- history(kind, meta) {
3061
- return [this.push(kind, asRecord2(meta))];
3492
+ return null;
3493
+ }
3494
+
3495
+ // src/lib/work-canvas/command-model.ts
3496
+ var INJECTION_KEYS = /* @__PURE__ */ new Set([
3497
+ "messages",
3498
+ "system",
3499
+ "user",
3500
+ "prompt",
3501
+ "thought",
3502
+ "instructions",
3503
+ "systemPrompt"
3504
+ ]);
3505
+ function asRecord2(value) {
3506
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
3507
+ return value;
3508
+ }
3509
+ function validateContext(raw, commandId) {
3510
+ const rec = asRecord2(raw);
3511
+ if (!rec) return { ok: false, error: "context is required" };
3512
+ for (const key of Object.keys(rec)) {
3513
+ if (INJECTION_KEYS.has(key) && key !== "prompt") {
3514
+ return { ok: false, error: "context contains disallowed fields" };
3515
+ }
3062
3516
  }
3063
- markGestureBusy(_busy) {
3517
+ if (rec.commandId != null && String(rec.commandId).trim() !== commandId) {
3518
+ return { ok: false, error: "context.commandId does not match commandId" };
3064
3519
  }
3065
- batch(incoming) {
3066
- const now = Date.now();
3067
- if (!this.buffer.length) this.lastFlush = now;
3068
- for (const event of incoming) {
3069
- const last = this.buffer[this.buffer.length - 1];
3070
- if (last && HIGH_FREQ.has(event.type) && eventKey(last) === eventKey(event)) {
3071
- this.buffer[this.buffer.length - 1] = {
3072
- ...event,
3073
- seq: last.seq,
3074
- ts: last.ts,
3075
- payload: mergePayload(last.payload, event.payload)
3076
- };
3077
- } else {
3078
- this.buffer.push(event);
3079
- }
3080
- }
3081
- if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
3082
- return [];
3520
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements.map(compactUnsysCanvasContextElement).filter(Boolean) : [];
3521
+ const live = Array.isArray(rec.liveElements) ? rec.liveElements.map(compactUnsysCanvasContextElement).filter(Boolean) : void 0;
3522
+ const prompt = typeof rec.prompt === "string" ? rec.prompt.replace(/\s+/g, " ").trim().slice(0, 4e3) : "";
3523
+ const boardLabel = typeof rec.boardLabel === "string" ? rec.boardLabel.trim().slice(0, 80) : void 0;
3524
+ const workspace = rec.workspace && typeof rec.workspace === "object" ? rec.workspace : void 0;
3525
+ const context = {
3526
+ selectedElements: selected
3527
+ };
3528
+ if (live?.length) context.liveElements = live;
3529
+ if (prompt) context.prompt = prompt;
3530
+ if (boardLabel) context.boardLabel = boardLabel;
3531
+ if (workspace) context.workspace = workspace;
3532
+ return { ok: true, context };
3533
+ }
3534
+ function parseUnsysCanvasModelClientBody(body, extras = []) {
3535
+ const rec = asRecord2(body);
3536
+ if (!rec) return { ok: false, status: 400, error: "JSON object required" };
3537
+ for (const key of ["messages", "system", "systemPrompt", "instructions", "user"]) {
3538
+ if (key in rec) {
3539
+ return { ok: false, status: 400, error: "Only commandId and context are allowed" };
3083
3540
  }
3084
- const flushed = this.buffer;
3085
- this.buffer = [];
3086
- this.lastFlush = now;
3087
- return flushed;
3088
3541
  }
3089
- flush() {
3090
- const flushed = this.buffer;
3091
- this.buffer = [];
3092
- this.lastFlush = Date.now();
3093
- return flushed;
3542
+ const commandId = String(rec.commandId || rec.canvasAskKind || "").trim();
3543
+ if (!commandId) return { ok: false, status: 400, error: "commandId is required" };
3544
+ if (!isUnsysCanvasKnownCommandId(commandId, extras)) {
3545
+ return { ok: false, status: 400, error: `Unknown command id: ${commandId}` };
3546
+ }
3547
+ const command = getUnsysCanvasCommand(commandId, extras);
3548
+ if (!command?.needsModel && !command?.buildPrompt) {
3549
+ return { ok: false, status: 400, error: `Command does not use a model: ${commandId}` };
3550
+ }
3551
+ let contextRaw = rec.context;
3552
+ if (!contextRaw) {
3553
+ contextRaw = {
3554
+ selectedElements: rec.selectedElements,
3555
+ liveElements: rec.liveElements,
3556
+ prompt: rec.thought ?? rec.prompt
3557
+ };
3094
3558
  }
3095
- };
3096
-
3097
- // src/lib/work-canvas/work-canvas-xai.ts
3098
- var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
3099
- var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
3100
- function unsysCanvasXaiNeedsBoardContext(kind) {
3101
- return !kind || kind === "ask" || kind === "draw";
3559
+ const context = validateContext(contextRaw, commandId);
3560
+ if (!context.ok) return { ok: false, status: 400, error: context.error };
3561
+ return { ok: true, commandId, context: context.context };
3102
3562
  }
3103
- function unsysCanvasXaiMaxTokens(kind) {
3104
- if (kind === "concepts") return 220;
3105
- if (kind === "simplify") return 280;
3106
- if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
3107
- if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
3108
- return 800;
3563
+ function buildUnsysCanvasModelRequest(input) {
3564
+ const extras = input.extras ?? [];
3565
+ const command = getUnsysCanvasCommand(input.commandId, extras);
3566
+ if (!command) {
3567
+ throw new Error(`Unknown canvas command: ${input.commandId}`);
3568
+ }
3569
+ const context = input.context ?? extractUnsysCanvasCommandContext({
3570
+ commandId: input.commandId,
3571
+ scene: input.scene,
3572
+ selectedElements: input.selectedElements,
3573
+ prompt: input.prompt,
3574
+ workspace: input.workspace
3575
+ });
3576
+ const built = buildUnsysCanvasCommandPrompt(input.commandId, context, extras);
3577
+ return {
3578
+ commandId: input.commandId,
3579
+ messages: built.messages,
3580
+ responseFormat: built.responseFormat,
3581
+ jsonSchema: built.jsonSchema,
3582
+ maxTokens: built.maxTokens,
3583
+ timeoutMs: built.timeoutMs,
3584
+ signal: input.signal,
3585
+ context
3586
+ };
3109
3587
  }
3110
- function unsysCanvasXaiFetchTimeout(kind) {
3111
- return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
3588
+ async function handleCanvasModelRequest(body, options) {
3589
+ const parsed = parseUnsysCanvasModelClientBody(body, options.extras);
3590
+ if (!parsed.ok) return parsed;
3591
+ try {
3592
+ const request = buildUnsysCanvasModelRequest({
3593
+ commandId: parsed.commandId,
3594
+ context: parsed.context,
3595
+ extras: options.extras,
3596
+ signal: options.signal
3597
+ });
3598
+ const result = await options.runModel(request);
3599
+ const text = String(result?.text ?? "");
3600
+ const reply = parseUnsysCanvasCommandResponse(parsed.commandId, text, options.extras);
3601
+ return { ok: true, ...reply };
3602
+ } catch (error) {
3603
+ const message = error instanceof Error ? error.message : "Canvas model failed";
3604
+ return { ok: false, status: 500, error: message };
3605
+ }
3606
+ }
3607
+ async function handleCanvasModelHttpRequest(req, options) {
3608
+ const body = await req.json().catch(() => null);
3609
+ const result = await handleCanvasModelRequest(body, {
3610
+ runModel: options.runModel,
3611
+ extras: options.extras,
3612
+ signal: req.signal
3613
+ });
3614
+ if (!result.ok) {
3615
+ return Response.json(
3616
+ { error: { message: result.error } },
3617
+ { status: result.status }
3618
+ );
3619
+ }
3620
+ return Response.json({
3621
+ message: result.text,
3622
+ canvasElements: result.elements,
3623
+ raw: result.raw
3624
+ });
3112
3625
  }
3113
- function unsysCanvasContextSkipChrome(el) {
3114
- const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
3115
- return part === "header" || part === "label" || part === "body";
3626
+ function choiceContent(data) {
3627
+ const choices = Array.isArray(data.choices) ? data.choices : [];
3628
+ const first = choices[0];
3629
+ if (!first || typeof first !== "object") return "";
3630
+ const message = first.message;
3631
+ const content = message?.content;
3632
+ if (typeof content === "string") return content;
3633
+ if (Array.isArray(content)) {
3634
+ return content.map((part) => part && typeof part === "object" && "text" in part ? String(part.text || "") : "").filter(Boolean).join("\n");
3635
+ }
3636
+ return "";
3116
3637
  }
3117
- function unsysCanvasCompactListing(scene, options) {
3118
- const live = serializeUnsysCanvasScene(scene).elements.filter(
3119
- (el) => !el.isDeleted && el.type !== "cursor" && !unsysCanvasContextSkipChrome(el)
3120
- );
3121
- if (!live.length) return "(no live elements)";
3122
- const cap = Math.max(1, UNSYS_CANVAS_CONTEXT_MAX_MARKS);
3123
- const shown = live.slice(0, cap);
3124
- const lines = shown.map((el) => {
3125
- const text = String(el.originalText || el.text || "").replace(/\s+/g, " ").trim().slice(0, UNSYS_CANVAS_CONTEXT_TEXT_MAX);
3126
- return text ? `[${el.type}] ${JSON.stringify(text)}` : `[${el.type}]`;
3127
- });
3128
- if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
3129
- return lines.join("\n");
3638
+ function modelSendsReasoningEffort(model) {
3639
+ const id = model.toLowerCase();
3640
+ if (!id || id.includes("non-reasoning")) return false;
3641
+ return /^grok-4\.(5|6|7)/.test(id) || id.includes("grok-4.20") && id.includes("reasoning");
3642
+ }
3643
+ function createUnsysCanvasXaiBrowserRunner(options) {
3644
+ const fetchImpl = options.fetch ?? fetch;
3645
+ return async (request) => {
3646
+ const apiKey = String(await options.getApiKey() || "").trim();
3647
+ if (!apiKey) {
3648
+ throw new Error("No API key.");
3649
+ }
3650
+ const baseURL = String(await options.getBaseUrl?.() || "").replace(/\/+$/, "") || "https://api.x.ai/v1";
3651
+ const model = typeof options.model === "function" ? options.model(request.commandId) : options.model || "grok-4.7";
3652
+ const timeout = request.timeoutMs || 6e4;
3653
+ const signal = request.signal ?? AbortSignal.timeout(timeout);
3654
+ const body = {
3655
+ model,
3656
+ messages: request.messages,
3657
+ max_tokens: request.maxTokens,
3658
+ temperature: 0.55
3659
+ };
3660
+ if (request.responseFormat === "json") {
3661
+ body.response_format = { type: "json_object" };
3662
+ } else if (request.responseFormat === "json_schema" && request.jsonSchema) {
3663
+ body.response_format = { type: "json_schema", json_schema: request.jsonSchema };
3664
+ }
3665
+ if (modelSendsReasoningEffort(model)) {
3666
+ body.reasoning_effort = options.reasoningEffort ?? "low";
3667
+ }
3668
+ const response = await fetchImpl(`${baseURL}/chat/completions`, {
3669
+ method: "POST",
3670
+ headers: {
3671
+ Authorization: `Bearer ${apiKey}`,
3672
+ "Content-Type": "application/json"
3673
+ },
3674
+ body: JSON.stringify(body),
3675
+ signal
3676
+ });
3677
+ const data = await response.json().catch(() => ({}));
3678
+ if (!response.ok) {
3679
+ const err = data.error;
3680
+ const message = typeof err === "string" ? err : err && typeof err === "object" && "message" in err ? String(err.message || "") : "";
3681
+ throw new Error(message.trim() || `Canvas model failed (${response.status})`);
3682
+ }
3683
+ const text = choiceContent(data).trim();
3684
+ if (!text) throw new Error("Canvas chat returned an empty reply.");
3685
+ return { text };
3686
+ };
3130
3687
  }
3131
- function unsysCanvasTurnContextMessage(scene, input) {
3132
- const board = String(input?.boardLabel || "CHAPTER").trim() || "CHAPTER";
3133
- const listing = unsysCanvasCompactListing(scene);
3134
- const body = `CURRENT ${board} WORK CANVAS (compact: type and text of live marks; positions omitted). Co-author this board: your reply is placed as a Work note the learner can move and edit. ${unsysCanvasXaiToolsInstruction()}
3135
- ${listing}`;
3136
- return unsysCanvasWithDomainPrefix(body, input?.workspace);
3688
+ function createUnsysCanvasModelProxyRunner(options) {
3689
+ const fetchImpl = options.fetch ?? fetch;
3690
+ return async (request) => {
3691
+ const headers = {
3692
+ "Content-Type": "application/json",
3693
+ ...options.headers ? await options.headers() : {}
3694
+ };
3695
+ const response = await fetchImpl(options.url, {
3696
+ method: "POST",
3697
+ headers,
3698
+ body: JSON.stringify({
3699
+ commandId: request.commandId,
3700
+ context: request.context
3701
+ }),
3702
+ signal: request.signal ?? AbortSignal.timeout(request.timeoutMs || 6e4)
3703
+ });
3704
+ const data = await response.json().catch(() => ({}));
3705
+ if (!response.ok) {
3706
+ const err = asRecord2(data.error);
3707
+ const message = err && typeof err.message === "string" && err.message || (typeof data.error === "string" ? data.error : "") || `Canvas model failed (${response.status})`;
3708
+ throw new Error(message);
3709
+ }
3710
+ const raw = typeof data.raw === "string" && data.raw.trim() ? data.raw : typeof data.message === "string" ? data.message : "";
3711
+ if (!raw.trim()) throw new Error("Canvas chat returned an empty reply.");
3712
+ return { text: raw };
3713
+ };
3137
3714
  }
3138
- var UNSYS_CONCEPT_LABEL_MAX = 8;
3139
- var UNSYS_CONCEPT_LABEL_MAX_CHARS = 72;
3140
- function unsysCanvasCleanConceptLabel(raw) {
3141
- return String(raw || "").replace(/^\s*(?:[-*•]+|\d+[.)])\s+/, "").replace(/\s+/g, " ").trim();
3715
+ async function runUnsysCanvasModelAsk(runModel, input) {
3716
+ const request = buildUnsysCanvasModelRequest(input);
3717
+ const result = await runModel(request);
3718
+ return parseUnsysCanvasCommandResponse(input.commandId, result.text, input.extras);
3142
3719
  }
3143
- function unsysCanvasTakeConceptLabels(items) {
3144
- const out = [];
3145
- const seen = /* @__PURE__ */ new Set();
3146
- for (const item of items) {
3147
- const label = unsysCanvasCleanConceptLabel(item);
3148
- if (label.length < 2 || label.length > UNSYS_CONCEPT_LABEL_MAX_CHARS) continue;
3149
- const key = label.toLowerCase();
3150
- if (seen.has(key)) continue;
3151
- seen.add(key);
3152
- out.push(label);
3153
- if (out.length >= UNSYS_CONCEPT_LABEL_MAX) break;
3154
- }
3155
- return out;
3720
+
3721
+ // src/lib/events.ts
3722
+ var UNSYS_CANVAS_EVENT_TYPES = [
3723
+ "element:added",
3724
+ "element:updated",
3725
+ "element:deleted",
3726
+ "element:moved",
3727
+ "element:resized",
3728
+ "text:edited",
3729
+ "selection:changed",
3730
+ "tool:changed",
3731
+ "viewport:changed",
3732
+ "command:run",
3733
+ "command:complete",
3734
+ "prompt:submit",
3735
+ "dictate:start",
3736
+ "dictate:stop",
3737
+ "dictate:text",
3738
+ "laser:gesture",
3739
+ "latex:render",
3740
+ "undo",
3741
+ "redo"
3742
+ ];
3743
+ var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
3744
+ var HIGH_FREQ = /* @__PURE__ */ new Set([
3745
+ "viewport:changed",
3746
+ "element:moved",
3747
+ "element:resized",
3748
+ "element:updated",
3749
+ "text:edited"
3750
+ ]);
3751
+ function asRecord3(value) {
3752
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
3753
+ return value;
3156
3754
  }
3157
- function unsysCanvasConceptLabels(raw, payload) {
3158
- const source = String(raw || "").trim();
3159
- const parsed = extractJsonObject(source);
3160
- const fromJson = parsed?.concepts ?? parsed?.labels;
3161
- if (Array.isArray(fromJson)) {
3162
- const labels = unsysCanvasTakeConceptLabels(fromJson.map((item) => String(item ?? "")));
3163
- if (labels.length) return labels;
3164
- }
3165
- const fromElements = unsysCanvasTakeConceptLabels(
3166
- (payload?.elements ?? []).map((el) => String(el?.label?.text || el?.text || ""))
3167
- );
3168
- if (fromElements.length) return fromElements;
3169
- const prose = stripLearnerFacingWrappers(String(payload?.text || parsed?.text || source).trim());
3170
- const lines = prose.split(/\n+/).map((line) => line.trim()).filter(Boolean);
3171
- const fromLines = unsysCanvasTakeConceptLabels(lines);
3172
- if (fromLines.length >= 2) return fromLines;
3173
- if (fromLines.length === 1 && lines.length === 1) {
3174
- const parts = fromLines[0].split(/\s*(?:,|;|•)\s+|\s+and\s+/i);
3175
- const fromParts = unsysCanvasTakeConceptLabels(parts);
3176
- if (fromParts.length >= 2) return fromParts;
3755
+ function elementMap(elements) {
3756
+ const map = /* @__PURE__ */ new Map();
3757
+ for (const el of elements) {
3758
+ if (el && typeof el.id === "string") map.set(el.id, el);
3177
3759
  }
3178
- return fromLines;
3760
+ return map;
3179
3761
  }
3180
- function compressUnsysCanvasSelection(scene, selectedElements, summary) {
3181
- const current = serializeUnsysCanvasScene(scene);
3182
- const text = unsysCanvasCommandProse(String(summary ?? ""));
3183
- const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3184
- if (!text || !liveSelected.length) return current;
3185
- const bounds = unsysCanvasContentBounds(liveSelected);
3186
- const created = unsysCanvasXaiNoteElements({
3187
- text,
3188
- x: bounds?.minX ?? TEXT_ORIGIN_X,
3189
- y: bounds?.minY ?? TEXT_ORIGIN_Y,
3190
- label: unsysCanvasNoteLabel("selective-compress"),
3191
- customData: {
3192
- [UNSYS_CANVAS_COMPRESS_WORK_CUSTOM_DATA_KEY]: true,
3193
- ileSelectiveCompression: true,
3194
- author: "xai"
3195
- }
3196
- }).elements;
3197
- if (!created.length) return current;
3198
- const remove = new Set(liveSelected.map((el) => el.id));
3199
- const kept = current.elements.filter((el) => !remove.has(el.id));
3200
- const settled = settleUnsysCanvasIncoming(
3201
- created,
3202
- kept.filter((el) => !el.isDeleted)
3203
- );
3204
- return {
3205
- ...current,
3206
- elements: [...kept, ...settled],
3207
- appState: {
3208
- ...current.appState,
3209
- selectedElementIds: {}
3762
+ function changedProps(prev, next) {
3763
+ const changed = {};
3764
+ const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
3765
+ for (const key of keys) {
3766
+ if (SKIP_KEYS.has(key)) continue;
3767
+ const from = prev?.[key];
3768
+ const to = next[key];
3769
+ if (JSON.stringify(from) !== JSON.stringify(to)) {
3770
+ changed[key] = { from, to };
3210
3771
  }
3211
- };
3772
+ }
3773
+ return changed;
3212
3774
  }
3213
- function parseUnsysCanvasLayoutEdits(raw) {
3214
- let record = null;
3215
- if (typeof raw === "string") {
3216
- record = extractJsonObject(raw);
3217
- } else if (raw && typeof raw === "object" && !Array.isArray(raw)) {
3218
- record = raw;
3775
+ function selectedIds(appState) {
3776
+ const raw = asRecord3(appState.selectedElementIds);
3777
+ return Object.keys(raw).filter((id) => raw[id]);
3778
+ }
3779
+ function zoomValue(appState) {
3780
+ const zoom = appState.zoom;
3781
+ if (zoom && typeof zoom === "object" && "value" in zoom) {
3782
+ return Number(zoom.value) || 1;
3219
3783
  }
3220
- const list = record && Array.isArray(record.elements) ? record.elements : Array.isArray(raw) ? raw : [];
3221
- const edits = [];
3222
- for (const item of list) {
3223
- if (!item || typeof item !== "object") continue;
3224
- const rec = item;
3225
- const id = typeof rec.id === "string" ? rec.id.trim() : "";
3226
- const text = typeof rec.text === "string" ? rec.text.trim() : "";
3227
- const x = Number(rec.x);
3228
- const y = Number(rec.y);
3229
- edits.push({
3230
- id,
3231
- text: text || null,
3232
- x: Number.isFinite(x) ? x : null,
3233
- y: Number.isFinite(y) ? y : null
3234
- });
3784
+ return Number(zoom) || 1;
3785
+ }
3786
+ function toolName(appState) {
3787
+ const tool = appState.activeTool;
3788
+ if (typeof tool === "string") return tool;
3789
+ if (tool && typeof tool === "object" && "type" in tool) {
3790
+ return String(tool.type || "") || null;
3235
3791
  }
3236
- return edits;
3792
+ return null;
3237
3793
  }
3238
- function unsysCanvasEditForElement(edits, el, indexAmongSelected, matchById) {
3239
- if (matchById) return edits.find((edit) => edit.id === el.id) ?? null;
3240
- return edits[indexAmongSelected] ?? null;
3794
+ function snapshot(scene) {
3795
+ const rec = asRecord3(scene);
3796
+ const elements = Array.isArray(rec.elements) ? rec.elements : [];
3797
+ return {
3798
+ elements,
3799
+ appState: asRecord3(rec.appState),
3800
+ files: asRecord3(rec.files)
3801
+ };
3241
3802
  }
3242
- function unsysCanvasLayoutReply(raw, elements) {
3243
- const source = String(raw || "");
3244
- if (parseUnsysCanvasLayoutEdits(source).length) return source;
3245
- const list = (elements ?? []).filter((el) => el && typeof el === "object");
3246
- if (list.length) return { elements: list };
3247
- return source;
3803
+ function eventKey(event) {
3804
+ const id = typeof event.payload.id === "string" ? event.payload.id : "";
3805
+ return `${event.type}:${id}`;
3248
3806
  }
3249
- function applyUnsysCanvasSuggestInsight(scene, selectedElements, suggestion) {
3250
- const current = serializeUnsysCanvasScene(scene);
3251
- const text = unsysCanvasCommandProse(String(suggestion ?? ""));
3252
- const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3253
- if (!text || !liveSelected.length) return current;
3254
- const origin = unsysCanvasEmptyNearbyOrigin({
3255
- elements: current.elements,
3256
- near: liveSelected,
3257
- box: { width: UNSYS_CANVAS_TEXT_BOX_WIDTH, height: 80 }
3258
- });
3259
- const created = unsysCanvasXaiNoteElements({
3260
- text,
3261
- x: origin.x,
3262
- y: origin.y,
3263
- label: unsysCanvasNoteLabel("suggest-insight"),
3264
- customData: {
3265
- author: "xai",
3266
- ileSuggestedInsight: true
3807
+ function mergePayload(prev, next) {
3808
+ const merged = { ...prev, ...next };
3809
+ if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
3810
+ if ("to" in next) merged.to = next.to;
3811
+ if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
3812
+ const a = prev.changed;
3813
+ const b = next.changed;
3814
+ const changed = { ...a };
3815
+ for (const [key, value] of Object.entries(b)) {
3816
+ const earlier = a[key];
3817
+ changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
3267
3818
  }
3268
- }).elements;
3269
- if (!created.length) return current;
3270
- const settled = settleUnsysCanvasIncoming(
3271
- created,
3272
- current.elements.filter((el) => !el.isDeleted)
3273
- );
3274
- return {
3275
- ...current,
3276
- elements: [...current.elements, ...settled]
3277
- };
3819
+ merged.changed = changed;
3820
+ }
3821
+ return merged;
3278
3822
  }
3279
- function unsysCanvasSceneVisiblyChanged(before, after) {
3280
- const previous = serializeUnsysCanvasScene(before).elements.filter((el) => !el.isDeleted);
3281
- const next = serializeUnsysCanvasScene(after).elements.filter((el) => !el.isDeleted);
3282
- if (previous.length !== next.length) return true;
3283
- const byId = new Map(previous.map((el) => [el.id, el]));
3284
- for (const el of next) {
3285
- const prior = byId.get(el.id);
3286
- if (!prior) return true;
3287
- if (prior.x !== el.x || prior.y !== el.y || prior.width !== el.width || prior.height !== el.height || String(prior.text || "") !== String(el.text || "") || String(prior.originalText || "") !== String(el.originalText || "")) {
3288
- return true;
3823
+ var UnsysCanvasEventCollector = class {
3824
+ constructor(options) {
3825
+ this.seq = 0;
3826
+ this.prev = null;
3827
+ this.buffer = [];
3828
+ this.lastFlush = 0;
3829
+ this.batchMs = options?.batchMs ?? 0;
3830
+ }
3831
+ reset(scene) {
3832
+ this.prev = snapshot(scene);
3833
+ this.seq = 0;
3834
+ this.buffer = [];
3835
+ this.lastFlush = 0;
3836
+ }
3837
+ syncWithoutEmit(scene) {
3838
+ this.prev = snapshot(scene);
3839
+ }
3840
+ push(type, payload) {
3841
+ this.seq += 1;
3842
+ return { seq: this.seq, ts: Date.now(), type, payload };
3843
+ }
3844
+ observeScene(scene, _opts) {
3845
+ const next = snapshot(scene);
3846
+ const prev = this.prev ?? { elements: [], appState: {}};
3847
+ const events = [];
3848
+ const prevEls = elementMap(prev.elements);
3849
+ const nextEls = elementMap(next.elements);
3850
+ for (const [id, el] of nextEls) {
3851
+ const before = prevEls.get(id);
3852
+ const deleted = Boolean(el.isDeleted);
3853
+ const wasDeleted = Boolean(before?.isDeleted);
3854
+ if (!before || wasDeleted && !deleted) {
3855
+ if (!deleted) {
3856
+ events.push(
3857
+ this.push("element:added", {
3858
+ id,
3859
+ type: el.type,
3860
+ element: el
3861
+ })
3862
+ );
3863
+ }
3864
+ continue;
3865
+ }
3866
+ if (!wasDeleted && deleted) {
3867
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
3868
+ continue;
3869
+ }
3870
+ if (deleted) continue;
3871
+ const changed = changedProps(before, el);
3872
+ if (!Object.keys(changed).length) continue;
3873
+ events.push(
3874
+ this.push("element:updated", {
3875
+ id,
3876
+ type: el.type,
3877
+ changed
3878
+ })
3879
+ );
3880
+ if ("x" in changed || "y" in changed) {
3881
+ events.push(
3882
+ this.push("element:moved", {
3883
+ id,
3884
+ type: el.type,
3885
+ from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
3886
+ to: { x: el.x, y: el.y }
3887
+ })
3888
+ );
3889
+ }
3890
+ if ("width" in changed || "height" in changed) {
3891
+ events.push(
3892
+ this.push("element:resized", {
3893
+ id,
3894
+ type: el.type,
3895
+ from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
3896
+ to: { width: el.width, height: el.height }
3897
+ })
3898
+ );
3899
+ }
3900
+ if ("text" in changed || "originalText" in changed) {
3901
+ events.push(
3902
+ this.push("text:edited", {
3903
+ id,
3904
+ type: el.type,
3905
+ from: changed.text?.from ?? changed.originalText?.from ?? before.text,
3906
+ to: el.text ?? el.originalText
3907
+ })
3908
+ );
3909
+ }
3910
+ }
3911
+ for (const [id, el] of prevEls) {
3912
+ if (nextEls.has(id)) continue;
3913
+ if (el.isDeleted) continue;
3914
+ events.push(this.push("element:deleted", { id, type: el.type, element: el }));
3915
+ }
3916
+ const prevSel = selectedIds(prev.appState);
3917
+ const nextSel = selectedIds(next.appState);
3918
+ if (prevSel.join(",") !== nextSel.join(",")) {
3919
+ events.push(this.push("selection:changed", { from: prevSel, to: nextSel }));
3920
+ }
3921
+ const prevTool = toolName(prev.appState);
3922
+ const nextTool = toolName(next.appState);
3923
+ if (prevTool !== nextTool) {
3924
+ events.push(this.push("tool:changed", { from: prevTool, to: nextTool }));
3925
+ }
3926
+ const prevView = {
3927
+ zoom: zoomValue(prev.appState),
3928
+ scrollX: Number(prev.appState.scrollX) || 0,
3929
+ scrollY: Number(prev.appState.scrollY) || 0
3930
+ };
3931
+ const nextView = {
3932
+ zoom: zoomValue(next.appState),
3933
+ scrollX: Number(next.appState.scrollX) || 0,
3934
+ scrollY: Number(next.appState.scrollY) || 0
3935
+ };
3936
+ if (prevView.zoom !== nextView.zoom || prevView.scrollX !== nextView.scrollX || prevView.scrollY !== nextView.scrollY) {
3937
+ events.push(this.push("viewport:changed", { from: prevView, to: nextView }));
3289
3938
  }
3939
+ this.prev = next;
3940
+ return this.batch(events);
3290
3941
  }
3291
- return false;
3292
- }
3293
- function unsysCanvasAskFallback(kind) {
3294
- if (!kind || kind === "ask") return "Learn more failed. Try again.";
3295
- return `${kind} failed. Try again.`;
3296
- }
3297
- function applyUnsysCanvasAskReply(input) {
3298
- const live = serializeUnsysCanvasScene(input.live);
3299
- const selected = expandUnsysCanvasCommandSelection(live, input.selectedElements);
3300
- const kind = input.kind ?? null;
3301
- const noteLabel = unsysCanvasNoteLabel(kind);
3302
- const source = kind && kind !== "ask" ? String(input.payload.raw || "") : String(input.payload.text || "");
3303
- const layoutReply = unsysCanvasLayoutReply(input.payload.raw, input.payload.elements);
3304
- const merge = (text, extra) => mergeUnsysCanvasTurnOntoLiveWorkCanvas(
3305
- live,
3306
- {
3307
- text,
3308
- elements: input.payload.elements,
3309
- turnId: input.payload.turnId,
3310
- origin: input.payload.origin,
3311
- label: noteLabel
3312
- },
3313
- {
3314
- fallbackOrigin: input.fallbackOrigin,
3315
- reserved: input.reserved
3942
+ command(id, meta) {
3943
+ const rec = asRecord3(meta);
3944
+ const inputs = asRecord3(rec.inputs);
3945
+ const selected = Array.isArray(rec.selectedElements) ? rec.selectedElements : [];
3946
+ const selectedElementIds = Array.isArray(inputs.selectedElementIds) ? inputs.selectedElementIds : selected.map((el) => el && typeof el === "object" && "id" in el ? String(el.id || "") : "").filter(Boolean);
3947
+ const prompt = typeof inputs.prompt === "string" ? inputs.prompt : typeof rec.prompt === "string" ? rec.prompt : void 0;
3948
+ const eventInputs = prompt ? { selectedElementIds, prompt } : { selectedElementIds };
3949
+ return [
3950
+ this.push("command:run", {
3951
+ id: id ?? null,
3952
+ args: rec,
3953
+ inputs: eventInputs,
3954
+ outputs: rec.outputs ?? null
3955
+ })
3956
+ ];
3957
+ }
3958
+ commandComplete(id, meta) {
3959
+ const rec = asRecord3(meta);
3960
+ return [
3961
+ this.push("command:complete", {
3962
+ id: id ?? null,
3963
+ inputs: rec.inputs ?? {},
3964
+ outputs: rec.outputs ?? {}
3965
+ })
3966
+ ];
3967
+ }
3968
+ dictate(meta) {
3969
+ const rec = asRecord3(meta);
3970
+ const type = rec.phase === "start" ? "dictate:start" : rec.phase === "stop" ? "dictate:stop" : "dictate:text";
3971
+ return [this.push(type, rec)];
3972
+ }
3973
+ prompt(text, meta) {
3974
+ return [this.push("prompt:submit", { text: text ?? "", ...asRecord3(meta) })];
3975
+ }
3976
+ laser(meta) {
3977
+ return [this.push("laser:gesture", asRecord3(meta))];
3978
+ }
3979
+ latex(meta) {
3980
+ return [this.push("latex:render", asRecord3(meta))];
3981
+ }
3982
+ history(kind, meta) {
3983
+ return [this.push(kind, asRecord3(meta))];
3984
+ }
3985
+ markGestureBusy(_busy) {
3986
+ }
3987
+ batch(incoming) {
3988
+ const now = Date.now();
3989
+ if (!this.buffer.length) this.lastFlush = now;
3990
+ for (const event of incoming) {
3991
+ const last = this.buffer[this.buffer.length - 1];
3992
+ if (last && HIGH_FREQ.has(event.type) && eventKey(last) === eventKey(event)) {
3993
+ this.buffer[this.buffer.length - 1] = {
3994
+ ...event,
3995
+ seq: last.seq,
3996
+ ts: last.ts,
3997
+ payload: mergePayload(last.payload, event.payload)
3998
+ };
3999
+ } else {
4000
+ this.buffer.push(event);
4001
+ }
3316
4002
  }
3317
- );
3318
- let next = live;
3319
- if (kind === "selective-compress") {
3320
- next = compressUnsysCanvasSelection(live, selected, source);
3321
- } else if (kind === "refactor") {
3322
- next = replaceUnsysCanvasSelection(live, selected, {
3323
- text: input.payload.text,
3324
- elements: input.payload.elements,
3325
- turnId: input.payload.turnId,
3326
- label: noteLabel
3327
- });
3328
- } else if (kind === "simplify") {
3329
- const text = stripLearnerFacingWrappers(String(input.payload.text || "").trim());
3330
- if (text) {
3331
- next = fanUnsysCanvasLabeledNodes(live, selected, [text], "ileSimplify").scene;
4003
+ if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
4004
+ return [];
3332
4005
  }
3333
- } else if (kind === "concepts") {
3334
- const labels = unsysCanvasConceptLabels(source, {
3335
- text: input.payload.text,
3336
- elements: input.payload.elements
3337
- });
3338
- next = fanUnsysCanvasLabeledNodes(live, selected, labels, "ileConcepts").scene;
3339
- } else if (kind === "suggest-insight") {
3340
- next = applyUnsysCanvasSuggestInsight(live, selected, source);
3341
- } else if (kind === "declutter" || kind === "clear-overlaps") {
3342
- next = applyUnsysCanvasPositionEdits(live, selected, layoutReply);
3343
- } else {
3344
- next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
4006
+ const flushed = this.buffer;
4007
+ this.buffer = [];
4008
+ this.lastFlush = now;
4009
+ return flushed;
3345
4010
  }
3346
- if (unsysCanvasSceneVisiblyChanged(live, next)) return withUnsysCanvasAutoLayout(next);
3347
- const fallback = stripLearnerFacingWrappers(String(input.payload.text || "").trim()) || unsysCanvasAskFallback(kind);
3348
- return withUnsysCanvasAutoLayout(merge(fallback));
3349
- }
3350
- function applyUnsysCanvasPositionEdits(scene, selectedElements, reply) {
3351
- const current = serializeUnsysCanvasScene(scene);
3352
- const liveSelected = unsysCanvasSelectedLive(current, selectedElements);
3353
- if (!liveSelected.length) return current;
3354
- const edits = parseUnsysCanvasLayoutEdits(reply);
3355
- if (!edits.length) return current;
3356
- const selectedIds2 = new Set(liveSelected.map((el) => el.id));
3357
- const matchById = edits.some((edit) => edit.id && selectedIds2.has(edit.id));
3358
- let ordinal = 0;
3359
- return {
3360
- ...current,
3361
- elements: current.elements.map((el) => {
3362
- if (!selectedIds2.has(el.id) || el.isDeleted) return el;
3363
- const edit = unsysCanvasEditForElement(edits, el, ordinal, matchById);
3364
- ordinal += 1;
3365
- if (!edit || edit.x == null && edit.y == null) return el;
3366
- return {
3367
- ...el,
3368
- x: edit.x == null ? el.x : edit.x,
3369
- y: edit.y == null ? el.y : edit.y,
3370
- version: (Number(el.version) || 1) + 1
3371
- };
3372
- })
3373
- };
3374
- }
4011
+ flush() {
4012
+ const flushed = this.buffer;
4013
+ this.buffer = [];
4014
+ this.lastFlush = Date.now();
4015
+ return flushed;
4016
+ }
4017
+ };
3375
4018
 
3376
4019
  // src/lib/work-canvas/work-canvas-url.ts
3377
4020
  var UNSYS_CANVAS_HASH_PREFIX = "tc1.";
@@ -3586,7 +4229,427 @@ function assertOnAsk(onAsk) {
3586
4229
  throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
3587
4230
  }
3588
4231
  }
4232
+ function assertCanvasModel(input) {
4233
+ if (typeof input.runModel === "function" || typeof input.onAsk === "function") return;
4234
+ throw new Error("UnsysCanvas requires a runModel or onAsk handler; the package does not call any LLM.");
4235
+ }
4236
+
4237
+ // src/lib/collaboration/collab-url.ts
4238
+ var UNSYS_CANVAS_COLLAB_HASH_PREFIX = "uc1.";
4239
+ var ROOM_ID_BYTES = 12;
4240
+ var KEY_BYTES = 32;
4241
+ function bytesToUnsysCanvasCollabB64(bytes) {
4242
+ const chunk = 8192;
4243
+ let binary = "";
4244
+ for (let i = 0; i < bytes.length; i += chunk) {
4245
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
4246
+ }
4247
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
4248
+ }
4249
+ function unsysCanvasCollabB64ToBytes(value) {
4250
+ const trimmed = String(value || "").trim();
4251
+ if (!trimmed || /[^A-Za-z0-9_-]/.test(trimmed)) return null;
4252
+ try {
4253
+ const padded = trimmed.replace(/-/g, "+").replace(/_/g, "/");
4254
+ const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
4255
+ const binary = atob(padded + pad);
4256
+ const bytes = new Uint8Array(binary.length);
4257
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
4258
+ return bytes;
4259
+ } catch {
4260
+ return null;
4261
+ }
4262
+ }
4263
+ function generateUnsysCanvasCollabRoomId() {
4264
+ const bytes = new Uint8Array(ROOM_ID_BYTES);
4265
+ crypto.getRandomValues(bytes);
4266
+ return bytesToUnsysCanvasCollabB64(bytes);
4267
+ }
4268
+ function generateUnsysCanvasCollabKey() {
4269
+ const bytes = new Uint8Array(KEY_BYTES);
4270
+ crypto.getRandomValues(bytes);
4271
+ return bytesToUnsysCanvasCollabB64(bytes);
4272
+ }
4273
+ function generateUnsysCanvasCollabRoom() {
4274
+ return {
4275
+ roomId: generateUnsysCanvasCollabRoomId(),
4276
+ key: generateUnsysCanvasCollabKey()
4277
+ };
4278
+ }
4279
+ function buildUnsysCanvasCollabHash(room) {
4280
+ const roomId = String(room.roomId || "").trim();
4281
+ const key = String(room.key || "").trim();
4282
+ if (!roomId || !key) return "";
4283
+ return `#${UNSYS_CANVAS_COLLAB_HASH_PREFIX}${roomId}.${key}`;
4284
+ }
4285
+ function parseUnsysCanvasCollabHash(hash) {
4286
+ const raw = String(hash || "").trim();
4287
+ const body = raw.startsWith("#") ? raw.slice(1) : raw;
4288
+ if (!body.startsWith(UNSYS_CANVAS_COLLAB_HASH_PREFIX)) return null;
4289
+ const rest = body.slice(UNSYS_CANVAS_COLLAB_HASH_PREFIX.length);
4290
+ const dot = rest.indexOf(".");
4291
+ if (dot <= 0 || dot === rest.length - 1) return null;
4292
+ const roomId = rest.slice(0, dot);
4293
+ const key = rest.slice(dot + 1);
4294
+ if (!unsysCanvasCollabB64ToBytes(roomId) || !unsysCanvasCollabB64ToBytes(key)) return null;
4295
+ const keyBytes = unsysCanvasCollabB64ToBytes(key);
4296
+ if (!keyBytes || keyBytes.byteLength < 16) return null;
4297
+ return { roomId, key };
4298
+ }
4299
+ function isUnsysCanvasCollabHash(hash) {
4300
+ return parseUnsysCanvasCollabHash(hash) !== null;
4301
+ }
4302
+ function readUnsysCanvasCollabHashFromLocation(hash = typeof window === "undefined" ? "" : window.location.hash) {
4303
+ return parseUnsysCanvasCollabHash(hash);
4304
+ }
4305
+ function replaceUnsysCanvasCollabLocationHash(room) {
4306
+ const next = buildUnsysCanvasCollabHash(room);
4307
+ replaceUnsysCanvasLocationHash(next);
4308
+ return next;
4309
+ }
4310
+ function buildUnsysCanvasCollabShareUrl(room, href = typeof window === "undefined" ? "" : window.location.href) {
4311
+ const url = String(href || "");
4312
+ const hash = buildUnsysCanvasCollabHash(room);
4313
+ const hashAt = url.indexOf("#");
4314
+ const base = hashAt >= 0 ? url.slice(0, hashAt) : url;
4315
+ return `${base}${hash}`;
4316
+ }
4317
+
4318
+ // src/lib/collaboration/collab-reconcile.ts
4319
+ function versionOf(el) {
4320
+ return Number(el?.version) || 0;
4321
+ }
4322
+ function versionNonceOf(el) {
4323
+ return Number(el?.versionNonce) || 0;
4324
+ }
4325
+ function shouldDiscardRemoteUnsysCanvasElement(local, remote, editingIds) {
4326
+ if (editingIds?.has(remote.id)) return true;
4327
+ if (!local) return false;
4328
+ if (editingIds?.has(local.id)) return true;
4329
+ if (versionOf(local) > versionOf(remote)) return true;
4330
+ if (versionOf(local) === versionOf(remote) && versionNonceOf(local) < versionNonceOf(remote)) {
4331
+ return true;
4332
+ }
4333
+ return false;
4334
+ }
4335
+ function reconcileUnsysCanvasElements(local, remote, options) {
4336
+ const localList = Array.isArray(local) ? local.filter((el) => el && typeof el.id === "string") : [];
4337
+ const remoteList = Array.isArray(remote) ? remote.filter((el) => el && typeof el.id === "string") : [];
4338
+ const editingIds = options?.editingIds ? new Set(options.editingIds) : null;
4339
+ const localMap = new Map(localList.map((el) => [el.id, el]));
4340
+ const added = /* @__PURE__ */ new Set();
4341
+ const next = [];
4342
+ for (const remoteEl of remoteList) {
4343
+ const localEl = localMap.get(remoteEl.id);
4344
+ if (shouldDiscardRemoteUnsysCanvasElement(localEl, remoteEl, editingIds)) {
4345
+ if (localEl && !added.has(localEl.id)) {
4346
+ next.push(localEl);
4347
+ added.add(localEl.id);
4348
+ }
4349
+ continue;
4350
+ }
4351
+ next.push(remoteEl);
4352
+ added.add(remoteEl.id);
4353
+ }
4354
+ for (const localEl of localList) {
4355
+ if (added.has(localEl.id)) continue;
4356
+ next.push(localEl);
4357
+ added.add(localEl.id);
4358
+ }
4359
+ return next;
4360
+ }
4361
+ function reconcileUnsysCanvasFiles(local, remote) {
4362
+ return { ...local ?? {}, ...remote ?? {} };
4363
+ }
4364
+ function reconcileUnsysCanvasScene(local, remote, options) {
4365
+ return {
4366
+ elements: reconcileUnsysCanvasElements(local?.elements, remote?.elements, options),
4367
+ files: reconcileUnsysCanvasFiles(local?.files, remote?.files ?? {})
4368
+ };
4369
+ }
4370
+
4371
+ // src/lib/collaboration/collab-crypto.ts
4372
+ var IV_BYTES = 12;
4373
+ var MAGIC = 1;
4374
+ function subtle() {
4375
+ const api = globalThis.crypto?.subtle;
4376
+ if (!api) throw new Error("Web Crypto is required for board collaboration.");
4377
+ return api;
4378
+ }
4379
+ async function importUnsysCanvasCollabCryptoKey(keyB64) {
4380
+ const raw = unsysCanvasCollabB64ToBytes(keyB64);
4381
+ if (!raw || raw.byteLength < 16) throw new Error("Invalid collaboration key.");
4382
+ const material = raw.byteLength === 16 || raw.byteLength === 32 ? raw : raw.slice(0, 32);
4383
+ return subtle().importKey("raw", toBuffer(material), "AES-GCM", false, ["encrypt", "decrypt"]);
4384
+ }
4385
+ async function encryptUnsysCanvasCollabBytes(keyB64, plaintext) {
4386
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
4387
+ const iv = new Uint8Array(IV_BYTES);
4388
+ globalThis.crypto.getRandomValues(iv);
4389
+ const cipher = new Uint8Array(
4390
+ await subtle().encrypt({ name: "AES-GCM", iv }, cryptoKey, toBuffer(plaintext))
4391
+ );
4392
+ const packed = new Uint8Array(1 + iv.byteLength + cipher.byteLength);
4393
+ packed[0] = MAGIC;
4394
+ packed.set(iv, 1);
4395
+ packed.set(cipher, 1 + iv.byteLength);
4396
+ return packed;
4397
+ }
4398
+ async function decryptUnsysCanvasCollabBytes(keyB64, packed) {
4399
+ if (!packed.byteLength || packed[0] !== MAGIC) throw new Error("Unknown collaboration payload.");
4400
+ if (packed.byteLength < 1 + IV_BYTES + 16) throw new Error("Truncated collaboration payload.");
4401
+ const iv = packed.subarray(1, 1 + IV_BYTES);
4402
+ const cipher = packed.subarray(1 + IV_BYTES);
4403
+ const cryptoKey = await importUnsysCanvasCollabCryptoKey(keyB64);
4404
+ const plain = await subtle().decrypt({ name: "AES-GCM", iv: toBuffer(iv) }, cryptoKey, toBuffer(cipher));
4405
+ return new Uint8Array(plain);
4406
+ }
4407
+ async function encryptUnsysCanvasCollabJson(keyB64, value) {
4408
+ return encryptUnsysCanvasCollabBytes(keyB64, new TextEncoder().encode(JSON.stringify(value)));
4409
+ }
4410
+ async function decryptUnsysCanvasCollabJson(keyB64, packed) {
4411
+ const bytes = await decryptUnsysCanvasCollabBytes(keyB64, packed);
4412
+ return JSON.parse(new TextDecoder().decode(bytes));
4413
+ }
4414
+ function toBuffer(bytes) {
4415
+ const copy = new Uint8Array(bytes.byteLength);
4416
+ copy.set(bytes);
4417
+ return copy.buffer;
4418
+ }
4419
+
4420
+ // src/lib/collaboration/collab-session.ts
4421
+ function isPlainMessage(value) {
4422
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4423
+ const rec = value;
4424
+ if (rec.v !== 1 || typeof rec.from !== "string" || !rec.from) return false;
4425
+ if (rec.type !== "hello" && rec.type !== "scene" && rec.type !== "pointer") return false;
4426
+ return true;
4427
+ }
4428
+ function collaboratorFromUser(user, extra) {
4429
+ return {
4430
+ id: user.id,
4431
+ username: user.name,
4432
+ color: user.color,
4433
+ userState: "active",
4434
+ ...extra
4435
+ };
4436
+ }
4437
+ var UnsysCanvasCollabSession = class {
4438
+ constructor(options) {
4439
+ this.socket = null;
4440
+ this.collaborators = /* @__PURE__ */ new Map();
4441
+ this.closed = false;
4442
+ this.roomId = options.roomId;
4443
+ this.key = options.key;
4444
+ this.user = options.user;
4445
+ this.transport = options.transport;
4446
+ this.handlers = options.handlers ?? {};
4447
+ this.getLocalScene = options.getLocalScene;
4448
+ this.getEditingIds = options.getEditingIds;
4449
+ }
4450
+ start() {
4451
+ if (this.socket || this.closed) return;
4452
+ this.socket = this.transport.open(this.roomId, {
4453
+ onOpen: () => {
4454
+ void this.sendHello();
4455
+ this.handlers.onOpen?.();
4456
+ },
4457
+ onMessage: (bytes) => {
4458
+ void this.handleBytes(bytes);
4459
+ },
4460
+ onClose: () => {
4461
+ this.handlers.onClose?.();
4462
+ },
4463
+ onError: (error) => {
4464
+ this.handlers.onError?.(error);
4465
+ }
4466
+ });
4467
+ }
4468
+ close() {
4469
+ this.closed = true;
4470
+ this.socket?.close();
4471
+ this.socket = null;
4472
+ this.collaborators = /* @__PURE__ */ new Map();
4473
+ this.emitCollaborators();
4474
+ }
4475
+ async broadcastScene(scene) {
4476
+ await this.send({
4477
+ v: 1,
4478
+ from: this.user.id,
4479
+ type: "scene",
4480
+ user: this.user,
4481
+ scene: {
4482
+ elements: scene.elements ?? [],
4483
+ files: scene.files ?? {}
4484
+ }
4485
+ });
4486
+ }
4487
+ async broadcastPointer(pointer) {
4488
+ await this.send({
4489
+ v: 1,
4490
+ from: this.user.id,
4491
+ type: "pointer",
4492
+ user: this.user,
4493
+ pointer
4494
+ });
4495
+ }
4496
+ async sendHello() {
4497
+ await this.send({ v: 1, from: this.user.id, type: "hello", user: this.user });
4498
+ const scene = this.getLocalScene?.();
4499
+ if (scene?.elements?.length) await this.broadcastScene(scene);
4500
+ }
4501
+ async send(message) {
4502
+ if (!this.socket || this.closed) return;
4503
+ try {
4504
+ const packed = await encryptUnsysCanvasCollabJson(this.key, message);
4505
+ this.socket.send(packed);
4506
+ } catch (error) {
4507
+ this.handlers.onError?.(error);
4508
+ }
4509
+ }
4510
+ async handleBytes(bytes) {
4511
+ if (this.closed) return;
4512
+ let parsed;
4513
+ try {
4514
+ parsed = await decryptUnsysCanvasCollabJson(this.key, bytes);
4515
+ } catch {
4516
+ return;
4517
+ }
4518
+ if (!isPlainMessage(parsed) || parsed.from === this.user.id) return;
4519
+ this.touchCollaborator(parsed);
4520
+ if (parsed.type === "hello") {
4521
+ const scene = this.getLocalScene?.();
4522
+ if (scene) await this.broadcastScene(scene);
4523
+ return;
4524
+ }
4525
+ if (parsed.type === "pointer") {
4526
+ this.collaborators.set(
4527
+ parsed.from,
4528
+ collaboratorFromUser(parsed.user, {
4529
+ pointer: parsed.pointer.pointer,
4530
+ button: parsed.pointer.button,
4531
+ selectedElementIds: parsed.pointer.selectedElementIds
4532
+ })
4533
+ );
4534
+ this.emitCollaborators();
4535
+ return;
4536
+ }
4537
+ if (parsed.type === "scene") {
4538
+ const local = this.getLocalScene?.() ?? { elements: [], files: {} };
4539
+ const remote = {
4540
+ elements: parsed.scene.elements ?? [],
4541
+ files: parsed.scene.files ?? {}
4542
+ };
4543
+ const merged = reconcileUnsysCanvasScene(local, remote, {
4544
+ editingIds: this.getEditingIds?.() ?? null
4545
+ });
4546
+ this.handlers.onRemoteScene?.(merged, parsed.user);
4547
+ }
4548
+ }
4549
+ touchCollaborator(message) {
4550
+ const prev = this.collaborators.get(message.from);
4551
+ this.collaborators.set(message.from, {
4552
+ ...collaboratorFromUser(message.user),
4553
+ pointer: prev?.pointer,
4554
+ button: prev?.button,
4555
+ selectedElementIds: prev?.selectedElementIds
4556
+ });
4557
+ this.emitCollaborators();
4558
+ }
4559
+ emitCollaborators() {
4560
+ this.handlers.onCollaborators?.(new Map(this.collaborators));
4561
+ }
4562
+ };
4563
+
4564
+ // src/lib/collaboration/memory-transport.ts
4565
+ function createUnsysCanvasMemoryTransportHub() {
4566
+ const peers = /* @__PURE__ */ new Map();
4567
+ let nextId = 1;
4568
+ const createTransport = () => ({
4569
+ open(roomId, handlers) {
4570
+ const id = nextId;
4571
+ nextId += 1;
4572
+ const peer = { id, roomId, handlers };
4573
+ peers.set(id, peer);
4574
+ queueMicrotask(() => {
4575
+ if (peers.get(id) === peer) handlers.onOpen?.();
4576
+ });
4577
+ return {
4578
+ send(bytes) {
4579
+ const copy = new Uint8Array(bytes);
4580
+ for (const other of peers.values()) {
4581
+ if (other.id === id || other.roomId !== roomId) continue;
4582
+ other.handlers.onMessage(copy);
4583
+ }
4584
+ },
4585
+ close() {
4586
+ peers.delete(id);
4587
+ handlers.onClose?.();
4588
+ }
4589
+ };
4590
+ }
4591
+ });
4592
+ return { createTransport };
4593
+ }
4594
+
4595
+ // src/lib/collaboration/websocket-transport.ts
4596
+ function asBytes(data) {
4597
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
4598
+ if (data instanceof Uint8Array) return data;
4599
+ if (typeof Blob !== "undefined" && data instanceof Blob) return null;
4600
+ return null;
4601
+ }
4602
+ function createUnsysCanvasWebsocketTransport(options) {
4603
+ const url = String(options.url || "").trim();
4604
+ return {
4605
+ open(roomId, handlers) {
4606
+ if (!url || typeof WebSocket === "undefined") {
4607
+ queueMicrotask(() => handlers.onError?.(new Error("Collaboration relay URL is missing.")));
4608
+ return { send() {
4609
+ }, close() {
4610
+ } };
4611
+ }
4612
+ const ws = new WebSocket(url);
4613
+ ws.binaryType = "arraybuffer";
4614
+ let opened = false;
4615
+ ws.onopen = () => {
4616
+ opened = true;
4617
+ ws.send(JSON.stringify({ type: "join", roomId }));
4618
+ handlers.onOpen?.();
4619
+ };
4620
+ ws.onmessage = (event) => {
4621
+ if (typeof event.data === "string") return;
4622
+ const bytes = asBytes(event.data);
4623
+ if (bytes) handlers.onMessage(bytes);
4624
+ };
4625
+ ws.onerror = () => {
4626
+ handlers.onError?.(new Error("Collaboration relay error."));
4627
+ };
4628
+ ws.onclose = () => {
4629
+ if (opened) handlers.onClose?.();
4630
+ };
4631
+ return {
4632
+ send(bytes) {
4633
+ if (ws.readyState !== WebSocket.OPEN) return;
4634
+ const copy = new Uint8Array(bytes.byteLength);
4635
+ copy.set(bytes);
4636
+ ws.send(copy);
4637
+ },
4638
+ close() {
4639
+ try {
4640
+ ws.close();
4641
+ } catch {
4642
+ }
4643
+ }
4644
+ };
4645
+ }
4646
+ };
4647
+ }
4648
+ function isUnsysCanvasRelayUrl(value) {
4649
+ const url = String(value || "").trim();
4650
+ return url.startsWith("ws://") || url.startsWith("wss://");
4651
+ }
3589
4652
 
3590
- export { DEFAULT_UNSYS_CANVAS_BOARD_STYLE, DEFAULT_UNSYS_CANVAS_STYLE_TOKENS, EMPTY_UNSYS_CANVAS_STYLE, UNSYS_CANVAS_COMMANDS, UNSYS_CANVAS_EVENT_TYPES, UNSYS_CANVAS_HASH_PREFIX, UnsysCanvasEventCollector, applyUnsysCanvasAskReply, assertOnAsk, buildUnsysCanvasCommandUserMessage, convertToExcalidrawElements, decodeUnsysCanvasHash, emptyUnsysCanvasScene, encodeUnsysCanvasHash, normalizeUnsysCanvasLinearElement, parseUnsysCanvasAskReply, parseUnsysCanvasStyle, readUnsysCanvasHashFromLocation, replaceUnsysCanvasLocationHash, runUnsysCanvasCommand, serializeUnsysCanvasScene, unsysCanvasAskFromSessionChat, unsysCanvasCommandsFor, unsysCanvasHasLiveElements, unsysCanvasSidebarStyleCssVars, unsysCanvasTurnContextMessage, unsysCanvasXaiFetchTimeout, unsysCanvasXaiMaxTokens, unsysCanvasXaiNeedsBoardContext };
4653
+ export { DEFAULT_UNSYS_CANVAS_BOARD_STYLE, DEFAULT_UNSYS_CANVAS_STYLE_TOKENS, EMPTY_UNSYS_CANVAS_STYLE, UNSYS_CANVAS_COLLAB_HASH_PREFIX, UNSYS_CANVAS_COMMANDS, UNSYS_CANVAS_COMMAND_SYSTEM_PROMPT, UNSYS_CANVAS_EVENT_TYPES, UNSYS_CANVAS_HASH_PREFIX, UnsysCanvasCollabSession, UnsysCanvasEventCollector, applyUnsysCanvasAskReply, assertCanvasModel, assertOnAsk, buildUnsysCanvasCollabHash, buildUnsysCanvasCollabShareUrl, buildUnsysCanvasCommandPrompt, buildUnsysCanvasCommandUserMessage, buildUnsysCanvasModelRequest, convertToExcalidrawElements, createUnsysCanvasMemoryTransportHub, createUnsysCanvasModelProxyRunner, createUnsysCanvasWebsocketTransport, createUnsysCanvasXaiBrowserRunner, decodeUnsysCanvasHash, decryptUnsysCanvasCollabJson, emptyUnsysCanvasScene, encodeUnsysCanvasHash, encryptUnsysCanvasCollabJson, extractUnsysCanvasCommandContext, generateUnsysCanvasCollabRoom, getUnsysCanvasCommand, handleCanvasModelHttpRequest, handleCanvasModelRequest, isUnsysCanvasCollabHash, isUnsysCanvasKnownCommandId, isUnsysCanvasRelayUrl, listUnsysCanvasCommandDefinitions, normalizeUnsysCanvasLinearElement, parseUnsysCanvasAskReply, parseUnsysCanvasCollabHash, parseUnsysCanvasCommandResponse, parseUnsysCanvasModelClientBody, parseUnsysCanvasStyle, readUnsysCanvasCollabHashFromLocation, readUnsysCanvasHashFromLocation, reconcileUnsysCanvasElements, reconcileUnsysCanvasFiles, reconcileUnsysCanvasScene, replaceUnsysCanvasCollabLocationHash, replaceUnsysCanvasLocationHash, runUnsysCanvasCommand, runUnsysCanvasModelAsk, serializeUnsysCanvasScene, unsysCanvasAskFromSessionChat, unsysCanvasCommandPlacement, unsysCanvasCommandsFor, unsysCanvasGestureCommandId, unsysCanvasHasLiveElements, unsysCanvasSidebarStyleCssVars, unsysCanvasTurnContextMessage, unsysCanvasXaiFetchTimeout, unsysCanvasXaiMaxTokens, unsysCanvasXaiNeedsBoardContext };
3591
4654
  //# sourceMappingURL=core.js.map
3592
4655
  //# sourceMappingURL=core.js.map