unsys-canvas 0.1.1 → 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/README.md +14 -5
- package/dist/core.d.ts +367 -7
- package/dist/core.js +1587 -511
- package/dist/core.js.map +1 -1
- package/dist/index.d.ts +386 -14
- package/dist/index.js +2606 -618
- package/dist/index.js.map +1 -1
- package/dist/styles.css +106 -0
- package/package.json +1 -1
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":
|
|
@@ -2374,17 +2393,21 @@ var UNSYS_CANVAS_COMMANDS = [
|
|
|
2374
2393
|
{
|
|
2375
2394
|
id: "simplify",
|
|
2376
2395
|
label: "Simplify",
|
|
2377
|
-
tooltip: "
|
|
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
|
-
replacesSelection:
|
|
2402
|
+
replacesSelection: false
|
|
2382
2403
|
},
|
|
2383
2404
|
{
|
|
2384
2405
|
id: "breakdown",
|
|
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 = []) {
|
|
@@ -2432,8 +2472,10 @@ function unsysCanvasCommandsFor(_guide, extras = []) {
|
|
|
2432
2472
|
shortcut: extra.shortcut ?? "",
|
|
2433
2473
|
needsSelection: extra.needsSelection ?? false,
|
|
2434
2474
|
boardOnly: false,
|
|
2435
|
-
replacesSelection:
|
|
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
|
}
|
|
@@ -2533,6 +2575,12 @@ function unsysCanvasBindFanArrow(arrow, start, end, hostBounds) {
|
|
|
2533
2575
|
{ id: arrow.id, type: "arrow" }
|
|
2534
2576
|
];
|
|
2535
2577
|
}
|
|
2578
|
+
function unsysCanvasFanNoteKind(mark) {
|
|
2579
|
+
if (mark === "ileConcepts") return "concepts";
|
|
2580
|
+
if (mark === "ileSimplify") return "simplify";
|
|
2581
|
+
if (mark === "ilePretty") return "pretty";
|
|
2582
|
+
return "breakdown";
|
|
2583
|
+
}
|
|
2536
2584
|
function unsysCanvasFanStem(host, hostRect, end, toX, toY, mark, hostBounds) {
|
|
2537
2585
|
const startX = hostRect.maxX;
|
|
2538
2586
|
const startY = (hostRect.minY + hostRect.maxY) / 2;
|
|
@@ -2637,7 +2685,7 @@ function fanUnsysCanvasLabeledNodes(scene, selectedElements, chunks, mark) {
|
|
|
2637
2685
|
x: hostRect.maxX + gapX,
|
|
2638
2686
|
y: cursorY,
|
|
2639
2687
|
width: innerWidth,
|
|
2640
|
-
label: unsysCanvasNoteLabel(mark
|
|
2688
|
+
label: unsysCanvasNoteLabel(unsysCanvasFanNoteKind(mark)),
|
|
2641
2689
|
customData: { [mark]: true }
|
|
2642
2690
|
});
|
|
2643
2691
|
created.push(...note.elements);
|
|
@@ -2690,6 +2738,80 @@ function fanUnsysCanvasLabeledNodes(scene, selectedElements, chunks, mark) {
|
|
|
2690
2738
|
parts
|
|
2691
2739
|
};
|
|
2692
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
|
+
}
|
|
2693
2815
|
function breakdownUnsysCanvasSelection(scene, selectedElements) {
|
|
2694
2816
|
const current = serializeUnsysCanvasScene(scene);
|
|
2695
2817
|
const expanded = expandUnsysCanvasCommandSelection(current, selectedElements);
|
|
@@ -2706,6 +2828,7 @@ function unsysCanvasCommandPrompt(action) {
|
|
|
2706
2828
|
if (action === "draw") return "Do/run";
|
|
2707
2829
|
if (action === "breakdown") return "Subdivide";
|
|
2708
2830
|
if (action === "concepts") return "Concepts";
|
|
2831
|
+
if (action === "pretty") return "Pretty";
|
|
2709
2832
|
return action;
|
|
2710
2833
|
}
|
|
2711
2834
|
function removeUnsysCanvasSelection(scene, selectedElements) {
|
|
@@ -2786,7 +2909,7 @@ function runUnsysCanvasCommand(input) {
|
|
|
2786
2909
|
target ? "Need at least two words to subdivide." : "Select text, or a labeled shape, to subdivide."
|
|
2787
2910
|
);
|
|
2788
2911
|
}
|
|
2789
|
-
if (input.action === "
|
|
2912
|
+
if (input.action === "refactor") {
|
|
2790
2913
|
const stripped = removeUnsysCanvasSelection(current, selected);
|
|
2791
2914
|
return {
|
|
2792
2915
|
scene: withUnsysCanvasAutoLayout(stripped.scene),
|
|
@@ -2794,571 +2917,1104 @@ function runUnsysCanvasCommand(input) {
|
|
|
2794
2917
|
parts: [],
|
|
2795
2918
|
selected,
|
|
2796
2919
|
prompt,
|
|
2797
|
-
ask: { kind:
|
|
2920
|
+
ask: { kind: "refactor", prompt },
|
|
2798
2921
|
notice: null
|
|
2799
2922
|
};
|
|
2800
2923
|
}
|
|
2924
|
+
if (input.action === "simplify") {
|
|
2925
|
+
return idle(null, { kind: "simplify", prompt });
|
|
2926
|
+
}
|
|
2801
2927
|
if (input.action === "concepts") {
|
|
2802
2928
|
return idle(null, { kind: "concepts", prompt });
|
|
2803
2929
|
}
|
|
2804
2930
|
if (input.action === "draw") {
|
|
2805
2931
|
return idle(null, { kind: "draw", prompt });
|
|
2806
2932
|
}
|
|
2933
|
+
if (input.action === "pretty") {
|
|
2934
|
+
return idle(null, { kind: "pretty", prompt });
|
|
2935
|
+
}
|
|
2807
2936
|
return idle(null);
|
|
2808
2937
|
}
|
|
2809
2938
|
|
|
2810
|
-
// src/lib/
|
|
2811
|
-
var
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
"
|
|
2815
|
-
"element:moved",
|
|
2816
|
-
"element:resized",
|
|
2817
|
-
"text:edited",
|
|
2818
|
-
"selection:changed",
|
|
2819
|
-
"tool:changed",
|
|
2820
|
-
"viewport:changed",
|
|
2821
|
-
"command:run",
|
|
2822
|
-
"prompt:submit",
|
|
2823
|
-
"dictate:start",
|
|
2824
|
-
"dictate:stop",
|
|
2825
|
-
"dictate:text",
|
|
2826
|
-
"laser:gesture",
|
|
2827
|
-
"latex:render",
|
|
2828
|
-
"undo",
|
|
2829
|
-
"redo"
|
|
2830
|
-
];
|
|
2831
|
-
var SKIP_KEYS = /* @__PURE__ */ new Set(["versionNonce", "updated", "seed", "index", "boundElements"]);
|
|
2832
|
-
var HIGH_FREQ = /* @__PURE__ */ new Set([
|
|
2833
|
-
"viewport:changed",
|
|
2834
|
-
"element:moved",
|
|
2835
|
-
"element:resized",
|
|
2836
|
-
"element:updated",
|
|
2837
|
-
"text:edited"
|
|
2838
|
-
]);
|
|
2839
|
-
function asRecord2(value) {
|
|
2840
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
2841
|
-
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";
|
|
2842
2944
|
}
|
|
2843
|
-
function
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
return
|
|
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;
|
|
2849
2952
|
}
|
|
2850
|
-
function
|
|
2851
|
-
|
|
2852
|
-
const keys = /* @__PURE__ */ new Set([...Object.keys(prev ?? {}), ...Object.keys(next)]);
|
|
2853
|
-
for (const key of keys) {
|
|
2854
|
-
if (SKIP_KEYS.has(key)) continue;
|
|
2855
|
-
const from = prev?.[key];
|
|
2856
|
-
const to = next[key];
|
|
2857
|
-
if (JSON.stringify(from) !== JSON.stringify(to)) {
|
|
2858
|
-
changed[key] = { from, to };
|
|
2859
|
-
}
|
|
2860
|
-
}
|
|
2861
|
-
return changed;
|
|
2953
|
+
function unsysCanvasXaiFetchTimeout(kind) {
|
|
2954
|
+
return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
|
|
2862
2955
|
}
|
|
2863
|
-
function
|
|
2864
|
-
const
|
|
2865
|
-
return
|
|
2956
|
+
function unsysCanvasContextSkipChrome(el) {
|
|
2957
|
+
const part = el.customData?.[BOARD_INSTRUCTION_NOTE_KEY];
|
|
2958
|
+
return part === "header" || part === "label" || part === "body";
|
|
2866
2959
|
}
|
|
2867
|
-
function
|
|
2868
|
-
const
|
|
2869
|
-
|
|
2870
|
-
|
|
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;
|
|
2871
2997
|
}
|
|
2872
|
-
return
|
|
2998
|
+
return out;
|
|
2873
2999
|
}
|
|
2874
|
-
function
|
|
2875
|
-
const
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
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;
|
|
2879
3007
|
}
|
|
2880
|
-
|
|
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;
|
|
2881
3022
|
}
|
|
2882
|
-
function
|
|
2883
|
-
const
|
|
2884
|
-
const
|
|
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
|
+
);
|
|
2885
3047
|
return {
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
3048
|
+
...current,
|
|
3049
|
+
elements: [...kept, ...settled],
|
|
3050
|
+
appState: {
|
|
3051
|
+
...current.appState,
|
|
3052
|
+
selectedElementIds: {}
|
|
3053
|
+
}
|
|
2889
3054
|
};
|
|
2890
3055
|
}
|
|
2891
|
-
function
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
if ("from" in prev || "from" in next) merged.from = prev.from ?? next.from;
|
|
2898
|
-
if ("to" in next) merged.to = next.to;
|
|
2899
|
-
if (prev.changed && next.changed && typeof prev.changed === "object" && typeof next.changed === "object") {
|
|
2900
|
-
const a = prev.changed;
|
|
2901
|
-
const b = next.changed;
|
|
2902
|
-
const changed = { ...a };
|
|
2903
|
-
for (const [key, value] of Object.entries(b)) {
|
|
2904
|
-
const earlier = a[key];
|
|
2905
|
-
changed[key] = { from: earlier ? earlier.from : value.from, to: value.to };
|
|
2906
|
-
}
|
|
2907
|
-
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;
|
|
2908
3062
|
}
|
|
2909
|
-
|
|
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
|
+
});
|
|
3078
|
+
}
|
|
3079
|
+
return edits;
|
|
2910
3080
|
}
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
}
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
const deleted = Boolean(el.isDeleted);
|
|
2941
|
-
const wasDeleted = Boolean(before?.isDeleted);
|
|
2942
|
-
if (!before || wasDeleted && !deleted) {
|
|
2943
|
-
if (!deleted) {
|
|
2944
|
-
events.push(
|
|
2945
|
-
this.push("element:added", {
|
|
2946
|
-
id,
|
|
2947
|
-
type: el.type,
|
|
2948
|
-
element: el
|
|
2949
|
-
})
|
|
2950
|
-
);
|
|
2951
|
-
}
|
|
2952
|
-
continue;
|
|
2953
|
-
}
|
|
2954
|
-
if (!wasDeleted && deleted) {
|
|
2955
|
-
events.push(this.push("element:deleted", { id, type: el.type, element: el }));
|
|
2956
|
-
continue;
|
|
2957
|
-
}
|
|
2958
|
-
if (deleted) continue;
|
|
2959
|
-
const changed = changedProps(before, el);
|
|
2960
|
-
if (!Object.keys(changed).length) continue;
|
|
2961
|
-
events.push(
|
|
2962
|
-
this.push("element:updated", {
|
|
2963
|
-
id,
|
|
2964
|
-
type: el.type,
|
|
2965
|
-
changed
|
|
2966
|
-
})
|
|
2967
|
-
);
|
|
2968
|
-
if ("x" in changed || "y" in changed) {
|
|
2969
|
-
events.push(
|
|
2970
|
-
this.push("element:moved", {
|
|
2971
|
-
id,
|
|
2972
|
-
type: el.type,
|
|
2973
|
-
from: { x: changed.x?.from ?? before.x, y: changed.y?.from ?? before.y },
|
|
2974
|
-
to: { x: el.x, y: el.y }
|
|
2975
|
-
})
|
|
2976
|
-
);
|
|
2977
|
-
}
|
|
2978
|
-
if ("width" in changed || "height" in changed) {
|
|
2979
|
-
events.push(
|
|
2980
|
-
this.push("element:resized", {
|
|
2981
|
-
id,
|
|
2982
|
-
type: el.type,
|
|
2983
|
-
from: { width: changed.width?.from ?? before.width, height: changed.height?.from ?? before.height },
|
|
2984
|
-
to: { width: el.width, height: el.height }
|
|
2985
|
-
})
|
|
2986
|
-
);
|
|
2987
|
-
}
|
|
2988
|
-
if ("text" in changed || "originalText" in changed) {
|
|
2989
|
-
events.push(
|
|
2990
|
-
this.push("text:edited", {
|
|
2991
|
-
id,
|
|
2992
|
-
type: el.type,
|
|
2993
|
-
from: changed.text?.from ?? changed.originalText?.from ?? before.text,
|
|
2994
|
-
to: el.text ?? el.originalText
|
|
2995
|
-
})
|
|
2996
|
-
);
|
|
2997
|
-
}
|
|
2998
|
-
}
|
|
2999
|
-
for (const [id, el] of prevEls) {
|
|
3000
|
-
if (nextEls.has(id)) continue;
|
|
3001
|
-
if (el.isDeleted) continue;
|
|
3002
|
-
events.push(this.push("element:deleted", { id, type: el.type, element: el }));
|
|
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
|
|
3003
3110
|
}
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
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;
|
|
3008
3132
|
}
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
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
|
|
3013
3159
|
}
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
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;
|
|
3026
3175
|
}
|
|
3027
|
-
|
|
3028
|
-
|
|
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()));
|
|
3029
3195
|
}
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
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;
|
|
3037
3297
|
}
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
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
|
+
);
|
|
3042
3322
|
}
|
|
3043
|
-
prompt(
|
|
3044
|
-
|
|
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));
|
|
3045
3457
|
}
|
|
3046
|
-
|
|
3047
|
-
|
|
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}`);
|
|
3048
3474
|
}
|
|
3049
|
-
|
|
3050
|
-
|
|
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;
|
|
3051
3491
|
}
|
|
3052
|
-
|
|
3053
|
-
|
|
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
|
+
}
|
|
3054
3516
|
}
|
|
3055
|
-
|
|
3517
|
+
if (rec.commandId != null && String(rec.commandId).trim() !== commandId) {
|
|
3518
|
+
return { ok: false, error: "context.commandId does not match commandId" };
|
|
3056
3519
|
}
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
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" };
|
|
3075
3540
|
}
|
|
3076
|
-
const flushed = this.buffer;
|
|
3077
|
-
this.buffer = [];
|
|
3078
|
-
this.lastFlush = now;
|
|
3079
|
-
return flushed;
|
|
3080
3541
|
}
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
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
|
+
};
|
|
3086
3558
|
}
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
var UNSYS_CANVAS_CONTEXT_TEXT_MAX = 220;
|
|
3091
|
-
var UNSYS_CANVAS_CONTEXT_MAX_MARKS = 24;
|
|
3092
|
-
function unsysCanvasXaiNeedsBoardContext(kind) {
|
|
3093
|
-
return !kind || kind === "ask" || kind === "draw";
|
|
3094
|
-
}
|
|
3095
|
-
function unsysCanvasXaiMaxTokens(kind) {
|
|
3096
|
-
if (kind === "concepts") return 220;
|
|
3097
|
-
if (kind === "simplify") return 280;
|
|
3098
|
-
if (kind === "refactor" || kind === "check" || kind === "suggest-insight") return 400;
|
|
3099
|
-
if (kind === "selective-compress" || kind === "clear-overlaps" || kind === "declutter") return 360;
|
|
3100
|
-
return 800;
|
|
3101
|
-
}
|
|
3102
|
-
function unsysCanvasXaiFetchTimeout(kind) {
|
|
3103
|
-
return unsysCanvasXaiNeedsBoardContext(kind) ? 6e4 : 45e3;
|
|
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 };
|
|
3104
3562
|
}
|
|
3105
|
-
function
|
|
3106
|
-
const
|
|
3107
|
-
|
|
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
|
+
};
|
|
3108
3587
|
}
|
|
3109
|
-
function
|
|
3110
|
-
const
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
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
|
|
3119
3624
|
});
|
|
3120
|
-
if (live.length > cap) lines.push(`\u2026and ${live.length - cap} more marks`);
|
|
3121
|
-
return lines.join("\n");
|
|
3122
3625
|
}
|
|
3123
|
-
function
|
|
3124
|
-
const
|
|
3125
|
-
const
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
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 "";
|
|
3129
3637
|
}
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
return
|
|
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
|
+
};
|
|
3134
3687
|
}
|
|
3135
|
-
function
|
|
3136
|
-
const
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
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
|
+
};
|
|
3148
3714
|
}
|
|
3149
|
-
function
|
|
3150
|
-
const
|
|
3151
|
-
const
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
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);
|
|
3719
|
+
}
|
|
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;
|
|
3754
|
+
}
|
|
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);
|
|
3169
3759
|
}
|
|
3170
|
-
return
|
|
3760
|
+
return map;
|
|
3171
3761
|
}
|
|
3172
|
-
function
|
|
3173
|
-
const
|
|
3174
|
-
const
|
|
3175
|
-
const
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
y: bounds?.minY ?? TEXT_ORIGIN_Y,
|
|
3182
|
-
label: unsysCanvasNoteLabel("selective-compress"),
|
|
3183
|
-
customData: {
|
|
3184
|
-
[UNSYS_CANVAS_COMPRESS_WORK_CUSTOM_DATA_KEY]: true,
|
|
3185
|
-
ileSelectiveCompression: true,
|
|
3186
|
-
author: "xai"
|
|
3187
|
-
}
|
|
3188
|
-
}).elements;
|
|
3189
|
-
if (!created.length) return current;
|
|
3190
|
-
const remove = new Set(liveSelected.map((el) => el.id));
|
|
3191
|
-
const kept = current.elements.filter((el) => !remove.has(el.id));
|
|
3192
|
-
const settled = settleUnsysCanvasIncoming(
|
|
3193
|
-
created,
|
|
3194
|
-
kept.filter((el) => !el.isDeleted)
|
|
3195
|
-
);
|
|
3196
|
-
return {
|
|
3197
|
-
...current,
|
|
3198
|
-
elements: [...kept, ...settled],
|
|
3199
|
-
appState: {
|
|
3200
|
-
...current.appState,
|
|
3201
|
-
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 };
|
|
3202
3771
|
}
|
|
3203
|
-
}
|
|
3772
|
+
}
|
|
3773
|
+
return changed;
|
|
3204
3774
|
}
|
|
3205
|
-
function
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
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;
|
|
3211
3783
|
}
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
const x = Number(rec.x);
|
|
3220
|
-
const y = Number(rec.y);
|
|
3221
|
-
edits.push({
|
|
3222
|
-
id,
|
|
3223
|
-
text: text || null,
|
|
3224
|
-
x: Number.isFinite(x) ? x : null,
|
|
3225
|
-
y: Number.isFinite(y) ? y : null
|
|
3226
|
-
});
|
|
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;
|
|
3227
3791
|
}
|
|
3228
|
-
return
|
|
3792
|
+
return null;
|
|
3229
3793
|
}
|
|
3230
|
-
function
|
|
3231
|
-
|
|
3232
|
-
|
|
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
|
+
};
|
|
3233
3802
|
}
|
|
3234
|
-
function
|
|
3235
|
-
const
|
|
3236
|
-
|
|
3237
|
-
const list = (elements ?? []).filter((el) => el && typeof el === "object");
|
|
3238
|
-
if (list.length) return { elements: list };
|
|
3239
|
-
return source;
|
|
3803
|
+
function eventKey(event) {
|
|
3804
|
+
const id = typeof event.payload.id === "string" ? event.payload.id : "";
|
|
3805
|
+
return `${event.type}:${id}`;
|
|
3240
3806
|
}
|
|
3241
|
-
function
|
|
3242
|
-
const
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
if (
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
text,
|
|
3253
|
-
x: origin.x,
|
|
3254
|
-
y: origin.y,
|
|
3255
|
-
label: unsysCanvasNoteLabel("suggest-insight"),
|
|
3256
|
-
customData: {
|
|
3257
|
-
author: "xai",
|
|
3258
|
-
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 };
|
|
3259
3818
|
}
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
created,
|
|
3264
|
-
current.elements.filter((el) => !el.isDeleted)
|
|
3265
|
-
);
|
|
3266
|
-
return {
|
|
3267
|
-
...current,
|
|
3268
|
-
elements: [...current.elements, ...settled]
|
|
3269
|
-
};
|
|
3819
|
+
merged.changed = changed;
|
|
3820
|
+
}
|
|
3821
|
+
return merged;
|
|
3270
3822
|
}
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
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 }));
|
|
3281
3938
|
}
|
|
3939
|
+
this.prev = next;
|
|
3940
|
+
return this.batch(events);
|
|
3282
3941
|
}
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
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
|
+
}
|
|
3308
4002
|
}
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
elements: input.payload.elements,
|
|
3317
|
-
turnId: input.payload.turnId,
|
|
3318
|
-
label: noteLabel
|
|
3319
|
-
});
|
|
3320
|
-
} else if (kind === "concepts") {
|
|
3321
|
-
const labels = unsysCanvasConceptLabels(source, {
|
|
3322
|
-
text: input.payload.text,
|
|
3323
|
-
elements: input.payload.elements
|
|
3324
|
-
});
|
|
3325
|
-
next = fanUnsysCanvasLabeledNodes(live, selected, labels, "ileConcepts").scene;
|
|
3326
|
-
} else if (kind === "suggest-insight") {
|
|
3327
|
-
next = applyUnsysCanvasSuggestInsight(live, selected, source);
|
|
3328
|
-
} else if (kind === "declutter" || kind === "clear-overlaps") {
|
|
3329
|
-
next = applyUnsysCanvasPositionEdits(live, selected, layoutReply);
|
|
3330
|
-
} else {
|
|
3331
|
-
next = merge(stripLearnerFacingWrappers(String(input.payload.text || "").trim()));
|
|
4003
|
+
if (now - this.lastFlush < this.batchMs && incoming.every((event) => HIGH_FREQ.has(event.type))) {
|
|
4004
|
+
return [];
|
|
4005
|
+
}
|
|
4006
|
+
const flushed = this.buffer;
|
|
4007
|
+
this.buffer = [];
|
|
4008
|
+
this.lastFlush = now;
|
|
4009
|
+
return flushed;
|
|
3332
4010
|
}
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
if (!liveSelected.length) return current;
|
|
3341
|
-
const edits = parseUnsysCanvasLayoutEdits(reply);
|
|
3342
|
-
if (!edits.length) return current;
|
|
3343
|
-
const selectedIds2 = new Set(liveSelected.map((el) => el.id));
|
|
3344
|
-
const matchById = edits.some((edit) => edit.id && selectedIds2.has(edit.id));
|
|
3345
|
-
let ordinal = 0;
|
|
3346
|
-
return {
|
|
3347
|
-
...current,
|
|
3348
|
-
elements: current.elements.map((el) => {
|
|
3349
|
-
if (!selectedIds2.has(el.id) || el.isDeleted) return el;
|
|
3350
|
-
const edit = unsysCanvasEditForElement(edits, el, ordinal, matchById);
|
|
3351
|
-
ordinal += 1;
|
|
3352
|
-
if (!edit || edit.x == null && edit.y == null) return el;
|
|
3353
|
-
return {
|
|
3354
|
-
...el,
|
|
3355
|
-
x: edit.x == null ? el.x : edit.x,
|
|
3356
|
-
y: edit.y == null ? el.y : edit.y,
|
|
3357
|
-
version: (Number(el.version) || 1) + 1
|
|
3358
|
-
};
|
|
3359
|
-
})
|
|
3360
|
-
};
|
|
3361
|
-
}
|
|
4011
|
+
flush() {
|
|
4012
|
+
const flushed = this.buffer;
|
|
4013
|
+
this.buffer = [];
|
|
4014
|
+
this.lastFlush = Date.now();
|
|
4015
|
+
return flushed;
|
|
4016
|
+
}
|
|
4017
|
+
};
|
|
3362
4018
|
|
|
3363
4019
|
// src/lib/work-canvas/work-canvas-url.ts
|
|
3364
4020
|
var UNSYS_CANVAS_HASH_PREFIX = "tc1.";
|
|
@@ -3573,7 +4229,427 @@ function assertOnAsk(onAsk) {
|
|
|
3573
4229
|
throw new Error("UnsysCanvas requires an onAsk handler; the package does not call any LLM.");
|
|
3574
4230
|
}
|
|
3575
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
|
+
}
|
|
3576
4652
|
|
|
3577
|
-
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 };
|
|
3578
4654
|
//# sourceMappingURL=core.js.map
|
|
3579
4655
|
//# sourceMappingURL=core.js.map
|