@gemboss/ui 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +238 -0
  3. package/catalog/editor.html +1 -1
  4. package/catalog/index.html +4 -4
  5. package/gemboss-ui.css +3 -3
  6. package/node/skill-flow/layout.js +194 -0
  7. package/node/skill-flow/model.js +279 -0
  8. package/package.json +31 -1
  9. package/parts/components.css +1 -1
  10. package/parts/core.css +1 -1
  11. package/parts/shell.css +1 -1
  12. package/src/assistant/host.tsx +21 -5
  13. package/src/assistant/sessions.tsx +36 -18
  14. package/src/auth-sso-plain.js +1 -1
  15. package/src/auth.tsx +2 -0
  16. package/src/collections.css +1 -1
  17. package/src/collections.tsx +5 -2
  18. package/src/dialog.tsx +4 -1
  19. package/src/editor/controls.tsx +18 -7
  20. package/src/editor/index.ts +1 -1
  21. package/src/editor/picker.tsx +9 -3
  22. package/src/editor/repeater.tsx +26 -14
  23. package/src/editor/swatch.ts +86 -0
  24. package/src/editor-color.css +1 -1
  25. package/src/editor-picker.css +1 -1
  26. package/src/editor-plain.js +1 -1
  27. package/src/editor-popover.css +1 -1
  28. package/src/editor.css +1 -1
  29. package/src/index.ts +17 -0
  30. package/src/job-card.css +1 -0
  31. package/src/job-card.tsx +130 -0
  32. package/src/list-page.css +1 -1
  33. package/src/members-data.ts +278 -0
  34. package/src/members.css +1 -0
  35. package/src/members.tsx +868 -0
  36. package/src/menu-extras.css +1 -1
  37. package/src/menu-select.css +1 -0
  38. package/src/menu.tsx +39 -12
  39. package/src/narration.css +1 -0
  40. package/src/save-bar.css +1 -0
  41. package/src/save-bar.tsx +50 -0
  42. package/src/skill-card.css +1 -0
  43. package/src/skill-card.tsx +146 -0
  44. package/src/skill-flow/canvas.tsx +593 -0
  45. package/src/skill-flow/index.ts +12 -0
  46. package/src/skill-flow/layout.ts +238 -0
  47. package/src/skill-flow/model.ts +412 -0
  48. package/src/skill-flow.css +1 -0
  49. package/src/skill-stats.css +1 -0
  50. package/src/skill-stats.tsx +213 -0
  51. package/src/skill-view.css +1 -0
  52. package/src/skill-view.tsx +249 -0
  53. package/src/theme-dark.css +1 -1
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Where each box of a skill's flow stands (dagre), for the canvas (`./canvas.tsx`). Lifted from content-radar's lib/skill-flow.js
3
+ * `layoutFlow` (03/11/2026) with the lanes as a parameter. It imports @dagrejs/dagre, an OPTIONAL peer of the kit: only the
4
+ * `@gemboss/ui/skill-flow` entry reaches this file, never the kit's index, so a surface that does not draw a flow never loads it.
5
+ *
6
+ * Box sizes are estimated from the words (the canvas has fixed widths and boxes grow in height): skill-flow.css keeps the same
7
+ * numbers (padding, type size, the tool pills). Change one, change the other.
8
+ */
9
+ import * as dagreModule from "@dagrejs/dagre";
10
+ import { FLOW_DIRECTIONS, shortTool, validateFlow, type Flow, type FlowDirection, type FlowEdgeKind, type FlowMessages, type FlowNode, type FlowPhase } from "./model";
11
+
12
+ // dagre 3 is an ES module with named exports; dagre 1.x (the peer range starts at 1.1) is CommonJS, which plain Node hands to an
13
+ // ES module as its `default` (this file also ships as plain JavaScript for Node: pack-lib.mjs NODE_COPIES). A bundler gives both.
14
+ type Dagre = typeof dagreModule;
15
+ const dagre: Dagre = (dagreModule as { graphlib?: unknown }).graphlib ? dagreModule : (dagreModule as unknown as { default: Dagre }).default;
16
+
17
+ const NODE_W: Record<string, number> = { start: 184, end: 184, step: 212, stop: 212, decision: 212, exit: 188 };
18
+ const LANE = { head: 34, pad: 14, gap: 44, min: 240, side: 40 };
19
+
20
+ export function nodeSize(n: Pick<FlowNode, "kind" | "label" | "tools" | "human">): { width: number; height: number } {
21
+ const width = NODE_W[n.kind] || 212;
22
+ const inner = width - (n.kind === "decision" ? 44 : 26);
23
+ const eyebrow = n.kind === "step" && !n.human ? 0 : 16;
24
+ const lines = Math.min(2, Math.max(1, Math.ceil(n.label.length / Math.floor(inner / 7.6))));
25
+ let rows = 0;
26
+ let used = Infinity;
27
+ for (const t of n.tools || []) {
28
+ const w = Math.ceil(shortTool(t).length * 6.7) + 14;
29
+ if (used + 4 + w > inner) { rows += 1; used = w; } else used += 4 + w;
30
+ }
31
+ const height = 18 + eyebrow + lines * 18 + (rows ? 6 + rows * 18 + (rows - 1) * 4 : 0);
32
+ return { width, height: Math.max(height, 44) };
33
+ }
34
+
35
+ type Sized = FlowNode & { size: { width: number; height: number } };
36
+ type Pos = { x: number; y: number };
37
+
38
+ // One dagre pass. Measured on content-radar's playbooks (24/10/2026): dagre's default alignment pushed the main line one column
39
+ // over after every branch that leaves the skill, a staircase. So: an exit node does NOT go into dagre, it stands right of its
40
+ // decision ("No →", as on paper); "UR" keeps the main line in one column, then everything is flipped so side branches leave to the
41
+ // RIGHT: a box's left edge is kept for the line coming in from the lane before.
42
+ function dagreLayout(nodes: Sized[], edges: Flow["edges"], rankdir: FlowDirection) {
43
+ const tb = rankdir === "TB";
44
+ const ids = new Set(nodes.map((n) => n.id));
45
+ const byId = new Map(nodes.map((n) => [n.id, n]));
46
+ const side = new Map<string, string>();
47
+ for (const n of nodes) {
48
+ if (n.kind !== "exit") continue;
49
+ const into = edges.find((e) => e.to === n.id && ids.has(e.from) && byId.get(e.from)!.kind !== "exit");
50
+ if (into) side.set(n.id, into.from);
51
+ }
52
+ const g = new dagre.graphlib.Graph();
53
+ g.setGraph({ rankdir, align: "UR", nodesep: 22, ranksep: 40, edgesep: 12, marginx: 0, marginy: 0 });
54
+ g.setDefaultEdgeLabel(() => ({}));
55
+ for (const n of nodes) if (!side.has(n.id)) g.setNode(n.id, { ...n.size });
56
+ // A loop edge (back to fix) does not rank: it goes backwards.
57
+ for (const e of edges) {
58
+ if (e.kind === "loop" || !g.hasNode(e.from) || !g.hasNode(e.to)) continue;
59
+ g.setEdge(e.from, e.to, { minlen: 1, weight: e.kind === "no" ? 1 : 3 });
60
+ }
61
+ dagre.layout(g as never);
62
+ const gr = g.graph() as { width?: number; height?: number };
63
+ let width = gr.width || 0;
64
+ let height = gr.height || 0;
65
+ const pos = new Map<string, Pos>();
66
+ for (const n of nodes) {
67
+ if (side.has(n.id)) continue;
68
+ const p = g.node(n.id) as unknown as Pos;
69
+ // Flip across the flow's axis (TB: left ↔ right; LR: top ↔ bottom).
70
+ pos.set(n.id, tb ? { x: width - p.x - n.size.width / 2, y: p.y - n.size.height / 2 } : { x: p.x - n.size.width / 2, y: height - p.y - n.size.height / 2 });
71
+ }
72
+ const placed = () => [...pos.entries()].map(([id, p]) => ({ ...p, w: byId.get(id)!.size.width, h: byId.get(id)!.size.height }));
73
+ for (const [id, parent] of side) {
74
+ const n = byId.get(id)!;
75
+ const pn = byId.get(parent)!;
76
+ const p = pos.get(parent)!;
77
+ // Right after the decision, and after anything already on that row (a side branch, another exit of the same decision).
78
+ let q: Pos;
79
+ if (tb) {
80
+ const y = Math.max(0, p.y + (pn.size.height - n.size.height) / 2);
81
+ const row = placed().filter((b) => b.y < y + n.size.height && b.y + b.h > y && b.x >= p.x);
82
+ q = { x: Math.max(...row.map((b) => b.x + b.w)) + LANE.side, y };
83
+ } else {
84
+ const x = Math.max(0, p.x + (pn.size.width - n.size.width) / 2);
85
+ const col = placed().filter((b) => b.x < x + n.size.width && b.x + b.w > x && b.y >= p.y);
86
+ q = { x, y: Math.max(...col.map((b) => b.y + b.h)) + LANE.side };
87
+ }
88
+ pos.set(id, q);
89
+ width = Math.max(width, q.x + n.size.width);
90
+ height = Math.max(height, q.y + n.size.height);
91
+ }
92
+ return { pos, width, height };
93
+ }
94
+
95
+ export interface FlowBand { phase: string; label: string; lane: number; x: number; y: number; width: number; height: number }
96
+ export interface LaidNode { id: string; type: FlowNode["kind"]; lane: number; position: Pos; width: number; height: number; data: FlowNode }
97
+ export interface LaidEdge {
98
+ id: string; source: string; target: string; sourceHandle: string; targetHandle: string; type: "flow";
99
+ data: { kind: FlowEdgeKind; label: string; offset?: number; centerX?: number; centerY?: number };
100
+ }
101
+ export interface FlowLayout { direction: FlowDirection; lanes: boolean; width: number; height: number; bands: FlowBand[]; nodes: LaidNode[]; edges: LaidEdge[] }
102
+
103
+ /**
104
+ * A flow (checked or not) → where each box stands, for React Flow.
105
+ * - `lanes: false` (default): one stream in `direction`, the phases as bands one after another (label in the margin). Narrow screens.
106
+ * - `lanes: true`: each phase a lane side by side (TB: lanes are columns, read top down then the next column). Wide screens.
107
+ * `lane` on a band and a node is the phase's index in `phases`: the canvas colours by it. Handles: `s-<side>` (source) /
108
+ * `t-<side>` (target), side t | b | l | r: a node on the canvas carries all eight. `height` is an estimate (real words may run
109
+ * a line longer); the canvas lets the box grow.
110
+ */
111
+ export function layoutFlow(input: unknown, { phases, direction, lanes = false, messages }: {
112
+ phases: readonly FlowPhase[]; direction?: FlowDirection; lanes?: boolean;
113
+ /** The words of a problem when the flow does not pass validateFlow (model.ts FLOW_MESSAGES is the English). */
114
+ messages?: Partial<FlowMessages>;
115
+ }): FlowLayout {
116
+ // The drawing only: the caller may carry extra keys at the top (a note, a source), and examples (with `html` from a server)
117
+ // do not move a box. validateFlow takes neither, so both go before it checks.
118
+ const bare = (n: unknown) => (n && typeof n === "object" && !Array.isArray(n) ? (({ examples: _x, ...rest }: Record<string, unknown>) => rest)(n as Record<string, unknown>) : n);
119
+ const obj = input && typeof input === "object" && !Array.isArray(input) ? (input as Record<string, unknown>) : null;
120
+ const flow = validateFlow(obj ? { direction: obj.direction, nodes: Array.isArray(obj.nodes) ? obj.nodes.map(bare) : obj.nodes, edges: obj.edges } : input, { phases, messages });
121
+ const dir: FlowDirection = direction && FLOW_DIRECTIONS.includes(direction) ? direction : flow.direction;
122
+ const tb = dir === "TB";
123
+ const list: Sized[] = flow.nodes.map((n) => ({ ...n, size: nodeSize(n) }));
124
+ const byId = new Map(list.map((n) => [n.id, n]));
125
+ const at = new Map<string, Pos>();
126
+ const laneOf = Object.fromEntries(phases.map((p, i) => [p.key, i]));
127
+ const labelOf = Object.fromEntries(phases.map((p) => [p.key, p.label]));
128
+ const present = phases.map((p) => p.key).filter((p) => list.some((n) => n.phase === p));
129
+ const laneIdx = Object.fromEntries(present.map((p, i) => [p, i]));
130
+ const bands: Array<Omit<FlowBand, "label" | "lane">> = [];
131
+ let width: number;
132
+ let height: number;
133
+
134
+ if (lanes) {
135
+ let off = 0;
136
+ for (const ph of present) {
137
+ const sub = list.filter((n) => n.phase === ph);
138
+ const L = dagreLayout(sub, flow.edges.filter((e) => byId.get(e.from)!.phase === ph && byId.get(e.to)!.phase === ph), dir);
139
+ const cross = tb ? L.width : L.height;
140
+ const inner = Math.max(cross, LANE.min - 2 * LANE.pad);
141
+ const shift = (inner - cross) / 2;
142
+ for (const n of sub) {
143
+ const p = L.pos.get(n.id)!;
144
+ at.set(n.id, tb ? { x: off + LANE.pad + shift + p.x, y: LANE.head + LANE.pad + p.y } : { x: LANE.head + LANE.pad + p.x, y: off + LANE.pad + shift + p.y });
145
+ }
146
+ const main = LANE.head + 2 * LANE.pad + (tb ? L.height : L.width);
147
+ bands.push(tb ? { phase: ph, x: off, y: 0, width: inner + 2 * LANE.pad, height: main } : { phase: ph, x: 0, y: off, width: main, height: inner + 2 * LANE.pad });
148
+ off += inner + 2 * LANE.pad + LANE.gap;
149
+ }
150
+ // Every lane the same length, as a table.
151
+ const span = Math.max(...bands.map((b) => (tb ? b.height : b.width)));
152
+ for (const b of bands) { if (tb) b.height = span; else b.width = span; }
153
+ width = tb ? off - LANE.gap : span;
154
+ height = tb ? span : off - LANE.gap;
155
+ } else {
156
+ const L = dagreLayout(list, flow.edges, dir);
157
+ for (const n of list) {
158
+ const p = L.pos.get(n.id)!;
159
+ at.set(n.id, tb ? { x: LANE.head + LANE.pad + p.x, y: LANE.pad + p.y } : { x: LANE.pad + p.x, y: LANE.head + LANE.pad + p.y });
160
+ }
161
+ // A wider margin at the end: a loop goes round the main line on the right (TB) / below it (LR).
162
+ width = tb ? LANE.head + LANE.pad + LANE.side * 2 + L.width : 2 * LANE.pad + L.width;
163
+ height = tb ? 2 * LANE.pad + L.height : LANE.head + LANE.pad + LANE.side * 2 + L.height;
164
+ // A phase's band runs along the flow from its first box to its last; two bands meet in the middle of the gap between them.
165
+ const span = present.map((ph) => {
166
+ const own = list.filter((n) => n.phase === ph).map((n) => { const p = at.get(n.id)!; return tb ? [p.y, p.y + n.size.height] : [p.x, p.x + n.size.width]; });
167
+ return { phase: ph, a: Math.min(...own.map((r) => r[0]!)), b: Math.max(...own.map((r) => r[1]!)) };
168
+ });
169
+ const total = tb ? height : width;
170
+ span.forEach((s, i) => {
171
+ const lo = i === 0 ? 0 : (span[i - 1]!.b + s.a) / 2;
172
+ const hi = i === span.length - 1 ? total : (s.b + span[i + 1]!.a) / 2;
173
+ bands.push(tb ? { phase: s.phase, x: 0, y: lo, width, height: Math.max(hi - lo, 0) } : { phase: s.phase, x: lo, y: 0, width: Math.max(hi - lo, 0), height });
174
+ });
175
+ }
176
+
177
+ // Which side of a box each line leaves from: forward along the flow, bottom → top; into another lane, right → left (or back)
178
+ // and down the gap between the two lanes (centerX), never across a lane's boxes; back within a lane (a loop), round the
179
+ // outside of every box in between.
180
+ const box = (id: string) => {
181
+ const n = byId.get(id)!;
182
+ const p = at.get(id)!;
183
+ const len = tb ? n.size.height : n.size.width;
184
+ const cross = tb ? n.size.width : n.size.height;
185
+ return { m: tb ? p.y : p.x, len, c: tb ? p.x : p.y, mid: (tb ? p.x : p.y) + cross / 2, end: (tb ? p.x : p.y) + cross };
186
+ };
187
+ const F = tb ? ["b", "t"] : ["r", "l"];
188
+ const PLUS = tb ? ["r", "l"] : ["b", "t"];
189
+ const MINUS = tb ? ["l", "r"] : ["t", "b"];
190
+ const BACK = tb ? ["r", "r"] : ["b", "b"];
191
+ const gapAfter = (ph: string) => { const b = bands.find((x) => x.phase === ph)!; return tb ? b.x + b.width + LANE.gap / 2 : b.y + b.height + LANE.gap / 2; };
192
+ const edges: LaidEdge[] = flow.edges.map((e, i) => {
193
+ const s = box(e.from);
194
+ const t = box(e.to);
195
+ const sp = byId.get(e.from)!.phase;
196
+ const tp = byId.get(e.to)!.phase;
197
+ const dl = lanes ? laneIdx[tp]! - laneIdx[sp]! : 0;
198
+ const data: LaidEdge["data"] = { kind: e.kind, label: e.label };
199
+ let pick: string[];
200
+ if (dl) {
201
+ pick = dl > 0 ? PLUS : MINUS;
202
+ // The gap right after the lane in front (the source's going forward, the target's coming back); a forward line takes the
203
+ // left half of the gap and a loop the right half, so a solid and a dashed line never lie on each other.
204
+ data[tb ? "centerX" : "centerY"] = gapAfter(dl > 0 ? present[laneIdx[tp]! - 1]! : tp) + (e.kind === "loop" ? 8 : -8);
205
+ } else if (t.m >= s.m + s.len - 2) {
206
+ // A branch that leaves a decision sideways goes out of the box's side ("No ←"), so two branches never share a point and
207
+ // the Yes / No labels never sit on each other.
208
+ const sideways = byId.get(e.from)!.kind === "decision" && Math.abs(t.mid - s.mid) > 24;
209
+ pick = sideways ? [t.mid < s.mid ? MINUS[0]! : PLUS[0]!, F[1]!] : F;
210
+ // A straight line would cross a box in between (a jump over a step): go round on the right, like a loop.
211
+ const a = Math.min(s.mid, t.mid) - 4;
212
+ const b = Math.max(s.mid, t.mid) + 4;
213
+ const scope = list.filter((n) => n.id !== e.from && n.id !== e.to && (!lanes || n.phase === sp)).map((n) => box(n.id));
214
+ if (!sideways && scope.some((n) => n.m < t.m && n.m + n.len > s.m + s.len && n.c < b && n.end > a)) {
215
+ pick = BACK;
216
+ const far = Math.max(...scope.filter((n) => n.m < t.m + t.len && n.m + n.len > s.m).map((n) => n.end), s.end, t.end);
217
+ data.offset = Math.round(Math.max(20, far - Math.max(s.end, t.end) + 20));
218
+ }
219
+ } else if (t.m + t.len <= s.m + 2) {
220
+ pick = BACK;
221
+ const lo = Math.min(s.m, t.m);
222
+ const hi = Math.max(s.m + s.len, t.m + t.len);
223
+ const far = Math.max(...list.filter((n) => !lanes || n.phase === sp).map((n) => box(n.id)).filter((b) => b.m < hi && b.m + b.len > lo).map((b) => b.end));
224
+ data.offset = Math.round(Math.max(20, far - Math.max(s.end, t.end) + 20));
225
+ } else pick = t.c > s.c ? PLUS : MINUS;
226
+ return { id: `e${i}-${e.from}-${e.to}`, source: e.from, target: e.to, sourceHandle: `s-${pick[0]}`, targetHandle: `t-${pick[1]}`, type: "flow", data };
227
+ });
228
+
229
+ return {
230
+ direction: dir,
231
+ lanes: Boolean(lanes),
232
+ width,
233
+ height,
234
+ bands: bands.map((b) => ({ ...b, label: labelOf[b.phase] ?? b.phase, lane: laneOf[b.phase] ?? 0 })),
235
+ nodes: list.map(({ size, ...n }) => ({ id: n.id, type: n.kind, lane: laneOf[n.phase] ?? 0, position: at.get(n.id)!, width: size.width, height: size.height, data: n })),
236
+ edges,
237
+ };
238
+ }
@@ -0,0 +1,412 @@
1
+ /**
2
+ * A SKILL'S FLOW, AS DATA (03/11/2026, lifted from content-radar's lib/skill-flow.js: Chris 27/10/2026, "làm đúng kiểu bên content
3
+ * radar … dùng chung theo gemboss ui để sau update cho dễ"). Pure: no file reads, no React, no layout library. The canvas
4
+ * (`./canvas.tsx`) and the layout (`./layout.ts`, dagre) read what this module checks; a server checks a flow.json with it before
5
+ * it hands one to a browser.
6
+ *
7
+ * The one change from content-radar: the LANES are the caller's. content-radar's four (prep · write · check · publish) were its
8
+ * writer's phases imported straight into the module; here every function that needs them takes `phases`, so GemBoss's packs bring
9
+ * their own (read · frame · build · check) and content-radar keeps its own.
10
+ *
11
+ * Format (plain JSON; label / detail / examples are the skill's data, in the skill's language; the words around the canvas are the
12
+ * surface's, English by default):
13
+ * { direction: "TB" | "LR",
14
+ * nodes: [{ id, label, kind, phase, detail?, tools?: ["gemboss_…"], human?, examples?: [{ title, kind, md }] }],
15
+ * edges: [{ from, to, label?, kind? }] }
16
+ * node kind: start | step | decision | stop (a person confirms) | exit (leaves this skill, another one takes over) | end
17
+ * phase: one of the caller's phase keys, the node's lane
18
+ * edge kind: normal | yes | no | loop (back to fix, e.g. a check failed → build again)
19
+ * examples: 1–3 made-up examples of one step. kind: input | output | good | bad | tool. `md` is short Markdown; the server may
20
+ * attach `html` (flowWithHtml) so the browser needs no Markdown library.
21
+ */
22
+
23
+ export const FLOW_NODE_KINDS = ["start", "step", "decision", "stop", "exit", "end"] as const;
24
+ export const FLOW_EDGE_KINDS = ["normal", "yes", "no", "loop"] as const;
25
+ export const FLOW_DIRECTIONS = ["TB", "LR"] as const;
26
+ export const FLOW_EXAMPLE_KINDS = ["input", "output", "good", "bad", "tool"] as const;
27
+
28
+ export type FlowNodeKind = (typeof FLOW_NODE_KINDS)[number];
29
+ export type FlowEdgeKind = (typeof FLOW_EDGE_KINDS)[number];
30
+ export type FlowDirection = (typeof FLOW_DIRECTIONS)[number];
31
+ export type FlowExampleKind = (typeof FLOW_EXAMPLE_KINDS)[number];
32
+
33
+ /** One lane of the canvas: a key the flow's nodes name in `phase`, and the words drawn on it. Order = left to right (or top down). */
34
+ export interface FlowPhase { key: string; label: string }
35
+
36
+ export interface FlowExample { title: string; kind: FlowExampleKind; md: string; html?: string }
37
+ export interface FlowNode {
38
+ id: string;
39
+ label: string;
40
+ kind: FlowNodeKind;
41
+ phase: string;
42
+ detail: string;
43
+ tools: string[];
44
+ /** A person does this step (always true for `stop`). */
45
+ human: boolean;
46
+ examples: FlowExample[];
47
+ }
48
+ export interface FlowEdge { from: string; to: string; label: string; kind: FlowEdgeKind }
49
+ export interface Flow { direction: FlowDirection; nodes: FlowNode[]; edges: FlowEdge[] }
50
+
51
+ /** Length ceilings: a label sits in a two-line box, an edge label is a small pill on a line; longer words go in `detail`. */
52
+ export const FLOW_LIMITS = { nodes: 60, label: 48, detail: 700, edgeLabel: 28, tools: 4, examples: 3, exampleTitle: 60, exampleMd: 900 } as const;
53
+
54
+ const TERMINAL = new Set<string>(["end", "exit"]);
55
+ const TOP_KEYS = new Set(["direction", "nodes", "edges"]);
56
+ const NODE_KEYS = new Set(["id", "label", "kind", "phase", "detail", "tools", "human", "examples"]);
57
+ const EXAMPLE_KEYS = new Set(["title", "kind", "md"]);
58
+ const EDGE_KEYS = new Set(["from", "to", "label", "kind"]);
59
+ const ID = /^[a-z0-9][a-z0-9-]*$/;
60
+ // A tool name as an MCP client sees it: `gemboss_get_skill`, `gemboss.get_skill`, `radar_skill_get`.
61
+ const TOOL = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)?$/;
62
+
63
+ const text = (v: unknown) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : "");
64
+ const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
65
+
66
+ // ── The words of a problem (04/11/2026, Chris: "Kit thêm slot, giữ giao diện content-radar") ──────────────────────────────
67
+ // content-radar's own check says every problem in Vietnamese; the kit's said them in English only, so content-radar kept a copy
68
+ // of the whole check to keep its words. Now a problem is a CODE with its params, and the words are a table the caller may
69
+ // replace: `validateFlow(flow, { phases, messages })`. The English table below is the old text, word for word.
70
+ type None = Record<string, never>;
71
+ /** Every problem validateFlow can find, and what its words need. */
72
+ export interface FlowProblemParams {
73
+ notJson: None;
74
+ notObject: None;
75
+ topKey: { key: string };
76
+ direction: { value: string; allowed: string };
77
+ nodesList: None;
78
+ edgesList: None;
79
+ tooManyNodes: { max: number };
80
+ /** A node or an edge that is not an object (an example has `exampleObject`). */
81
+ notAnObject: None;
82
+ /** A node's, an example's or an edge's key; `known`: the keys it may have, joined. */
83
+ unknownKey: { key: string; known: string };
84
+ idFormat: None;
85
+ idTwice: None;
86
+ noLabel: None;
87
+ labelLong: { length: number; max: number };
88
+ /** A node's, an example's or an edge's kind; `allowed`: the kinds, joined with " | ". */
89
+ kind: { value: string; allowed: string };
90
+ phase: { value: string; allowed: string };
91
+ detailText: None;
92
+ detailLong: { max: number };
93
+ toolsList: None;
94
+ toolName: { name: string };
95
+ toolTwice: None;
96
+ toolsMany: { max: number };
97
+ humanBool: None;
98
+ examplesList: None;
99
+ examplesMany: { max: number };
100
+ exampleObject: None;
101
+ htmlText: None;
102
+ noTitle: None;
103
+ titleLong: { max: number };
104
+ mdEmpty: None;
105
+ mdLong: { length: number; max: number };
106
+ noNode: { id: string };
107
+ selfEdge: None;
108
+ branchFromStep: { kind: "yes" | "no" };
109
+ edgeLabelText: None;
110
+ edgeLabelLong: { max: number };
111
+ edgeTwice: None;
112
+ /** 0: no start node; 2 or more: too many. */
113
+ startCount: { count: number };
114
+ noEnd: None;
115
+ startIncoming: { id: string };
116
+ endOutgoing: { id: string; kind: string };
117
+ deadEnd: { id: string };
118
+ decisionBranches: { id: string };
119
+ unreachable: { ids: string[] };
120
+ neverEnds: { ids: string[] };
121
+ }
122
+ export type FlowProblemCode = keyof FlowProblemParams;
123
+ /** Where a problem is: a node (1-based, its id when it has one), one of its examples, or an edge. Absent: the flow as a whole. */
124
+ export type FlowAt = { node: number; id?: string; example?: number } | { edge: number; from?: string; to?: string };
125
+ export type FlowProblem = { [K in FlowProblemCode]: { code: K; params: FlowProblemParams[K]; at?: FlowAt } }[FlowProblemCode];
126
+
127
+ /** The words: one function per problem, three that say where it is, and `invalid`, the one error's message round the list. */
128
+ export type FlowMessages = { [K in FlowProblemCode]: (p: FlowProblemParams[K]) => string } & {
129
+ node: (at: { n: number; id?: string }) => string;
130
+ /** `node`: the node's own words ("node #3 "ask""). */
131
+ example: (at: { node: string; n: number }) => string;
132
+ edge: (at: { n: number; from?: string; to?: string }) => string;
133
+ /** Every problem already in words, each with where it is ("node #3: no label"). */
134
+ invalid: (lines: string[]) => string;
135
+ };
136
+
137
+ /** The English words (what validateFlow has always said). A surface passes its own for some or all of them. */
138
+ export const FLOW_MESSAGES: FlowMessages = {
139
+ notJson: () => "invalid flow: not JSON",
140
+ notObject: () => "invalid flow: must be an object { direction, nodes, edges }",
141
+ invalid: (lines) => `invalid flow (${lines.length} problem${lines.length === 1 ? "" : "s"}): ${lines.join("; ")}`,
142
+ node: ({ n, id }) => `node #${n}${id ? ` "${id}"` : ""}`,
143
+ example: ({ node, n }) => `${node}, example #${n}`,
144
+ edge: ({ n, from, to }) => `edge #${n}${from ? ` ${from} → ${to}` : ""}`,
145
+ topKey: ({ key }) => `unknown key "${key}" at the top (only direction, nodes, edges)`,
146
+ direction: ({ value, allowed }) => `direction "${value}" is not one of ${allowed}`,
147
+ nodesList: () => "nodes must be a list with at least one node",
148
+ edgesList: () => "edges must be a list",
149
+ tooManyNodes: ({ max }) => `more than ${max} nodes: split the skill or merge steps`,
150
+ notAnObject: () => "must be an object",
151
+ unknownKey: ({ key, known }) => `unknown key "${key}" (known: ${known})`,
152
+ idFormat: () => 'id must be lowercase letters, digits and dashes (e.g. "gather")',
153
+ idTwice: () => "id used twice",
154
+ noLabel: () => "no label",
155
+ labelLong: ({ length, max }) => `label is ${length} characters (at most ${max}; put the rest in detail)`,
156
+ kind: ({ value, allowed }) => `kind "${value}" is not one of ${allowed}`,
157
+ phase: ({ value, allowed }) => `phase "${value}" is not one of ${allowed}`,
158
+ detailText: () => "detail must be text",
159
+ detailLong: ({ max }) => `detail is longer than ${max} characters`,
160
+ toolsList: () => "tools must be a list of tool names",
161
+ toolName: ({ name }) => `tool name "${name}" is not valid`,
162
+ toolTwice: () => "a tool is named twice",
163
+ toolsMany: ({ max }) => `more than ${max} tools (the box is full: split the step)`,
164
+ humanBool: () => "human must be true or false",
165
+ examplesList: () => "examples must be a list",
166
+ examplesMany: ({ max }) => `more than ${max} examples`,
167
+ exampleObject: () => "must be an object { title, kind, md }",
168
+ htmlText: () => "html must be text",
169
+ noTitle: () => "no title",
170
+ titleLong: ({ max }) => `title is longer than ${max} characters`,
171
+ mdEmpty: () => "md is empty",
172
+ mdLong: ({ length, max }) => `md is ${length} characters (at most ${max})`,
173
+ noNode: ({ id }) => `no node "${id}"`,
174
+ selfEdge: () => "a node points at itself",
175
+ branchFromStep: ({ kind }) => `a ${kind} edge only leaves a decision`,
176
+ edgeLabelText: () => "label must be text",
177
+ edgeLabelLong: ({ max }) => `label is longer than ${max} characters`,
178
+ edgeTwice: () => "the same edge twice",
179
+ startCount: ({ count }) => (count ? `${count} start nodes (only one)` : "no start node"),
180
+ noEnd: () => "no end node",
181
+ startIncoming: ({ id }) => `start node "${id}" must have no edge coming in`,
182
+ endOutgoing: ({ id, kind }) => `node "${id}" (${kind}) ends the flow and must have no edge going out`,
183
+ deadEnd: ({ id }) => `node "${id}" is a dead end: no edge goes out (use kind end or exit to finish)`,
184
+ decisionBranches: ({ id }) => `node "${id}" (decision) needs at least two branches`,
185
+ unreachable: ({ ids }) => `not reachable from start: ${ids.join(", ")}`,
186
+ neverEnds: ({ ids }) => `loops forever, never reaches an end or exit: ${ids.join(", ")}`,
187
+ };
188
+
189
+ /** What validateFlow throws: its message is the whole list in the caller's words; `problems` is the same list as data. */
190
+ export class FlowError extends Error {
191
+ problems: FlowProblem[];
192
+ constructor(message: string, problems: FlowProblem[]) {
193
+ super(message);
194
+ this.problems = problems;
195
+ }
196
+ }
197
+
198
+ /** One problem in words, with where it is ("node #3 "ask": no label"). */
199
+ export function flowProblemText(p: FlowProblem, messages?: Partial<FlowMessages>): string {
200
+ const M: FlowMessages = messages ? { ...FLOW_MESSAGES, ...messages } : FLOW_MESSAGES;
201
+ const words = (M[p.code] as (params: unknown) => string)(p.params);
202
+ if (!p.at) return words;
203
+ const a = p.at;
204
+ let where: string;
205
+ if ("edge" in a) where = M.edge({ n: a.edge, from: a.from, to: a.to });
206
+ else {
207
+ where = M.node({ n: a.node, id: a.id });
208
+ if (a.example) where = M.example({ node: where, n: a.example });
209
+ }
210
+ return `${where}: ${words}`;
211
+ }
212
+
213
+ /**
214
+ * Check a flow and return it normalised (whitespace collapsed; defaults for kind, tools, human, direction). Throws ONE error
215
+ * (a FlowError) that lists every problem, so whoever edits the file sees the whole list at once: in English, or in the words
216
+ * of `messages`.
217
+ */
218
+ export function validateFlow(input: unknown, { phases, allowHtml = false, messages }: {
219
+ phases: readonly FlowPhase[];
220
+ /** Keep an example's `html` (a server rendered its Markdown, flowWithHtml). A flow FILE never carries html: off by default. */
221
+ allowHtml?: boolean;
222
+ /** The words of the problems, for some or all of them (FLOW_MESSAGES is the English). */
223
+ messages?: Partial<FlowMessages>;
224
+ }): Flow {
225
+ const M: FlowMessages = messages ? { ...FLOW_MESSAGES, ...messages } : FLOW_MESSAGES;
226
+ const problems: FlowProblem[] = [];
227
+ const add = <K extends FlowProblemCode>(code: K, params: FlowProblemParams[K], at?: FlowAt) => {
228
+ problems.push((at ? { code, params, at } : { code, params }) as FlowProblem);
229
+ };
230
+ const fail = () => new FlowError(M.invalid(problems.map((p) => flowProblemText(p, M))), problems);
231
+ const fatal = (code: "notJson" | "notObject") => new FlowError(M[code]({}), [{ code, params: {} }]);
232
+
233
+ let x: unknown = input;
234
+ if (typeof x === "string") { try { x = JSON.parse(x); } catch { throw fatal("notJson"); } }
235
+ if (!isObject(x)) throw fatal("notObject");
236
+ const keys = phases.map((p) => p.key);
237
+ for (const k of Object.keys(x)) if (!TOP_KEYS.has(k)) add("topKey", { key: k });
238
+ const direction = (x.direction == null ? "TB" : x.direction) as FlowDirection;
239
+ if (!FLOW_DIRECTIONS.includes(direction)) add("direction", { value: String(direction), allowed: FLOW_DIRECTIONS.join(" | ") });
240
+ if (!Array.isArray(x.nodes) || !x.nodes.length) add("nodesList", {});
241
+ if (!Array.isArray(x.edges)) add("edgesList", {});
242
+ if (!Array.isArray(x.nodes) || !Array.isArray(x.edges)) throw fail();
243
+ if (x.nodes.length > FLOW_LIMITS.nodes) add("tooManyNodes", { max: FLOW_LIMITS.nodes });
244
+
245
+ const nodes: FlowNode[] = [];
246
+ const byId = new Map<string, FlowNode>();
247
+ (x.nodes as unknown[]).forEach((n, i) => {
248
+ const at: { node: number; id?: string } = isObject(n) && typeof n.id === "string" && n.id ? { node: i + 1, id: n.id } : { node: i + 1 };
249
+ if (!isObject(n)) { add("notAnObject", {}, at); return; }
250
+ for (const k of Object.keys(n)) if (!NODE_KEYS.has(k)) add("unknownKey", { key: k, known: [...NODE_KEYS].join(", ") }, at);
251
+ const id = text(n.id);
252
+ if (!ID.test(id)) add("idFormat", {}, at);
253
+ else if (byId.has(id)) add("idTwice", {}, at);
254
+ const label = text(n.label);
255
+ if (!label) add("noLabel", {}, at);
256
+ else if (label.length > FLOW_LIMITS.label) add("labelLong", { length: label.length, max: FLOW_LIMITS.label }, at);
257
+ const kind = (n.kind == null ? "step" : n.kind) as FlowNodeKind;
258
+ if (!FLOW_NODE_KINDS.includes(kind)) add("kind", { value: String(kind), allowed: FLOW_NODE_KINDS.join(" | ") }, at);
259
+ const phase = typeof n.phase === "string" ? n.phase : "";
260
+ if (!keys.includes(phase)) add("phase", { value: phase, allowed: keys.join(" | ") }, at);
261
+ if (n.detail != null && typeof n.detail !== "string") add("detailText", {}, at);
262
+ const detail = text(n.detail);
263
+ if (detail.length > FLOW_LIMITS.detail) add("detailLong", { max: FLOW_LIMITS.detail }, at);
264
+ let tools: string[] = [];
265
+ if (n.tools != null) {
266
+ if (!Array.isArray(n.tools)) add("toolsList", {}, at);
267
+ else {
268
+ tools = n.tools.map(text);
269
+ for (const t of tools) if (!TOOL.test(t)) add("toolName", { name: t }, at);
270
+ if (new Set(tools).size !== tools.length) add("toolTwice", {}, at);
271
+ if (tools.length > FLOW_LIMITS.tools) add("toolsMany", { max: FLOW_LIMITS.tools }, at);
272
+ }
273
+ }
274
+ if (n.human != null && typeof n.human !== "boolean") add("humanBool", {}, at);
275
+ const examples: FlowExample[] = [];
276
+ if (n.examples != null) {
277
+ if (!Array.isArray(n.examples)) add("examplesList", {}, at);
278
+ else {
279
+ if (n.examples.length > FLOW_LIMITS.examples) add("examplesMany", { max: FLOW_LIMITS.examples }, at);
280
+ (n.examples as unknown[]).forEach((ex, j) => {
281
+ const ea: FlowAt = { ...at, example: j + 1 };
282
+ if (!isObject(ex)) { add("exampleObject", {}, ea); return; }
283
+ for (const k of Object.keys(ex)) if (!EXAMPLE_KEYS.has(k) && !(allowHtml && k === "html")) add("unknownKey", { key: k, known: "title, kind, md" }, ea);
284
+ if (allowHtml && ex.html != null && typeof ex.html !== "string") add("htmlText", {}, ea);
285
+ const title = text(ex.title);
286
+ if (!title) add("noTitle", {}, ea);
287
+ else if (title.length > FLOW_LIMITS.exampleTitle) add("titleLong", { max: FLOW_LIMITS.exampleTitle }, ea);
288
+ if (!FLOW_EXAMPLE_KINDS.includes(ex.kind as FlowExampleKind)) add("kind", { value: String(ex.kind ?? ""), allowed: FLOW_EXAMPLE_KINDS.join(" | ") }, ea);
289
+ // md keeps its line breaks (Markdown); only the ends are trimmed.
290
+ const md = typeof ex.md === "string" ? ex.md.replace(/\r\n?/g, "\n").trim() : "";
291
+ if (!md) add("mdEmpty", {}, ea);
292
+ else if (md.length > FLOW_LIMITS.exampleMd) add("mdLong", { length: md.length, max: FLOW_LIMITS.exampleMd }, ea);
293
+ examples.push({ title, kind: ex.kind as FlowExampleKind, md, ...(allowHtml && typeof ex.html === "string" ? { html: ex.html } : {}) });
294
+ });
295
+ }
296
+ }
297
+ const node: FlowNode = { id, label, kind, phase, detail, tools, human: n.human === true || kind === "stop", examples };
298
+ nodes.push(node);
299
+ if (ID.test(id) && !byId.has(id)) byId.set(id, node);
300
+ });
301
+
302
+ const edges: FlowEdge[] = [];
303
+ const pairs = new Set<string>();
304
+ (x.edges as unknown[]).forEach((e, i) => {
305
+ const at: FlowAt = isObject(e) && e.from ? { edge: i + 1, from: String(e.from), to: String(e.to) } : { edge: i + 1 };
306
+ if (!isObject(e)) { add("notAnObject", {}, at); return; }
307
+ for (const k of Object.keys(e)) if (!EDGE_KEYS.has(k)) add("unknownKey", { key: k, known: [...EDGE_KEYS].join(", ") }, at);
308
+ const from = text(e.from);
309
+ const to = text(e.to);
310
+ if (!byId.has(from)) add("noNode", { id: from }, at);
311
+ if (!byId.has(to)) add("noNode", { id: to }, at);
312
+ if (from && from === to) add("selfEdge", {}, at);
313
+ const kind = (e.kind == null ? "normal" : e.kind) as FlowEdgeKind;
314
+ if (!FLOW_EDGE_KINDS.includes(kind)) add("kind", { value: String(kind), allowed: FLOW_EDGE_KINDS.join(" | ") }, at);
315
+ if ((kind === "yes" || kind === "no") && byId.get(from) && byId.get(from)!.kind !== "decision") add("branchFromStep", { kind }, at);
316
+ if (e.label != null && typeof e.label !== "string") add("edgeLabelText", {}, at);
317
+ const label = text(e.label);
318
+ if (label.length > FLOW_LIMITS.edgeLabel) add("edgeLabelLong", { max: FLOW_LIMITS.edgeLabel }, at);
319
+ if (pairs.has(`${from}>${to}`)) add("edgeTwice", {}, at);
320
+ pairs.add(`${from}>${to}`);
321
+ edges.push({ from, to, label, kind });
322
+ });
323
+
324
+ // The shape of the whole: one way in, somewhere to end, no dead end, every node reachable and every node able to finish.
325
+ const ok = edges.filter((e) => byId.has(e.from) && byId.has(e.to));
326
+ const outs = (id: string) => ok.filter((e) => e.from === id);
327
+ const starts = nodes.filter((n) => n.kind === "start");
328
+ if (starts.length !== 1) add("startCount", { count: starts.length });
329
+ if (!nodes.some((n) => n.kind === "end")) add("noEnd", {});
330
+ for (const n of byId.values()) {
331
+ const out = outs(n.id).length;
332
+ if (n.kind === "start" && ok.some((e) => e.to === n.id)) add("startIncoming", { id: n.id });
333
+ if (TERMINAL.has(n.kind) && out) add("endOutgoing", { id: n.id, kind: n.kind });
334
+ if (!TERMINAL.has(n.kind) && !out) add("deadEnd", { id: n.id });
335
+ if (n.kind === "decision" && out && out < 2) add("decisionBranches", { id: n.id });
336
+ }
337
+ if (starts.length === 1 && byId.has(starts[0]!.id)) {
338
+ const seen = walk(starts[0]!.id, ok, "from", "to");
339
+ const lost = [...byId.keys()].filter((id) => !seen.has(id));
340
+ if (lost.length) add("unreachable", { ids: lost });
341
+ }
342
+ const ends = [...byId.values()].filter((n) => TERMINAL.has(n.kind)).map((n) => n.id);
343
+ if (ends.length) {
344
+ const back = new Set<string>();
345
+ for (const id of ends) for (const s of walk(id, ok, "to", "from")) back.add(s);
346
+ const stuck = [...byId.keys()].filter((id) => !back.has(id));
347
+ if (stuck.length) add("neverEnds", { ids: stuck });
348
+ }
349
+ if (problems.length) throw fail();
350
+ return { direction, nodes, edges };
351
+ }
352
+
353
+ function walk(from: string, edges: FlowEdge[], a: "from" | "to", b: "from" | "to"): Set<string> {
354
+ const seen = new Set([from]);
355
+ const queue = [from];
356
+ while (queue.length) {
357
+ const id = queue.shift()!;
358
+ for (const e of edges) if (e[a] === id && !seen.has(e[b])) { seen.add(e[b]); queue.push(e[b]); }
359
+ }
360
+ return seen;
361
+ }
362
+
363
+ /** Attach `html` to every example with the caller's Markdown renderer (a server route): the browser needs no Markdown library. */
364
+ export function flowWithHtml<F extends Flow>(flow: F, render: (md: string) => string): F {
365
+ return { ...flow, nodes: flow.nodes.map((n) => ({ ...n, examples: (n.examples || []).map((x) => ({ ...x, html: render(x.md) })) })) };
366
+ }
367
+
368
+ /** The phases a flow actually uses, in the caller's order. */
369
+ export const phasesIn = (flow: Pick<Flow, "nodes">, phases: readonly FlowPhase[]): FlowPhase[] =>
370
+ phases.filter((p) => flow.nodes.some((n) => n.phase === p.key));
371
+
372
+ /** A tool's short name in a box: the surface's own prefix off (`gemboss_get_skill` → `get_skill`). */
373
+ export const shortTool = (t: string, prefixes: readonly string[] = ["gemboss_", "gemboss.", "radar_"]): string => {
374
+ const s = String(t);
375
+ const p = prefixes.find((x) => s.startsWith(x));
376
+ return p ? s.slice(p.length) : s;
377
+ };
378
+
379
+ // ── Zoom (pure, so it can be tested; the canvas calls it) ────────────────────────────────────────────────────────────────
380
+ /** 10%–400%, as the GemBoss admin's own canvases (use-canvas-viewport.ts): zoom out freely, as a design tool does. */
381
+ export const FLOW_ZOOM = { min: 0.1, max: 4 } as const;
382
+
383
+ /** Whether a plain wheel pans the canvas: always in full screen; in a page only once zoomed in past the fit (until then the wheel
384
+ * scrolls the page, so a reader is never trapped in a tall box in the middle of it). ⌘ / Ctrl + wheel always zooms. */
385
+ export const flowWheelPans = ({ zoom, home, full = false }: { zoom: number; home: number; full?: boolean }) =>
386
+ Boolean(full || (home > 0 && zoom > home * 1.02));
387
+
388
+ /** ⌘ + wheel (React Flow zooms with Ctrl and a pinch only): the new viewport around the pointer (px, py inside the canvas), with
389
+ * d3-zoom's own wheelDelta (line 0.05, page 1, pixel 0.002) so it feels the same as Ctrl + wheel. The point under the pointer stays. */
390
+ export function wheelZoom(
391
+ vp: { x: number; y: number; zoom: number },
392
+ { px, py, deltaY, deltaMode = 0 }: { px: number; py: number; deltaY: number; deltaMode?: number },
393
+ { min = FLOW_ZOOM.min, max = FLOW_ZOOM.max }: { min?: number; max?: number } = {},
394
+ ): { x: number; y: number; zoom: number } {
395
+ const d = -Number(deltaY || 0) * (deltaMode === 1 ? 0.05 : deltaMode ? 1 : 0.002);
396
+ const zoom = Math.min(max, Math.max(min, vp.zoom * 2 ** d));
397
+ const r = zoom / vp.zoom;
398
+ return { x: px - (px - vp.x) * r, y: py - (py - vp.y) * r, zoom };
399
+ }
400
+
401
+ /** A zoom level to print: 1 → "100%". */
402
+ export const zoomLabel = (z: number) => `${Math.round(Number(z || 0) * 100)}%`;
403
+
404
+ /** A key while the canvas has focus → "in" | "out" | "reset" | null. + (and = without Shift) / − / 0, with or without ⌘ / Ctrl: focus
405
+ * inside the canvas, ⌘ + zooms the CANVAS, not the page. Alt is left alone. */
406
+ export function flowZoomKey({ key, altKey = false }: { key?: string; altKey?: boolean } = {}): "in" | "out" | "reset" | null {
407
+ if (altKey) return null;
408
+ if (key === "+" || key === "=") return "in";
409
+ if (key === "-" || key === "_" || key === "−") return "out";
410
+ if (key === "0") return "reset";
411
+ return null;
412
+ }