@dudko.dev/agent-web-react 0.0.26 → 0.0.27

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.
@@ -0,0 +1,3390 @@
1
+ import {
2
+ AlertIcon,
3
+ BookIcon,
4
+ CheckIcon,
5
+ ChevronIcon,
6
+ DownloadIcon,
7
+ PlusIcon,
8
+ SpinnerIcon,
9
+ StopIcon,
10
+ ToolIcon,
11
+ XIcon,
12
+ errMessage,
13
+ formatTokens
14
+ } from "./chunk-LCJZEGB5.js";
15
+
16
+ // src/canvas/Canvas.tsx
17
+ import {
18
+ createContext,
19
+ forwardRef,
20
+ useCallback,
21
+ useContext,
22
+ useEffect,
23
+ useId,
24
+ useImperativeHandle,
25
+ useLayoutEffect,
26
+ useMemo,
27
+ useRef,
28
+ useState
29
+ } from "react";
30
+
31
+ // src/canvas/geometry.ts
32
+ var DEFAULT_MIN_ZOOM = 0.25;
33
+ var DEFAULT_MAX_ZOOM = 2;
34
+ var IDENTITY_VIEWPORT = { x: 0, y: 0, zoom: 1 };
35
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
36
+ var screenToWorld = (point, viewport) => ({
37
+ x: (point.x - viewport.x) / viewport.zoom,
38
+ y: (point.y - viewport.y) / viewport.zoom
39
+ });
40
+ var worldToScreen = (point, viewport) => ({
41
+ x: point.x * viewport.zoom + viewport.x,
42
+ y: point.y * viewport.zoom + viewport.y
43
+ });
44
+ var panBy = (viewport, dx, dy) => ({
45
+ ...viewport,
46
+ x: viewport.x + dx,
47
+ y: viewport.y + dy
48
+ });
49
+ var zoomAt = (viewport, zoom, anchor, minZoom = DEFAULT_MIN_ZOOM, maxZoom = DEFAULT_MAX_ZOOM) => {
50
+ const next = clamp(zoom, minZoom, maxZoom);
51
+ if (next === viewport.zoom) return viewport;
52
+ const world = screenToWorld(anchor, viewport);
53
+ return { zoom: next, x: anchor.x - world.x * next, y: anchor.y - world.y * next };
54
+ };
55
+ var pinchViewport = (viewport, before, after, minZoom = DEFAULT_MIN_ZOOM, maxZoom = DEFAULT_MAX_ZOOM) => {
56
+ const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
57
+ const middle = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
58
+ const was = distance(before[0], before[1]);
59
+ const is = distance(after[0], after[1]);
60
+ const zoom = clamp(was > 0 ? viewport.zoom * is / was : viewport.zoom, minZoom, maxZoom);
61
+ const world = screenToWorld(middle(before[0], before[1]), viewport);
62
+ const at = middle(after[0], after[1]);
63
+ return { zoom, x: at.x - world.x * zoom, y: at.y - world.y * zoom };
64
+ };
65
+ var boundsOf = (rects) => {
66
+ if (rects.length === 0) return void 0;
67
+ let left = Infinity;
68
+ let top = Infinity;
69
+ let right = -Infinity;
70
+ let bottom = -Infinity;
71
+ for (const r of rects) {
72
+ left = Math.min(left, r.x);
73
+ top = Math.min(top, r.y);
74
+ right = Math.max(right, r.x + r.width);
75
+ bottom = Math.max(bottom, r.y + r.height);
76
+ }
77
+ return { x: left, y: top, width: right - left, height: bottom - top };
78
+ };
79
+ var fitAxis = (start, length, room, zoom, padding) => length * zoom <= room - padding * 2 + 0.5 ? (room - length * zoom) / 2 - start * zoom : padding - start * zoom;
80
+ var fitViewport = (rects, size, options = {}) => {
81
+ const bounds = boundsOf(rects);
82
+ if (!bounds || size.width <= 0 || size.height <= 0) return IDENTITY_VIEWPORT;
83
+ const { minZoom = DEFAULT_MIN_ZOOM, maxZoom = 1 } = options;
84
+ const padding = Math.min(options.padding ?? 48, size.width / 8, size.height / 8);
85
+ const zoom = clamp(
86
+ Math.min(
87
+ (size.width - padding * 2) / Math.max(bounds.width, 1),
88
+ (size.height - padding * 2) / Math.max(bounds.height, 1)
89
+ ),
90
+ minZoom,
91
+ maxZoom
92
+ );
93
+ return {
94
+ zoom,
95
+ x: fitAxis(bounds.x, bounds.width, size.width, zoom, padding),
96
+ y: fitAxis(bounds.y, bounds.height, size.height, zoom, padding)
97
+ };
98
+ };
99
+ var centerOn = (rect, size, zoom) => ({
100
+ zoom,
101
+ x: size.width / 2 - (rect.x + rect.width / 2) * zoom,
102
+ y: size.height / 2 - (rect.y + rect.height / 2) * zoom
103
+ });
104
+ var isRectVisible = (rect, size, viewport) => {
105
+ const a = worldToScreen(rect, viewport);
106
+ const b = worldToScreen({ x: rect.x + rect.width, y: rect.y + rect.height }, viewport);
107
+ return b.x > 0 && b.y > 0 && a.x < size.width && a.y < size.height;
108
+ };
109
+ var snapTo = (value, grid) => (
110
+ // `+ 0`: a rounded-away negative is 0, not -0.
111
+ grid > 0 ? Math.round(value / grid) * grid + 0 : value
112
+ );
113
+ var snapPoint = (point, grid) => ({
114
+ x: snapTo(point.x, grid),
115
+ y: snapTo(point.y, grid)
116
+ });
117
+ var rectContains = (rect, point) => point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
118
+ var hitNode = (nodes, point) => {
119
+ for (let i = nodes.length - 1; i >= 0; i--) {
120
+ if (rectContains(nodes[i], point)) return nodes[i].id;
121
+ }
122
+ return void 0;
123
+ };
124
+ var inputAnchor = (rect) => ({ x: rect.x, y: rect.y + rect.height / 2 });
125
+ var outputAnchor = (rect, index = 0, count = 1) => ({
126
+ x: rect.x + rect.width,
127
+ y: rect.y + rect.height * (index + 1) / (Math.max(count, 1) + 1)
128
+ });
129
+ var edgeCurve = (from, to, options = {}) => {
130
+ const dx = to.x - from.x;
131
+ const dy = to.y - from.y;
132
+ if (dx >= 40) {
133
+ const reach2 = Math.max(dx / 2, 40);
134
+ return {
135
+ p0: from,
136
+ p1: { x: from.x + reach2, y: from.y },
137
+ p2: { x: to.x - reach2, y: to.y },
138
+ p3: to
139
+ };
140
+ }
141
+ const reach = clamp(60 + Math.abs(dx) / 4, 60, 220);
142
+ const clearance = options.clearance ?? 90;
143
+ const swing = Math.abs(dy) < clearance ? clearance + Math.abs(dy) / 2 : 0;
144
+ return {
145
+ p0: from,
146
+ p1: { x: from.x + reach, y: from.y + swing },
147
+ p2: { x: to.x - reach, y: to.y + swing },
148
+ p3: to
149
+ };
150
+ };
151
+ var round = (n) => Math.round(n * 100) / 100;
152
+ var curvePath = ({ p0, p1, p2, p3 }) => `M ${round(p0.x)} ${round(p0.y)} C ${round(p1.x)} ${round(p1.y)}, ${round(p2.x)} ${round(p2.y)}, ${round(p3.x)} ${round(p3.y)}`;
153
+ var curvePoint = ({ p0, p1, p2, p3 }, t) => {
154
+ const u = 1 - t;
155
+ const a = u * u * u;
156
+ const b = 3 * u * u * t;
157
+ const c = 3 * u * t * t;
158
+ const d = t * t * t;
159
+ return {
160
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
161
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
162
+ };
163
+ };
164
+ var distanceToSegment = (p, a, b) => {
165
+ const dx = b.x - a.x;
166
+ const dy = b.y - a.y;
167
+ const length = dx * dx + dy * dy;
168
+ const t = length === 0 ? 0 : clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / length, 0, 1);
169
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
170
+ };
171
+ var distanceToCurve = (curve, point, samples = 24) => {
172
+ let best = Infinity;
173
+ let previous = curve.p0;
174
+ for (let i = 1; i <= samples; i++) {
175
+ const next = curvePoint(curve, i / samples);
176
+ best = Math.min(best, distanceToSegment(point, previous, next));
177
+ previous = next;
178
+ }
179
+ return best;
180
+ };
181
+ var hitEdge = (edges, point, tolerance = 8) => {
182
+ let best;
183
+ let bestDistance = Infinity;
184
+ for (const edge of edges) {
185
+ const distance = distanceToCurve(edge.curve, point);
186
+ if (distance <= tolerance && distance < bestDistance) {
187
+ best = edge.id;
188
+ bestDistance = distance;
189
+ }
190
+ }
191
+ return best;
192
+ };
193
+ var readingOrder = (nodes, column = 40) => nodes.map((node, index) => ({ node, index })).sort((a, b) => {
194
+ const ax = Math.round(a.node.x / column);
195
+ const bx = Math.round(b.node.x / column);
196
+ return ax - bx || a.node.y - b.node.y || a.index - b.index;
197
+ }).map(({ node }) => node.id);
198
+
199
+ // src/canvas/Canvas.tsx
200
+ import { jsx, jsxs } from "react/jsx-runtime";
201
+ var defaultCanvasLabels = {
202
+ canvas: "Canvas",
203
+ help: "Tab moves between nodes and their connections. Arrow keys move the selected node, Enter opens it, Delete removes it, C starts a connection, Escape clears the selection. On the canvas itself the arrow keys pan, plus and minus zoom, 0 fits everything.",
204
+ node: "node",
205
+ edge: (from, to, description) => `Connection from ${from} to ${to}${description ? `: ${description}` : ""}`,
206
+ port: (node, port) => `Connect ${node}${port ? ` (${port})` : ""} to another node`,
207
+ connectsTo: (names) => `Connects to: ${names}.`,
208
+ receivesFrom: (names) => `Receives from: ${names}.`,
209
+ zoomIn: "Zoom in",
210
+ zoomOut: "Zoom out",
211
+ fit: "Fit to view",
212
+ zoomLevel: (percent) => `${percent}%`,
213
+ connectHint: (from) => `Pick the node to connect ${from} to`,
214
+ cancel: "Cancel",
215
+ connected: (from, to) => `Connected ${from} to ${to}`
216
+ };
217
+ var PortContext = createContext(void 0);
218
+ var DEFAULT_SIZE = { width: 240, height: 96 };
219
+ var DEFAULT_PORT = "out";
220
+ var DRAG_THRESHOLD = 4;
221
+ var DOUBLE_TAP_MS = 350;
222
+ var INTERACTIVE = "button, a, input, textarea, select, summary, [data-awr-nodrag]";
223
+ var EDITABLE = 'input, textarea, select, [contenteditable="true"]';
224
+ var TONES = ["default", "active", "done", "muted", "danger"];
225
+ var useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
226
+ var domId = (id) => encodeURIComponent(id).replace(/[^a-zA-Z0-9_-]/g, "_");
227
+ var cx = (...parts) => parts.filter(Boolean).join(" ");
228
+ var CanvasPort = ({ id = DEFAULT_PORT, label, className }) => {
229
+ const ctx = useContext(PortContext);
230
+ return /* @__PURE__ */ jsx(
231
+ "button",
232
+ {
233
+ type: "button",
234
+ className: cx(
235
+ "awr-canvas__port",
236
+ ctx?.active === id && "awr-canvas__port--active",
237
+ className
238
+ ),
239
+ "data-awr-port": id,
240
+ "aria-label": ctx ? ctx.labels.port(ctx.nodeLabel, label) : label,
241
+ "aria-pressed": ctx?.active === id,
242
+ disabled: ctx?.disabled
243
+ }
244
+ );
245
+ };
246
+ var Canvas = forwardRef((props, ref) => {
247
+ const {
248
+ nodes,
249
+ edges,
250
+ renderNode,
251
+ selection = null,
252
+ onSelectionChange,
253
+ onViewportChange,
254
+ onNodeMove,
255
+ onNodeMoveEnd,
256
+ onConnect,
257
+ onDelete,
258
+ onOpen,
259
+ snap = 20,
260
+ showGrid = true,
261
+ showControls = true,
262
+ minZoom = DEFAULT_MIN_ZOOM,
263
+ maxZoom = DEFAULT_MAX_ZOOM,
264
+ fitOnMount = true,
265
+ fitKey,
266
+ autoFitMinZoom,
267
+ readOnly = false,
268
+ className,
269
+ style,
270
+ children
271
+ } = props;
272
+ const labels = useMemo(() => ({ ...defaultCanvasLabels, ...props.labels }), [props.labels]);
273
+ const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");
274
+ const rootRef = useRef(null);
275
+ const nodeEls = useRef(/* @__PURE__ */ new Map());
276
+ const [size, setSize] = useState({ width: 0, height: 0 });
277
+ const [measured, setMeasured] = useState({});
278
+ const [ownViewport, setOwnViewport] = useState(IDENTITY_VIEWPORT);
279
+ const controlled = props.viewport !== void 0;
280
+ const viewport = props.viewport ?? ownViewport;
281
+ const viewportRef = useRef(viewport);
282
+ viewportRef.current = viewport;
283
+ const setViewport = useCallback(
284
+ (next) => {
285
+ const value = typeof next === "function" ? next(viewportRef.current) : next;
286
+ if (value.x === viewportRef.current.x && value.y === viewportRef.current.y && value.zoom === viewportRef.current.zoom) {
287
+ return;
288
+ }
289
+ viewportRef.current = value;
290
+ touched.current = true;
291
+ if (!controlled) setOwnViewport(value);
292
+ onViewportChange?.(value);
293
+ },
294
+ [controlled, onViewportChange]
295
+ );
296
+ const touched = useRef(false);
297
+ const rectOf = useCallback(
298
+ (node) => {
299
+ const m = measured[node.id];
300
+ return {
301
+ x: node.x,
302
+ y: node.y,
303
+ width: m?.width ?? node.width ?? DEFAULT_SIZE.width,
304
+ height: m?.height ?? node.height ?? DEFAULT_SIZE.height
305
+ };
306
+ },
307
+ [measured]
308
+ );
309
+ const nodeById = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
310
+ const nodesRef = useRef(nodes);
311
+ nodesRef.current = nodes;
312
+ const rectOfRef = useRef(rectOf);
313
+ rectOfRef.current = rectOf;
314
+ const measure = useCallback((ids) => {
315
+ const zoom = viewportRef.current.zoom || 1;
316
+ setMeasured((current) => {
317
+ let next = current;
318
+ const live = new Set(nodeEls.current.keys());
319
+ for (const id of Object.keys(current)) {
320
+ if (!live.has(id)) {
321
+ if (next === current) next = { ...current };
322
+ delete next[id];
323
+ }
324
+ }
325
+ for (const id of ids ?? live) {
326
+ const el = nodeEls.current.get(id);
327
+ if (!el) continue;
328
+ const box = el.getBoundingClientRect();
329
+ const ports = {};
330
+ for (const port of el.querySelectorAll("[data-awr-port]")) {
331
+ const p = port.getBoundingClientRect();
332
+ ports[port.dataset.awrPort] = {
333
+ x: Math.round((p.left + p.width / 2 - box.left) / zoom),
334
+ y: Math.round((p.top + p.height / 2 - box.top) / zoom)
335
+ };
336
+ }
337
+ const value = { width: el.offsetWidth, height: el.offsetHeight, ports };
338
+ const before = current[id];
339
+ const same = before && before.width === value.width && before.height === value.height && Object.keys(before.ports).length === Object.keys(ports).length && Object.entries(ports).every(
340
+ ([key2, p]) => before.ports[key2]?.x === p.x && before.ports[key2]?.y === p.y
341
+ );
342
+ if (!same) {
343
+ if (next === current) next = { ...current };
344
+ next[id] = value;
345
+ }
346
+ }
347
+ return next;
348
+ });
349
+ }, []);
350
+ const observer = useRef(void 0);
351
+ useIsomorphicLayoutEffect(() => {
352
+ const root = rootRef.current;
353
+ if (!root || typeof ResizeObserver === "undefined") {
354
+ if (root) setSize({ width: root.clientWidth, height: root.clientHeight });
355
+ return;
356
+ }
357
+ const ro = new ResizeObserver((entries) => {
358
+ const changed = [];
359
+ for (const entry of entries) {
360
+ if (entry.target === root) {
361
+ setSize({ width: root.clientWidth, height: root.clientHeight });
362
+ } else {
363
+ const id = entry.target.dataset.awrNode;
364
+ if (id) changed.push(id);
365
+ }
366
+ }
367
+ if (changed.length) measure(changed);
368
+ });
369
+ observer.current = ro;
370
+ ro.observe(root);
371
+ for (const el of nodeEls.current.values()) ro.observe(el);
372
+ setSize({ width: root.clientWidth, height: root.clientHeight });
373
+ return () => {
374
+ ro.disconnect();
375
+ observer.current = void 0;
376
+ };
377
+ }, [measure]);
378
+ const shape = nodes.map((n) => `${n.id}:${(n.ports ?? []).map((p) => p.id).join(",")}`).join("|");
379
+ useIsomorphicLayoutEffect(() => {
380
+ measure();
381
+ }, [shape, measure]);
382
+ const setNodeEl = useCallback((id, el) => {
383
+ const before = nodeEls.current.get(id);
384
+ if (before === el) return;
385
+ if (before) observer.current?.unobserve(before);
386
+ if (el) {
387
+ nodeEls.current.set(id, el);
388
+ observer.current?.observe(el);
389
+ } else {
390
+ nodeEls.current.delete(id);
391
+ }
392
+ }, []);
393
+ const [order, setOrder] = useState(() => readingOrder(nodes));
394
+ const reorder = useCallback(() => {
395
+ const next = readingOrder(nodesRef.current);
396
+ setOrder(
397
+ (current) => current.length === next.length && current.every((id, i) => id === next[i]) ? current : next
398
+ );
399
+ }, []);
400
+ const idsKey = nodes.map((n) => n.id).join("|");
401
+ useEffect(() => {
402
+ reorder();
403
+ }, [idsKey, reorder]);
404
+ const ordered = useMemo(() => {
405
+ const known = order.filter((id) => nodeById.has(id));
406
+ const rest = nodes.filter((n) => !order.includes(n.id)).map((n) => n.id);
407
+ return [...known, ...rest].map((id) => nodeById.get(id));
408
+ }, [order, nodes, nodeById]);
409
+ const sizeRef = useRef(size);
410
+ sizeRef.current = size;
411
+ const fitTo = useCallback(
412
+ (smallest) => {
413
+ const rects = nodesRef.current.map((n) => rectOfRef.current(n));
414
+ if (rects.length === 0 || sizeRef.current.width === 0) return;
415
+ setViewport(
416
+ fitViewport(rects, sizeRef.current, {
417
+ // Room for an edge that loops back around its nodes.
418
+ padding: 64,
419
+ minZoom: smallest,
420
+ maxZoom: Math.min(1, maxZoom)
421
+ })
422
+ );
423
+ touched.current = false;
424
+ },
425
+ [setViewport, maxZoom]
426
+ );
427
+ const fit = useCallback(() => fitTo(minZoom), [fitTo, minZoom]);
428
+ const autoFit = useCallback(
429
+ () => fitTo(Math.max(minZoom, autoFitMinZoom ?? minZoom)),
430
+ [fitTo, minZoom, autoFitMinZoom]
431
+ );
432
+ const fitted = useRef(null);
433
+ const allMeasured = nodes.length > 0 && nodes.every((n) => measured[n.id]);
434
+ useEffect(() => {
435
+ if (size.width === 0 || !allMeasured) return;
436
+ const first = fitted.current === null;
437
+ const wanted = fitOnMount && !controlled;
438
+ if (first ? !wanted : fitted.current === fitKey) {
439
+ if (first) fitted.current = fitKey;
440
+ else if (wanted && !touched.current) autoFit();
441
+ return;
442
+ }
443
+ fitted.current = fitKey;
444
+ autoFit();
445
+ }, [size.width, size.height, allMeasured, fitKey, fitOnMount, controlled, autoFit]);
446
+ const zoomStep = useCallback(
447
+ (factor) => {
448
+ const { width, height } = sizeRef.current;
449
+ setViewport(
450
+ (v) => zoomAt(v, v.zoom * factor, { x: width / 2, y: height / 2 }, minZoom, maxZoom)
451
+ );
452
+ },
453
+ [setViewport, minZoom, maxZoom]
454
+ );
455
+ const reveal = useCallback(
456
+ (nodeId, always = false) => {
457
+ const node = nodesRef.current.find((n) => n.id === nodeId);
458
+ if (!node || sizeRef.current.width === 0) return;
459
+ const rect = rectOfRef.current(node);
460
+ if (always || !isRectVisible(rect, sizeRef.current, viewportRef.current)) {
461
+ setViewport(centerOn(rect, sizeRef.current, viewportRef.current.zoom));
462
+ }
463
+ },
464
+ [setViewport]
465
+ );
466
+ const select = useCallback(
467
+ (next) => {
468
+ if (next?.kind === selection?.kind && next?.id === selection?.id) return;
469
+ onSelectionChange?.(next);
470
+ },
471
+ [selection, onSelectionChange]
472
+ );
473
+ const [connectFrom, setConnectFrom] = useState();
474
+ const [dragLine, setDragLine] = useState();
475
+ const [dragging, setDragging] = useState();
476
+ const [announcement, setAnnouncement] = useState("");
477
+ const labelOf = useCallback((id) => nodeById.get(id)?.label ?? id, [nodeById]);
478
+ const startConnect = useCallback(
479
+ (node, port) => {
480
+ if (readOnly) return;
481
+ setConnectFrom({ node, port });
482
+ setAnnouncement(labels.connectHint(labelOf(node)));
483
+ },
484
+ [readOnly, labels, labelOf]
485
+ );
486
+ const finishConnect = useCallback(
487
+ (from, port, to) => {
488
+ setConnectFrom(void 0);
489
+ if (from === to || !nodeById.has(to)) return;
490
+ onConnect?.({ from, to, ...port && port !== DEFAULT_PORT ? { fromPort: port } : {} });
491
+ setAnnouncement(labels.connected(labelOf(from), labelOf(to)));
492
+ },
493
+ [nodeById, onConnect, labels, labelOf]
494
+ );
495
+ useEffect(() => {
496
+ if (connectFrom && !nodeById.has(connectFrom.node)) setConnectFrom(void 0);
497
+ }, [connectFrom, nodeById]);
498
+ useImperativeHandle(
499
+ ref,
500
+ () => ({
501
+ fit,
502
+ zoomIn: () => zoomStep(1.25),
503
+ zoomOut: () => zoomStep(0.8),
504
+ center: (nodeId) => reveal(nodeId, true),
505
+ reveal: (nodeId) => reveal(nodeId),
506
+ getViewport: () => viewportRef.current,
507
+ getSize: () => sizeRef.current,
508
+ focus: (target) => {
509
+ const root = rootRef.current;
510
+ if (!root) return;
511
+ if (target.kind === "node") {
512
+ reveal(target.id);
513
+ nodeEls.current.get(target.id)?.focus({ preventScroll: true });
514
+ } else {
515
+ const el = [...root.querySelectorAll("button[data-awr-edge]")].find(
516
+ (b) => b.dataset.awrEdge === target.id
517
+ );
518
+ const edge = el && edgesRef.current.find((e) => e.id === target.id);
519
+ if (edge) reveal(edge.from);
520
+ el?.focus({ preventScroll: true });
521
+ }
522
+ }
523
+ }),
524
+ [fit, zoomStep, reveal]
525
+ );
526
+ const edgesRef = useRef(edges);
527
+ edgesRef.current = edges;
528
+ const pointers = useRef(/* @__PURE__ */ new Map());
529
+ const gesture = useRef(void 0);
530
+ const last = useRef({ x: 0, y: 0 });
531
+ const lastTap = useRef(void 0);
532
+ const toLocal = (e) => {
533
+ const box = rootRef.current.getBoundingClientRect();
534
+ return { x: e.clientX - box.left, y: e.clientY - box.top };
535
+ };
536
+ const onPointerDown = (e) => {
537
+ if (e.pointerType === "mouse" && e.button !== 0 && e.button !== 1) return;
538
+ const target = e.target;
539
+ if (target.closest("[data-awr-canvas-ignore]")) return;
540
+ const nodeEl = target.closest("[data-awr-node]");
541
+ const portEl = target.closest("[data-awr-port]");
542
+ if (nodeEl && !portEl && target !== nodeEl && target.closest(INTERACTIVE)) return;
543
+ const local = toLocal(e);
544
+ pointers.current.set(e.pointerId, local);
545
+ try {
546
+ e.currentTarget.setPointerCapture(e.pointerId);
547
+ } catch {
548
+ }
549
+ last.current = local;
550
+ if (pointers.current.size === 2) {
551
+ gesture.current = { kind: "pinch", start: local, moved: true };
552
+ setDragLine(void 0);
553
+ setDragging(void 0);
554
+ return;
555
+ }
556
+ if (pointers.current.size > 2) return;
557
+ const edgeEl = target.closest("[data-awr-edge]");
558
+ if (e.button === 1) {
559
+ gesture.current = { kind: "pan", start: local, moved: false };
560
+ e.preventDefault();
561
+ } else if (portEl && nodeEl && !readOnly) {
562
+ gesture.current = {
563
+ kind: "connect",
564
+ from: nodeEl.dataset.awrNode,
565
+ port: portEl.dataset.awrPort,
566
+ start: local,
567
+ moved: false
568
+ };
569
+ } else if (nodeEl) {
570
+ const id = nodeEl.dataset.awrNode;
571
+ const node = nodeById.get(id);
572
+ if (!node) return;
573
+ const origin = { x: node.x, y: node.y };
574
+ gesture.current = { kind: "node", id, start: local, origin, moved: false, at: origin };
575
+ if (!connectFrom) select({ kind: "node", id });
576
+ } else if (edgeEl) {
577
+ gesture.current = {
578
+ kind: "edge",
579
+ id: edgeEl.dataset.awrEdge,
580
+ start: local,
581
+ moved: false
582
+ };
583
+ } else {
584
+ gesture.current = { kind: "pan", start: local, moved: false };
585
+ }
586
+ };
587
+ const onPointerMove = (e) => {
588
+ const before = pointers.current.get(e.pointerId);
589
+ if (!before) return;
590
+ const local = toLocal(e);
591
+ const g = gesture.current;
592
+ if (g?.kind === "pinch") {
593
+ if (pointers.current.size < 2) return;
594
+ const [a, b] = [...pointers.current.entries()];
595
+ const was = [a[1], b[1]];
596
+ pointers.current.set(e.pointerId, local);
597
+ const is = [
598
+ pointers.current.get(a[0]),
599
+ pointers.current.get(b[0])
600
+ ];
601
+ setViewport((v) => pinchViewport(v, was, is, minZoom, maxZoom));
602
+ return;
603
+ }
604
+ pointers.current.set(e.pointerId, local);
605
+ if (!g) return;
606
+ if (!g.moved) {
607
+ if (Math.hypot(local.x - g.start.x, local.y - g.start.y) < DRAG_THRESHOLD) return;
608
+ g.moved = true;
609
+ if (g.kind === "node" && !readOnly) setDragging(g.id);
610
+ }
611
+ if (g.kind === "pan" || g.kind === "edge" || g.kind === "node" && readOnly) {
612
+ setViewport((v) => panBy(v, local.x - last.current.x, local.y - last.current.y));
613
+ } else if (g.kind === "node") {
614
+ const zoom = viewportRef.current.zoom;
615
+ const next = snapPoint(
616
+ {
617
+ x: g.origin.x + (local.x - g.start.x) / zoom,
618
+ y: g.origin.y + (local.y - g.start.y) / zoom
619
+ },
620
+ snap
621
+ );
622
+ if (next.x !== g.at.x || next.y !== g.at.y) {
623
+ g.at = next;
624
+ onNodeMove?.(g.id, next);
625
+ }
626
+ } else if (g.kind === "connect") {
627
+ setDragLine({ from: g.from, port: g.port, to: screenToWorld(local, viewportRef.current) });
628
+ }
629
+ last.current = local;
630
+ };
631
+ const tapped = (key2) => {
632
+ const now = Date.now();
633
+ const double = lastTap.current?.key === key2 && now - lastTap.current.time < DOUBLE_TAP_MS;
634
+ lastTap.current = double ? void 0 : { key: key2, time: now };
635
+ return double;
636
+ };
637
+ const onPointerEnd = (e) => {
638
+ if (!pointers.current.has(e.pointerId)) return;
639
+ const local = toLocal(e);
640
+ pointers.current.delete(e.pointerId);
641
+ try {
642
+ e.currentTarget.releasePointerCapture(e.pointerId);
643
+ } catch {
644
+ }
645
+ const g = gesture.current;
646
+ if (!g) return;
647
+ if (g.kind === "pinch") {
648
+ if (pointers.current.size === 0) gesture.current = void 0;
649
+ return;
650
+ }
651
+ gesture.current = void 0;
652
+ setDragging(void 0);
653
+ setDragLine(void 0);
654
+ if (e.type === "pointercancel") return;
655
+ if (g.kind === "pan") {
656
+ if (g.moved) return;
657
+ if (connectFrom) setConnectFrom(void 0);
658
+ else select(null);
659
+ } else if (g.kind === "node") {
660
+ if (g.moved) {
661
+ if (!readOnly) {
662
+ onNodeMoveEnd?.(g.id, g.at);
663
+ reorder();
664
+ }
665
+ } else if (connectFrom) {
666
+ finishConnect(connectFrom.node, connectFrom.port, g.id);
667
+ } else if (tapped(`node:${g.id}`)) {
668
+ onOpen?.({ kind: "node", id: g.id });
669
+ }
670
+ } else if (g.kind === "edge") {
671
+ if (g.moved) return;
672
+ select({ kind: "edge", id: g.id });
673
+ if (tapped(`edge:${g.id}`)) onOpen?.({ kind: "edge", id: g.id });
674
+ } else if (g.kind === "connect") {
675
+ if (!g.moved) {
676
+ if (connectFrom?.node === g.from && connectFrom.port === g.port) setConnectFrom(void 0);
677
+ else startConnect(g.from, g.port);
678
+ return;
679
+ }
680
+ const world = screenToWorld(local, viewportRef.current);
681
+ const rects = ordered.map((n) => ({ id: n.id, ...rectOf(n) }));
682
+ const to = hitNode(rects, world);
683
+ if (to) finishConnect(g.from, g.port, to);
684
+ }
685
+ };
686
+ useEffect(() => {
687
+ const root = rootRef.current;
688
+ if (!root) return;
689
+ const onWheel = (e) => {
690
+ if (e.target.closest?.("[data-awr-canvas-ignore]")) return;
691
+ e.preventDefault();
692
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? root.clientHeight : 1;
693
+ if (e.ctrlKey || e.metaKey) {
694
+ const box = root.getBoundingClientRect();
695
+ const anchor = { x: e.clientX - box.left, y: e.clientY - box.top };
696
+ const factor = Math.exp(-e.deltaY * unit / 240);
697
+ setViewport((v) => zoomAt(v, v.zoom * factor, anchor, minZoom, maxZoom));
698
+ } else {
699
+ setViewport((v) => panBy(v, -e.deltaX * unit, -e.deltaY * unit));
700
+ }
701
+ };
702
+ const stop = (e) => e.preventDefault();
703
+ root.addEventListener("wheel", onWheel, { passive: false });
704
+ root.addEventListener("gesturestart", stop);
705
+ root.addEventListener("gesturechange", stop);
706
+ return () => {
707
+ root.removeEventListener("wheel", onWheel);
708
+ root.removeEventListener("gesturestart", stop);
709
+ root.removeEventListener("gesturechange", stop);
710
+ };
711
+ }, [setViewport, minZoom, maxZoom]);
712
+ const onKeyDown = (e) => {
713
+ const target = e.target;
714
+ if (target.closest("[data-awr-canvas-ignore]") || target.matches(EDITABLE)) return;
715
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
716
+ const root = rootRef.current;
717
+ if (e.key === "Escape") {
718
+ if (connectFrom) setConnectFrom(void 0);
719
+ else if (selection) select(null);
720
+ else return;
721
+ e.preventDefault();
722
+ return;
723
+ }
724
+ const nodeEl = target.closest("[data-awr-node]");
725
+ const portEl = target.closest("[data-awr-port]");
726
+ const activate = e.key === "Enter" || e.key === " ";
727
+ const remove = e.key === "Delete" || e.key === "Backspace";
728
+ if (portEl && nodeEl) {
729
+ if (!activate) return;
730
+ e.preventDefault();
731
+ const id = nodeEl.dataset.awrNode;
732
+ if (connectFrom?.node === id && connectFrom.port === portEl.dataset.awrPort) {
733
+ setConnectFrom(void 0);
734
+ } else {
735
+ startConnect(id, portEl.dataset.awrPort);
736
+ }
737
+ return;
738
+ }
739
+ if (nodeEl && target === nodeEl) {
740
+ const id = nodeEl.dataset.awrNode;
741
+ const node = nodeById.get(id);
742
+ if (!node) return;
743
+ const arrows = {
744
+ ArrowLeft: { x: -1, y: 0 },
745
+ ArrowRight: { x: 1, y: 0 },
746
+ ArrowUp: { x: 0, y: -1 },
747
+ ArrowDown: { x: 0, y: 1 }
748
+ };
749
+ const arrow = arrows[e.key];
750
+ if (arrow) {
751
+ e.preventDefault();
752
+ if (readOnly) return;
753
+ const step = (snap > 0 ? snap : 10) * (e.shiftKey ? 5 : 1);
754
+ const next = snapPoint({ x: node.x + arrow.x * step, y: node.y + arrow.y * step }, snap);
755
+ onNodeMove?.(id, next);
756
+ onNodeMoveEnd?.(id, next);
757
+ } else if (activate) {
758
+ e.preventDefault();
759
+ if (connectFrom) finishConnect(connectFrom.node, connectFrom.port, id);
760
+ else onOpen?.({ kind: "node", id });
761
+ } else if (e.key === "c" || e.key === "C") {
762
+ e.preventDefault();
763
+ startConnect(id, node.ports?.[0]?.id);
764
+ } else if (remove && !readOnly) {
765
+ e.preventDefault();
766
+ onDelete?.({ kind: "node", id });
767
+ root.focus({ preventScroll: true });
768
+ }
769
+ return;
770
+ }
771
+ const edgeEl = target.closest("button[data-awr-edge]");
772
+ if (edgeEl) {
773
+ const id = edgeEl.dataset.awrEdge;
774
+ if (activate) {
775
+ e.preventDefault();
776
+ select({ kind: "edge", id });
777
+ onOpen?.({ kind: "edge", id });
778
+ } else if (remove && !readOnly) {
779
+ e.preventDefault();
780
+ onDelete?.({ kind: "edge", id });
781
+ root.focus({ preventScroll: true });
782
+ }
783
+ return;
784
+ }
785
+ if (target !== root) return;
786
+ const pan = {
787
+ ArrowLeft: [48, 0],
788
+ ArrowRight: [-48, 0],
789
+ ArrowUp: [0, 48],
790
+ ArrowDown: [0, -48]
791
+ };
792
+ if (pan[e.key]) {
793
+ e.preventDefault();
794
+ setViewport((v) => panBy(v, pan[e.key][0], pan[e.key][1]));
795
+ } else if (e.key === "+" || e.key === "=") {
796
+ e.preventDefault();
797
+ zoomStep(1.25);
798
+ } else if (e.key === "-" || e.key === "_") {
799
+ e.preventDefault();
800
+ zoomStep(0.8);
801
+ } else if (e.key === "0") {
802
+ e.preventDefault();
803
+ fit();
804
+ }
805
+ };
806
+ const onFocus = (e) => {
807
+ const target = e.target;
808
+ let byKeyboard = false;
809
+ try {
810
+ byKeyboard = target.matches(":focus-visible");
811
+ } catch {
812
+ byKeyboard = false;
813
+ }
814
+ if (!byKeyboard) return;
815
+ if (target.dataset.awrNode !== void 0) {
816
+ reveal(target.dataset.awrNode);
817
+ if (!connectFrom) select({ kind: "node", id: target.dataset.awrNode });
818
+ } else if (target.dataset.awrEdge !== void 0 && target.tagName === "BUTTON") {
819
+ if (!connectFrom) select({ kind: "edge", id: target.dataset.awrEdge });
820
+ }
821
+ };
822
+ const onBlur = (e) => {
823
+ if (e.target.dataset.awrNode !== void 0) reorder();
824
+ };
825
+ const portPoint = useCallback(
826
+ (node, portId) => {
827
+ const rect = rectOf(node);
828
+ const ports = node.ports;
829
+ const id = portId ?? ports?.[0]?.id ?? DEFAULT_PORT;
830
+ const at = measured[node.id]?.ports[id];
831
+ if (at) return { x: node.x + at.x, y: node.y + at.y };
832
+ const index = ports ? Math.max(
833
+ 0,
834
+ ports.findIndex((p) => p.id === id)
835
+ ) : 0;
836
+ return outputAnchor(rect, index, ports?.length ?? 1);
837
+ },
838
+ [measured, rectOf]
839
+ );
840
+ const drawn = useMemo(() => {
841
+ const out = [];
842
+ for (const edge of edges) {
843
+ const from = nodeById.get(edge.from);
844
+ const to = nodeById.get(edge.to);
845
+ if (!from || !to) continue;
846
+ const a = rectOf(from);
847
+ const b = rectOf(to);
848
+ const curve = edgeCurve(portPoint(from, edge.fromPort), inputAnchor(b), {
849
+ clearance: Math.max(a.height, b.height) / 2 + 44
850
+ });
851
+ out.push({ edge, curve, path: curvePath(curve), middle: curvePoint(curve, 0.5) });
852
+ }
853
+ return out;
854
+ }, [edges, nodeById, rectOf, portPoint]);
855
+ const outgoing = useMemo(() => {
856
+ const map = /* @__PURE__ */ new Map();
857
+ for (const d of drawn) map.set(d.edge.from, [...map.get(d.edge.from) ?? [], d]);
858
+ return map;
859
+ }, [drawn]);
860
+ const neighbours = useMemo(() => {
861
+ const to = /* @__PURE__ */ new Map();
862
+ const from = /* @__PURE__ */ new Map();
863
+ for (const { edge } of drawn) {
864
+ const said = edge.description ?? edge.label;
865
+ to.set(edge.from, [
866
+ ...to.get(edge.from) ?? [],
867
+ said ? `${labelOf(edge.to)} (${said})` : labelOf(edge.to)
868
+ ]);
869
+ from.set(edge.to, [...from.get(edge.to) ?? [], labelOf(edge.from)]);
870
+ }
871
+ return { to, from };
872
+ }, [drawn, labelOf]);
873
+ const dragPath = useMemo(() => {
874
+ if (!dragLine) return void 0;
875
+ const from = nodeById.get(dragLine.from);
876
+ if (!from) return void 0;
877
+ return curvePath(edgeCurve(portPoint(from, dragLine.port), dragLine.to, { clearance: 0 }));
878
+ }, [dragLine, nodeById, portPoint]);
879
+ let grid = (snap > 0 ? snap : 20) * viewport.zoom;
880
+ while (grid < 14) grid *= 2;
881
+ const rootStyle = {
882
+ ...style,
883
+ "--awr-canvas-x": `${viewport.x}px`,
884
+ "--awr-canvas-y": `${viewport.y}px`,
885
+ "--awr-canvas-grid": `${grid}px`
886
+ };
887
+ const selectedEdge = selection?.kind === "edge" ? selection.id : void 0;
888
+ const selectedNode = selection?.kind === "node" ? selection.id : void 0;
889
+ return /* @__PURE__ */ jsxs(
890
+ "div",
891
+ {
892
+ ref: rootRef,
893
+ className: cx(
894
+ "awr-canvas",
895
+ showGrid && "awr-canvas--grid",
896
+ connectFrom && "awr-canvas--connecting",
897
+ (dragging || dragLine) && "awr-canvas--dragging",
898
+ className
899
+ ),
900
+ style: rootStyle,
901
+ role: "application",
902
+ "aria-label": labels.canvas,
903
+ "aria-describedby": `${uid}-help`,
904
+ tabIndex: 0,
905
+ onPointerDown,
906
+ onPointerMove,
907
+ onPointerUp: onPointerEnd,
908
+ onPointerCancel: onPointerEnd,
909
+ onKeyDown,
910
+ onFocus,
911
+ onBlur,
912
+ children: [
913
+ /* @__PURE__ */ jsxs(
914
+ "div",
915
+ {
916
+ className: "awr-canvas__world",
917
+ style: {
918
+ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`
919
+ },
920
+ children: [
921
+ /* @__PURE__ */ jsxs("svg", { className: "awr-canvas__edges", "aria-hidden": "true", focusable: "false", children: [
922
+ /* @__PURE__ */ jsx("defs", { children: [...TONES, "selected"].map((tone) => /* @__PURE__ */ jsx(
923
+ "marker",
924
+ {
925
+ id: `${uid}-arrow-${tone}`,
926
+ viewBox: "0 0 10 10",
927
+ markerWidth: "10",
928
+ markerHeight: "10",
929
+ refX: "9",
930
+ refY: "5",
931
+ orient: "auto",
932
+ markerUnits: "userSpaceOnUse",
933
+ children: /* @__PURE__ */ jsx(
934
+ "path",
935
+ {
936
+ d: "M1 1.5 9 5 1 8.5z",
937
+ className: `awr-canvas__arrow awr-canvas__arrow--${tone}`
938
+ }
939
+ )
940
+ },
941
+ tone
942
+ )) }),
943
+ drawn.map(({ edge, path }) => {
944
+ const tone = edge.tone ?? "default";
945
+ const selected = edge.id === selectedEdge;
946
+ return /* @__PURE__ */ jsxs(
947
+ "g",
948
+ {
949
+ className: cx(
950
+ "awr-canvas__edge",
951
+ `awr-canvas__edge--${tone}`,
952
+ selected && "awr-canvas__edge--selected"
953
+ ),
954
+ children: [
955
+ /* @__PURE__ */ jsx("path", { className: "awr-canvas__edge-hit", d: path, "data-awr-edge": edge.id }),
956
+ /* @__PURE__ */ jsx(
957
+ "path",
958
+ {
959
+ className: "awr-canvas__edge-line",
960
+ d: path,
961
+ markerEnd: `url(#${uid}-arrow-${selected ? "selected" : tone})`
962
+ }
963
+ )
964
+ ]
965
+ },
966
+ edge.id
967
+ );
968
+ }),
969
+ dragPath && /* @__PURE__ */ jsx("path", { className: "awr-canvas__edge-line awr-canvas__edge-draft", d: dragPath })
970
+ ] }),
971
+ ordered.map((node) => {
972
+ const selected = node.id === selectedNode;
973
+ const state = {
974
+ selected,
975
+ dragging: dragging === node.id,
976
+ connectable: Boolean(
977
+ connectFrom && connectFrom.node !== node.id || dragLine && dragLine.from !== node.id
978
+ )
979
+ };
980
+ const said = [
981
+ node.description,
982
+ neighbours.to.get(node.id)?.length ? labels.connectsTo(neighbours.to.get(node.id).join(", ")) : void 0,
983
+ neighbours.from.get(node.id)?.length ? labels.receivesFrom(neighbours.from.get(node.id).join(", ")) : void 0
984
+ ].filter(Boolean).join(" ");
985
+ const port = {
986
+ nodeLabel: node.label,
987
+ labels,
988
+ disabled: readOnly,
989
+ active: connectFrom?.node === node.id ? connectFrom.port ?? DEFAULT_PORT : void 0
990
+ };
991
+ return /* @__PURE__ */ jsxs(PortContext.Provider, { value: port, children: [
992
+ /* @__PURE__ */ jsxs(
993
+ "div",
994
+ {
995
+ ref: (el) => setNodeEl(node.id, el),
996
+ className: cx(
997
+ "awr-canvas__node",
998
+ selected && "awr-canvas__node--selected",
999
+ state.dragging && "awr-canvas__node--dragging",
1000
+ state.connectable && "awr-canvas__node--connectable"
1001
+ ),
1002
+ style: { transform: `translate(${node.x}px, ${node.y}px)` },
1003
+ "data-awr-node": node.id,
1004
+ role: "group",
1005
+ "aria-roledescription": labels.node,
1006
+ "aria-label": node.label,
1007
+ "aria-describedby": said ? `${uid}-n-${domId(node.id)}` : void 0,
1008
+ tabIndex: 0,
1009
+ children: [
1010
+ renderNode(node, state),
1011
+ !node.ports && /* @__PURE__ */ jsx(CanvasPort, { className: "awr-canvas__port--default" }),
1012
+ said && /* @__PURE__ */ jsx("span", { id: `${uid}-n-${domId(node.id)}`, className: "awr-canvas__sr", children: said })
1013
+ ]
1014
+ }
1015
+ ),
1016
+ (outgoing.get(node.id) ?? []).map(({ edge, middle }) => /* @__PURE__ */ jsx(
1017
+ "button",
1018
+ {
1019
+ type: "button",
1020
+ className: cx(
1021
+ "awr-canvas__edge-handle",
1022
+ `awr-canvas__edge-handle--${edge.tone ?? "default"}`,
1023
+ edge.label ? "awr-canvas__edge-handle--label" : void 0,
1024
+ edge.id === selectedEdge && "awr-canvas__edge-handle--selected"
1025
+ ),
1026
+ style: { left: middle.x, top: middle.y },
1027
+ "data-awr-edge": edge.id,
1028
+ "aria-label": labels.edge(
1029
+ labelOf(edge.from),
1030
+ labelOf(edge.to),
1031
+ edge.description ?? edge.label
1032
+ ),
1033
+ "aria-pressed": edge.id === selectedEdge,
1034
+ children: edge.label ? /* @__PURE__ */ jsx("span", { children: edge.label }) : null
1035
+ },
1036
+ edge.id
1037
+ ))
1038
+ ] }, node.id);
1039
+ })
1040
+ ]
1041
+ }
1042
+ ),
1043
+ children,
1044
+ connectFrom && /* @__PURE__ */ jsxs("div", { className: "awr-canvas__hint", "data-awr-canvas-ignore": "", children: [
1045
+ /* @__PURE__ */ jsx("span", { children: labels.connectHint(labelOf(connectFrom.node)) }),
1046
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => setConnectFrom(void 0), children: labels.cancel })
1047
+ ] }),
1048
+ showControls && /* @__PURE__ */ jsxs("div", { className: "awr-canvas__controls", "data-awr-canvas-ignore": "", children: [
1049
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": labels.zoomOut, onClick: () => zoomStep(0.8), children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M5 12h14" }) }) }),
1050
+ /* @__PURE__ */ jsx("output", { className: "awr-canvas__zoom", children: labels.zoomLevel(Math.round(viewport.zoom * 100)) }),
1051
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": labels.zoomIn, onClick: () => zoomStep(1.25), children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M12 5v14M5 12h14" }) }) }),
1052
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": labels.fit, onClick: fit, children: /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M4 9V5h4M20 9V5h-4M4 15v4h4M20 15v4h-4" }) }) })
1053
+ ] }),
1054
+ /* @__PURE__ */ jsx("span", { id: `${uid}-help`, className: "awr-canvas__sr", children: labels.help }),
1055
+ /* @__PURE__ */ jsx("span", { className: "awr-canvas__sr", role: "status", "aria-live": "polite", children: announcement })
1056
+ ]
1057
+ }
1058
+ );
1059
+ });
1060
+ Canvas.displayName = "Canvas";
1061
+
1062
+ // src/pipeline/PipelineEditor.tsx
1063
+ import { useCallback as useCallback2, useEffect as useEffect3, useId as useId3, useMemo as useMemo3, useRef as useRef2, useState as useState3 } from "react";
1064
+ import {
1065
+ validatePipeline
1066
+ } from "@dudko.dev/agent-web";
1067
+
1068
+ // src/pipeline/codegen.ts
1069
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
1070
+ var identifier = (name, suffix, taken) => {
1071
+ const words = name.split(/[^A-Za-z0-9]+/).filter(Boolean);
1072
+ let base2 = words.map((w, i) => (i === 0 ? w.charAt(0).toLowerCase() : w.charAt(0).toUpperCase()) + w.slice(1)).join("");
1073
+ if (!base2 || /^[0-9]/.test(base2)) base2 = `x${base2}`;
1074
+ base2 += suffix;
1075
+ let out = base2;
1076
+ for (let n = 2; taken.has(out); n++) out = `${base2}${n}`;
1077
+ taken.add(out);
1078
+ return out;
1079
+ };
1080
+ var namesOf = (definition, field) => [...new Set(definition.nodes.flatMap((n) => n[field] ?? []))];
1081
+ var quote = (text) => `'${text.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029")}'`;
1082
+ var key = (name) => IDENTIFIER.test(name) ? name : quote(name);
1083
+ var literal = (value, indent = "") => {
1084
+ const inner = `${indent} `;
1085
+ if (typeof value === "string") return quote(value);
1086
+ if (value === null || typeof value !== "object") return String(value);
1087
+ if (Array.isArray(value)) {
1088
+ if (value.length === 0) return "[]";
1089
+ const flat2 = `[${value.map((v) => literal(v, inner)).join(", ")}]`;
1090
+ if (flat2.length + indent.length <= 80 && !flat2.includes("\n")) return flat2;
1091
+ return `[
1092
+ ${value.map((v) => `${inner}${literal(v, inner)},`).join("\n")}
1093
+ ${indent}]`;
1094
+ }
1095
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
1096
+ if (entries.length === 0) return "{}";
1097
+ const flat = `{ ${entries.map(([k, v]) => `${key(k)}: ${literal(v, inner)}`).join(", ")} }`;
1098
+ if (flat.length + indent.length <= 80 && !flat.includes("\n")) return flat;
1099
+ return `{
1100
+ ${entries.map(([k, v]) => `${inner}${key(k)}: ${literal(v, inner)},`).join("\n")}
1101
+ ${indent}}`;
1102
+ };
1103
+ var registry = (field, names, suffix, taken, note) => names.length === 0 ? void 0 : ` ${field}: { ${names.map((n) => `${key(n)}: ${identifier(n, suffix, taken)}`).join(", ")} }, // ${note}`;
1104
+ var pipelineToCode = (definition, options = {}) => {
1105
+ const { target = "browser", positions = false, input = "Your request" } = options;
1106
+ const browser = target === "browser";
1107
+ const pkg = browser ? "@dudko.dev/agent-web" : "@dudko.dev/agent";
1108
+ const def = positions ? definition : {
1109
+ ...definition,
1110
+ nodes: definition.nodes.map((n) => {
1111
+ const { position, ...rest } = n;
1112
+ void position;
1113
+ return rest;
1114
+ })
1115
+ };
1116
+ const taken = /* @__PURE__ */ new Set(["definition", "pipeline", "result", "config", "model", "credentials"]);
1117
+ const models = [...new Set(definition.nodes.flatMap((n) => n.model ? [n.model] : []))];
1118
+ const registries = [
1119
+ registry(
1120
+ "models",
1121
+ models,
1122
+ "Model",
1123
+ taken,
1124
+ browser ? "a LanguageModel or a ProviderModelSpec each" : "a model spec each"
1125
+ ),
1126
+ registry("skills", namesOf(definition, "skills"), "Skill", taken, "a Skill each"),
1127
+ registry("tools", namesOf(definition, "tools"), "Tools", taken, "a named group of tools each"),
1128
+ registry(
1129
+ "mcpServers",
1130
+ namesOf(definition, "mcpServers"),
1131
+ "Mcp",
1132
+ taken,
1133
+ browser ? "a connectMcpHttp result each" : "an MCP server config each"
1134
+ )
1135
+ ].filter(Boolean);
1136
+ const lines = [
1137
+ `import { createPipeline, nodeResolver } from '${pkg}'`,
1138
+ `import type { PipelineDefinition } from '${pkg}'`,
1139
+ "",
1140
+ `const definition: PipelineDefinition = ${literal(def)}`,
1141
+ "",
1142
+ "const pipeline = createPipeline(definition, {",
1143
+ " // What the names in the definition stand for. A name that is not here fails its node.",
1144
+ " resolveNode: nodeResolver({",
1145
+ browser ? " base: { model, credentials }, // a BrowserAgentConfig: every node starts from it" : " base: config, // an IAgentConfig: every node starts from it",
1146
+ ...registries,
1147
+ " }),",
1148
+ "})",
1149
+ "",
1150
+ "const result = await pipeline.run({",
1151
+ ` input: ${literal(input)},`,
1152
+ " onEvent: (e) => {",
1153
+ " if (e.type === 'pipeline.node.started') console.log('\u2192', e.nodeId, `#${e.visit}`)",
1154
+ " },",
1155
+ "})",
1156
+ "console.log(result.text)",
1157
+ ...browser ? [] : ["await pipeline.close() // closes the node agents (their MCP connections)"],
1158
+ ""
1159
+ ];
1160
+ return lines.join("\n");
1161
+ };
1162
+
1163
+ // src/pipeline/edit.ts
1164
+ import { normalizePipeline } from "@dudko.dev/agent-web";
1165
+ var emptyPipeline = () => ({
1166
+ version: 1,
1167
+ entry: "agent",
1168
+ nodes: [{ id: "agent", name: "Agent", position: { x: 0, y: 0 } }],
1169
+ edges: []
1170
+ });
1171
+ var ensureEdgeIds = (definition) => definition.edges.every((e) => typeof e.id === "string" && e.id.length > 0) ? definition : normalizePipeline(definition);
1172
+ var unique = (taken, base2) => {
1173
+ if (!taken.has(base2)) return base2;
1174
+ for (let n = 2; ; n++) {
1175
+ if (!taken.has(`${base2}-${n}`)) return `${base2}-${n}`;
1176
+ }
1177
+ };
1178
+ var slugifyId = (text) => text.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
1179
+ var uniqueNodeId = (definition, base2 = "node") => unique(new Set(definition.nodes.map((n) => n.id)), slugifyId(base2) || "node");
1180
+ var uniqueEdgeId = (definition) => {
1181
+ const taken = new Set(definition.edges.map((e, i) => e.id ?? `e${i}`));
1182
+ for (let n = definition.edges.length; ; n++) {
1183
+ if (!taken.has(`e${n}`)) return `e${n}`;
1184
+ }
1185
+ };
1186
+ var isEmpty = (value) => value === void 0 || value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
1187
+ var applyPatch = (target, patch, keep) => {
1188
+ const out = { ...target };
1189
+ let changed = false;
1190
+ for (const [key2, value] of Object.entries(patch)) {
1191
+ if (isEmpty(value) && !keep.includes(key2)) {
1192
+ if (key2 in out) {
1193
+ delete out[key2];
1194
+ changed = true;
1195
+ }
1196
+ } else if (JSON.stringify(out[key2]) !== JSON.stringify(value)) {
1197
+ out[key2] = value;
1198
+ changed = true;
1199
+ }
1200
+ }
1201
+ return changed ? out : target;
1202
+ };
1203
+ var addNode = (definition, node = {}) => {
1204
+ const id = uniqueNodeId(definition, node.id || node.name || "node");
1205
+ const nodes = [...definition.nodes, { ...node, id }];
1206
+ const hasEntry = definition.nodes.some((n) => n.id === definition.entry);
1207
+ return { ...definition, nodes, ...hasEntry ? {} : { entry: id } };
1208
+ };
1209
+ var updateNode = (definition, id, patch) => {
1210
+ const index = definition.nodes.findIndex((n) => n.id === id);
1211
+ if (index < 0) return definition;
1212
+ const next = applyPatch(definition.nodes[index], patch, ["id"]);
1213
+ if (next === definition.nodes[index]) return definition;
1214
+ const nodes = [...definition.nodes];
1215
+ nodes[index] = next;
1216
+ return { ...definition, nodes };
1217
+ };
1218
+ var moveNode = (definition, id, position) => updateNode(definition, id, { position: { x: Math.round(position.x), y: Math.round(position.y) } });
1219
+ var removeNode = (definition, id) => {
1220
+ if (!definition.nodes.some((n) => n.id === id)) return definition;
1221
+ const nodes = definition.nodes.filter((n) => n.id !== id);
1222
+ return {
1223
+ ...definition,
1224
+ nodes,
1225
+ edges: definition.edges.filter((e) => e.from !== id && e.to !== id),
1226
+ entry: definition.entry === id ? nodes[0]?.id ?? "" : definition.entry
1227
+ };
1228
+ };
1229
+ var renameNode = (definition, id, nextId) => {
1230
+ const to = nextId.trim();
1231
+ if (!to || to === id) return definition;
1232
+ if (!definition.nodes.some((n) => n.id === id)) return definition;
1233
+ if (definition.nodes.some((n) => n.id === to)) return definition;
1234
+ return {
1235
+ ...definition,
1236
+ nodes: definition.nodes.map((n) => n.id === id ? { ...n, id: to } : n),
1237
+ edges: definition.edges.map(
1238
+ (e) => e.from === id || e.to === id ? { ...e, from: e.from === id ? to : e.from, to: e.to === id ? to : e.to } : e
1239
+ ),
1240
+ entry: definition.entry === id ? to : definition.entry
1241
+ };
1242
+ };
1243
+ var setEntry = (definition, id) => definition.entry === id || !definition.nodes.some((n) => n.id === id) ? definition : { ...definition, entry: id };
1244
+ var cleanCondition = (when) => !when || when.kind === "always" ? void 0 : when;
1245
+ var sameCondition = (a, b) => JSON.stringify(cleanCondition(a) ?? null) === JSON.stringify(cleanCondition(b) ?? null);
1246
+ var addEdge = (definition, edge) => {
1247
+ const has = (id2) => definition.nodes.some((n) => n.id === id2);
1248
+ if (!has(edge.from) || !has(edge.to)) return definition;
1249
+ const base2 = ensureEdgeIds(definition);
1250
+ if (base2.edges.some(
1251
+ (e) => e.from === edge.from && e.to === edge.to && sameCondition(e.when, edge.when)
1252
+ )) {
1253
+ return definition;
1254
+ }
1255
+ const id = edge.id && !base2.edges.some((e) => e.id === edge.id) ? edge.id : uniqueEdgeId(base2);
1256
+ const when = cleanCondition(edge.when);
1257
+ const added = { id, from: edge.from, to: edge.to, ...when ? { when } : {} };
1258
+ return { ...base2, edges: [...base2.edges, added] };
1259
+ };
1260
+ var edgeIndex = (definition, id) => definition.edges.findIndex((e, i) => (e.id ?? `e${i}`) === id);
1261
+ var updateEdge = (definition, id, patch) => {
1262
+ const base2 = ensureEdgeIds(definition);
1263
+ const index = edgeIndex(base2, id);
1264
+ if (index < 0) return definition;
1265
+ const has = (nodeId) => base2.nodes.some((n) => n.id === nodeId);
1266
+ if (patch.from !== void 0 && !has(patch.from) || patch.to !== void 0 && !has(patch.to)) {
1267
+ return definition;
1268
+ }
1269
+ const before = base2.edges[index];
1270
+ const { when: was, ...ends } = before;
1271
+ const when = cleanCondition("when" in patch ? patch.when : was);
1272
+ const next = {
1273
+ ...ends,
1274
+ ...patch.from !== void 0 ? { from: patch.from } : {},
1275
+ ...patch.to !== void 0 ? { to: patch.to } : {},
1276
+ ...when ? { when } : {}
1277
+ };
1278
+ if (JSON.stringify(next) === JSON.stringify(before)) return definition;
1279
+ const edges = [...base2.edges];
1280
+ edges[index] = next;
1281
+ return { ...base2, edges };
1282
+ };
1283
+ var removeEdge = (definition, id) => {
1284
+ const base2 = ensureEdgeIds(definition);
1285
+ const index = edgeIndex(base2, id);
1286
+ if (index < 0) return definition;
1287
+ return { ...base2, edges: base2.edges.filter((_, i) => i !== index) };
1288
+ };
1289
+ var renameRoute = (definition, nodeId, label, nextLabel) => {
1290
+ const node = definition.nodes.find((n) => n.id === nodeId);
1291
+ if (!node?.routes?.some((r) => r.label === label) || label === nextLabel) return definition;
1292
+ if (node.routes.some((r) => r.label === nextLabel)) return definition;
1293
+ return {
1294
+ ...definition,
1295
+ nodes: definition.nodes.map(
1296
+ (n) => n.id === nodeId ? {
1297
+ ...n,
1298
+ routes: (n.routes ?? []).map(
1299
+ (r) => r.label === label ? { ...r, label: nextLabel } : r
1300
+ )
1301
+ } : n
1302
+ ),
1303
+ edges: definition.edges.map(
1304
+ (e) => e.from === nodeId && e.when?.kind === "route" && e.when.label === label ? { ...e, when: { kind: "route", label: nextLabel } } : e
1305
+ )
1306
+ };
1307
+ };
1308
+ var setLimits = (definition, patch) => {
1309
+ const before = definition.limits ?? {};
1310
+ const limits = applyPatch(before, patch, []);
1311
+ if (limits === before) return definition;
1312
+ const { limits: was, ...rest } = definition;
1313
+ void was;
1314
+ return Object.keys(limits).length > 0 ? { ...rest, limits } : rest;
1315
+ };
1316
+ var setPipelineName = (definition, name) => {
1317
+ if ((definition.name ?? "") === name) return definition;
1318
+ const { name: was, ...rest } = definition;
1319
+ void was;
1320
+ return name ? { ...rest, name } : rest;
1321
+ };
1322
+ var autoLayout = (definition, options = {}) => {
1323
+ const { columnGap = 320, rowGap = 170, all = false } = options;
1324
+ const placed = (n) => !all && typeof n.position?.x === "number" && typeof n.position?.y === "number";
1325
+ if (definition.nodes.every(placed)) return definition;
1326
+ const depth = /* @__PURE__ */ new Map();
1327
+ const ids = new Set(definition.nodes.map((n) => n.id));
1328
+ const walk = (start, from) => {
1329
+ const queue = [start];
1330
+ depth.set(start, from);
1331
+ while (queue.length) {
1332
+ const id = queue.shift();
1333
+ for (const edge of definition.edges) {
1334
+ if (edge.from === id && ids.has(edge.to) && !depth.has(edge.to)) {
1335
+ depth.set(edge.to, depth.get(id) + 1);
1336
+ queue.push(edge.to);
1337
+ }
1338
+ }
1339
+ }
1340
+ };
1341
+ if (ids.has(definition.entry)) walk(definition.entry, 0);
1342
+ for (const node of definition.nodes) {
1343
+ if (!depth.has(node.id)) walk(node.id, Math.max(-1, ...depth.values()) + 1);
1344
+ }
1345
+ const rows = /* @__PURE__ */ new Map();
1346
+ const columns = /* @__PURE__ */ new Map();
1347
+ for (const node of definition.nodes) {
1348
+ const d = depth.get(node.id);
1349
+ columns.set(d, (columns.get(d) ?? 0) + 1);
1350
+ }
1351
+ const tallest = Math.max(...columns.values());
1352
+ return {
1353
+ ...definition,
1354
+ nodes: definition.nodes.map((node) => {
1355
+ const d = depth.get(node.id);
1356
+ const row = rows.get(d) ?? 0;
1357
+ rows.set(d, row + 1);
1358
+ if (placed(node)) return node;
1359
+ const offset = (tallest - columns.get(d)) * rowGap / 2;
1360
+ return { ...node, position: { x: d * columnGap, y: Math.round(offset + row * rowGap) } };
1361
+ })
1362
+ };
1363
+ };
1364
+ var nextNodePosition = (definition) => {
1365
+ const positions = definition.nodes.map((n) => n.position).filter(Boolean);
1366
+ if (positions.length === 0) return { x: 0, y: 0 };
1367
+ const right = Math.max(...positions.map((p) => p.x));
1368
+ const bottom = Math.max(...positions.filter((p) => p.x === right).map((p) => p.y));
1369
+ return { x: right, y: bottom + 170 };
1370
+ };
1371
+ var issueTarget = (issue, definition) => {
1372
+ if (issue.edgeId !== void 0 || issue.edgeIndex !== void 0) {
1373
+ const index = issue.edgeIndex ?? definition.edges.findIndex((e, i) => (e.id ?? `e${i}`) === issue.edgeId);
1374
+ const edge = definition.edges[index];
1375
+ if (edge) return { kind: "edge", id: edge.id ?? `e${index}` };
1376
+ }
1377
+ if (issue.nodeId !== void 0 && definition.nodes.some((n) => n.id === issue.nodeId)) {
1378
+ return { kind: "node", id: issue.nodeId };
1379
+ }
1380
+ return null;
1381
+ };
1382
+ var parsePipelineJson = (text) => {
1383
+ let value;
1384
+ try {
1385
+ value = JSON.parse(text);
1386
+ } catch (err) {
1387
+ throw new Error(`not JSON: ${err.message}`);
1388
+ }
1389
+ const def = value;
1390
+ if (typeof def !== "object" || def === null || Array.isArray(def)) {
1391
+ throw new Error("a pipeline definition must be an object");
1392
+ }
1393
+ if (!Array.isArray(def.nodes) || !Array.isArray(def.edges)) {
1394
+ throw new Error("a pipeline definition needs `nodes` and `edges` arrays");
1395
+ }
1396
+ if (def.nodes.some((n) => typeof n !== "object" || n === null || typeof n.id !== "string")) {
1397
+ throw new Error("every node needs an `id`");
1398
+ }
1399
+ if (def.edges.some(
1400
+ (e) => typeof e !== "object" || e === null || typeof e.from !== "string" || typeof e.to !== "string"
1401
+ )) {
1402
+ throw new Error("every edge needs `from` and `to`");
1403
+ }
1404
+ return autoLayout(
1405
+ ensureEdgeIds({
1406
+ ...def,
1407
+ entry: typeof def.entry === "string" ? def.entry : ""
1408
+ })
1409
+ );
1410
+ };
1411
+
1412
+ // src/pipeline/icons.tsx
1413
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1414
+ var base = (size = 16) => ({
1415
+ width: size,
1416
+ height: size,
1417
+ viewBox: "0 0 24 24",
1418
+ fill: "none",
1419
+ stroke: "currentColor",
1420
+ strokeWidth: 2,
1421
+ strokeLinecap: "round",
1422
+ strokeLinejoin: "round",
1423
+ "aria-hidden": true
1424
+ });
1425
+ var TrashIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v5M14 11v5" }) });
1426
+ var FitIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M4 9V5h4M20 9V5h-4M4 15v4h4M20 15v4h-4" }) });
1427
+ var MinusIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M5 12h14" }) });
1428
+ var UploadIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M12 16V4M7 9l5-5 5 5M4 20h16" }) });
1429
+ var CodeIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "m8 8-4 4 4 4M16 8l4 4-4 4M13.5 5l-3 14" }) });
1430
+ var PlayIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M7 4.5v15l12-7.5z", fill: "currentColor" }) });
1431
+ var PlugIcon = ({ size, className }) => /* @__PURE__ */ jsx2("svg", { ...base(size), className, children: /* @__PURE__ */ jsx2("path", { d: "M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0zM12 17v4" }) });
1432
+ var SkipIcon = ({ size, className }) => /* @__PURE__ */ jsxs2("svg", { ...base(size), className, children: [
1433
+ /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "12", r: "8" }),
1434
+ /* @__PURE__ */ jsx2("path", { d: "m6.5 17.5 11-11" })
1435
+ ] });
1436
+
1437
+ // src/pipeline/labels.tsx
1438
+ import { createContext as createContext2, useContext as useContext2, useMemo as useMemo2 } from "react";
1439
+ import { jsx as jsx3 } from "react/jsx-runtime";
1440
+ var defaultPipelineLabels = {
1441
+ toolbar: "Pipeline tools",
1442
+ addNode: "Add node",
1443
+ deleteSelected: "Delete",
1444
+ fit: "Fit",
1445
+ zoomIn: "Zoom in",
1446
+ zoomOut: "Zoom out",
1447
+ importJson: "Import JSON",
1448
+ exportJson: "Export JSON",
1449
+ copyCode: "Copy as code",
1450
+ newNodeName: (n) => `Agent ${n}`,
1451
+ importFailed: (reason) => `Could not import: ${reason}`,
1452
+ issues: "Issues",
1453
+ noIssues: "No issues",
1454
+ errors: (n) => `${n} error${n === 1 ? "" : "s"}`,
1455
+ warnings: (n) => `${n} warning${n === 1 ? "" : "s"}`,
1456
+ issueError: "Error",
1457
+ issueWarning: "Warning",
1458
+ canvas: { ...defaultCanvasLabels, canvas: "Pipeline canvas" },
1459
+ emptyCanvas: "No nodes yet. Add one to start.",
1460
+ nodeDescription: (status, visits) => visits > 1 ? `${status}, visit ${visits}.` : `${status}.`,
1461
+ nodeStatus: {
1462
+ idle: "idle",
1463
+ waiting: "waiting",
1464
+ running: "running",
1465
+ done: "done",
1466
+ failed: "failed",
1467
+ skipped: "skipped"
1468
+ },
1469
+ entry: "entry",
1470
+ defaultModel: "default model",
1471
+ skillsBadge: (n) => `${n} skill${n === 1 ? "" : "s"}`,
1472
+ toolsBadge: (n) => `${n} tool group${n === 1 ? "" : "s"}`,
1473
+ mcpBadge: (n) => `${n} MCP server${n === 1 ? "" : "s"}`,
1474
+ visits: (n) => `\xD7${n}`,
1475
+ anyOutput: "any",
1476
+ activityPlanning: "planning\u2026",
1477
+ activityReplanning: "checking the plan\u2026",
1478
+ activityAnswering: "writing the answer\u2026",
1479
+ activityStep: (index, total, step) => `${index}/${total} ${step}`,
1480
+ activityTool: (name) => `tool: ${name}`,
1481
+ skippedBy: {
1482
+ maxNodeVisits: "visit limit reached",
1483
+ maxRuns: "run limit reached"
1484
+ },
1485
+ inspector: "Inspector",
1486
+ inspectorNode: "Node",
1487
+ inspectorEdge: "Connection",
1488
+ inspectorPipeline: "Pipeline",
1489
+ close: "Close",
1490
+ expand: "Show details",
1491
+ collapse: "Hide details",
1492
+ fieldId: "Id",
1493
+ fieldIdHint: "Unique; edges and events name the node by it.",
1494
+ idTaken: "Another node has this id.",
1495
+ idEmpty: "A node needs an id.",
1496
+ fieldName: "Name",
1497
+ fieldInstructions: "Instructions",
1498
+ instructionsPlaceholder: "The role of this node: what it does with what it receives.",
1499
+ fieldModel: "Model",
1500
+ unknownOption: (name) => `${name} (not available)`,
1501
+ fieldSkills: "Skills",
1502
+ fieldTools: "Tools",
1503
+ fieldMcp: "MCP servers",
1504
+ noOptions: "None available.",
1505
+ fieldRoutes: "Routes",
1506
+ routesHint: "After it answers, the node picks one. Each becomes an output port.",
1507
+ routeLabel: "Label",
1508
+ routeDescription: "When to pick it",
1509
+ addRoute: "Add route",
1510
+ removeRoute: (label) => `Remove route ${label}`,
1511
+ fieldJoin: "When several nodes lead here",
1512
+ joinAll: "Wait for all of them",
1513
+ joinAny: "Run on any of them",
1514
+ isEntry: "This node receives the request.",
1515
+ makeEntry: "Make it the entry",
1516
+ deleteNode: "Delete node",
1517
+ edgeEnds: (from, to) => `${from} \u2192 ${to}`,
1518
+ fieldCondition: "Fires",
1519
+ conditionKinds: {
1520
+ always: "always",
1521
+ contains: "contains",
1522
+ matches: "matches",
1523
+ route: "route",
1524
+ otherwise: "otherwise"
1525
+ },
1526
+ conditionHints: {
1527
+ always: "Every time the source node answers.",
1528
+ contains: "When the answer contains this text.",
1529
+ matches: "When this pattern occurs in the answer. No backreferences or lookaround.",
1530
+ route: "When the source node picks this route.",
1531
+ otherwise: "When no other connection of the source node fired."
1532
+ },
1533
+ fieldText: "Text",
1534
+ caseSensitive: "Match case",
1535
+ fieldPattern: "Pattern",
1536
+ fieldFlags: "Flags",
1537
+ fieldRoute: "Route",
1538
+ noRoutes: "The source node has no routes. Add one to it first.",
1539
+ deleteEdge: "Delete connection",
1540
+ pipelineName: "Name",
1541
+ pipelineNamePlaceholder: "Untitled pipeline",
1542
+ fieldEntry: "Entry node",
1543
+ fieldMaxNodeVisits: "Visits per node",
1544
+ fieldMaxRuns: "Node runs in total",
1545
+ limitDefault: (n) => `default ${n}`,
1546
+ counts: (nodes, edges) => `${nodes} node${nodes === 1 ? "" : "s"}, ${edges} connection${edges === 1 ? "" : "s"}`,
1547
+ runPlaceholder: "What should the pipeline work on?",
1548
+ runInput: "Request",
1549
+ run: "Run",
1550
+ stop: "Stop",
1551
+ fixErrorsFirst: "Fix the errors before running.",
1552
+ runStatus: {
1553
+ idle: "Not run yet",
1554
+ running: "Running\u2026",
1555
+ done: "Finished",
1556
+ failed: "Failed",
1557
+ stopped: "Stopped"
1558
+ },
1559
+ stoppedBy: {
1560
+ maxNodeVisits: "A node reached its visit limit, so a loop was cut short.",
1561
+ maxRuns: "The pipeline reached its limit of node runs.",
1562
+ aborted: "Stopped before it finished."
1563
+ },
1564
+ announceNode: (name, status) => `${name}: ${status}`,
1565
+ results: "Result",
1566
+ showResults: "Show the result",
1567
+ hideResults: "Hide the result",
1568
+ finalAnswer: "Final answer",
1569
+ nodeOutputs: "Node outputs",
1570
+ noOutputYet: "Nothing yet.",
1571
+ visitTitle: (name, visit) => visit > 1 ? `${name} \xB7 visit ${visit}` : name,
1572
+ routeTaken: (label) => `route: ${label}`,
1573
+ receivedFrom: (names) => `from ${names}`,
1574
+ usage: (input, output) => `in ${input} \xB7 out ${output}`,
1575
+ runsCount: (n) => `${n} node run${n === 1 ? "" : "s"}`,
1576
+ codeTitle: "Copy as code",
1577
+ codeBrowser: "Browser",
1578
+ codeNode: "Node",
1579
+ copy: "Copy",
1580
+ copied: "Copied"
1581
+ };
1582
+ var NESTED = [
1583
+ "canvas",
1584
+ "nodeStatus",
1585
+ "skippedBy",
1586
+ "conditionKinds",
1587
+ "conditionHints",
1588
+ "runStatus",
1589
+ "stoppedBy"
1590
+ ];
1591
+ var mergePipelineLabels = (base2, over) => {
1592
+ if (!over) return base2;
1593
+ const out = { ...base2, ...over };
1594
+ for (const key2 of NESTED) {
1595
+ if (over[key2]) out[key2] = { ...base2[key2], ...over[key2] };
1596
+ }
1597
+ return out;
1598
+ };
1599
+ var LabelsContext = createContext2(defaultPipelineLabels);
1600
+ var PipelineLabelsProvider = ({ labels, children }) => {
1601
+ const parent = useContext2(LabelsContext);
1602
+ const value = useMemo2(() => mergePipelineLabels(parent, labels), [parent, labels]);
1603
+ return /* @__PURE__ */ jsx3(LabelsContext.Provider, { value, children });
1604
+ };
1605
+ var usePipelineLabels = (over) => {
1606
+ const ctx = useContext2(LabelsContext);
1607
+ return useMemo2(() => mergePipelineLabels(ctx, over), [ctx, over]);
1608
+ };
1609
+
1610
+ // src/pipeline/PipelineInspector.tsx
1611
+ import { useEffect as useEffect2, useId as useId2, useState as useState2 } from "react";
1612
+ import {
1613
+ PIPELINE_LIMITS
1614
+ } from "@dudko.dev/agent-web";
1615
+ import { Fragment, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1616
+ var KINDS = ["always", "contains", "matches", "route", "otherwise"];
1617
+ var edgeIdAt = (definition, edge) => edge.id ?? `e${definition.edges.indexOf(edge)}`;
1618
+ var Field = ({
1619
+ label,
1620
+ hint,
1621
+ error,
1622
+ children
1623
+ }) => {
1624
+ const id = useId2();
1625
+ const noteId = `${id}-note`;
1626
+ return /* @__PURE__ */ jsxs3("div", { className: "awr-pfield", children: [
1627
+ /* @__PURE__ */ jsx4("label", { className: "awr-pfield__label", htmlFor: id, children: label }),
1628
+ children(id, hint || error ? noteId : void 0),
1629
+ (error || hint) && /* @__PURE__ */ jsx4("p", { id: noteId, className: `awr-pfield__hint${error ? " awr-pfield__hint--error" : ""}`, children: error ?? hint })
1630
+ ] });
1631
+ };
1632
+ var Choices = ({
1633
+ label,
1634
+ options,
1635
+ value,
1636
+ onChange,
1637
+ disabled,
1638
+ L
1639
+ }) => {
1640
+ const known = options ?? [];
1641
+ const all = [
1642
+ ...known,
1643
+ ...value.filter((id) => !known.some((o) => o.id === id)).map((id) => ({ id, label: L.unknownOption(id) }))
1644
+ ];
1645
+ return /* @__PURE__ */ jsxs3("fieldset", { className: "awr-pfield awr-pfield--choices", children: [
1646
+ /* @__PURE__ */ jsx4("legend", { className: "awr-pfield__label", children: label }),
1647
+ all.length === 0 ? /* @__PURE__ */ jsx4("p", { className: "awr-pfield__hint", children: L.noOptions }) : /* @__PURE__ */ jsx4("div", { className: "awr-pchips", children: all.map((option) => {
1648
+ const on = value.includes(option.id);
1649
+ return /* @__PURE__ */ jsxs3(
1650
+ "label",
1651
+ {
1652
+ className: `awr-pchip${on ? " awr-pchip--on" : ""}`,
1653
+ title: option.description,
1654
+ children: [
1655
+ /* @__PURE__ */ jsx4(
1656
+ "input",
1657
+ {
1658
+ type: "checkbox",
1659
+ checked: on,
1660
+ disabled,
1661
+ onChange: () => onChange(on ? value.filter((v) => v !== option.id) : [...value, option.id])
1662
+ }
1663
+ ),
1664
+ /* @__PURE__ */ jsx4("span", { children: option.label ?? option.id })
1665
+ ]
1666
+ },
1667
+ option.id
1668
+ );
1669
+ }) })
1670
+ ] });
1671
+ };
1672
+ var NodeForm = ({
1673
+ node,
1674
+ props,
1675
+ L
1676
+ }) => {
1677
+ const { value, onChange, readOnly = false } = props;
1678
+ const patch = (p) => onChange(updateNode(value, node.id, p));
1679
+ const [idDraft, setIdDraft] = useState2(node.id);
1680
+ useEffect2(() => setIdDraft(node.id), [node.id]);
1681
+ const idClean = idDraft.trim();
1682
+ const idError = !idClean ? L.idEmpty : idClean !== node.id && value.nodes.some((n) => n.id === idClean) ? L.idTaken : void 0;
1683
+ const commitId = () => {
1684
+ if (idError || idClean === node.id) {
1685
+ setIdDraft(node.id);
1686
+ return;
1687
+ }
1688
+ const next = renameNode(value, node.id, idClean);
1689
+ onChange(next);
1690
+ props.onSelectionChange?.({ kind: "node", id: idClean });
1691
+ };
1692
+ const routes = node.routes ?? [];
1693
+ const models = props.models ?? [];
1694
+ const isEntry = value.entry === node.id;
1695
+ const freeRoute = () => {
1696
+ for (let n = routes.length + 1; ; n++) {
1697
+ if (!routes.some((r) => r.label === `route-${n}`)) return `route-${n}`;
1698
+ }
1699
+ };
1700
+ return /* @__PURE__ */ jsxs3(Fragment, { children: [
1701
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldName, children: (id) => /* @__PURE__ */ jsx4(
1702
+ "input",
1703
+ {
1704
+ id,
1705
+ className: "awr-pinput",
1706
+ value: node.name ?? "",
1707
+ placeholder: node.id,
1708
+ readOnly,
1709
+ "data-awr-first-field": "",
1710
+ onChange: (e) => patch({ name: e.target.value })
1711
+ }
1712
+ ) }),
1713
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldId, hint: L.fieldIdHint, error: idError, children: (id, describedBy) => /* @__PURE__ */ jsx4(
1714
+ "input",
1715
+ {
1716
+ id,
1717
+ className: "awr-pinput awr-pinput--mono",
1718
+ value: idDraft,
1719
+ readOnly,
1720
+ spellCheck: false,
1721
+ "aria-invalid": Boolean(idError),
1722
+ "aria-describedby": describedBy,
1723
+ onChange: (e) => setIdDraft(e.target.value),
1724
+ onBlur: commitId,
1725
+ onKeyDown: (e) => {
1726
+ if (e.key === "Enter") commitId();
1727
+ }
1728
+ }
1729
+ ) }),
1730
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldInstructions, children: (id) => /* @__PURE__ */ jsx4(
1731
+ "textarea",
1732
+ {
1733
+ id,
1734
+ className: "awr-pinput awr-pinput--area",
1735
+ rows: 5,
1736
+ value: node.instructions ?? "",
1737
+ placeholder: L.instructionsPlaceholder,
1738
+ readOnly,
1739
+ onChange: (e) => patch({ instructions: e.target.value })
1740
+ }
1741
+ ) }),
1742
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldModel, children: (id) => /* @__PURE__ */ jsxs3(
1743
+ "select",
1744
+ {
1745
+ id,
1746
+ className: "awr-pinput",
1747
+ value: node.model ?? "",
1748
+ disabled: readOnly,
1749
+ onChange: (e) => patch({ model: e.target.value || void 0 }),
1750
+ children: [
1751
+ /* @__PURE__ */ jsx4("option", { value: "", children: L.defaultModel }),
1752
+ models.map((m) => /* @__PURE__ */ jsx4("option", { value: m.id, children: m.label ?? m.id }, m.id)),
1753
+ node.model && !models.some((m) => m.id === node.model) && /* @__PURE__ */ jsx4("option", { value: node.model, children: L.unknownOption(node.model) })
1754
+ ]
1755
+ }
1756
+ ) }),
1757
+ /* @__PURE__ */ jsx4(
1758
+ Choices,
1759
+ {
1760
+ label: L.fieldSkills,
1761
+ options: props.skills,
1762
+ value: node.skills ?? [],
1763
+ onChange: (skills) => patch({ skills }),
1764
+ disabled: readOnly,
1765
+ L
1766
+ }
1767
+ ),
1768
+ /* @__PURE__ */ jsx4(
1769
+ Choices,
1770
+ {
1771
+ label: L.fieldTools,
1772
+ options: props.tools,
1773
+ value: node.tools ?? [],
1774
+ onChange: (tools) => patch({ tools }),
1775
+ disabled: readOnly,
1776
+ L
1777
+ }
1778
+ ),
1779
+ /* @__PURE__ */ jsx4(
1780
+ Choices,
1781
+ {
1782
+ label: L.fieldMcp,
1783
+ options: props.mcpServers,
1784
+ value: node.mcpServers ?? [],
1785
+ onChange: (mcpServers) => patch({ mcpServers }),
1786
+ disabled: readOnly,
1787
+ L
1788
+ }
1789
+ ),
1790
+ /* @__PURE__ */ jsxs3("fieldset", { className: "awr-pfield awr-pfield--routes", children: [
1791
+ /* @__PURE__ */ jsx4("legend", { className: "awr-pfield__label", children: L.fieldRoutes }),
1792
+ /* @__PURE__ */ jsx4("p", { className: "awr-pfield__hint", children: L.routesHint }),
1793
+ routes.map((route, index) => /* @__PURE__ */ jsxs3("div", { className: "awr-proute", children: [
1794
+ /* @__PURE__ */ jsx4(
1795
+ "input",
1796
+ {
1797
+ className: "awr-pinput awr-pinput--mono",
1798
+ value: route.label,
1799
+ "aria-label": L.routeLabel,
1800
+ placeholder: L.routeLabel,
1801
+ readOnly,
1802
+ spellCheck: false,
1803
+ onChange: (e) => onChange(renameRoute(value, node.id, route.label, e.target.value))
1804
+ }
1805
+ ),
1806
+ /* @__PURE__ */ jsx4(
1807
+ "input",
1808
+ {
1809
+ className: "awr-pinput",
1810
+ value: route.description ?? "",
1811
+ "aria-label": L.routeDescription,
1812
+ placeholder: L.routeDescription,
1813
+ readOnly,
1814
+ onChange: (e) => patch({
1815
+ routes: routes.map((r, i) => {
1816
+ if (i !== index) return r;
1817
+ const { description, ...rest } = r;
1818
+ void description;
1819
+ return e.target.value ? { ...rest, description: e.target.value } : rest;
1820
+ })
1821
+ })
1822
+ }
1823
+ ),
1824
+ !readOnly && /* @__PURE__ */ jsx4(
1825
+ "button",
1826
+ {
1827
+ type: "button",
1828
+ className: "awr-pbtn awr-pbtn--icon",
1829
+ "aria-label": L.removeRoute(route.label),
1830
+ onClick: () => patch({ routes: routes.filter((_, i) => i !== index) }),
1831
+ children: /* @__PURE__ */ jsx4(XIcon, { size: 14 })
1832
+ }
1833
+ )
1834
+ ] }, index)),
1835
+ !readOnly && routes.length < PIPELINE_LIMITS.maxRoutes && /* @__PURE__ */ jsxs3(
1836
+ "button",
1837
+ {
1838
+ type: "button",
1839
+ className: "awr-pbtn",
1840
+ onClick: () => patch({ routes: [...routes, { label: freeRoute() }] }),
1841
+ children: [
1842
+ /* @__PURE__ */ jsx4(PlusIcon, { size: 14 }),
1843
+ L.addRoute
1844
+ ]
1845
+ }
1846
+ )
1847
+ ] }),
1848
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldJoin, children: (id) => /* @__PURE__ */ jsxs3(
1849
+ "select",
1850
+ {
1851
+ id,
1852
+ className: "awr-pinput",
1853
+ value: node.join ?? "all",
1854
+ disabled: readOnly,
1855
+ onChange: (e) => patch({ join: e.target.value === "any" ? "any" : void 0 }),
1856
+ children: [
1857
+ /* @__PURE__ */ jsx4("option", { value: "all", children: L.joinAll }),
1858
+ /* @__PURE__ */ jsx4("option", { value: "any", children: L.joinAny })
1859
+ ]
1860
+ }
1861
+ ) }),
1862
+ /* @__PURE__ */ jsxs3("div", { className: "awr-pinspector__actions", children: [
1863
+ isEntry ? /* @__PURE__ */ jsx4("p", { className: "awr-pfield__hint", children: L.isEntry }) : !readOnly && /* @__PURE__ */ jsx4(
1864
+ "button",
1865
+ {
1866
+ type: "button",
1867
+ className: "awr-pbtn",
1868
+ onClick: () => onChange(setEntry(value, node.id)),
1869
+ children: L.makeEntry
1870
+ }
1871
+ ),
1872
+ !readOnly && /* @__PURE__ */ jsxs3(
1873
+ "button",
1874
+ {
1875
+ type: "button",
1876
+ className: "awr-pbtn awr-pbtn--danger",
1877
+ onClick: () => {
1878
+ onChange(removeNode(value, node.id));
1879
+ props.onSelectionChange?.(null);
1880
+ },
1881
+ children: [
1882
+ /* @__PURE__ */ jsx4(TrashIcon, { size: 14 }),
1883
+ L.deleteNode
1884
+ ]
1885
+ }
1886
+ )
1887
+ ] })
1888
+ ] });
1889
+ };
1890
+ var EdgeForm = ({
1891
+ edge,
1892
+ props,
1893
+ L
1894
+ }) => {
1895
+ const { value, onChange, readOnly = false } = props;
1896
+ const id = edgeIdAt(value, edge);
1897
+ const nameOf = (nodeId) => value.nodes.find((n) => n.id === nodeId)?.name || nodeId;
1898
+ const routes = value.nodes.find((n) => n.id === edge.from)?.routes ?? [];
1899
+ const when = edge.when ?? { kind: "always" };
1900
+ const set = (next) => onChange(updateEdge(value, id, { when: next }));
1901
+ const setKind = (kind) => {
1902
+ if (kind === "contains") set({ kind, text: "" });
1903
+ else if (kind === "matches") set({ kind, pattern: "" });
1904
+ else if (kind === "route") set({ kind, label: routes[0]?.label ?? "" });
1905
+ else set({ kind });
1906
+ };
1907
+ return /* @__PURE__ */ jsxs3(Fragment, { children: [
1908
+ /* @__PURE__ */ jsx4("p", { className: "awr-pinspector__ends", children: L.edgeEnds(nameOf(edge.from), nameOf(edge.to)) }),
1909
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldCondition, hint: L.conditionHints[when.kind], children: (fieldId, describedBy) => /* @__PURE__ */ jsx4(
1910
+ "select",
1911
+ {
1912
+ id: fieldId,
1913
+ className: "awr-pinput",
1914
+ value: when.kind,
1915
+ disabled: readOnly,
1916
+ "aria-describedby": describedBy,
1917
+ "data-awr-first-field": "",
1918
+ onChange: (e) => setKind(e.target.value),
1919
+ children: KINDS.map((kind) => /* @__PURE__ */ jsx4("option", { value: kind, children: L.conditionKinds[kind] }, kind))
1920
+ }
1921
+ ) }),
1922
+ when.kind === "contains" && /* @__PURE__ */ jsxs3(Fragment, { children: [
1923
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldText, children: (fieldId) => /* @__PURE__ */ jsx4(
1924
+ "input",
1925
+ {
1926
+ id: fieldId,
1927
+ className: "awr-pinput",
1928
+ value: when.text,
1929
+ readOnly,
1930
+ onChange: (e) => set({ ...when, text: e.target.value })
1931
+ }
1932
+ ) }),
1933
+ /* @__PURE__ */ jsxs3("label", { className: "awr-pcheck", children: [
1934
+ /* @__PURE__ */ jsx4(
1935
+ "input",
1936
+ {
1937
+ type: "checkbox",
1938
+ checked: when.caseSensitive === true,
1939
+ disabled: readOnly,
1940
+ onChange: (e) => {
1941
+ const { caseSensitive, ...rest } = when;
1942
+ void caseSensitive;
1943
+ set(e.target.checked ? { ...rest, caseSensitive: true } : rest);
1944
+ }
1945
+ }
1946
+ ),
1947
+ /* @__PURE__ */ jsx4("span", { children: L.caseSensitive })
1948
+ ] })
1949
+ ] }),
1950
+ when.kind === "matches" && /* @__PURE__ */ jsxs3("div", { className: "awr-pfield-row", children: [
1951
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldPattern, children: (fieldId) => /* @__PURE__ */ jsx4(
1952
+ "input",
1953
+ {
1954
+ id: fieldId,
1955
+ className: "awr-pinput awr-pinput--mono",
1956
+ value: when.pattern,
1957
+ readOnly,
1958
+ spellCheck: false,
1959
+ onChange: (e) => set({ ...when, pattern: e.target.value })
1960
+ }
1961
+ ) }),
1962
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldFlags, children: (fieldId) => /* @__PURE__ */ jsx4(
1963
+ "input",
1964
+ {
1965
+ id: fieldId,
1966
+ className: "awr-pinput awr-pinput--mono awr-pinput--short",
1967
+ value: when.flags ?? "",
1968
+ placeholder: "imsu",
1969
+ readOnly,
1970
+ spellCheck: false,
1971
+ maxLength: 4,
1972
+ onChange: (e) => {
1973
+ const { flags, ...rest } = when;
1974
+ void flags;
1975
+ set(e.target.value ? { ...rest, flags: e.target.value } : rest);
1976
+ }
1977
+ }
1978
+ ) })
1979
+ ] }),
1980
+ when.kind === "route" && (routes.length === 0 ? /* @__PURE__ */ jsx4("p", { className: "awr-pfield__hint awr-pfield__hint--error", children: L.noRoutes }) : /* @__PURE__ */ jsx4(Field, { label: L.fieldRoute, children: (fieldId) => /* @__PURE__ */ jsxs3(
1981
+ "select",
1982
+ {
1983
+ id: fieldId,
1984
+ className: "awr-pinput",
1985
+ value: when.label,
1986
+ disabled: readOnly,
1987
+ onChange: (e) => set({ kind: "route", label: e.target.value }),
1988
+ children: [
1989
+ !routes.some((r) => r.label === when.label) && /* @__PURE__ */ jsx4("option", { value: when.label, children: L.unknownOption(when.label) }),
1990
+ routes.map((r) => /* @__PURE__ */ jsx4("option", { value: r.label, children: r.label }, r.label))
1991
+ ]
1992
+ }
1993
+ ) })),
1994
+ !readOnly && /* @__PURE__ */ jsx4("div", { className: "awr-pinspector__actions", children: /* @__PURE__ */ jsxs3(
1995
+ "button",
1996
+ {
1997
+ type: "button",
1998
+ className: "awr-pbtn awr-pbtn--danger",
1999
+ onClick: () => {
2000
+ onChange(removeEdge(value, id));
2001
+ props.onSelectionChange?.(null);
2002
+ },
2003
+ children: [
2004
+ /* @__PURE__ */ jsx4(TrashIcon, { size: 14 }),
2005
+ L.deleteEdge
2006
+ ]
2007
+ }
2008
+ ) })
2009
+ ] });
2010
+ };
2011
+ var LimitField = ({
2012
+ label,
2013
+ value,
2014
+ fallback,
2015
+ max,
2016
+ readOnly,
2017
+ onChange,
2018
+ L
2019
+ }) => /* @__PURE__ */ jsx4(Field, { label, children: (id) => /* @__PURE__ */ jsx4(
2020
+ "input",
2021
+ {
2022
+ id,
2023
+ className: "awr-pinput",
2024
+ type: "number",
2025
+ inputMode: "numeric",
2026
+ min: 1,
2027
+ max,
2028
+ value: value ?? "",
2029
+ placeholder: L.limitDefault(fallback),
2030
+ readOnly,
2031
+ onChange: (e) => {
2032
+ const n = e.target.value === "" ? void 0 : Number(e.target.value);
2033
+ onChange(n === void 0 || Number.isNaN(n) ? void 0 : n);
2034
+ }
2035
+ }
2036
+ ) });
2037
+ var PipelineForm = ({ props, L }) => {
2038
+ const { value, onChange, readOnly = false } = props;
2039
+ return /* @__PURE__ */ jsxs3(Fragment, { children: [
2040
+ /* @__PURE__ */ jsx4(Field, { label: L.pipelineName, children: (id) => /* @__PURE__ */ jsx4(
2041
+ "input",
2042
+ {
2043
+ id,
2044
+ className: "awr-pinput",
2045
+ value: value.name ?? "",
2046
+ placeholder: L.pipelineNamePlaceholder,
2047
+ readOnly,
2048
+ "data-awr-first-field": "",
2049
+ onChange: (e) => onChange(setPipelineName(value, e.target.value))
2050
+ }
2051
+ ) }),
2052
+ /* @__PURE__ */ jsx4(Field, { label: L.fieldEntry, children: (id) => /* @__PURE__ */ jsxs3(
2053
+ "select",
2054
+ {
2055
+ id,
2056
+ className: "awr-pinput",
2057
+ value: value.entry,
2058
+ disabled: readOnly,
2059
+ onChange: (e) => onChange(setEntry(value, e.target.value)),
2060
+ children: [
2061
+ !value.nodes.some((n) => n.id === value.entry) && /* @__PURE__ */ jsx4("option", { value: value.entry }),
2062
+ value.nodes.map((n) => /* @__PURE__ */ jsx4("option", { value: n.id, children: n.name || n.id }, n.id))
2063
+ ]
2064
+ }
2065
+ ) }),
2066
+ /* @__PURE__ */ jsxs3("div", { className: "awr-pfield-row", children: [
2067
+ /* @__PURE__ */ jsx4(
2068
+ LimitField,
2069
+ {
2070
+ label: L.fieldMaxNodeVisits,
2071
+ value: value.limits?.maxNodeVisits,
2072
+ fallback: PIPELINE_LIMITS.maxNodeVisits,
2073
+ max: PIPELINE_LIMITS.maxNodeVisitsCeiling,
2074
+ readOnly,
2075
+ onChange: (maxNodeVisits) => onChange(setLimits(value, { maxNodeVisits })),
2076
+ L
2077
+ }
2078
+ ),
2079
+ /* @__PURE__ */ jsx4(
2080
+ LimitField,
2081
+ {
2082
+ label: L.fieldMaxRuns,
2083
+ value: value.limits?.maxRuns,
2084
+ fallback: PIPELINE_LIMITS.maxRuns,
2085
+ max: PIPELINE_LIMITS.maxRunsCeiling,
2086
+ readOnly,
2087
+ onChange: (maxRuns) => onChange(setLimits(value, { maxRuns })),
2088
+ L
2089
+ }
2090
+ )
2091
+ ] }),
2092
+ /* @__PURE__ */ jsx4("p", { className: "awr-pfield__hint", children: L.counts(value.nodes.length, value.edges.length) })
2093
+ ] });
2094
+ };
2095
+ var inspectorTitle = (value, selection, labels) => {
2096
+ if (selection?.kind === "node") {
2097
+ const node = value.nodes.find((n) => n.id === selection.id);
2098
+ if (node) return { kind: labels.inspectorNode, name: node.name || node.id };
2099
+ }
2100
+ if (selection?.kind === "edge") {
2101
+ const edge = value.edges.find((e) => edgeIdAt(value, e) === selection.id);
2102
+ const nameOf = (id) => value.nodes.find((n) => n.id === id)?.name || id;
2103
+ if (edge) {
2104
+ return {
2105
+ kind: labels.inspectorEdge,
2106
+ name: labels.edgeEnds(nameOf(edge.from), nameOf(edge.to))
2107
+ };
2108
+ }
2109
+ }
2110
+ return { kind: labels.inspectorPipeline, name: value.name || labels.pipelineNamePlaceholder };
2111
+ };
2112
+ var PipelineInspector = (props) => {
2113
+ const L = usePipelineLabels(props.labels);
2114
+ const { value, selection } = props;
2115
+ const node = selection?.kind === "node" ? value.nodes.find((n) => n.id === selection.id) : void 0;
2116
+ const edge = selection?.kind === "edge" ? value.edges.find((e) => edgeIdAt(value, e) === selection.id) : void 0;
2117
+ return /* @__PURE__ */ jsxs3("div", { className: "awr-pinspector", children: [
2118
+ node ? /* @__PURE__ */ jsx4(NodeForm, { node, props, L }) : edge ? /* @__PURE__ */ jsx4(EdgeForm, { edge, props, L }) : /* @__PURE__ */ jsx4(PipelineForm, { props, L }),
2119
+ props.footer
2120
+ ] });
2121
+ };
2122
+
2123
+ // src/pipeline/PipelineNodeCard.tsx
2124
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
2125
+ var routePortId = (label) => `route:${label}`;
2126
+ var OUTPUT_PORT = "out";
2127
+ var activityText = (activity, labels) => {
2128
+ if (!activity) return labels.activityPlanning;
2129
+ if (activity.tool) return labels.activityTool(activity.tool);
2130
+ if (activity.phase === "synthesize") return labels.activityAnswering;
2131
+ if (activity.phase === "replan") return labels.activityReplanning;
2132
+ if (activity.step) {
2133
+ return labels.activityStep(activity.stepIndex ?? 1, activity.stepTotal ?? 1, activity.step);
2134
+ }
2135
+ return labels.activityPlanning;
2136
+ };
2137
+ var PipelineNodeCard = ({
2138
+ node,
2139
+ view,
2140
+ entry = false,
2141
+ modelLabel,
2142
+ invalid = false,
2143
+ labels: over
2144
+ }) => {
2145
+ const L = usePipelineLabels(over);
2146
+ const { status } = view;
2147
+ const skills = node.skills?.length ?? 0;
2148
+ const tools = node.tools?.length ?? 0;
2149
+ const mcp = node.mcpServers?.length ?? 0;
2150
+ const routes = node.routes ?? [];
2151
+ const note = status === "running" ? activityText(view.activity, L) : status === "failed" ? view.error : status === "skipped" && view.skipped ? L.skippedBy[view.skipped] : void 0;
2152
+ return /* @__PURE__ */ jsxs4(
2153
+ "div",
2154
+ {
2155
+ className: `awr-pnode awr-pnode--${status}${invalid ? " awr-pnode--invalid" : ""}`,
2156
+ "data-status": status,
2157
+ children: [
2158
+ /* @__PURE__ */ jsxs4("div", { className: "awr-pnode__head", children: [
2159
+ /* @__PURE__ */ jsx5("span", { className: "awr-pnode__status", title: L.nodeStatus[status], children: status === "running" ? /* @__PURE__ */ jsx5(SpinnerIcon, { size: 14 }) : status === "done" ? /* @__PURE__ */ jsx5(CheckIcon, { size: 14 }) : status === "failed" ? /* @__PURE__ */ jsx5(AlertIcon, { size: 14 }) : status === "skipped" ? /* @__PURE__ */ jsx5(SkipIcon, { size: 14 }) : /* @__PURE__ */ jsx5("span", { className: "awr-pnode__dot" }) }),
2160
+ /* @__PURE__ */ jsx5("span", { className: "awr-pnode__name", children: node.name || node.id }),
2161
+ view.visits > 1 && /* @__PURE__ */ jsx5("span", { className: "awr-pnode__visits", children: L.visits(view.visits) }),
2162
+ entry && /* @__PURE__ */ jsx5("span", { className: "awr-pnode__entry", children: L.entry })
2163
+ ] }),
2164
+ /* @__PURE__ */ jsxs4("div", { className: "awr-pnode__meta", children: [
2165
+ /* @__PURE__ */ jsx5("span", { className: `awr-pnode__model${node.model ? "" : " awr-pnode__model--default"}`, children: modelLabel ?? node.model ?? L.defaultModel }),
2166
+ skills > 0 && /* @__PURE__ */ jsxs4("span", { className: "awr-pnode__badge", title: L.skillsBadge(skills), children: [
2167
+ /* @__PURE__ */ jsx5(BookIcon, { size: 12 }),
2168
+ skills,
2169
+ /* @__PURE__ */ jsx5("span", { className: "awr-pipeline__sr", children: L.skillsBadge(skills) })
2170
+ ] }),
2171
+ tools > 0 && /* @__PURE__ */ jsxs4("span", { className: "awr-pnode__badge", title: L.toolsBadge(tools), children: [
2172
+ /* @__PURE__ */ jsx5(ToolIcon, { size: 12 }),
2173
+ tools,
2174
+ /* @__PURE__ */ jsx5("span", { className: "awr-pipeline__sr", children: L.toolsBadge(tools) })
2175
+ ] }),
2176
+ mcp > 0 && /* @__PURE__ */ jsxs4("span", { className: "awr-pnode__badge", title: L.mcpBadge(mcp), children: [
2177
+ /* @__PURE__ */ jsx5(PlugIcon, { size: 12 }),
2178
+ mcp,
2179
+ /* @__PURE__ */ jsx5("span", { className: "awr-pipeline__sr", children: L.mcpBadge(mcp) })
2180
+ ] })
2181
+ ] }),
2182
+ note && /* @__PURE__ */ jsx5("div", { className: "awr-pnode__note", children: note }),
2183
+ routes.length > 0 && /* @__PURE__ */ jsxs4("ul", { className: "awr-pnode__routes", children: [
2184
+ routes.map((route) => /* @__PURE__ */ jsxs4("li", { className: "awr-pnode__route", title: route.description, children: [
2185
+ /* @__PURE__ */ jsx5("span", { className: "awr-pnode__route-label", children: route.label }),
2186
+ /* @__PURE__ */ jsx5(CanvasPort, { id: routePortId(route.label), label: route.label })
2187
+ ] }, route.label)),
2188
+ /* @__PURE__ */ jsxs4("li", { className: "awr-pnode__route awr-pnode__route--any", children: [
2189
+ /* @__PURE__ */ jsx5("span", { className: "awr-pnode__route-label", children: L.anyOutput }),
2190
+ /* @__PURE__ */ jsx5(CanvasPort, { id: OUTPUT_PORT, label: L.anyOutput })
2191
+ ] })
2192
+ ] })
2193
+ ]
2194
+ }
2195
+ );
2196
+ };
2197
+
2198
+ // src/pipeline/state.ts
2199
+ var ZERO = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
2200
+ var IDLE_NODE = { status: "idle", visits: 0, from: [], outputs: [] };
2201
+ var createInitialPipelineState = () => ({
2202
+ status: "idle",
2203
+ nodes: {},
2204
+ edges: {},
2205
+ lastFired: [],
2206
+ visits: [],
2207
+ text: "",
2208
+ usage: ZERO,
2209
+ runs: 0
2210
+ });
2211
+ var pipelineNodeView = (state, nodeId) => state.nodes[nodeId] ?? IDLE_NODE;
2212
+ var sum = (a, b) => {
2213
+ const out = { ...a ?? ZERO };
2214
+ for (const [key2, value] of Object.entries(b ?? {})) {
2215
+ if (typeof value === "number" && Number.isFinite(value)) out[key2] = (out[key2] ?? 0) + value;
2216
+ }
2217
+ return out;
2218
+ };
2219
+ var withNode = (state, nodeId, patch) => ({
2220
+ ...state,
2221
+ nodes: { ...state.nodes, [nodeId]: patch(pipelineNodeView(state, nodeId)) }
2222
+ });
2223
+ var settle = (state, visitStatus) => {
2224
+ const nodes = {};
2225
+ for (const [id, node] of Object.entries(state.nodes)) {
2226
+ if (node.status === "running" || node.status === "waiting") {
2227
+ const { activity, ...rest } = node;
2228
+ void activity;
2229
+ nodes[id] = { ...rest, status: node.outputs.length > 0 ? "done" : "idle" };
2230
+ } else {
2231
+ nodes[id] = node;
2232
+ }
2233
+ }
2234
+ const edges = {};
2235
+ for (const [id, edge] of Object.entries(state.edges)) {
2236
+ edges[id] = edge.live ? { ...edge, live: false } : edge;
2237
+ }
2238
+ return {
2239
+ ...state,
2240
+ nodes,
2241
+ edges,
2242
+ visits: state.visits.map((v) => v.status === "running" ? { ...v, status: visitStatus } : v)
2243
+ };
2244
+ };
2245
+ var quiet = (state, to) => {
2246
+ let edges = state.edges;
2247
+ for (const [id, edge] of Object.entries(state.edges)) {
2248
+ if (edge.live && edge.to === to) {
2249
+ if (edges === state.edges) edges = { ...state.edges };
2250
+ edges[id] = { ...edge, live: false };
2251
+ }
2252
+ }
2253
+ return edges;
2254
+ };
2255
+ var patchVisit = (visits, nodeId, visit, patch) => visits.map((v) => v.nodeId === nodeId && v.visit === visit ? { ...v, ...patch } : v);
2256
+ var activityOf = (current, event) => {
2257
+ const base2 = current ?? { toolCalls: 0 };
2258
+ switch (event.type) {
2259
+ case "run.start":
2260
+ return { phase: "plan", toolCalls: 0 };
2261
+ case "step.start":
2262
+ return {
2263
+ phase: "execute",
2264
+ step: event.step.description,
2265
+ stepIndex: event.index,
2266
+ stepTotal: event.total,
2267
+ toolCalls: base2.toolCalls
2268
+ };
2269
+ case "step.tool-call":
2270
+ return { ...base2, phase: "execute", tool: event.name, toolCalls: base2.toolCalls + 1 };
2271
+ case "step.tool-result":
2272
+ case "step.complete": {
2273
+ if (base2.tool === void 0) return current;
2274
+ const { tool, ...rest } = base2;
2275
+ void tool;
2276
+ return rest;
2277
+ }
2278
+ case "replan.decision":
2279
+ return base2.phase === "replan" && base2.tool === void 0 ? current : { toolCalls: base2.toolCalls, phase: "replan" };
2280
+ case "final.text-delta":
2281
+ case "final.reasoning-delta":
2282
+ return base2.phase === "synthesize" ? current : { toolCalls: base2.toolCalls, phase: "synthesize" };
2283
+ default:
2284
+ return current;
2285
+ }
2286
+ };
2287
+ var reduceEvent = (state, event) => {
2288
+ switch (event.type) {
2289
+ case "pipeline.started":
2290
+ return event.pipeline === state.name ? state : { ...state, name: event.pipeline };
2291
+ case "pipeline.node.started": {
2292
+ const next = withNode(state, event.nodeId, (node) => {
2293
+ const { error, skipped, activity, ...rest } = node;
2294
+ void [error, skipped, activity];
2295
+ return { ...rest, status: "running", visits: event.visit, from: event.from };
2296
+ });
2297
+ return {
2298
+ ...next,
2299
+ runs: state.runs + 1,
2300
+ visits: [
2301
+ ...state.visits,
2302
+ { nodeId: event.nodeId, visit: event.visit, from: event.from, status: "running" }
2303
+ ]
2304
+ };
2305
+ }
2306
+ case "pipeline.node.finished": {
2307
+ const output = {
2308
+ visit: event.visit,
2309
+ text: event.text,
2310
+ ...event.route !== void 0 ? { route: event.route } : {}
2311
+ };
2312
+ const next = withNode(state, event.nodeId, (node) => {
2313
+ const { activity, ...rest } = node;
2314
+ void activity;
2315
+ return {
2316
+ ...rest,
2317
+ status: "done",
2318
+ outputs: [...node.outputs, output],
2319
+ ...event.usage ? { usage: sum(node.usage, event.usage) } : {}
2320
+ };
2321
+ });
2322
+ return {
2323
+ ...next,
2324
+ edges: quiet(state, event.nodeId),
2325
+ lastFired: [],
2326
+ usage: sum(state.usage, event.usage),
2327
+ visits: patchVisit(state.visits, event.nodeId, event.visit, {
2328
+ status: "done",
2329
+ text: event.text,
2330
+ ...event.route !== void 0 ? { route: event.route } : {},
2331
+ ...event.usage ? { usage: event.usage } : {}
2332
+ })
2333
+ };
2334
+ }
2335
+ case "pipeline.node.failed": {
2336
+ const settled = settle(
2337
+ {
2338
+ ...state,
2339
+ visits: patchVisit(state.visits, event.nodeId, event.visit, {
2340
+ status: "failed",
2341
+ error: event.error
2342
+ })
2343
+ },
2344
+ "stopped"
2345
+ );
2346
+ const next = withNode(settled, event.nodeId, (node) => {
2347
+ const { activity, ...rest } = node;
2348
+ void activity;
2349
+ return { ...rest, status: "failed", error: event.error };
2350
+ });
2351
+ return { ...next, status: "failed", error: event.error, failedNode: event.nodeId };
2352
+ }
2353
+ case "pipeline.node.skipped": {
2354
+ const next = withNode(state, event.nodeId, (node) => ({
2355
+ ...node,
2356
+ status: "skipped",
2357
+ skipped: event.reason,
2358
+ from: event.from
2359
+ }));
2360
+ return { ...next, edges: quiet(state, event.nodeId) };
2361
+ }
2362
+ case "pipeline.edge": {
2363
+ const before = state.edges[event.edgeId];
2364
+ const edge = {
2365
+ from: event.from,
2366
+ to: event.to,
2367
+ fired: event.fired,
2368
+ visit: event.visit,
2369
+ count: (before?.count ?? 0) + (event.fired ? 1 : 0),
2370
+ live: event.fired
2371
+ };
2372
+ const next = {
2373
+ ...state,
2374
+ edges: { ...state.edges, [event.edgeId]: edge },
2375
+ lastFired: event.fired ? [...state.lastFired, event.edgeId] : state.lastFired
2376
+ };
2377
+ if (!event.fired) return next;
2378
+ const target = pipelineNodeView(next, event.to);
2379
+ if (target.status === "running" || target.status === "waiting") return next;
2380
+ return withNode(next, event.to, (node) => ({ ...node, status: "waiting" }));
2381
+ }
2382
+ case "pipeline.finished": {
2383
+ const settled = settle(state, event.stoppedBy === "aborted" ? "stopped" : "done");
2384
+ const { stoppedBy, ...rest } = settled;
2385
+ void stoppedBy;
2386
+ return {
2387
+ ...rest,
2388
+ status: event.stoppedBy === "aborted" ? "stopped" : "done",
2389
+ runs: event.runs,
2390
+ ...event.stoppedBy ? { stoppedBy: event.stoppedBy } : {}
2391
+ };
2392
+ }
2393
+ default: {
2394
+ if (event.nodeId === void 0) return state;
2395
+ const node = state.nodes[event.nodeId];
2396
+ if (!node || node.status !== "running") return state;
2397
+ const activity = activityOf(node.activity, event);
2398
+ if (activity === node.activity) return state;
2399
+ return withNode(state, event.nodeId, (n) => ({ ...n, activity }));
2400
+ }
2401
+ }
2402
+ };
2403
+ var pipelineStateReducer = (state, action) => {
2404
+ switch (action.type) {
2405
+ case "reset":
2406
+ return createInitialPipelineState();
2407
+ case "run.start":
2408
+ return { ...createInitialPipelineState(), status: "running", input: action.input };
2409
+ case "event":
2410
+ return reduceEvent(state, action.event);
2411
+ case "run.result": {
2412
+ const { result } = action;
2413
+ const settled = state.status === "running" ? settle(state, "done") : state;
2414
+ const { stoppedBy, ...rest } = settled;
2415
+ void stoppedBy;
2416
+ return {
2417
+ ...rest,
2418
+ status: state.status === "running" ? result.stoppedBy === "aborted" ? "stopped" : "done" : state.status,
2419
+ text: result.text,
2420
+ usage: result.usage,
2421
+ runs: result.runs,
2422
+ ...result.stoppedBy ? { stoppedBy: result.stoppedBy } : {}
2423
+ };
2424
+ }
2425
+ case "run.error": {
2426
+ const settled = settle(state, "stopped");
2427
+ return {
2428
+ ...settled,
2429
+ status: "failed",
2430
+ // The node's own words (from `pipeline.node.failed`) say more than the wrapper's.
2431
+ error: state.error ?? action.error,
2432
+ ...action.nodeId && !state.failedNode ? { failedNode: action.nodeId } : {}
2433
+ };
2434
+ }
2435
+ }
2436
+ };
2437
+
2438
+ // src/pipeline/PipelineEditor.tsx
2439
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
2440
+ var conditionSummary = (when, labels) => {
2441
+ switch (when?.kind) {
2442
+ case "route":
2443
+ return when.label;
2444
+ case "contains":
2445
+ return `${labels.conditionKinds.contains} \u201C${when.text}\u201D`;
2446
+ case "matches":
2447
+ return `/${when.pattern}/${when.flags ?? ""}`;
2448
+ case "otherwise":
2449
+ return labels.conditionKinds.otherwise;
2450
+ default:
2451
+ return "";
2452
+ }
2453
+ };
2454
+ var download = (name, text) => {
2455
+ const url = URL.createObjectURL(new Blob([text], { type: "application/json" }));
2456
+ const a = document.createElement("a");
2457
+ a.href = url;
2458
+ a.download = name;
2459
+ document.body.appendChild(a);
2460
+ a.click();
2461
+ a.remove();
2462
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
2463
+ };
2464
+ var copyText = async (text) => {
2465
+ try {
2466
+ await navigator.clipboard.writeText(text);
2467
+ return true;
2468
+ } catch {
2469
+ try {
2470
+ const area = document.createElement("textarea");
2471
+ area.value = text;
2472
+ area.style.position = "fixed";
2473
+ area.style.opacity = "0";
2474
+ document.body.appendChild(area);
2475
+ area.select();
2476
+ const ok = document.execCommand("copy");
2477
+ area.remove();
2478
+ return ok;
2479
+ } catch {
2480
+ return false;
2481
+ }
2482
+ }
2483
+ };
2484
+ var PipelineCodeDialog = ({
2485
+ definition,
2486
+ open,
2487
+ onClose,
2488
+ input,
2489
+ labels: over
2490
+ }) => {
2491
+ const L = usePipelineLabels(over);
2492
+ const ref = useRef2(null);
2493
+ const [target, setTarget] = useState3("browser");
2494
+ const [copied, setCopied] = useState3(false);
2495
+ const titleId = useId3();
2496
+ const code = useMemo3(
2497
+ () => open ? pipelineToCode(definition, { target, ...input ? { input } : {} }) : "",
2498
+ [open, definition, target, input]
2499
+ );
2500
+ useEffect3(() => {
2501
+ const dialog = ref.current;
2502
+ if (!dialog) return;
2503
+ if (open && !dialog.open) {
2504
+ if (typeof dialog.showModal === "function") dialog.showModal();
2505
+ else dialog.setAttribute("open", "");
2506
+ } else if (!open && dialog.open) {
2507
+ dialog.close();
2508
+ }
2509
+ }, [open]);
2510
+ useEffect3(() => setCopied(false), [code]);
2511
+ return /* @__PURE__ */ jsx6(
2512
+ "dialog",
2513
+ {
2514
+ ref,
2515
+ className: "awr-pcode",
2516
+ "aria-labelledby": titleId,
2517
+ onClose,
2518
+ onClick: (e) => {
2519
+ if (e.target === e.currentTarget) onClose();
2520
+ },
2521
+ children: open && /* @__PURE__ */ jsxs5("div", { className: "awr-pcode__body", children: [
2522
+ /* @__PURE__ */ jsxs5("div", { className: "awr-pcode__head", children: [
2523
+ /* @__PURE__ */ jsx6("h2", { id: titleId, className: "awr-pcode__title", children: L.codeTitle }),
2524
+ /* @__PURE__ */ jsx6(
2525
+ "button",
2526
+ {
2527
+ type: "button",
2528
+ className: "awr-pbtn awr-pbtn--icon",
2529
+ "aria-label": L.close,
2530
+ onClick: onClose,
2531
+ children: /* @__PURE__ */ jsx6(XIcon, { size: 16 })
2532
+ }
2533
+ )
2534
+ ] }),
2535
+ /* @__PURE__ */ jsxs5("div", { className: "awr-pcode__bar", children: [
2536
+ /* @__PURE__ */ jsx6("div", { className: "awr-pseg", role: "tablist", "aria-label": L.codeTitle, children: ["browser", "node"].map((t) => /* @__PURE__ */ jsx6(
2537
+ "button",
2538
+ {
2539
+ type: "button",
2540
+ role: "tab",
2541
+ "aria-selected": target === t,
2542
+ className: `awr-pseg__item${target === t ? " is-active" : ""}`,
2543
+ onClick: () => setTarget(t),
2544
+ children: t === "browser" ? L.codeBrowser : L.codeNode
2545
+ },
2546
+ t
2547
+ )) }),
2548
+ /* @__PURE__ */ jsxs5(
2549
+ "button",
2550
+ {
2551
+ type: "button",
2552
+ className: "awr-pbtn awr-pbtn--primary",
2553
+ onClick: () => void copyText(code).then(setCopied),
2554
+ children: [
2555
+ copied ? /* @__PURE__ */ jsx6(CheckIcon, { size: 14 }) : /* @__PURE__ */ jsx6(CodeIcon, { size: 14 }),
2556
+ /* @__PURE__ */ jsx6("span", { "aria-live": "polite", children: copied ? L.copied : L.copy })
2557
+ ]
2558
+ }
2559
+ )
2560
+ ] }),
2561
+ /* @__PURE__ */ jsx6("pre", { className: "awr-pcode__pre", tabIndex: 0, children: /* @__PURE__ */ jsx6("code", { children: code }) })
2562
+ ] })
2563
+ }
2564
+ );
2565
+ };
2566
+ var PipelineResults = ({
2567
+ state,
2568
+ definition,
2569
+ renderContent,
2570
+ footer,
2571
+ labels: over
2572
+ }) => {
2573
+ const L = usePipelineLabels(over);
2574
+ const nameOf = (id) => definition.nodes.find((n) => n.id === id)?.name || id;
2575
+ const render = (text) => renderContent ? renderContent(text) : /* @__PURE__ */ jsx6("div", { className: "awr-presults__plain", children: text });
2576
+ return /* @__PURE__ */ jsxs5("div", { className: `awr-presults awr-presults--${state.status}`, children: [
2577
+ /* @__PURE__ */ jsxs5("div", { className: "awr-presults__summary", children: [
2578
+ /* @__PURE__ */ jsx6("span", { className: `awr-presults__status awr-presults__status--${state.status}`, children: L.runStatus[state.status] }),
2579
+ state.runs > 0 && /* @__PURE__ */ jsx6("span", { children: L.runsCount(state.runs) }),
2580
+ state.usage.totalTokens > 0 && /* @__PURE__ */ jsx6("span", { children: L.usage(formatTokens(state.usage.inputTokens), formatTokens(state.usage.outputTokens)) })
2581
+ ] }),
2582
+ state.error && /* @__PURE__ */ jsxs5("p", { className: "awr-presults__error", role: "alert", children: [
2583
+ state.failedNode ? `${nameOf(state.failedNode)}: ` : "",
2584
+ state.error
2585
+ ] }),
2586
+ state.stoppedBy && /* @__PURE__ */ jsx6("p", { className: "awr-presults__note", children: L.stoppedBy[state.stoppedBy] }),
2587
+ /* @__PURE__ */ jsxs5("div", { className: "awr-presults__columns", children: [
2588
+ /* @__PURE__ */ jsxs5("section", { className: "awr-presults__final", "aria-label": L.finalAnswer, children: [
2589
+ /* @__PURE__ */ jsx6("h3", { className: "awr-presults__heading", children: L.finalAnswer }),
2590
+ state.text ? /* @__PURE__ */ jsx6("div", { className: "awr-presults__text", children: render(state.text) }) : /* @__PURE__ */ jsx6("p", { className: "awr-presults__empty", children: L.noOutputYet })
2591
+ ] }),
2592
+ /* @__PURE__ */ jsxs5("section", { className: "awr-presults__outputs", "aria-label": L.nodeOutputs, children: [
2593
+ /* @__PURE__ */ jsx6("h3", { className: "awr-presults__heading", children: L.nodeOutputs }),
2594
+ state.visits.length === 0 ? /* @__PURE__ */ jsx6("p", { className: "awr-presults__empty", children: L.noOutputYet }) : /* @__PURE__ */ jsx6("ol", { className: "awr-presults__visits", children: state.visits.map((visit) => /* @__PURE__ */ jsx6("li", { children: /* @__PURE__ */ jsxs5("details", { className: `awr-pvisit awr-pvisit--${visit.status}`, children: [
2595
+ /* @__PURE__ */ jsxs5("summary", { className: "awr-pvisit__summary", children: [
2596
+ /* @__PURE__ */ jsx6("span", { className: "awr-pvisit__name", children: L.visitTitle(nameOf(visit.nodeId), visit.visit) }),
2597
+ visit.route && /* @__PURE__ */ jsx6("span", { className: "awr-pvisit__route", children: L.routeTaken(visit.route) }),
2598
+ /* @__PURE__ */ jsx6("span", { className: "awr-pvisit__status", children: L.nodeStatus[visit.status === "stopped" ? "idle" : visit.status] })
2599
+ ] }),
2600
+ visit.from.length > 0 && /* @__PURE__ */ jsx6("p", { className: "awr-pvisit__from", children: L.receivedFrom(visit.from.map(nameOf).join(", ")) }),
2601
+ visit.error && /* @__PURE__ */ jsx6("p", { className: "awr-presults__error", children: visit.error }),
2602
+ visit.text !== void 0 && /* @__PURE__ */ jsx6("div", { className: "awr-presults__text", children: render(visit.text) })
2603
+ ] }) }, `${visit.nodeId}#${visit.visit}`)) })
2604
+ ] })
2605
+ ] }),
2606
+ footer
2607
+ ] });
2608
+ };
2609
+ var PipelineIssues = ({ validation, onPick, labels: over }) => {
2610
+ const L = usePipelineLabels(over);
2611
+ const rows = [
2612
+ ...validation.errors.map((issue) => ({ issue, error: true })),
2613
+ ...validation.warnings.map((issue) => ({ issue, error: false }))
2614
+ ];
2615
+ if (rows.length === 0) return /* @__PURE__ */ jsx6("p", { className: "awr-pissues__none", children: L.noIssues });
2616
+ return /* @__PURE__ */ jsx6("ul", { className: "awr-pissues", children: rows.map(({ issue, error }, index) => /* @__PURE__ */ jsx6("li", { children: /* @__PURE__ */ jsxs5(
2617
+ "button",
2618
+ {
2619
+ type: "button",
2620
+ className: `awr-pissue awr-pissue--${error ? "error" : "warning"}`,
2621
+ onClick: () => onPick?.(issue),
2622
+ children: [
2623
+ /* @__PURE__ */ jsx6("span", { className: "awr-pissue__kind", children: error ? L.issueError : L.issueWarning }),
2624
+ /* @__PURE__ */ jsx6("span", { className: "awr-pissue__text", children: issue.message })
2625
+ ]
2626
+ }
2627
+ ) }, index)) });
2628
+ };
2629
+ var IDLE = createInitialPipelineState();
2630
+ var PipelineEditor = (props) => {
2631
+ const {
2632
+ value,
2633
+ onChange,
2634
+ controller,
2635
+ showToolbar = true,
2636
+ showInspector = true,
2637
+ showRunBar = true,
2638
+ showResults = true,
2639
+ showIssues = true,
2640
+ showImport = true,
2641
+ showExport = true,
2642
+ showCode = true,
2643
+ showZoom = true,
2644
+ showGrid = true,
2645
+ snap = 20,
2646
+ readOnly = false,
2647
+ narrowWidth = 760,
2648
+ renderNode,
2649
+ renderContent,
2650
+ slots,
2651
+ theme,
2652
+ className
2653
+ } = props;
2654
+ const L = usePipelineLabels(props.labels);
2655
+ const state = controller ?? IDLE;
2656
+ const validate = props.validate ?? validatePipeline;
2657
+ const def = useMemo3(() => autoLayout(ensureEdgeIds(value)), [value]);
2658
+ const validation = useMemo3(() => validate(def), [validate, def]);
2659
+ const invalid = useMemo3(() => {
2660
+ const nodes = /* @__PURE__ */ new Set();
2661
+ const edges = /* @__PURE__ */ new Set();
2662
+ for (const issue of validation.errors) {
2663
+ const target = issueTarget(issue, def);
2664
+ if (target?.kind === "edge") edges.add(target.id);
2665
+ else if (target?.kind === "node") nodes.add(target.id);
2666
+ }
2667
+ return { nodes, edges };
2668
+ }, [validation, def]);
2669
+ const [ownSelection, setOwnSelection] = useState3(null);
2670
+ const rawSelection = props.selection !== void 0 ? props.selection : ownSelection;
2671
+ const selection = useMemo3(() => {
2672
+ if (!rawSelection) return null;
2673
+ const exists = rawSelection.kind === "node" ? def.nodes.some((n) => n.id === rawSelection.id) : def.edges.some((e) => e.id === rawSelection.id);
2674
+ return exists ? rawSelection : null;
2675
+ }, [rawSelection, def]);
2676
+ const { onSelectionChange } = props;
2677
+ const select = useCallback2(
2678
+ (next) => {
2679
+ setOwnSelection(next);
2680
+ onSelectionChange?.(next);
2681
+ },
2682
+ [onSelectionChange]
2683
+ );
2684
+ const rootRef = useRef2(null);
2685
+ const canvasRef = useRef2(null);
2686
+ const inspectorRef = useRef2(null);
2687
+ const [narrow, setNarrow] = useState3(
2688
+ () => typeof window !== "undefined" && window.innerWidth < narrowWidth
2689
+ );
2690
+ useEffect3(() => {
2691
+ const el = rootRef.current;
2692
+ if (!el) return;
2693
+ const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth);
2694
+ measure();
2695
+ if (typeof ResizeObserver === "undefined") return;
2696
+ const ro = new ResizeObserver(measure);
2697
+ ro.observe(el);
2698
+ return () => ro.disconnect();
2699
+ }, [narrowWidth]);
2700
+ const [sheetOpen, setSheetOpen] = useState3(false);
2701
+ const [issuesOpen, setIssuesOpen] = useState3(false);
2702
+ const [codeOpen, setCodeOpen] = useState3(false);
2703
+ const [resultsOpen, setResultsOpen] = useState3(true);
2704
+ const [notice, setNotice] = useState3();
2705
+ const [ownInput, setOwnInput] = useState3("");
2706
+ const input = props.input ?? ownInput;
2707
+ const setInput = (text) => {
2708
+ setOwnInput(text);
2709
+ props.onInputChange?.(text);
2710
+ };
2711
+ const [loads, setLoads] = useState3(0);
2712
+ const focusFields = useRef2(false);
2713
+ const openInspector = useCallback2(
2714
+ (target) => {
2715
+ select(target);
2716
+ setSheetOpen(true);
2717
+ focusFields.current = true;
2718
+ },
2719
+ [select]
2720
+ );
2721
+ useEffect3(() => {
2722
+ if (!focusFields.current) return;
2723
+ focusFields.current = false;
2724
+ inspectorRef.current?.querySelector("[data-awr-first-field]")?.focus();
2725
+ });
2726
+ const pendingFocus = useRef2(void 0);
2727
+ useEffect3(() => {
2728
+ const id = pendingFocus.current;
2729
+ if (!id || !def.nodes.some((n) => n.id === id)) return;
2730
+ pendingFocus.current = void 0;
2731
+ canvasRef.current?.focus({ kind: "node", id });
2732
+ });
2733
+ const canvasNodes = useMemo3(
2734
+ () => def.nodes.map((node) => {
2735
+ const view = pipelineNodeView(state, node.id);
2736
+ const routes = node.routes ?? [];
2737
+ return {
2738
+ id: node.id,
2739
+ x: node.position?.x ?? 0,
2740
+ y: node.position?.y ?? 0,
2741
+ label: node.name || node.id,
2742
+ description: [
2743
+ def.entry === node.id ? `${L.entry}.` : "",
2744
+ L.nodeDescription(L.nodeStatus[view.status], view.visits)
2745
+ ].filter(Boolean).join(" "),
2746
+ ...routes.length > 0 ? {
2747
+ ports: [
2748
+ { id: OUTPUT_PORT, label: L.anyOutput },
2749
+ ...routes.map((r) => ({ id: routePortId(r.label), label: r.label }))
2750
+ ]
2751
+ } : {}
2752
+ };
2753
+ }),
2754
+ [def, state, L]
2755
+ );
2756
+ const canvasEdges = useMemo3(
2757
+ () => def.edges.map((edge) => {
2758
+ const id = edge.id;
2759
+ const run = state.edges[id];
2760
+ const source = def.nodes.find((n) => n.id === edge.from);
2761
+ const label = conditionSummary(edge.when, L);
2762
+ const route = edge.when?.kind === "route" ? edge.when.label : void 0;
2763
+ const routed = route !== void 0 && source?.routes?.some((r) => r.label === route);
2764
+ return {
2765
+ id,
2766
+ from: edge.from,
2767
+ to: edge.to,
2768
+ ...routed ? { fromPort: routePortId(route) } : {},
2769
+ ...label ? { label } : {},
2770
+ tone: invalid.edges.has(id) ? "danger" : run?.live ? "active" : run && run.count > 0 ? "done" : run ? "muted" : "default"
2771
+ };
2772
+ }),
2773
+ [def, state.edges, invalid, L]
2774
+ );
2775
+ const modelLabel = useCallback2(
2776
+ (node) => node.model ? props.models?.find((m) => m.id === node.model)?.label : void 0,
2777
+ [props.models]
2778
+ );
2779
+ const handleAdd = () => {
2780
+ const id = uniqueNodeId(def, "agent");
2781
+ const canvas = canvasRef.current;
2782
+ const size = canvas?.getSize();
2783
+ let position = { x: 0, y: 0 };
2784
+ if (canvas && size && size.width > 0) {
2785
+ const middle = screenToWorld({ x: size.width / 2, y: size.height / 2 }, canvas.getViewport());
2786
+ position = snapPoint({ x: middle.x - 120, y: middle.y - 48 }, snap);
2787
+ }
2788
+ while (def.nodes.some((n) => n.position?.x === position.x && n.position?.y === position.y)) {
2789
+ position = { x: position.x + 40, y: position.y + 40 };
2790
+ }
2791
+ onChange(addNode(def, { id, name: L.newNodeName(def.nodes.length + 1), position }));
2792
+ select({ kind: "node", id });
2793
+ pendingFocus.current = id;
2794
+ };
2795
+ const handleDelete = (target = selection) => {
2796
+ if (!target || readOnly) return;
2797
+ onChange(target.kind === "node" ? removeNode(def, target.id) : removeEdge(def, target.id));
2798
+ select(null);
2799
+ };
2800
+ const handleConnect = ({ from, to, fromPort }) => {
2801
+ const route = fromPort?.startsWith("route:") ? fromPort.slice("route:".length) : void 0;
2802
+ const next = addEdge(def, {
2803
+ from,
2804
+ to,
2805
+ ...route !== void 0 ? { when: { kind: "route", label: route } } : {}
2806
+ });
2807
+ if (next === def) return;
2808
+ onChange(next);
2809
+ const added = next.edges[next.edges.length - 1];
2810
+ select({ kind: "edge", id: added.id });
2811
+ };
2812
+ const fileRef = useRef2(null);
2813
+ const handleImport = async (file) => {
2814
+ if (!file) return;
2815
+ try {
2816
+ onChange(parsePipelineJson(await file.text()));
2817
+ setNotice(void 0);
2818
+ select(null);
2819
+ setLoads((n) => n + 1);
2820
+ } catch (err) {
2821
+ setNotice(L.importFailed(errMessage(err)));
2822
+ }
2823
+ };
2824
+ const handleExport = () => download(`${slugifyId(def.name ?? "") || "pipeline"}.json`, `${JSON.stringify(def, null, 2)}
2825
+ `);
2826
+ const pickIssue = (issue) => {
2827
+ const target = issueTarget(issue, def);
2828
+ setIssuesOpen(false);
2829
+ if (!target) {
2830
+ select(null);
2831
+ setSheetOpen(true);
2832
+ return;
2833
+ }
2834
+ select(target);
2835
+ canvasRef.current?.focus(target);
2836
+ };
2837
+ const running = controller?.isRunning ?? false;
2838
+ const canRun = Boolean(controller) && validation.ok && input.trim().length > 0;
2839
+ const submit = (e) => {
2840
+ e.preventDefault();
2841
+ if (!controller) return;
2842
+ if (running) {
2843
+ controller.stop();
2844
+ return;
2845
+ }
2846
+ if (!canRun) return;
2847
+ setResultsOpen(true);
2848
+ void controller.run(input.trim());
2849
+ };
2850
+ const said = useRef2({});
2851
+ const [announcement, setAnnouncement] = useState3("");
2852
+ useEffect3(() => {
2853
+ const now = {};
2854
+ let message = "";
2855
+ for (const [id, node] of Object.entries(state.nodes)) {
2856
+ now[id] = `${node.status}:${node.visits}`;
2857
+ if (said.current[id] !== now[id] && node.status !== "idle" && node.status !== "waiting") {
2858
+ const name = def.nodes.find((n) => n.id === id)?.name || id;
2859
+ message = L.announceNode(name, L.nodeStatus[node.status]);
2860
+ if (node.status === "running") canvasRef.current?.reveal(id);
2861
+ }
2862
+ }
2863
+ said.current = now;
2864
+ if (message) setAnnouncement(message);
2865
+ }, [state.nodes, def.nodes, L]);
2866
+ const title = inspectorTitle(def, selection, L);
2867
+ const errorCount = validation.errors.length;
2868
+ const warningCount = validation.warnings.length;
2869
+ const hasRun = state.status !== "idle";
2870
+ const resultsId = useId3();
2871
+ const issuesId = useId3();
2872
+ const inspectorId = useId3();
2873
+ const tool = (key2, label, icon, onClick, options = {}) => /* @__PURE__ */ jsxs5(
2874
+ "button",
2875
+ {
2876
+ type: "button",
2877
+ className: `awr-pbtn awr-ptool${options.primary ? " awr-pbtn--primary" : ""}${options.hideNarrow ? " awr-ptool--wide-only" : ""}`,
2878
+ "aria-label": label,
2879
+ title: label,
2880
+ "data-tool": key2,
2881
+ disabled: options.disabled,
2882
+ onClick,
2883
+ children: [
2884
+ icon,
2885
+ options.text !== false && /* @__PURE__ */ jsx6("span", { className: "awr-ptool__text", children: label })
2886
+ ]
2887
+ },
2888
+ key2
2889
+ );
2890
+ return /* @__PURE__ */ jsxs5(
2891
+ "div",
2892
+ {
2893
+ ref: rootRef,
2894
+ className: ["awr-pipeline", narrow ? "awr-pipeline--narrow" : "", className].filter(Boolean).join(" "),
2895
+ "data-awr-theme": theme,
2896
+ "data-status": state.status,
2897
+ children: [
2898
+ showToolbar && /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__toolbar", role: "toolbar", "aria-label": L.toolbar, children: [
2899
+ slots?.toolbarStart,
2900
+ !readOnly && /* @__PURE__ */ jsxs5("div", { className: "awr-ptools", children: [
2901
+ tool("add", L.addNode, /* @__PURE__ */ jsx6(PlusIcon, { size: 16 }), handleAdd, { primary: true }),
2902
+ tool("delete", L.deleteSelected, /* @__PURE__ */ jsx6(TrashIcon, { size: 16 }), () => handleDelete(), {
2903
+ disabled: !selection
2904
+ })
2905
+ ] }),
2906
+ showZoom && /* @__PURE__ */ jsxs5("div", { className: "awr-ptools", children: [
2907
+ tool(
2908
+ "zoom-out",
2909
+ L.zoomOut,
2910
+ /* @__PURE__ */ jsx6(MinusIcon, { size: 16 }),
2911
+ () => canvasRef.current?.zoomOut(),
2912
+ { text: false, hideNarrow: true }
2913
+ ),
2914
+ tool(
2915
+ "zoom-in",
2916
+ L.zoomIn,
2917
+ /* @__PURE__ */ jsx6(PlusIcon, { size: 16 }),
2918
+ () => canvasRef.current?.zoomIn(),
2919
+ { text: false, hideNarrow: true }
2920
+ ),
2921
+ tool("fit", L.fit, /* @__PURE__ */ jsx6(FitIcon, { size: 16 }), () => canvasRef.current?.fit())
2922
+ ] }),
2923
+ (showImport || showExport || showCode) && /* @__PURE__ */ jsxs5("div", { className: "awr-ptools", children: [
2924
+ showImport && !readOnly && tool(
2925
+ "import",
2926
+ L.importJson,
2927
+ /* @__PURE__ */ jsx6(UploadIcon, { size: 16 }),
2928
+ () => fileRef.current?.click()
2929
+ ),
2930
+ showExport && tool("export", L.exportJson, /* @__PURE__ */ jsx6(DownloadIcon, { size: 16 }), handleExport),
2931
+ showCode && tool("code", L.copyCode, /* @__PURE__ */ jsx6(CodeIcon, { size: 16 }), () => setCodeOpen(true))
2932
+ ] }),
2933
+ /* @__PURE__ */ jsx6(
2934
+ "input",
2935
+ {
2936
+ ref: fileRef,
2937
+ type: "file",
2938
+ accept: "application/json,.json",
2939
+ hidden: true,
2940
+ onChange: (e) => {
2941
+ void handleImport(e.target.files?.[0]);
2942
+ e.target.value = "";
2943
+ }
2944
+ }
2945
+ ),
2946
+ /* @__PURE__ */ jsx6("span", { className: "awr-pipeline__spacer" }),
2947
+ slots?.toolbarEnd,
2948
+ showIssues && /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__issues", children: [
2949
+ /* @__PURE__ */ jsxs5(
2950
+ "button",
2951
+ {
2952
+ type: "button",
2953
+ className: `awr-pbtn awr-pissues-chip${errorCount ? " awr-pissues-chip--error" : warningCount ? " awr-pissues-chip--warning" : " awr-pissues-chip--ok"}`,
2954
+ "aria-expanded": issuesOpen,
2955
+ "aria-controls": issuesId,
2956
+ "data-tool": "issues",
2957
+ onClick: () => setIssuesOpen((open) => !open),
2958
+ children: [
2959
+ errorCount || warningCount ? /* @__PURE__ */ jsx6(AlertIcon, { size: 15 }) : /* @__PURE__ */ jsx6(CheckIcon, { size: 15 }),
2960
+ /* @__PURE__ */ jsxs5("span", { className: "awr-pipeline__sr", children: [
2961
+ L.issues,
2962
+ ": "
2963
+ ] }),
2964
+ /* @__PURE__ */ jsx6("span", { className: "awr-pissues-chip__text", children: errorCount || warningCount ? [
2965
+ errorCount ? L.errors(errorCount) : "",
2966
+ warningCount ? L.warnings(warningCount) : ""
2967
+ ].filter(Boolean).join(" \xB7 ") : L.noIssues }),
2968
+ /* @__PURE__ */ jsx6("span", { className: "awr-pissues-chip__count", "aria-hidden": "true", children: errorCount + warningCount || "" })
2969
+ ]
2970
+ }
2971
+ ),
2972
+ issuesOpen && /* @__PURE__ */ jsx6("div", { id: issuesId, className: "awr-pipeline__issues-panel", children: /* @__PURE__ */ jsx6(
2973
+ PipelineIssues,
2974
+ {
2975
+ validation,
2976
+ onPick: pickIssue,
2977
+ labels: props.labels
2978
+ }
2979
+ ) })
2980
+ ] })
2981
+ ] }),
2982
+ notice && /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__notice", role: "alert", children: [
2983
+ /* @__PURE__ */ jsx6("span", { children: notice }),
2984
+ /* @__PURE__ */ jsx6(
2985
+ "button",
2986
+ {
2987
+ type: "button",
2988
+ className: "awr-pbtn awr-pbtn--icon",
2989
+ "aria-label": L.close,
2990
+ onClick: () => setNotice(void 0),
2991
+ children: /* @__PURE__ */ jsx6(XIcon, { size: 14 })
2992
+ }
2993
+ )
2994
+ ] }),
2995
+ /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__stage", children: [
2996
+ /* @__PURE__ */ jsxs5(
2997
+ Canvas,
2998
+ {
2999
+ ref: canvasRef,
3000
+ className: "awr-pipeline__canvas",
3001
+ nodes: canvasNodes,
3002
+ edges: canvasEdges,
3003
+ selection,
3004
+ onSelectionChange: select,
3005
+ onNodeMove: (id, position) => onChange(moveNode(def, id, position)),
3006
+ onConnect: handleConnect,
3007
+ onDelete: handleDelete,
3008
+ onOpen: openInspector,
3009
+ snap,
3010
+ showGrid,
3011
+ showControls: false,
3012
+ readOnly,
3013
+ fitKey: `${props.fitKey ?? ""}:${loads}`,
3014
+ autoFitMinZoom: narrow ? 0.7 : void 0,
3015
+ labels: L.canvas,
3016
+ renderNode: (canvasNode, nodeState) => {
3017
+ const node = def.nodes.find((n) => n.id === canvasNode.id);
3018
+ const view = pipelineNodeView(state, node.id);
3019
+ const entry = def.entry === node.id;
3020
+ const bad = invalid.nodes.has(node.id);
3021
+ const card = /* @__PURE__ */ jsx6(
3022
+ PipelineNodeCard,
3023
+ {
3024
+ node,
3025
+ view,
3026
+ entry,
3027
+ invalid: bad,
3028
+ modelLabel: modelLabel(node),
3029
+ labels: props.labels
3030
+ }
3031
+ );
3032
+ return renderNode ? renderNode({ node, view, entry, selected: nodeState.selected, invalid: bad, card }) : card;
3033
+ },
3034
+ children: [
3035
+ def.nodes.length === 0 && /* @__PURE__ */ jsx6("p", { className: "awr-pipeline__empty", children: L.emptyCanvas }),
3036
+ slots?.canvas
3037
+ ]
3038
+ }
3039
+ ),
3040
+ showInspector && /* @__PURE__ */ jsxs5(
3041
+ "aside",
3042
+ {
3043
+ ref: inspectorRef,
3044
+ id: inspectorId,
3045
+ className: `awr-pipeline__inspector${sheetOpen ? " is-open" : ""}`,
3046
+ "aria-label": L.inspector,
3047
+ onKeyDown: (e) => {
3048
+ if (e.key === "Escape" && narrow && sheetOpen) setSheetOpen(false);
3049
+ },
3050
+ children: [
3051
+ /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__inspector-head", children: [
3052
+ /* @__PURE__ */ jsxs5(
3053
+ "button",
3054
+ {
3055
+ type: "button",
3056
+ className: "awr-pipeline__inspector-title",
3057
+ "aria-expanded": narrow ? sheetOpen : void 0,
3058
+ "aria-label": narrow ? sheetOpen ? L.collapse : L.expand : void 0,
3059
+ disabled: !narrow,
3060
+ onClick: () => setSheetOpen((open) => !open),
3061
+ children: [
3062
+ /* @__PURE__ */ jsx6("span", { className: "awr-pipeline__inspector-kind", children: title.kind }),
3063
+ /* @__PURE__ */ jsx6("span", { className: "awr-pipeline__inspector-name", children: title.name }),
3064
+ /* @__PURE__ */ jsx6(ChevronIcon, { size: 16, className: "awr-pipeline__inspector-chevron" })
3065
+ ]
3066
+ }
3067
+ ),
3068
+ selection && /* @__PURE__ */ jsx6(
3069
+ "button",
3070
+ {
3071
+ type: "button",
3072
+ className: "awr-pbtn awr-pbtn--icon",
3073
+ "aria-label": L.close,
3074
+ onClick: () => {
3075
+ select(null);
3076
+ setSheetOpen(false);
3077
+ },
3078
+ children: /* @__PURE__ */ jsx6(XIcon, { size: 16 })
3079
+ }
3080
+ )
3081
+ ] }),
3082
+ /* @__PURE__ */ jsx6("div", { className: "awr-pipeline__inspector-body", children: /* @__PURE__ */ jsx6(
3083
+ PipelineInspector,
3084
+ {
3085
+ value: def,
3086
+ onChange,
3087
+ selection,
3088
+ onSelectionChange: select,
3089
+ models: props.models,
3090
+ skills: props.skills,
3091
+ tools: props.tools,
3092
+ mcpServers: props.mcpServers,
3093
+ readOnly,
3094
+ footer: slots?.inspectorFooter,
3095
+ labels: props.labels
3096
+ }
3097
+ ) })
3098
+ ]
3099
+ }
3100
+ )
3101
+ ] }),
3102
+ controller && (showRunBar || showResults) && /* @__PURE__ */ jsxs5("div", { className: "awr-pipeline__dock", children: [
3103
+ showRunBar && /* @__PURE__ */ jsxs5("form", { className: "awr-pipeline__run", onSubmit: submit, children: [
3104
+ /* @__PURE__ */ jsx6(
3105
+ "input",
3106
+ {
3107
+ className: "awr-pinput awr-pipeline__run-input",
3108
+ value: input,
3109
+ placeholder: L.runPlaceholder,
3110
+ "aria-label": L.runInput,
3111
+ disabled: running,
3112
+ enterKeyHint: "go",
3113
+ onChange: (e) => setInput(e.target.value)
3114
+ }
3115
+ ),
3116
+ running ? /* @__PURE__ */ jsxs5("button", { type: "submit", className: "awr-pbtn awr-pbtn--stop awr-pipeline__run-btn", children: [
3117
+ /* @__PURE__ */ jsx6(StopIcon, { size: 15 }),
3118
+ L.stop
3119
+ ] }) : /* @__PURE__ */ jsxs5(
3120
+ "button",
3121
+ {
3122
+ type: "submit",
3123
+ className: "awr-pbtn awr-pbtn--primary awr-pipeline__run-btn",
3124
+ disabled: !canRun,
3125
+ title: validation.ok ? void 0 : L.fixErrorsFirst,
3126
+ children: [
3127
+ /* @__PURE__ */ jsx6(PlayIcon, { size: 15 }),
3128
+ L.run
3129
+ ]
3130
+ }
3131
+ ),
3132
+ showResults && hasRun && /* @__PURE__ */ jsxs5(
3133
+ "button",
3134
+ {
3135
+ type: "button",
3136
+ className: "awr-pbtn awr-pipeline__results-toggle",
3137
+ "aria-expanded": resultsOpen,
3138
+ "aria-controls": resultsId,
3139
+ "aria-label": resultsOpen ? L.hideResults : L.showResults,
3140
+ onClick: () => setResultsOpen((open) => !open),
3141
+ children: [
3142
+ /* @__PURE__ */ jsx6("span", { className: "awr-ptool__text", children: L.results }),
3143
+ /* @__PURE__ */ jsx6(
3144
+ ChevronIcon,
3145
+ {
3146
+ size: 16,
3147
+ className: resultsOpen ? "awr-pipeline__chevron--up" : void 0
3148
+ }
3149
+ )
3150
+ ]
3151
+ }
3152
+ ),
3153
+ slots?.runBarEnd
3154
+ ] }),
3155
+ showResults && hasRun && resultsOpen && /* @__PURE__ */ jsx6("div", { id: resultsId, className: "awr-pipeline__results", children: /* @__PURE__ */ jsx6(
3156
+ PipelineResults,
3157
+ {
3158
+ state,
3159
+ definition: def,
3160
+ renderContent,
3161
+ footer: slots?.resultsFooter,
3162
+ labels: props.labels
3163
+ }
3164
+ ) })
3165
+ ] }),
3166
+ showCode && /* @__PURE__ */ jsx6(
3167
+ PipelineCodeDialog,
3168
+ {
3169
+ definition: def,
3170
+ open: codeOpen,
3171
+ onClose: () => setCodeOpen(false),
3172
+ input: input.trim() || void 0,
3173
+ labels: props.labels
3174
+ }
3175
+ ),
3176
+ /* @__PURE__ */ jsx6("span", { className: "awr-pipeline__sr", role: "status", "aria-live": "polite", children: announcement })
3177
+ ]
3178
+ }
3179
+ );
3180
+ };
3181
+
3182
+ // src/pipeline/use-pipeline.ts
3183
+ import { useCallback as useCallback3, useEffect as useEffect4, useMemo as useMemo4, useReducer, useRef as useRef3 } from "react";
3184
+ import {
3185
+ createPipeline,
3186
+ nodeResolver,
3187
+ PipelineNodeError,
3188
+ validatePipeline as validatePipeline2
3189
+ } from "@dudko.dev/agent-web";
3190
+ var usePipeline = (definition, options = {}) => {
3191
+ const [state, dispatch] = useReducer(pipelineStateReducer, void 0, createInitialPipelineState);
3192
+ const validation = useMemo4(() => validatePipeline2(definition), [definition]);
3193
+ const latest = useRef3({ definition, options, validation });
3194
+ latest.current = { definition, options, validation };
3195
+ const built = useRef3(void 0);
3196
+ const controller = useRef3(void 0);
3197
+ const result = useRef3(void 0);
3198
+ const running = useRef3(false);
3199
+ const mounted = useRef3(true);
3200
+ const close = useCallback3(() => {
3201
+ const before = built.current;
3202
+ built.current = void 0;
3203
+ void before?.pipeline.close().catch(() => {
3204
+ });
3205
+ }, []);
3206
+ useEffect4(() => {
3207
+ mounted.current = true;
3208
+ return () => {
3209
+ mounted.current = false;
3210
+ controller.current?.abort();
3211
+ close();
3212
+ };
3213
+ }, [close]);
3214
+ const run = useCallback3(
3215
+ async (input) => {
3216
+ if (running.current) return void 0;
3217
+ const { definition: def, options: opts, validation: checked } = latest.current;
3218
+ dispatch({ type: "run.start", input });
3219
+ result.current = void 0;
3220
+ if (!checked.ok) {
3221
+ dispatch({
3222
+ type: "run.error",
3223
+ error: checked.errors.map((e) => e.message).join("; "),
3224
+ nodeId: checked.errors.find((e) => e.nodeId)?.nodeId
3225
+ });
3226
+ return void 0;
3227
+ }
3228
+ running.current = true;
3229
+ const abort = new AbortController();
3230
+ controller.current = abort;
3231
+ try {
3232
+ const key2 = [
3233
+ def,
3234
+ opts.resolveNode,
3235
+ opts.runNode,
3236
+ opts.base,
3237
+ opts.models,
3238
+ opts.skills,
3239
+ opts.tools,
3240
+ opts.mcpServers,
3241
+ opts.configure
3242
+ ];
3243
+ if (!built.current || built.current.key.some((value, i) => value !== key2[i])) {
3244
+ close();
3245
+ const resolveNode = opts.resolveNode ?? (opts.base ? nodeResolver({
3246
+ base: opts.base,
3247
+ models: opts.models,
3248
+ skills: opts.skills,
3249
+ tools: opts.tools,
3250
+ mcpServers: opts.mcpServers,
3251
+ configure: opts.configure
3252
+ }) : void 0);
3253
+ built.current = {
3254
+ key: key2,
3255
+ pipeline: createPipeline(def, { runNode: opts.runNode, resolveNode })
3256
+ };
3257
+ }
3258
+ const done = await built.current.pipeline.run({
3259
+ input,
3260
+ signal: abort.signal,
3261
+ onEvent: (event) => {
3262
+ if (mounted.current) dispatch({ type: "event", event });
3263
+ latest.current.options.onEvent?.(event);
3264
+ }
3265
+ });
3266
+ result.current = done;
3267
+ if (mounted.current) dispatch({ type: "run.result", result: done });
3268
+ return done;
3269
+ } catch (err) {
3270
+ if (mounted.current) {
3271
+ dispatch({
3272
+ type: "run.error",
3273
+ error: errMessage(err),
3274
+ nodeId: err instanceof PipelineNodeError ? err.nodeId : void 0
3275
+ });
3276
+ }
3277
+ return void 0;
3278
+ } finally {
3279
+ running.current = false;
3280
+ if (controller.current === abort) controller.current = void 0;
3281
+ }
3282
+ },
3283
+ [close]
3284
+ );
3285
+ const stop = useCallback3(() => controller.current?.abort(), []);
3286
+ const reset = useCallback3(() => {
3287
+ if (running.current) return;
3288
+ result.current = void 0;
3289
+ dispatch({ type: "reset" });
3290
+ }, []);
3291
+ return {
3292
+ ...state,
3293
+ run,
3294
+ stop,
3295
+ reset,
3296
+ isRunning: state.status === "running",
3297
+ validation,
3298
+ result: result.current
3299
+ };
3300
+ };
3301
+
3302
+ // src/pipeline.ts
3303
+ import {
3304
+ createPipeline as createPipeline2,
3305
+ nodeResolver as nodeResolver2,
3306
+ normalizePipeline as normalizePipeline2,
3307
+ validatePipeline as validatePipeline3,
3308
+ PIPELINE_LIMITS as PIPELINE_LIMITS2,
3309
+ PipelineNodeError as PipelineNodeError2,
3310
+ PipelineValidationError
3311
+ } from "@dudko.dev/agent-web";
3312
+ export {
3313
+ Canvas,
3314
+ CanvasPort,
3315
+ DEFAULT_MAX_ZOOM,
3316
+ DEFAULT_MIN_ZOOM,
3317
+ IDENTITY_VIEWPORT,
3318
+ OUTPUT_PORT,
3319
+ PIPELINE_LIMITS2 as PIPELINE_LIMITS,
3320
+ PipelineCodeDialog,
3321
+ PipelineEditor,
3322
+ PipelineInspector,
3323
+ PipelineIssues,
3324
+ PipelineLabelsProvider,
3325
+ PipelineNodeCard,
3326
+ PipelineNodeError2 as PipelineNodeError,
3327
+ PipelineResults,
3328
+ PipelineValidationError,
3329
+ activityText,
3330
+ addEdge,
3331
+ addNode,
3332
+ autoLayout,
3333
+ boundsOf,
3334
+ centerOn,
3335
+ clamp,
3336
+ conditionSummary,
3337
+ createInitialPipelineState,
3338
+ createPipeline2 as createPipeline,
3339
+ curvePath,
3340
+ curvePoint,
3341
+ defaultCanvasLabels,
3342
+ defaultPipelineLabels,
3343
+ distanceToCurve,
3344
+ edgeCurve,
3345
+ emptyPipeline,
3346
+ ensureEdgeIds,
3347
+ fitViewport,
3348
+ hitEdge,
3349
+ hitNode,
3350
+ inputAnchor,
3351
+ inspectorTitle,
3352
+ isRectVisible,
3353
+ issueTarget,
3354
+ mergePipelineLabels,
3355
+ moveNode,
3356
+ nextNodePosition,
3357
+ nodeResolver2 as nodeResolver,
3358
+ normalizePipeline2 as normalizePipeline,
3359
+ outputAnchor,
3360
+ panBy,
3361
+ parsePipelineJson,
3362
+ pinchViewport,
3363
+ pipelineNodeView,
3364
+ pipelineStateReducer,
3365
+ pipelineToCode,
3366
+ readingOrder,
3367
+ rectContains,
3368
+ removeEdge,
3369
+ removeNode,
3370
+ renameNode,
3371
+ renameRoute,
3372
+ routePortId,
3373
+ screenToWorld,
3374
+ setEntry,
3375
+ setLimits,
3376
+ setPipelineName,
3377
+ slugifyId,
3378
+ snapPoint,
3379
+ snapTo,
3380
+ uniqueEdgeId,
3381
+ uniqueNodeId,
3382
+ updateEdge,
3383
+ updateNode,
3384
+ usePipeline,
3385
+ usePipelineLabels,
3386
+ validatePipeline3 as validatePipeline,
3387
+ worldToScreen,
3388
+ zoomAt
3389
+ };
3390
+ //# sourceMappingURL=pipeline.js.map