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