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