@particle-academy/fancy-flow 0.66.0 → 0.66.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/chunk-27RZJAE2.js +2586 -0
  2. package/dist/chunk-27RZJAE2.js.map +1 -0
  3. package/dist/{chunk-FNYLKSFJ.js → chunk-2QTEELJE.js} +4 -3
  4. package/dist/chunk-2QTEELJE.js.map +1 -0
  5. package/dist/{chunk-MTONBM53.js → chunk-6AYC3BWI.js} +4 -4
  6. package/dist/{chunk-MTONBM53.js.map → chunk-6AYC3BWI.js.map} +1 -1
  7. package/dist/{chunk-IEYCNFXZ.js → chunk-6TH646CS.js} +127 -5
  8. package/dist/chunk-6TH646CS.js.map +1 -0
  9. package/dist/{chunk-UCCTXJXL.js → chunk-BUNFPBTF.js} +5 -4
  10. package/dist/chunk-BUNFPBTF.js.map +1 -0
  11. package/dist/{chunk-B7HKJJVV.js → chunk-FV3D366L.js} +3 -3
  12. package/dist/{chunk-B7HKJJVV.js.map → chunk-FV3D366L.js.map} +1 -1
  13. package/dist/{chunk-HQGOFGAL.js → chunk-OWENS2H5.js} +64 -2754
  14. package/dist/chunk-OWENS2H5.js.map +1 -0
  15. package/dist/{chunk-PNHZHEWE.js → chunk-RE3XNVSB.js} +3 -3
  16. package/dist/{chunk-PNHZHEWE.js.map → chunk-RE3XNVSB.js.map} +1 -1
  17. package/dist/durable.cjs +153 -9213
  18. package/dist/durable.cjs.map +1 -1
  19. package/dist/durable.js +1 -2
  20. package/dist/durable.js.map +1 -1
  21. package/dist/engine.cjs +103 -9165
  22. package/dist/engine.cjs.map +1 -1
  23. package/dist/engine.js +4 -5
  24. package/dist/engine.js.map +1 -1
  25. package/dist/index.cjs +11135 -11121
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +15 -13
  28. package/dist/index.js.map +1 -1
  29. package/dist/registry/index.d.cts +15 -3
  30. package/dist/registry/index.d.ts +15 -3
  31. package/dist/registry.cjs +11166 -11153
  32. package/dist/registry.cjs.map +1 -1
  33. package/dist/registry.js +4 -3
  34. package/dist/runtime.cjs +10772 -10924
  35. package/dist/runtime.cjs.map +1 -1
  36. package/dist/runtime.js +4 -4
  37. package/dist/schema.cjs +85 -9147
  38. package/dist/schema.cjs.map +1 -1
  39. package/dist/schema.js +3 -4
  40. package/dist/screens.cjs +7 -52
  41. package/dist/screens.cjs.map +1 -1
  42. package/dist/screens.js +6 -5
  43. package/dist/screens.js.map +1 -1
  44. package/dist/ux.cjs +89 -9147
  45. package/dist/ux.cjs.map +1 -1
  46. package/dist/ux.js +1 -2
  47. package/dist/ux.js.map +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-FNYLKSFJ.js.map +0 -1
  50. package/dist/chunk-HQGOFGAL.js.map +0 -1
  51. package/dist/chunk-IEYCNFXZ.js.map +0 -1
  52. package/dist/chunk-UCCTXJXL.js.map +0 -1
@@ -1,27 +1,7 @@
1
- import { RichInputPreview } from './chunk-F5RPRB7A.js';
2
- import { getLlmClient, getWorkflowResolver, isResolutionFailure, getTerminalHost } from './chunk-2QXKDLGT.js';
3
- import ReactExports, { createContext, forwardRef, memo, useMemo, useState, useRef, useEffect, useCallback, useContext, createElement, useSyncExternalStore, useDebugValue, useLayoutEffect } from 'react';
4
1
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
+ import ReactExports, { createContext, forwardRef, memo, useMemo, useState, useRef, useEffect, useCallback, useContext, useSyncExternalStore, useDebugValue, useLayoutEffect } from 'react';
5
3
  import { createPortal } from 'react-dom';
6
4
 
7
- // node_modules/classcat/index.js
8
- function cc(names) {
9
- if (typeof names === "string" || typeof names === "number") return "" + names;
10
- let out = "";
11
- if (Array.isArray(names)) {
12
- for (let i = 0, tmp; i < names.length; i++) {
13
- if ((tmp = cc(names[i])) !== "") {
14
- out += (out && " ") + tmp;
15
- }
16
- }
17
- } else {
18
- for (let k in names) {
19
- if (names[k]) out += (out && " ") + k;
20
- }
21
- }
22
- return out;
23
- }
24
-
25
5
  // node_modules/d3-dispatch/src/dispatch.js
26
6
  var noop = { value: () => {
27
7
  } };
@@ -993,7 +973,7 @@ function defaultTouchable() {
993
973
  return navigator.maxTouchPoints || "ontouchstart" in this;
994
974
  }
995
975
  function drag_default() {
996
- var filter2 = defaultFilter, container = defaultContainer, subject = defaultSubject, touchable = defaultTouchable, gestures = {}, listeners2 = dispatch_default("start", "drag", "end"), active = 0, mousedownx, mousedowny, mousemoving, touchending, clickDistance2 = 0;
976
+ var filter2 = defaultFilter, container = defaultContainer, subject = defaultSubject, touchable = defaultTouchable, gestures = {}, listeners = dispatch_default("start", "drag", "end"), active = 0, mousedownx, mousedowny, mousemoving, touchending, clickDistance2 = 0;
997
977
  function drag(selection2) {
998
978
  selection2.on("mousedown.drag", mousedowned).filter(touchable).on("touchstart.drag", touchstarted).on("touchmove.drag", touchmoved, nonpassive).on("touchend.drag touchcancel.drag", touchended).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
999
979
  }
@@ -1056,7 +1036,7 @@ function drag_default() {
1056
1036
  }
1057
1037
  }
1058
1038
  function beforestart(that, container2, event, d, identifier, touch) {
1059
- var dispatch2 = listeners2.copy(), p = pointer_default(touch || event, container2), dx, dy, s;
1039
+ var dispatch2 = listeners.copy(), p = pointer_default(touch || event, container2), dx, dy, s;
1060
1040
  if ((s = subject.call(that, new DragEvent("beforestart", {
1061
1041
  sourceEvent: event,
1062
1042
  target: drag,
@@ -1115,8 +1095,8 @@ function drag_default() {
1115
1095
  return arguments.length ? (touchable = typeof _ === "function" ? _ : constant_default2(!!_), drag) : touchable;
1116
1096
  };
1117
1097
  drag.on = function() {
1118
- var value = listeners2.on.apply(listeners2, arguments);
1119
- return value === listeners2 ? drag : value;
1098
+ var value = listeners.on.apply(listeners, arguments);
1099
+ return value === listeners ? drag : value;
1120
1100
  };
1121
1101
  drag.clickDistance = function(_) {
1122
1102
  return arguments.length ? (clickDistance2 = (_ = +_) * _, drag) : Math.sqrt(clickDistance2);
@@ -2087,38 +2067,38 @@ function attrRemoveNS2(fullname) {
2087
2067
  this.removeAttributeNS(fullname.space, fullname.local);
2088
2068
  };
2089
2069
  }
2090
- function attrConstant2(name, interpolate2, value1) {
2070
+ function attrConstant2(name, interpolate, value1) {
2091
2071
  var string00, string1 = value1 + "", interpolate0;
2092
2072
  return function() {
2093
2073
  var string0 = this.getAttribute(name);
2094
- return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
2074
+ return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
2095
2075
  };
2096
2076
  }
2097
- function attrConstantNS2(fullname, interpolate2, value1) {
2077
+ function attrConstantNS2(fullname, interpolate, value1) {
2098
2078
  var string00, string1 = value1 + "", interpolate0;
2099
2079
  return function() {
2100
2080
  var string0 = this.getAttributeNS(fullname.space, fullname.local);
2101
- return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
2081
+ return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
2102
2082
  };
2103
2083
  }
2104
- function attrFunction2(name, interpolate2, value) {
2084
+ function attrFunction2(name, interpolate, value) {
2105
2085
  var string00, string10, interpolate0;
2106
2086
  return function() {
2107
2087
  var string0, value1 = value(this), string1;
2108
2088
  if (value1 == null) return void this.removeAttribute(name);
2109
2089
  string0 = this.getAttribute(name);
2110
2090
  string1 = value1 + "";
2111
- return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
2091
+ return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
2112
2092
  };
2113
2093
  }
2114
- function attrFunctionNS2(fullname, interpolate2, value) {
2094
+ function attrFunctionNS2(fullname, interpolate, value) {
2115
2095
  var string00, string10, interpolate0;
2116
2096
  return function() {
2117
2097
  var string0, value1 = value(this), string1;
2118
2098
  if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);
2119
2099
  string0 = this.getAttributeNS(fullname.space, fullname.local);
2120
2100
  string1 = value1 + "";
2121
- return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
2101
+ return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
2122
2102
  };
2123
2103
  }
2124
2104
  function attr_default2(name, value) {
@@ -2328,11 +2308,11 @@ function selection_default2() {
2328
2308
  }
2329
2309
 
2330
2310
  // node_modules/d3-transition/src/transition/style.js
2331
- function styleNull(name, interpolate2) {
2311
+ function styleNull(name, interpolate) {
2332
2312
  var string00, string10, interpolate0;
2333
2313
  return function() {
2334
2314
  var string0 = styleValue(this, name), string1 = (this.style.removeProperty(name), styleValue(this, name));
2335
- return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, string10 = string1);
2315
+ return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = interpolate(string00 = string0, string10 = string1);
2336
2316
  };
2337
2317
  }
2338
2318
  function styleRemove2(name) {
@@ -2340,19 +2320,19 @@ function styleRemove2(name) {
2340
2320
  this.style.removeProperty(name);
2341
2321
  };
2342
2322
  }
2343
- function styleConstant2(name, interpolate2, value1) {
2323
+ function styleConstant2(name, interpolate, value1) {
2344
2324
  var string00, string1 = value1 + "", interpolate0;
2345
2325
  return function() {
2346
2326
  var string0 = styleValue(this, name);
2347
- return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate2(string00 = string0, value1);
2327
+ return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
2348
2328
  };
2349
2329
  }
2350
- function styleFunction2(name, interpolate2, value) {
2330
+ function styleFunction2(name, interpolate, value) {
2351
2331
  var string00, string10, interpolate0;
2352
2332
  return function() {
2353
2333
  var string0 = styleValue(this, name), value1 = value(this), string1 = value1 + "";
2354
2334
  if (value1 == null) string1 = value1 = (this.style.removeProperty(name), styleValue(this, name));
2355
- return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate2(string00 = string0, value1));
2335
+ return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
2356
2336
  };
2357
2337
  }
2358
2338
  function styleMaybeRemove(id2, name) {
@@ -2454,9 +2434,9 @@ function transition_default() {
2454
2434
  // node_modules/d3-transition/src/transition/end.js
2455
2435
  function end_default() {
2456
2436
  var on0, on1, that = this, id2 = that._id, size = that.size();
2457
- return new Promise(function(resolve2, reject) {
2437
+ return new Promise(function(resolve, reject) {
2458
2438
  var cancel = { value: reject }, end = { value: function() {
2459
- if (--size === 0) resolve2();
2439
+ if (--size === 0) resolve();
2460
2440
  } };
2461
2441
  that.each(function() {
2462
2442
  var schedule = set2(this, id2), on = schedule.on;
@@ -2468,7 +2448,7 @@ function end_default() {
2468
2448
  }
2469
2449
  schedule.on = on1;
2470
2450
  });
2471
- if (size === 0) resolve2();
2451
+ if (size === 0) resolve();
2472
2452
  });
2473
2453
  }
2474
2454
 
@@ -2670,7 +2650,7 @@ function defaultConstrain(transform2, extent, translateExtent) {
2670
2650
  );
2671
2651
  }
2672
2652
  function zoom_default2() {
2673
- var filter2 = defaultFilter2, extent = defaultExtent, constrain = defaultConstrain, wheelDelta2 = defaultWheelDelta, touchable = defaultTouchable2, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], duration = 250, interpolate2 = zoom_default, listeners2 = dispatch_default("start", "zoom", "end"), touchstarting, touchfirst, touchending, touchDelay = 500, wheelDelay = 150, clickDistance2 = 0, tapDistance = 10;
2653
+ var filter2 = defaultFilter2, extent = defaultExtent, constrain = defaultConstrain, wheelDelta2 = defaultWheelDelta, touchable = defaultTouchable2, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], duration = 250, interpolate = zoom_default, listeners = dispatch_default("start", "zoom", "end"), touchstarting, touchfirst, touchending, touchDelay = 500, wheelDelay = 150, clickDistance2 = 0, tapDistance = 10;
2674
2654
  function zoom(selection2) {
2675
2655
  selection2.property("__zoom", defaultTransform).on("wheel.zoom", wheeled, { passive: false }).on("mousedown.zoom", mousedowned).on("dblclick.zoom", dblclicked).filter(touchable).on("touchstart.zoom", touchstarted).on("touchmove.zoom", touchmoved).on("touchend.zoom touchcancel.zoom", touchended).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
2676
2656
  }
@@ -2731,7 +2711,7 @@ function zoom_default2() {
2731
2711
  }).on("interrupt.zoom end.zoom", function() {
2732
2712
  gesture(this, arguments).event(event).end();
2733
2713
  }).tween("zoom", function() {
2734
- var that = this, args = arguments, g = gesture(that, args).event(event), e = extent.apply(that, args), p = point == null ? centroid(e) : typeof point === "function" ? point.apply(that, args) : point, w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]), a = that.__zoom, b = typeof transform2 === "function" ? transform2.apply(that, args) : transform2, i = interpolate2(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));
2714
+ var that = this, args = arguments, g = gesture(that, args).event(event), e = extent.apply(that, args), p = point == null ? centroid(e) : typeof point === "function" ? point.apply(that, args) : point, w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]), a = that.__zoom, b = typeof transform2 === "function" ? transform2.apply(that, args) : transform2, i = interpolate(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));
2735
2715
  return function(t) {
2736
2716
  if (t === 1) t = b;
2737
2717
  else {
@@ -2782,14 +2762,14 @@ function zoom_default2() {
2782
2762
  },
2783
2763
  emit: function(type) {
2784
2764
  var d = select_default2(this.that).datum();
2785
- listeners2.call(
2765
+ listeners.call(
2786
2766
  type,
2787
2767
  this.that,
2788
2768
  new ZoomEvent(type, {
2789
2769
  sourceEvent: this.sourceEvent,
2790
2770
  target: zoom,
2791
2771
  transform: this.that.__zoom,
2792
- dispatch: listeners2
2772
+ dispatch: listeners
2793
2773
  }),
2794
2774
  d
2795
2775
  );
@@ -2936,11 +2916,11 @@ function zoom_default2() {
2936
2916
  return arguments.length ? (duration = +_, zoom) : duration;
2937
2917
  };
2938
2918
  zoom.interpolate = function(_) {
2939
- return arguments.length ? (interpolate2 = _, zoom) : interpolate2;
2919
+ return arguments.length ? (interpolate = _, zoom) : interpolate;
2940
2920
  };
2941
2921
  zoom.on = function() {
2942
- var value = listeners2.on.apply(listeners2, arguments);
2943
- return value === listeners2 ? zoom : value;
2922
+ var value = listeners.on.apply(listeners, arguments);
2923
+ return value === listeners ? zoom : value;
2944
2924
  };
2945
2925
  zoom.clickDistance = function(_) {
2946
2926
  return arguments.length ? (clickDistance2 = (_ = +_) * _, zoom) : Math.sqrt(clickDistance2);
@@ -3429,13 +3409,13 @@ function areSetsEqual(a, b) {
3429
3409
  return true;
3430
3410
  }
3431
3411
  function withResolvers() {
3432
- let resolve2;
3412
+ let resolve;
3433
3413
  let reject;
3434
3414
  const promise = new Promise((res, rej) => {
3435
- resolve2 = res;
3415
+ resolve = res;
3436
3416
  reject = rej;
3437
3417
  });
3438
- return { promise, resolve: resolve2, reject };
3418
+ return { promise, resolve, reject };
3439
3419
  }
3440
3420
  function mergeAriaLabelConfig(partial) {
3441
3421
  return { ...defaultAriaLabelConfig, ...partial || {} };
@@ -5107,8 +5087,8 @@ function XYPanZoom({ domNode, minZoom, maxZoom, translateExtent, viewport, onPan
5107
5087
  d3ZoomInstance.wheelDelta(wheelDelta);
5108
5088
  async function setTransform(transform2, options) {
5109
5089
  if (d3Selection) {
5110
- return new Promise((resolve2) => {
5111
- d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).transform(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve2(true)), transform2);
5090
+ return new Promise((resolve) => {
5091
+ d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).transform(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve(true)), transform2);
5112
5092
  });
5113
5093
  }
5114
5094
  return false;
@@ -5210,16 +5190,16 @@ function XYPanZoom({ domNode, minZoom, maxZoom, translateExtent, viewport, onPan
5210
5190
  }
5211
5191
  async function scaleTo(zoom, options) {
5212
5192
  if (d3Selection) {
5213
- return new Promise((resolve2) => {
5214
- d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).scaleTo(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve2(true)), zoom);
5193
+ return new Promise((resolve) => {
5194
+ d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).scaleTo(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve(true)), zoom);
5215
5195
  });
5216
5196
  }
5217
5197
  return false;
5218
5198
  }
5219
5199
  async function scaleBy(factor, options) {
5220
5200
  if (d3Selection) {
5221
- return new Promise((resolve2) => {
5222
- d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).scaleBy(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve2(true)), factor);
5201
+ return new Promise((resolve) => {
5202
+ d3ZoomInstance?.interpolate(options?.interpolate === "linear" ? value_default : zoom_default).scaleBy(getD3Transition(d3Selection, options?.duration, options?.ease, () => resolve(true)), factor);
5223
5203
  });
5224
5204
  }
5225
5205
  return false;
@@ -5611,6 +5591,24 @@ function XYResizer({ domNode, nodeId, getStoreItems, onChange, onEnd }) {
5611
5591
  destroy
5612
5592
  };
5613
5593
  }
5594
+
5595
+ // node_modules/classcat/index.js
5596
+ function cc(names) {
5597
+ if (typeof names === "string" || typeof names === "number") return "" + names;
5598
+ let out = "";
5599
+ if (Array.isArray(names)) {
5600
+ for (let i = 0, tmp; i < names.length; i++) {
5601
+ if ((tmp = cc(names[i])) !== "") {
5602
+ out += (out && " ") + tmp;
5603
+ }
5604
+ }
5605
+ } else {
5606
+ for (let k in names) {
5607
+ if (names[k]) out += (out && " ") + k;
5608
+ }
5609
+ }
5610
+ return out;
5611
+ }
5614
5612
  function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector2, isEqual) {
5615
5613
  const instRef = useRef(null);
5616
5614
  let inst;
@@ -5671,20 +5669,20 @@ var use_sync_external_store_with_selector_default = { useSyncExternalStoreWithSe
5671
5669
  // node_modules/zustand/esm/vanilla.mjs
5672
5670
  var createStoreImpl = (createState) => {
5673
5671
  let state;
5674
- const listeners2 = /* @__PURE__ */ new Set();
5672
+ const listeners = /* @__PURE__ */ new Set();
5675
5673
  const setState = (partial, replace) => {
5676
5674
  const nextState = typeof partial === "function" ? partial(state) : partial;
5677
5675
  if (!Object.is(nextState, state)) {
5678
5676
  const previousState = state;
5679
5677
  state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
5680
- listeners2.forEach((listener) => listener(state, previousState));
5678
+ listeners.forEach((listener) => listener(state, previousState));
5681
5679
  }
5682
5680
  };
5683
5681
  const getState = () => state;
5684
5682
  const getInitialState2 = () => initialState;
5685
5683
  const subscribe = (listener) => {
5686
- listeners2.add(listener);
5687
- return () => listeners2.delete(listener);
5684
+ listeners.add(listener);
5685
+ return () => listeners.delete(listener);
5688
5686
  };
5689
5687
  const destroy = () => {
5690
5688
  if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production") {
@@ -5692,7 +5690,7 @@ var createStoreImpl = (createState) => {
5692
5690
  "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
5693
5691
  );
5694
5692
  }
5695
- listeners2.clear();
5693
+ listeners.clear();
5696
5694
  };
5697
5695
  const api = { setState, getState, getInitialState: getInitialState2, subscribe, destroy };
5698
5696
  const initialState = state = createState(setState, getState, api);
@@ -9038,2694 +9036,6 @@ function NodeToolbar({ nodeId, children: children2, className, style: style2, is
9038
9036
  return jsx(NodeToolbarPortal, { children: jsx("div", { style: wrapperStyle2, className: cc(["react-flow__node-toolbar", className]), ...rest, "data-id": nodesArray.reduce((acc, node) => `${acc}${node.id} `, "").trim(), children: children2 }) });
9039
9037
  }
9040
9038
 
9041
- // src/components/FlowEditor/human-fields.ts
9042
- var HUMAN_FIELD_TYPE_ALIASES = {
9043
- text: "text",
9044
- string: "text",
9045
- str: "text",
9046
- input: "text",
9047
- textarea: "textarea",
9048
- long_text: "textarea",
9049
- longtext: "textarea",
9050
- "long-text": "textarea",
9051
- multiline: "textarea",
9052
- paragraph: "textarea",
9053
- markdown: "textarea",
9054
- number: "number",
9055
- numeric: "number",
9056
- integer: "number",
9057
- int: "number",
9058
- float: "number",
9059
- decimal: "number",
9060
- select: "select",
9061
- enum: "select",
9062
- choice: "select",
9063
- choices: "select",
9064
- dropdown: "select",
9065
- options: "select",
9066
- radio: "select",
9067
- switch: "switch",
9068
- bool: "switch",
9069
- boolean: "switch",
9070
- checkbox: "switch",
9071
- toggle: "switch",
9072
- date: "date",
9073
- datetime: "datetime",
9074
- "datetime-local": "datetime",
9075
- datetimelocal: "datetime",
9076
- timestamp: "datetime",
9077
- time: "time",
9078
- email: "email",
9079
- "e-mail": "email",
9080
- url: "url",
9081
- uri: "url",
9082
- link: "url",
9083
- tel: "tel",
9084
- phone: "tel",
9085
- telephone: "tel",
9086
- password: "password",
9087
- secret: "password"
9088
- };
9089
- function humanFieldType(raw) {
9090
- if (typeof raw !== "string") return "text";
9091
- return HUMAN_FIELD_TYPE_ALIASES[raw.trim().toLowerCase()] ?? "text";
9092
- }
9093
- function humanFieldOptions(raw) {
9094
- const entries = [];
9095
- if (Array.isArray(raw)) {
9096
- for (const item of raw) {
9097
- if (typeof item === "string" || typeof item === "number") {
9098
- const value = String(item);
9099
- if (value !== "") entries.push({ value, label: value });
9100
- continue;
9101
- }
9102
- if (item && typeof item === "object") {
9103
- const value = item.value;
9104
- if (value === void 0 || value === null || value === "") continue;
9105
- const label = item.label;
9106
- entries.push({
9107
- value: String(value),
9108
- label: typeof label === "string" && label !== "" ? label : String(value)
9109
- });
9110
- }
9111
- }
9112
- } else if (raw && typeof raw === "object") {
9113
- for (const [value, label] of Object.entries(raw)) {
9114
- if (value === "") continue;
9115
- entries.push({ value, label: typeof label === "string" && label !== "" ? label : value });
9116
- }
9117
- }
9118
- return entries.length ? entries : void 0;
9119
- }
9120
- function humanInputFields(config) {
9121
- const raw = Array.isArray(config?.fields) ? config.fields : [];
9122
- const fields = raw.filter((f) => f && typeof f === "object" && typeof f.key === "string" && f.key).map((f) => ({
9123
- key: f.key,
9124
- label: typeof f.label === "string" && f.label ? f.label : f.key,
9125
- type: humanFieldType(f.type),
9126
- required: !!f.required,
9127
- placeholder: typeof f.placeholder === "string" ? f.placeholder : void 0,
9128
- options: humanFieldOptions(f.options ?? f.choices),
9129
- default: f.default
9130
- }));
9131
- if (fields.length) return fields;
9132
- const title = typeof config?.title === "string" && config.title ? config.title : "Your answer";
9133
- return [{ key: "value", label: title, type: "textarea", required: true }];
9134
- }
9135
- var FlowEditorContext = createContext(null);
9136
- var FlowEditorProvider = FlowEditorContext.Provider;
9137
- function useFlowEditor() {
9138
- const api = useContext(FlowEditorContext);
9139
- if (api === null) {
9140
- throw new Error("useFlowEditor() must be called inside <FlowEditor>.");
9141
- }
9142
- return api;
9143
- }
9144
- function useFlowEditorOptional() {
9145
- return useContext(FlowEditorContext);
9146
- }
9147
- var NOTE_COLORS = {
9148
- amber: { bg: "rgba(234, 179, 8, 0.14)", border: "rgba(234, 179, 8, 0.55)", title: "#a16207" },
9149
- sky: { bg: "rgba(14, 165, 233, 0.12)", border: "rgba(14, 165, 233, 0.5)", title: "#0369a1" },
9150
- violet: { bg: "rgba(139, 92, 246, 0.13)", border: "rgba(139, 92, 246, 0.5)", title: "#6d28d9" },
9151
- emerald: { bg: "rgba(16, 185, 129, 0.13)", border: "rgba(16, 185, 129, 0.5)", title: "#047857" },
9152
- rose: { bg: "rgba(244, 63, 94, 0.12)", border: "rgba(244, 63, 94, 0.5)", title: "#be123c" },
9153
- slate: { bg: "rgba(100, 116, 139, 0.12)", border: "rgba(100, 116, 139, 0.5)", title: "#475569" }
9154
- };
9155
- function coerceColor(v) {
9156
- return typeof v === "string" && v in NOTE_COLORS ? v : "amber";
9157
- }
9158
- function NoteNodeInner(props) {
9159
- const data = props.data;
9160
- const config = data.config ?? {};
9161
- const api = useFlowEditorOptional();
9162
- const hasConfigText = typeof config.text === "string" && config.text.length > 0;
9163
- const text3 = hasConfigText ? String(config.text) : typeof data.body === "string" ? data.body : typeof data.text === "string" ? data.text : "";
9164
- const title = typeof config.title === "string" && config.title || (!hasConfigText && typeof data.body === "string" && typeof data.label === "string" ? data.label : "");
9165
- const skin = NOTE_COLORS[coerceColor(config.color)];
9166
- const [editing, setEditing] = useState(false);
9167
- const [draft, setDraft] = useState(text3);
9168
- const areaRef = useRef(null);
9169
- useEffect(() => {
9170
- if (editing && areaRef.current) {
9171
- const el = areaRef.current;
9172
- el.focus();
9173
- el.setSelectionRange(el.value.length, el.value.length);
9174
- }
9175
- }, [editing]);
9176
- const commit = () => {
9177
- setEditing(false);
9178
- if (!api || draft === text3) return;
9179
- const current = api.nodes.find((n) => n.id === props.id);
9180
- if (!current) return;
9181
- api.updateNode({
9182
- ...current,
9183
- data: { ...current.data, config: { ...config, text: draft } }
9184
- });
9185
- };
9186
- return /* @__PURE__ */ jsxs(
9187
- "div",
9188
- {
9189
- className: ["ff-note", props.selected ? "ff-note--selected" : ""].filter(Boolean).join(" "),
9190
- style: { background: skin.bg, borderColor: skin.border },
9191
- onDoubleClick: api ? () => {
9192
- setDraft(text3);
9193
- setEditing(true);
9194
- } : void 0,
9195
- children: [
9196
- /* @__PURE__ */ jsx(NodeResizer, { isVisible: props.selected ?? false, color: skin.border, minWidth: 140, minHeight: 80 }),
9197
- title && /* @__PURE__ */ jsx("div", { className: "ff-note__title", style: { color: skin.title }, children: title }),
9198
- editing ? /* @__PURE__ */ jsx(
9199
- "textarea",
9200
- {
9201
- ref: areaRef,
9202
- className: "ff-note__input nodrag nowheel",
9203
- value: draft,
9204
- onChange: (e) => setDraft(e.target.value),
9205
- onBlur: commit,
9206
- onKeyDown: (e) => {
9207
- if (e.key === "Escape") setEditing(false);
9208
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) commit();
9209
- }
9210
- }
9211
- ) : /* @__PURE__ */ jsx("div", { className: "ff-note__body", children: text3 || /* @__PURE__ */ jsx("span", { className: "ff-note__placeholder", children: api ? "Double-click to write a note\u2026" : "Note" }) })
9212
- ]
9213
- }
9214
- );
9215
- }
9216
- var NoteNode = memo(NoteNodeInner);
9217
-
9218
- // src/registry/llm-router.ts
9219
- function declaredRoutes(config) {
9220
- const raw = config.routes;
9221
- if (!Array.isArray(raw)) return [];
9222
- return raw.map((r) => ({ port: String(r?.port ?? "").trim(), description: r?.description })).filter((r) => r.port !== "");
9223
- }
9224
- function resolveFallbackPort(routes, fallbackEnabled) {
9225
- if (fallbackEnabled) return "fallback";
9226
- return routes[0]?.port ?? "out";
9227
- }
9228
- var llmRouterExecutor = async (ctx) => {
9229
- const config = ctx.node.data?.config ?? {};
9230
- const routes = declaredRoutes(config);
9231
- if (routes.length === 0) {
9232
- ctx.abort("llm_router has no routes configured");
9233
- }
9234
- const client = getLlmClient();
9235
- if (!client) {
9236
- ctx.abort(
9237
- "No LLM client registered. Call registerLlmClient() with your provider adapter \u2014 fancy-flow ships the routing, not the model call."
9238
- );
9239
- }
9240
- const fallbackEnabled = config.fallback !== false;
9241
- const choice = await client.chooseRoute({
9242
- system: typeof config.system === "string" ? config.system : void 0,
9243
- prompt: String(config.prompt ?? ctx.inputs ?? ""),
9244
- routes,
9245
- provider: typeof config.provider === "string" ? config.provider : void 0,
9246
- model: typeof config.model === "string" ? config.model : void 0,
9247
- credential: typeof config.credential === "string" ? config.credential : void 0
9248
- });
9249
- const offered = new Set(routes.map((r) => r.port));
9250
- let port = choice?.port ?? "";
9251
- let reason = choice?.reason;
9252
- if (!offered.has(port)) {
9253
- const safe = resolveFallbackPort(routes, fallbackEnabled);
9254
- ctx.emit({
9255
- type: "log",
9256
- nodeId: ctx.node.id,
9257
- level: "warn",
9258
- message: `llm_router: model returned "${port || "(nothing)"}", which is not a declared route. Routing to "${safe}".`
9259
- });
9260
- reason = reason ?? `unrecognised route "${port}"`;
9261
- port = safe;
9262
- }
9263
- return { __port: port, value: { route: port, reason, input: ctx.inputs } };
9264
- };
9265
-
9266
- // src/registry/ports.ts
9267
- function resolvePortSpec(spec, config) {
9268
- if (spec === void 0) return void 0;
9269
- if (typeof spec !== "function") return spec;
9270
- try {
9271
- const resolved = spec(config);
9272
- return Array.isArray(resolved) ? resolved : void 0;
9273
- } catch {
9274
- return void 0;
9275
- }
9276
- }
9277
- function nodeConfig(node) {
9278
- return node.data?.config ?? {};
9279
- }
9280
- function resolveNodePorts(node, kind) {
9281
- const config = nodeConfig(node);
9282
- const data = node.data;
9283
- return {
9284
- inputs: data?.inputs ?? resolvePortSpec(kind?.inputs, config),
9285
- outputs: data?.outputs ?? resolvePortSpec(kind?.outputs, config)
9286
- };
9287
- }
9288
-
9289
- // src/runtime/run-identity.ts
9290
- function escapeSegment(value) {
9291
- return value.replace(/%/g, "%25").replace(/\//g, "%2F").replace(/#/g, "%23");
9292
- }
9293
- function renderSegment(value, occurrence) {
9294
- const escaped = escapeSegment(value);
9295
- return occurrence === void 0 || occurrence === null ? escaped : `${escaped}#${occurrence}`;
9296
- }
9297
- function instant(value) {
9298
- const ms = Date.parse(value);
9299
- if (Number.isNaN(ms)) {
9300
- throw new Error(
9301
- `RunIdentity: firstAttemptAt is not a parseable timestamp: ${JSON.stringify(value)}`
9302
- );
9303
- }
9304
- return ms;
9305
- }
9306
- var RunIdentity = class _RunIdentity {
9307
- constructor(runKey, path = [], attempt = 1, firstAttemptAt = (/* @__PURE__ */ new Date()).toISOString()) {
9308
- if (!runKey || runKey.trim() === "") {
9309
- throw new Error("RunIdentity: runKey must be a non-empty string.");
9310
- }
9311
- this.runKey = runKey;
9312
- this.path = Object.freeze([...path]);
9313
- this.attempt = Math.max(1, Math.trunc(attempt));
9314
- this.firstAttemptAt = firstAttemptAt;
9315
- Object.freeze(this);
9316
- }
9317
- /**
9318
- * The identity of one execution of one node — stable across retries of that
9319
- * execution, distinct from every other execution of the same node.
9320
- *
9321
- * Pass `occurrence` when an executor runs the same node more than once at the
9322
- * same level (a loop body, one item of a fan-out it drives itself).
9323
- */
9324
- stepKey(nodeId, occurrence) {
9325
- return `${this.runKey}:${[...this.path, renderSegment(nodeId, occurrence)].join("/")}`;
9326
- }
9327
- /**
9328
- * A child identity for work nested inside this step.
9329
- *
9330
- * `subflow` pushes the invoking node's id, so a node inside the child graph
9331
- * cannot collide with a same-named node in the parent. Attempt and
9332
- * `firstAttemptAt` are carried down unchanged: the nested work happens inside
9333
- * this step's attempt, and shares its clock.
9334
- */
9335
- descend(segment, occurrence) {
9336
- return new _RunIdentity(
9337
- this.runKey,
9338
- [...this.path, renderSegment(segment, occurrence)],
9339
- this.attempt,
9340
- this.firstAttemptAt
9341
- );
9342
- }
9343
- /** A copy on a different attempt, first-attempt clock preserved. */
9344
- withAttempt(attempt, firstAttemptAt) {
9345
- return new _RunIdentity(
9346
- this.runKey,
9347
- this.path,
9348
- attempt,
9349
- firstAttemptAt ?? this.firstAttemptAt
9350
- );
9351
- }
9352
- /**
9353
- * May this attempt reuse the step key and still be deduplicated?
9354
- *
9355
- * Providers forget idempotency keys — Stripe after 24 hours. Past that
9356
- * window, resending the key creates a second charge and sending a fresh one
9357
- * creates a second charge, so **the caller must refuse rather than pick
9358
- * between them**: a loud stuck run beats a silent double write.
9359
- *
9360
- * `true` on attempt 1 whatever the elapsed time — nothing was sent on an
9361
- * earlier attempt, so there is nothing for the provider to have forgotten.
9362
- * That is what lets a run park on a human gate for a week and then write.
9363
- *
9364
- * `windowSeconds: null` means the provider does not expire keys. `0` means
9365
- * it does not dedupe at all, so no retry may reuse a key — it is a real
9366
- * window, not an absent one, and the two must not be conflated: reading `0`
9367
- * as `null` turns "this provider does not dedupe" into "this provider
9368
- * dedupes forever", which is the more dangerous of the two by a distance.
9369
- */
9370
- isReplaySafe(windowSeconds, now2 = /* @__PURE__ */ new Date()) {
9371
- if (this.attempt <= 1) return true;
9372
- if (windowSeconds === null || windowSeconds === void 0) return true;
9373
- if (windowSeconds <= 0) return false;
9374
- const nowMs = typeof now2 === "string" ? instant(now2) : now2.getTime();
9375
- const elapsedSeconds = Math.max(0, (nowMs - instant(this.firstAttemptAt)) / 1e3);
9376
- return elapsedSeconds <= windowSeconds;
9377
- }
9378
- toJSON() {
9379
- return {
9380
- runKey: this.runKey,
9381
- path: [...this.path],
9382
- attempt: this.attempt,
9383
- firstAttemptAt: this.firstAttemptAt
9384
- };
9385
- }
9386
- /** Rebuild from a queue payload. */
9387
- static from(value) {
9388
- if (value instanceof _RunIdentity) return value;
9389
- if (typeof value === "string") return new _RunIdentity(value);
9390
- return new _RunIdentity(
9391
- value.runKey,
9392
- value.path ?? [],
9393
- value.attempt ?? 1,
9394
- value.firstAttemptAt ?? (/* @__PURE__ */ new Date()).toISOString()
9395
- );
9396
- }
9397
- };
9398
-
9399
- // src/runtime/terminal-transcript.ts
9400
- var ESC = String.fromCharCode(27);
9401
- var CSI = String.fromCharCode(155);
9402
- var BEL = String.fromCharCode(7);
9403
- var ANSI = new RegExp(
9404
- `[${ESC}${CSI}](?:\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)|[@-Z\\\\-_])`,
9405
- "g"
9406
- );
9407
- var MAX_PENDING_ESCAPE = 1024;
9408
- var MAX_BUFFER = 1e6;
9409
- var TerminalTranscript = class {
9410
- constructor() {
9411
- /** Stripped, complete text not yet consumed by a wait. */
9412
- this.text = "";
9413
- /** Raw bytes held back because they may be the start of an escape sequence. */
9414
- this.tail = "";
9415
- this.waiters = /* @__PURE__ */ new Set();
9416
- }
9417
- /** Feed raw terminal output in. Safe to call with any chunking. */
9418
- append(chunk) {
9419
- this.tail += chunk;
9420
- const safe = this.safeLength();
9421
- if (safe > 0) {
9422
- this.text += this.tail.slice(0, safe).replace(ANSI, "");
9423
- this.tail = this.tail.slice(safe);
9424
- }
9425
- if (this.text.length > MAX_BUFFER) {
9426
- this.text = this.text.slice(this.text.length - MAX_BUFFER);
9427
- }
9428
- for (const wake2 of [...this.waiters]) wake2();
9429
- }
9430
- /**
9431
- * How much of `tail` can be stripped now.
9432
- *
9433
- * Everything, unless the final `ESC` has not yet been terminated — in which
9434
- * case processing stops there and resumes when the rest arrives.
9435
- */
9436
- safeLength() {
9437
- const lastEsc = Math.max(this.tail.lastIndexOf(ESC), this.tail.lastIndexOf(CSI));
9438
- if (lastEsc === -1) return this.tail.length;
9439
- ANSI.lastIndex = lastEsc;
9440
- const match = ANSI.exec(this.tail);
9441
- ANSI.lastIndex = 0;
9442
- if (match && match.index === lastEsc) return this.tail.length;
9443
- if (this.tail.length - lastEsc > MAX_PENDING_ESCAPE) return this.tail.length;
9444
- return lastEsc;
9445
- }
9446
- /** Unconsumed output, escape sequences removed. */
9447
- peek() {
9448
- return this.text;
9449
- }
9450
- /** Drop everything currently buffered — used before typing a new command. */
9451
- clear() {
9452
- this.text = "";
9453
- this.tail = "";
9454
- }
9455
- /**
9456
- * Wait until `pattern` matches the unconsumed text.
9457
- *
9458
- * Checks what has ALREADY arrived before subscribing, because the common case
9459
- * is that the process answered while the previous node was still finishing.
9460
- *
9461
- * `exited` is raced deliberately. Without it, a shell that dies reports as
9462
- * "timed out waiting for X" — sending whoever reads it to lengthen a timeout
9463
- * for a process that is not running. Naming the exit is the difference
9464
- * between a diagnosis and a wrong lead.
9465
- */
9466
- waitFor(pattern, options) {
9467
- return new Promise((resolve2) => {
9468
- let settled = false;
9469
- let timer2;
9470
- const finish = (result) => {
9471
- if (settled) return;
9472
- settled = true;
9473
- this.waiters.delete(check);
9474
- if (timer2) clearTimeout(timer2);
9475
- resolve2(result);
9476
- };
9477
- const check = () => {
9478
- pattern.lastIndex = 0;
9479
- const match = pattern.exec(this.text);
9480
- if (!match) return;
9481
- const through = match.index + (match[0].length || 1);
9482
- const text3 = this.text.slice(0, through);
9483
- this.text = this.text.slice(through);
9484
- finish({ status: "matched", text: text3, match });
9485
- };
9486
- this.waiters.add(check);
9487
- check();
9488
- if (settled) return;
9489
- if (options.timeoutMs > 0) {
9490
- timer2 = setTimeout(() => {
9491
- const text3 = this.text;
9492
- this.text = "";
9493
- finish({ status: "timeout", text: text3 });
9494
- }, options.timeoutMs);
9495
- timer2.unref?.();
9496
- }
9497
- options.exited?.then(
9498
- (exit) => {
9499
- if (settled) return;
9500
- const text3 = this.text;
9501
- this.text = "";
9502
- finish({ status: "exited", text: text3, exitCode: exit.exitCode, signal: exit.signal });
9503
- },
9504
- () => {
9505
- }
9506
- );
9507
- });
9508
- }
9509
- };
9510
-
9511
- // src/runtime/terminal-sessions.ts
9512
- var TerminalSessions = class {
9513
- constructor(graph) {
9514
- this.graph = graph;
9515
- this.open = /* @__PURE__ */ new Map();
9516
- this.laneOf = /* @__PURE__ */ new Map();
9517
- this.transcripts = /* @__PURE__ */ new Map();
9518
- this.listening = /* @__PURE__ */ new Map();
9519
- }
9520
- /**
9521
- * The terminal lane a node belongs to, or null.
9522
- *
9523
- * Walks up `parentId` rather than checking only the immediate parent, and
9524
- * caches per node id — a graph is walked once per run, and the answer cannot
9525
- * change while it runs.
9526
- */
9527
- laneFor(nodeId, isTerminalLane) {
9528
- const cached = this.laneOf.get(nodeId);
9529
- if (cached !== void 0) return cached;
9530
- const byId = new Map(this.graph.nodes.map((n) => [n.id, n]));
9531
- const seen = /* @__PURE__ */ new Set();
9532
- let current = byId.get(nodeId);
9533
- let answer = null;
9534
- while (current) {
9535
- if (seen.has(current.id)) break;
9536
- seen.add(current.id);
9537
- if (current.id !== nodeId && isTerminalLane(current)) {
9538
- answer = current.id;
9539
- break;
9540
- }
9541
- const parentId = current.parentId;
9542
- current = parentId ? byId.get(parentId) : void 0;
9543
- }
9544
- this.laneOf.set(nodeId, answer);
9545
- return answer;
9546
- }
9547
- /**
9548
- * The session for a lane, opening it on first use.
9549
- *
9550
- * The PROMISE is cached, not the resolved session. Two nodes cannot run
9551
- * concurrently in the current engine, but a caller that awaits a
9552
- * half-finished open would otherwise start a second process — and two shells
9553
- * where a graph says one is the failure this class exists to prevent, arriving
9554
- * only under concurrency and therefore only sometimes.
9555
- */
9556
- session(laneId, spec) {
9557
- const existing = this.open.get(laneId);
9558
- if (existing) return existing;
9559
- const host = getTerminalHost();
9560
- if (!host) {
9561
- const failed = Promise.reject(
9562
- new Error(
9563
- "No terminal host is registered. A terminal lane needs one \u2014 call registerTerminalHost() from the desktop app, or install @particle-academy/fancy-flow/terminal/fancy-term-host."
9564
- )
9565
- );
9566
- this.open.set(laneId, failed);
9567
- failed.catch(() => {
9568
- });
9569
- return failed;
9570
- }
9571
- const opening = Promise.resolve(host.open(spec)).then((session) => {
9572
- const transcript = this.transcriptFor(laneId);
9573
- this.listening.set(laneId, session.onData((chunk) => transcript.append(chunk)));
9574
- return session;
9575
- });
9576
- this.open.set(laneId, opening);
9577
- opening.catch(() => {
9578
- });
9579
- return opening;
9580
- }
9581
- /**
9582
- * The accumulated output for a lane.
9583
- *
9584
- * Created on demand and kept for the run, so it exists before the session
9585
- * resolves and survives every node that reads it. Consuming is the reader's
9586
- * job — see `TerminalTranscript.waitFor`.
9587
- */
9588
- transcriptFor(laneId) {
9589
- const existing = this.transcripts.get(laneId);
9590
- if (existing) return existing;
9591
- const created = new TerminalTranscript();
9592
- this.transcripts.set(laneId, created);
9593
- return created;
9594
- }
9595
- /** True once a lane has a session — used to avoid opening one during teardown. */
9596
- isOpen(laneId) {
9597
- return this.open.has(laneId);
9598
- }
9599
- /**
9600
- * Close every session this run opened.
9601
- *
9602
- * Every close is attempted even if one throws: a host that fails to close one
9603
- * PTY must not strand the others, which would leave processes alive after the
9604
- * run reported that it had finished. Errors are returned rather than thrown,
9605
- * because teardown runs in a `finally` and throwing there would replace the
9606
- * run's real error with a cleanup error.
9607
- */
9608
- async closeAll() {
9609
- const errors = [];
9610
- for (const [laneId, pending] of this.open) {
9611
- try {
9612
- this.listening.get(laneId)?.();
9613
- this.listening.delete(laneId);
9614
- const session = await pending;
9615
- await session.close();
9616
- } catch (e) {
9617
- errors.push(e instanceof Error ? e : new Error(`${laneId}: ${String(e)}`));
9618
- }
9619
- }
9620
- this.open.clear();
9621
- this.listening.clear();
9622
- this.transcripts.clear();
9623
- return errors;
9624
- }
9625
- };
9626
- function specForLane(lane) {
9627
- const config = lane.data?.config ?? {};
9628
- const text3 = (key) => {
9629
- const value = config[key];
9630
- return typeof value === "string" && value !== "" ? value : void 0;
9631
- };
9632
- const env = config.env;
9633
- return {
9634
- command: text3("command"),
9635
- cwd: text3("cwd"),
9636
- env: env && typeof env === "object" && !Array.isArray(env) ? Object.fromEntries(
9637
- Object.entries(env).map(([k, v]) => [k, String(v)])
9638
- ) : void 0
9639
- };
9640
- }
9641
-
9642
- // src/runtime/workflow-props.ts
9643
- function typeOf(value) {
9644
- if (value === null) return "null";
9645
- if (Array.isArray(value)) return "array";
9646
- return typeof value;
9647
- }
9648
- function resolveWorkflowProps(declared, passed) {
9649
- const inputs = declared ?? [];
9650
- const given = passed ?? {};
9651
- const byName = new Map(inputs.map((input) => [input.name, input]));
9652
- for (const name of Object.keys(given)) {
9653
- if (!byName.has(name)) {
9654
- const known = inputs.map((input) => input.name);
9655
- const suffix = known.length === 0 ? "this workflow declares no inputs" : `known inputs: ${known.join(", ")}`;
9656
- return {
9657
- ok: false,
9658
- code: "unknown_input",
9659
- error: `Unknown workflow input "${name}" \u2014 ${suffix}.`
9660
- };
9661
- }
9662
- }
9663
- const resolved = {};
9664
- for (const input of inputs) {
9665
- const supplied = Object.prototype.hasOwnProperty.call(given, input.name);
9666
- const hasDefault = Object.prototype.hasOwnProperty.call(input, "default");
9667
- if (!supplied) {
9668
- if (hasDefault) {
9669
- resolved[input.name] = input.default;
9670
- continue;
9671
- }
9672
- if (input.required) {
9673
- return {
9674
- ok: false,
9675
- code: "missing_required",
9676
- error: `Missing required workflow input "${input.name}"${input.type ? ` (${input.type})` : ""}.`
9677
- };
9678
- }
9679
- continue;
9680
- }
9681
- const value = given[input.name];
9682
- if (input.type !== void 0) {
9683
- const actual = typeOf(value);
9684
- if (actual !== input.type) {
9685
- return {
9686
- ok: false,
9687
- code: "type_mismatch",
9688
- error: `Workflow input "${input.name}" expects ${input.type}, got ${actual}.`
9689
- };
9690
- }
9691
- }
9692
- resolved[input.name] = value;
9693
- }
9694
- return { ok: true, props: resolved };
9695
- }
9696
-
9697
- // src/runtime/run-flow.ts
9698
- async function runFlow(graph, executors, onEvent = () => {
9699
- }, options = {}) {
9700
- const { signal, initialInputs = {}, timeoutMs, depth = 0, resumeOutputs = {}, entryNodes } = options;
9701
- const run = options.run === void 0 ? void 0 : RunIdentity.from(options.run);
9702
- const outputs = {};
9703
- const portValues = /* @__PURE__ */ new Map();
9704
- const completed = /* @__PURE__ */ new Set();
9705
- const errors = [];
9706
- const order = topoSort(graph);
9707
- if (order === null) {
9708
- const msg = "Cycle detected in flow graph \u2014 aborting.";
9709
- onEvent({ type: "run-error", error: msg });
9710
- return { ok: false, outputs, error: msg };
9711
- }
9712
- const propsCheck = resolveWorkflowProps(graph.inputs, options.props);
9713
- if (!propsCheck.ok) {
9714
- onEvent({ type: "run-error", error: propsCheck.error });
9715
- return { ok: false, outputs, error: propsCheck.error };
9716
- }
9717
- const props = propsCheck.props;
9718
- const declaresProps = (graph.inputs?.length ?? 0) > 0;
9719
- const incomingByNode = indexIncoming(graph.edges);
9720
- const sessions = new TerminalSessions(graph);
9721
- const isTerminalLane = (candidate) => getNodeKind(candidate.type ?? "")?.name === "@particle-academy/terminal_lane";
9722
- const terminalAccessorFor = (node) => {
9723
- const laneId = sessions.laneFor(node.id, isTerminalLane);
9724
- if (laneId === null) return void 0;
9725
- const lane = graph.nodes.find((n) => n.id === laneId);
9726
- if (!lane) return void 0;
9727
- return {
9728
- session: () => sessions.session(laneId, specForLane(lane)),
9729
- // Awaits the session first on purpose. A transcript handed out before
9730
- // anything is feeding it would look perfectly healthy and match nothing,
9731
- // and "waited and nothing came" is the hardest failure here to tell apart
9732
- // from a process that is simply slow.
9733
- transcript: async () => {
9734
- await sessions.session(laneId, specForLane(lane));
9735
- return sessions.transcriptFor(laneId);
9736
- }
9737
- };
9738
- };
9739
- const timer2 = timeoutMs ? setTimeout(() => errors.push(`Run timed out after ${timeoutMs}ms`), timeoutMs) : null;
9740
- onEvent({ type: "run-start" });
9741
- try {
9742
- for (const node of order) {
9743
- if (signal?.aborted) throw new Error("aborted");
9744
- if (errors.length) break;
9745
- if (Object.prototype.hasOwnProperty.call(resumeOutputs, node.id)) {
9746
- const stored = resumeOutputs[node.id];
9747
- outputs[node.id] = stored;
9748
- const activated = activatedPorts(node, stored);
9749
- for (const portId of activated.ports) {
9750
- portValues.set(`${node.id}:${portId}`, activated.value);
9751
- onEvent({ type: "node-output", nodeId: node.id, portId, value: activated.value });
9752
- }
9753
- completed.add(node.id);
9754
- onEvent({ type: "node-status", nodeId: node.id, status: "done", text: "resumed" });
9755
- continue;
9756
- }
9757
- const incoming = incomingByNode.get(node.id) ?? [];
9758
- if (incoming.length === 0 && entryNodes !== void 0 && !entryNodes.includes(node.id)) {
9759
- onEvent({ type: "node-status", nodeId: node.id, status: "idle", text: "skipped" });
9760
- continue;
9761
- }
9762
- if (incoming.length > 0) {
9763
- const anyActive = incoming.some((e) => portValues.has(`${e.source}:${e.sourceHandle ?? "out"}`));
9764
- if (!anyActive) {
9765
- onEvent({ type: "node-status", nodeId: node.id, status: "idle", text: "skipped" });
9766
- continue;
9767
- }
9768
- }
9769
- const visualKind = getNodeKind(node.type ?? "");
9770
- const isLayout = visualKind?.category === "layout";
9771
- const isAnnotation = node.type === "note" || visualKind?.category === "annotation";
9772
- if (isLayout || isAnnotation) {
9773
- onEvent({
9774
- type: "node-status",
9775
- nodeId: node.id,
9776
- status: "idle",
9777
- text: isLayout ? "lane" : "annotation"
9778
- });
9779
- continue;
9780
- }
9781
- onEvent({ type: "node-status", nodeId: node.id, status: "running" });
9782
- announce(onEvent, node, "start");
9783
- const inputs = collectInputs(node, incoming, portValues, initialInputs, props, declaresProps);
9784
- const exec = pickExecutor(executors, node);
9785
- if (!exec) {
9786
- const tried = executorLookupIds(node);
9787
- const msg = `No executor registered for kind=${node.type} \u2014 tried ${tried.map((id2) => `"${id2}"`).join(", ")}. Key your registry by one of those.`;
9788
- errors.push(msg);
9789
- onEvent({ type: "node-status", nodeId: node.id, status: "error", text: msg });
9790
- onEvent({ type: "log", nodeId: node.id, level: "error", message: msg });
9791
- break;
9792
- }
9793
- try {
9794
- const result = await Promise.resolve(
9795
- exec({
9796
- node,
9797
- inputs,
9798
- abort: (reason) => {
9799
- throw new Error(reason ?? "aborted");
9800
- },
9801
- emit: onEvent,
9802
- executors,
9803
- depth,
9804
- run,
9805
- terminal: terminalAccessorFor(node)
9806
- })
9807
- );
9808
- outputs[node.id] = result;
9809
- const activated = activatedPorts(node, result);
9810
- for (const portId of activated.ports) {
9811
- portValues.set(`${node.id}:${portId}`, activated.value);
9812
- onEvent({ type: "node-output", nodeId: node.id, portId, value: activated.value });
9813
- }
9814
- completed.add(node.id);
9815
- onEvent({ type: "node-status", nodeId: node.id, status: "done" });
9816
- announce(onEvent, node, "end");
9817
- } catch (e) {
9818
- const msg = e instanceof Error ? e.message : String(e);
9819
- errors.push(msg);
9820
- onEvent({ type: "node-status", nodeId: node.id, status: "error", text: msg });
9821
- onEvent({ type: "log", nodeId: node.id, level: "error", message: msg });
9822
- break;
9823
- }
9824
- }
9825
- } finally {
9826
- if (timer2) clearTimeout(timer2);
9827
- for (const error of await sessions.closeAll()) {
9828
- onEvent({ type: "log", level: "warn", message: `terminal close failed: ${error.message}` });
9829
- }
9830
- }
9831
- const ok = errors.length === 0;
9832
- onEvent({ type: "run-end", ok });
9833
- return ok ? { ok, outputs } : { ok, outputs, error: errors[0] };
9834
- }
9835
- function indexIncoming(edges) {
9836
- const map = /* @__PURE__ */ new Map();
9837
- for (const e of edges) {
9838
- const list = map.get(e.target) ?? [];
9839
- list.push(e);
9840
- map.set(e.target, list);
9841
- }
9842
- return map;
9843
- }
9844
- function topoSort(graph) {
9845
- const inDegree = /* @__PURE__ */ new Map();
9846
- for (const n of graph.nodes) inDegree.set(n.id, 0);
9847
- for (const e of graph.edges) inDegree.set(e.target, (inDegree.get(e.target) ?? 0) + 1);
9848
- const queue = [];
9849
- for (const [id2, d] of inDegree) if (d === 0) queue.push(id2);
9850
- const ordered = [];
9851
- while (queue.length) {
9852
- const id2 = queue.shift();
9853
- ordered.push(id2);
9854
- for (const e of graph.edges) {
9855
- if (e.source !== id2) continue;
9856
- const next = (inDegree.get(e.target) ?? 0) - 1;
9857
- inDegree.set(e.target, next);
9858
- if (next === 0) queue.push(e.target);
9859
- }
9860
- }
9861
- if (ordered.length !== graph.nodes.length) return null;
9862
- const byId = new Map(graph.nodes.map((n) => [n.id, n]));
9863
- return ordered.map((id2) => byId.get(id2)).filter(Boolean);
9864
- }
9865
- function collectInputs(node, incoming, portValues, initial, props, declaresProps) {
9866
- const inputs = { ...initial[node.id] ?? {} };
9867
- if (incoming.length === 0) {
9868
- for (const [name, value] of Object.entries(props)) {
9869
- if (!(name in inputs)) inputs[name] = value;
9870
- }
9871
- }
9872
- for (const e of incoming) {
9873
- const portId = e.targetHandle ?? "in";
9874
- const key = `${e.source}:${e.sourceHandle ?? "out"}`;
9875
- if (!portValues.has(key)) continue;
9876
- inputs[portId] = portValues.get(key);
9877
- if (e.targetHandle == null && !(e.source in inputs)) {
9878
- inputs[e.source] = portValues.get(key);
9879
- }
9880
- }
9881
- if (declaresProps) inputs.$props = props;
9882
- return inputs;
9883
- }
9884
- function executorLookupIds(node) {
9885
- const ids = [node.id];
9886
- if (node.type) ids.push(node.type);
9887
- const typeKind = node.type ? getNodeKind(node.type) : null;
9888
- if (typeKind) {
9889
- for (const id2 of kindIds(typeKind)) ids.push(id2);
9890
- } else {
9891
- const declared = node.data?.kind;
9892
- const kindName = typeof declared === "string" && declared !== "" ? declared : null;
9893
- if (kindName) {
9894
- ids.push(kindName);
9895
- const dataKind = getNodeKind(kindName);
9896
- if (dataKind) {
9897
- for (const id2 of kindIds(dataKind)) ids.push(id2);
9898
- }
9899
- }
9900
- }
9901
- ids.push("*");
9902
- return [...new Set(ids)];
9903
- }
9904
- function pickExecutor(executors, node) {
9905
- for (const id2 of executorLookupIds(node)) {
9906
- if (executors[id2]) return executors[id2];
9907
- }
9908
- return getNodeKind(node.type ?? "")?.executor;
9909
- }
9910
- function activatedPorts(node, result) {
9911
- if (result && typeof result === "object") {
9912
- const r = result;
9913
- if (typeof r.__port === "string") {
9914
- return { ports: [r.__port], value: r.value };
9915
- }
9916
- if (typeof r.branch === "string") {
9917
- return { ports: [r.branch], value: Object.prototype.hasOwnProperty.call(r, "value") ? r.value : r };
9918
- }
9919
- }
9920
- const kind = getNodeKind(node.data?.kind ?? node.type ?? "") ?? void 0;
9921
- const declared = resolveNodePorts(node, kind).outputs?.map((p) => p.id);
9922
- return { ports: declared?.length ? declared : ["out"], value: result };
9923
- }
9924
- function announce(onEvent, node, phase) {
9925
- const data = node.data;
9926
- const raw = phase === "start" ? data?.startingMsg : data?.stoppingMsg;
9927
- if (typeof raw !== "string") return;
9928
- const message = raw.trim();
9929
- if (message === "") return;
9930
- onEvent({ type: "node-message", nodeId: node.id, phase, message });
9931
- }
9932
-
9933
- // src/registry/subflow.ts
9934
- var DEFAULT_MAX_DEPTH = 8;
9935
- function subflowMode(config) {
9936
- const mode = config.mode;
9937
- return mode === "stream" || mode === "both" ? mode : "output";
9938
- }
9939
- function subflowPorts(config) {
9940
- const mode = subflowMode(config);
9941
- const ports = [{ id: "out", label: "result" }];
9942
- if (mode === "stream" || mode === "both") ports.unshift({ id: "stream", label: "stream" });
9943
- return ports;
9944
- }
9945
- var subflowExecutor = async (ctx) => {
9946
- const config = ctx.node.data?.config ?? {};
9947
- const ref = String(config.workflow ?? "").trim();
9948
- if (!ref) ctx.abort("subflow has no workflow reference configured");
9949
- const resolver = getWorkflowResolver();
9950
- if (!resolver) {
9951
- ctx.abort(
9952
- "No workflow resolver registered. Call registerWorkflowResolver() so subflow can find the workflow it references."
9953
- );
9954
- }
9955
- const maxDepth = Number.isFinite(config.maxDepth) ? Number(config.maxDepth) : DEFAULT_MAX_DEPTH;
9956
- const depth = ctx.depth ?? 0;
9957
- if (depth + 1 > maxDepth) {
9958
- ctx.abort(
9959
- `subflow depth limit reached (${maxDepth}) at "${ref}" \u2014 a workflow is referencing itself, directly or through a chain.`
9960
- );
9961
- }
9962
- const pinned = config.version === void 0 || config.version === "" ? void 0 : Number(config.version);
9963
- if (pinned !== void 0 && !Number.isInteger(pinned)) {
9964
- ctx.abort(`subflow "${ref}" has a non-integer version pin (${String(config.version)}).`);
9965
- }
9966
- const resolved = await resolver(ref, pinned);
9967
- const child = isResolutionFailure(resolved) ? ctx.abort(
9968
- resolved.reason === "version-mismatch" ? resolved.message ?? `subflow "${ref}" is pinned to version ${pinned}, but the host has ${resolved.available ?? "a different version"}.` : resolved.message ?? `subflow could not resolve workflow "${ref}"`
9969
- ) : resolved;
9970
- if (!child) ctx.abort(`subflow could not resolve workflow "${ref}"`);
9971
- const mode = subflowMode(config);
9972
- const streaming = mode === "stream" || mode === "both";
9973
- const forward = (event) => {
9974
- if (!streaming) return;
9975
- const detail = event.type === "node-status" ? `${event.nodeId} ${event.status}` : event.type === "run-end" ? `finished (${event.ok ? "ok" : "failed"})` : event.type;
9976
- ctx.emit({
9977
- type: "log",
9978
- nodeId: ctx.node.id,
9979
- level: "info",
9980
- message: `[${ref}] ${detail}`
9981
- });
9982
- };
9983
- const result = await runFlow(
9984
- child,
9985
- // Inherit the parent's registry, then let the graph layer its own on top.
9986
- // The inherited half is the fix; the layered half keeps a graph that
9987
- // deliberately hands its child extra or different executors working.
9988
- { ...ctx.executors ?? {}, ...config.executors ?? {} },
9989
- forward,
9990
- {
9991
- initialInputs: config.inputs ?? {
9992
- // With no explicit mapping, hand the parent's inputs to the child's
9993
- // entry points — the obvious default, and it makes the simple case
9994
- // require no configuration at all.
9995
- __parent: ctx.inputs
9996
- },
9997
- depth: depth + 1,
9998
- // Push THIS node onto the identity path, so a node inside the child graph
9999
- // cannot share an idempotency key with a same-named node in the parent —
10000
- // or with the same child graph invoked from a different parent node.
10001
- // Attempt and the first-attempt clock ride down unchanged: the child's
10002
- // work happens inside this node's attempt.
10003
- run: ctx.run?.descend(ctx.node.id)
10004
- }
10005
- );
10006
- if (!result.ok) {
10007
- ctx.abort(`subflow "${ref}" failed: ${result.error ?? "unknown error"}`);
10008
- }
10009
- if (mode === "stream") {
10010
- return { __port: "stream", value: result.outputs };
10011
- }
10012
- if (mode === "both") {
10013
- return result.outputs;
10014
- }
10015
- return { __port: "out", value: result.outputs };
10016
- };
10017
-
10018
- // src/expressions/expr.ts
10019
- function wholeExpression(trimmed) {
10020
- if (trimmed.length < 4) return null;
10021
- if (!trimmed.startsWith("{{") || !trimmed.endsWith("}}")) return null;
10022
- return trimmed.slice(2, -2);
10023
- }
10024
- function interpolate(template, resolve2) {
10025
- let out = "";
10026
- let i = 0;
10027
- for (; ; ) {
10028
- const open = template.indexOf("{{", i);
10029
- if (open === -1) return out + template.slice(i);
10030
- const close = template.indexOf("}}", open + 2);
10031
- if (close === -1) return out + template.slice(i);
10032
- out += template.slice(i, open) + resolve2(template.slice(open + 2, close));
10033
- i = close + 2;
10034
- }
10035
- }
10036
- var FALSY_STRINGS = /* @__PURE__ */ new Set(["", "0", "false", "no", "off", "null"]);
10037
- var UnresolvedPathError = class extends Error {
10038
- constructor(path) {
10039
- super(
10040
- `Expression path "${path}" did not resolve. Under the "throw" policy an unresolvable path is an error rather than an empty string.`
10041
- );
10042
- this.path = path;
10043
- this.name = "UnresolvedPathError";
10044
- }
10045
- };
10046
- function tryResolvePath(path, context) {
10047
- const unresolved = { resolved: false, value: null };
10048
- const trimmed = path.trim();
10049
- if (trimmed === "") return unresolved;
10050
- const segments = trimmed.split(".");
10051
- let cursor;
10052
- const head = segments[0];
10053
- if (head === "$json" || head === "$input") {
10054
- cursor = context !== null && typeof context === "object" && "in" in context ? context.in : context;
10055
- segments.shift();
10056
- } else {
10057
- cursor = context;
10058
- }
10059
- for (const segment of segments) {
10060
- if (cursor === null || cursor === void 0) return unresolved;
10061
- if (typeof cursor !== "object") return unresolved;
10062
- const next = cursor[segment];
10063
- if (next === void 0) return unresolved;
10064
- cursor = next;
10065
- }
10066
- return { resolved: true, value: cursor === void 0 ? null : cursor };
10067
- }
10068
- function resolvePath(path, context) {
10069
- return tryResolvePath(path, context).value;
10070
- }
10071
- function evaluateExpression(template, context, options = {}) {
10072
- if (typeof template !== "string") return template;
10073
- const policy = options.onUnresolved ?? "empty";
10074
- const whole = wholeExpression(template.trim());
10075
- if (whole !== null) {
10076
- const r = tryResolvePath(whole, context);
10077
- if (r.resolved) return r.value;
10078
- if (policy === "throw") throw new UnresolvedPathError(whole);
10079
- return policy === "keep" ? template : null;
10080
- }
10081
- return interpolate(template, (path) => {
10082
- const r = tryResolvePath(path, context);
10083
- if (r.resolved) return stringify(r.value);
10084
- if (policy === "throw") throw new UnresolvedPathError(path);
10085
- return policy === "keep" ? `{{${path}}}` : "";
10086
- });
10087
- }
10088
- function truthy(value) {
10089
- if (typeof value === "boolean") return value;
10090
- if (value === null || value === void 0) return false;
10091
- if (typeof value === "string") return !FALSY_STRINGS.has(value.trim().toLowerCase());
10092
- if (Array.isArray(value)) return value.length > 0;
10093
- if (typeof value === "number") return value !== 0;
10094
- return Boolean(value);
10095
- }
10096
- function text(value) {
10097
- return stringify(value);
10098
- }
10099
- function stringify(value) {
10100
- if (typeof value === "string") return value;
10101
- if (typeof value === "boolean") return value ? "true" : "false";
10102
- if (value === null || value === void 0) return "";
10103
- if (typeof value === "number" || typeof value === "bigint") return String(value);
10104
- try {
10105
- return JSON.stringify(value) ?? "";
10106
- } catch {
10107
- return "";
10108
- }
10109
- }
10110
- function evaluateConfig(config, context, options = {}) {
10111
- const out = {};
10112
- for (const [key, value] of Object.entries(config)) {
10113
- out[key] = Array.isArray(value) ? value.map((v) => evaluateExpression(v, context, options)) : value !== null && typeof value === "object" ? evaluateConfig(value, context, options) : evaluateExpression(value, context, options);
10114
- }
10115
- return out;
10116
- }
10117
-
10118
- // src/registry/logic.ts
10119
- function configOf(node) {
10120
- return node?.data?.config ?? {};
10121
- }
10122
- function contextOf(inputs) {
10123
- return inputs;
10124
- }
10125
- function resolve(value, inputs) {
10126
- if (typeof value !== "string") return value;
10127
- return evaluateExpression(value, contextOf(inputs));
10128
- }
10129
- function conditionHolds(row, inputs) {
10130
- const left = resolve(row.left, inputs);
10131
- const right = resolve(row.right, inputs);
10132
- const operator = typeof row.operator === "string" ? row.operator : "eq";
10133
- const asText = (v) => text(v);
10134
- const asNumber = (v) => {
10135
- const n = typeof v === "number" ? v : Number(asText(v));
10136
- return Number.isFinite(n) ? n : NaN;
10137
- };
10138
- const numeric = (fn) => {
10139
- const a = asNumber(left);
10140
- const b = asNumber(right);
10141
- return Number.isFinite(a) && Number.isFinite(b) ? fn(a, b) : false;
10142
- };
10143
- const isEmpty = (v) => v === null || v === void 0 || v === "" || Array.isArray(v) && v.length === 0 || typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0;
10144
- switch (operator) {
10145
- // Compared as TEXT, deliberately. `right` is a text field in the schema, so
10146
- // `status == "2"` must match the number 2 an upstream node produced —
10147
- // strict equality there would fail on a difference the author cannot see.
10148
- case "eq":
10149
- return asText(left) === asText(right);
10150
- case "neq":
10151
- return asText(left) !== asText(right);
10152
- case "contains":
10153
- return asText(left).includes(asText(right));
10154
- case "not_contains":
10155
- return !asText(left).includes(asText(right));
10156
- case "gt":
10157
- return numeric((a, b) => a > b);
10158
- case "gte":
10159
- return numeric((a, b) => a >= b);
10160
- case "lt":
10161
- return numeric((a, b) => a < b);
10162
- case "lte":
10163
- return numeric((a, b) => a <= b);
10164
- case "truthy":
10165
- return truthy(left);
10166
- case "falsy":
10167
- return !truthy(left);
10168
- case "empty":
10169
- return isEmpty(left);
10170
- case "not_empty":
10171
- return !isEmpty(left);
10172
- default:
10173
- return false;
10174
- }
10175
- }
10176
- var branchExecutor = (ctx) => {
10177
- const config = configOf(ctx.node);
10178
- const inputs = ctx.inputs;
10179
- let taken;
10180
- const raw = config.condition;
10181
- if (typeof raw === "string" && raw.trim() !== "") {
10182
- taken = truthy(resolve(raw, inputs));
10183
- } else {
10184
- const rows = Array.isArray(config.conditions) ? config.conditions : [];
10185
- if (rows.length === 0) {
10186
- taken = false;
10187
- } else {
10188
- const results = rows.map((row) => conditionHolds(row, inputs));
10189
- taken = config.match === "any" ? results.some(Boolean) : results.every(Boolean);
10190
- }
10191
- }
10192
- return { __port: taken ? "true" : "false", value: ctx.inputs.in ?? ctx.inputs };
10193
- };
10194
- var transformExecutor = (ctx) => {
10195
- const config = configOf(ctx.node);
10196
- const inputs = ctx.inputs;
10197
- const passthrough = ctx.inputs.in ?? ctx.inputs;
10198
- if (config.mode === "expression") {
10199
- const expression = config.expression;
10200
- if (typeof expression !== "string" || expression.trim() === "") return passthrough;
10201
- return resolve(expression, inputs);
10202
- }
10203
- const rows = Array.isArray(config.fields) ? config.fields : [];
10204
- if (rows.length === 0) return passthrough;
10205
- const out = {};
10206
- let wrote = false;
10207
- for (const row of rows) {
10208
- const key = typeof row.key === "string" ? row.key.trim() : "";
10209
- if (key === "") continue;
10210
- out[key] = resolve(row.value, inputs);
10211
- wrote = true;
10212
- }
10213
- return wrote ? out : passthrough;
10214
- };
10215
- var mergeExecutor = (ctx) => {
10216
- const entries = Object.entries(ctx.inputs);
10217
- if (configOf(ctx.node).mode === "concat") {
10218
- const out = [];
10219
- for (const [, value] of entries) {
10220
- if (value === null || value === void 0) continue;
10221
- if (Array.isArray(value)) out.push(...value);
10222
- else out.push(value);
10223
- }
10224
- return out;
10225
- }
10226
- const merged = {};
10227
- for (const [port, value] of entries) {
10228
- if (value === null || value === void 0) continue;
10229
- if (typeof value === "object" && !Array.isArray(value)) Object.assign(merged, value);
10230
- else merged[port] = value;
10231
- }
10232
- return merged;
10233
- };
10234
- var forEachExecutor = (ctx) => {
10235
- const source = resolve(configOf(ctx.node).source, ctx.inputs);
10236
- let items;
10237
- if (Array.isArray(source)) items = source;
10238
- else if (source === null || source === void 0) items = [];
10239
- else if (typeof source === "object") items = Object.values(source);
10240
- else items = [source];
10241
- return { items, count: items.length };
10242
- };
10243
-
10244
- // src/registry/terminal-nodes.ts
10245
- var DEFAULT_TIMEOUT_MS = 12e4;
10246
- var ENTER = "\r";
10247
- function configOf2(node) {
10248
- return node?.data?.config ?? {};
10249
- }
10250
- function text2(config, key) {
10251
- const value = config[key];
10252
- return typeof value === "string" ? value : "";
10253
- }
10254
- function millis(config, key, fallback) {
10255
- const value = Number(config[key]);
10256
- return Number.isFinite(value) && value >= 0 ? value : fallback;
10257
- }
10258
- function exitMarker(nonce) {
10259
- const token = `__fancy_flow_exit_${nonce}__`;
10260
- return {
10261
- token,
10262
- // The expanded status is required to be digits. The shell ECHOES the typed
10263
- // command back first, and that echo contains the marker with `$?`
10264
- // unexpanded — so requiring digits is what stops the node matching its own
10265
- // command line and reporting success before anything has run.
10266
- pattern: new RegExp(`${token}:(\\d+)`)
10267
- };
10268
- }
10269
- var counter = 0;
10270
- function newNonce() {
10271
- counter += 1;
10272
- return `${Date.now().toString(36)}${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;
10273
- }
10274
- function withoutMarker(output, token) {
10275
- return output.split("\n").filter((line) => !line.includes(token)).join("\n").trim();
10276
- }
10277
- function fail(ctx, message) {
10278
- ctx.abort(message);
10279
- throw new Error(message);
10280
- }
10281
- function requireTerminal(ctx) {
10282
- if (!ctx.terminal) {
10283
- fail(
10284
- ctx,
10285
- `"${String(ctx.node.data?.label ?? ctx.node.id)}" is a terminal node but is not inside a terminal lane. Drag it into one \u2014 a terminal node outside a lane has no session to talk to, and opening a private shell for it would defeat the point of the lane.`
10286
- );
10287
- }
10288
- return ctx.terminal;
10289
- }
10290
- function compilePattern(ctx, raw, config) {
10291
- const flags = typeof config.flags === "string" ? config.flags.replace(/[gy]/g, "") : "";
10292
- try {
10293
- return config.mode === "regex" ? new RegExp(raw, flags) : new RegExp(raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags);
10294
- } catch (e) {
10295
- return fail(ctx, `terminal_await has an invalid regex: ${e instanceof Error ? e.message : String(e)}`);
10296
- }
10297
- }
10298
- var terminalRunExecutor = async (ctx) => {
10299
- const config = configOf2(ctx.node);
10300
- const command = text2(config, "command").trim();
10301
- if (!command) fail(ctx, "terminal_run has no command configured");
10302
- const terminal = requireTerminal(ctx);
10303
- const session = await terminal.session();
10304
- const transcript = await terminal.transcript();
10305
- const { token, pattern } = exitMarker(newNonce());
10306
- const timeoutMs = millis(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
10307
- transcript.clear();
10308
- await session.write(`${command}; printf '${token}:%s\\n' "$?"${ENTER}`);
10309
- const result = await transcript.waitFor(pattern, { timeoutMs, exited: session.exited });
10310
- if (result.status === "exited") {
10311
- fail(
10312
- ctx,
10313
- `The terminal exited (code ${result.exitCode}${result.signal ? `, signal ${result.signal}` : ""}) while running "${command}". The lane's session is gone, so every later node in this lane would fail too.`
10314
- );
10315
- }
10316
- if (result.status === "timeout") {
10317
- fail(
10318
- ctx,
10319
- `"${command}" did not finish within ${timeoutMs}ms. Raise the node's timeout if it is genuinely slow \u2014 but a command that waits for input never finishes at all, and needs terminal_send + terminal_await.`
10320
- );
10321
- }
10322
- const exitCode = Number(result.match[1]);
10323
- const output = withoutMarker(result.text, token);
10324
- const failOnNonZero = config.failOnNonZero !== false;
10325
- if (failOnNonZero && exitCode !== 0) {
10326
- ctx.abort(`"${command}" exited ${exitCode}.
10327
- ${output}`);
10328
- }
10329
- return { output, exitCode, command };
10330
- };
10331
- var terminalSendExecutor = async (ctx) => {
10332
- const config = configOf2(ctx.node);
10333
- const terminal = requireTerminal(ctx);
10334
- const session = await terminal.session();
10335
- const body = text2(config, "text");
10336
- const submit = config.submit !== false;
10337
- if (config.clearFirst === true) {
10338
- (await terminal.transcript()).clear();
10339
- }
10340
- await session.write(submit ? `${body}${ENTER}` : body);
10341
- return { sent: body, submitted: submit };
10342
- };
10343
- var terminalAwaitExecutor = async (ctx) => {
10344
- const config = configOf2(ctx.node);
10345
- const terminal = requireTerminal(ctx);
10346
- const session = await terminal.session();
10347
- const transcript = await terminal.transcript();
10348
- const raw = text2(config, "pattern").trim();
10349
- if (!raw) fail(ctx, "terminal_await has no pattern configured \u2014 there is nothing for it to wait for");
10350
- const pattern = compilePattern(ctx, raw, config);
10351
- const timeoutMs = millis(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
10352
- const result = await transcript.waitFor(pattern, {
10353
- timeoutMs,
10354
- exited: session.exited
10355
- });
10356
- if (result.status === "exited") {
10357
- fail(
10358
- ctx,
10359
- `The terminal exited (code ${result.exitCode}${result.signal ? `, signal ${result.signal}` : ""}) while waiting for ${JSON.stringify(raw)}. It never appeared, and the lane's session is gone.`
10360
- );
10361
- }
10362
- if (result.status === "timeout") {
10363
- if (config.onTimeout === "continue") {
10364
- ctx.emit({
10365
- type: "log",
10366
- nodeId: ctx.node.id,
10367
- level: "warn",
10368
- message: `terminal_await: ${JSON.stringify(raw)} did not appear within ${timeoutMs}ms; continuing as configured.`
10369
- });
10370
- return { matched: false, output: result.text, groups: [] };
10371
- }
10372
- fail(
10373
- ctx,
10374
- `${JSON.stringify(raw)} did not appear within ${timeoutMs}ms. Last output:
10375
- ${result.text.slice(-2e3)}`
10376
- );
10377
- }
10378
- return {
10379
- matched: true,
10380
- output: result.text,
10381
- matchedText: result.match[0],
10382
- // Capture groups are the reason to use regex mode at all — a prompt that
10383
- // reports a session id or a file path is only useful if the value comes out.
10384
- groups: result.match.slice(1)
10385
- };
10386
- };
10387
-
10388
- // src/registry/builtin.ts
10389
- var HUMAN_FIELD_OUTPUT_TYPE = {
10390
- text: "string",
10391
- textarea: "string",
10392
- select: "string",
10393
- date: "string",
10394
- datetime: "string",
10395
- time: "string",
10396
- email: "string",
10397
- url: "string",
10398
- tel: "string",
10399
- password: "string",
10400
- number: "number",
10401
- switch: "boolean"
10402
- };
10403
- function casePorts(cases) {
10404
- const byPort = /* @__PURE__ */ new Map();
10405
- if (cases && typeof cases === "object" && !Array.isArray(cases)) {
10406
- for (const [match, port] of Object.entries(cases)) {
10407
- if (typeof port !== "string" || port === "" || port === "default") continue;
10408
- const matches = byPort.get(port) ?? [];
10409
- matches.push(match);
10410
- byPort.set(port, matches);
10411
- }
10412
- }
10413
- const ports = [...byPort].map(([id2, matches]) => ({
10414
- id: id2,
10415
- label: matches.join("|")
10416
- }));
10417
- return [...ports, { id: "default", label: "default" }];
10418
- }
10419
- function routePorts(routes, fallback) {
10420
- const ports = [];
10421
- const seen = /* @__PURE__ */ new Set();
10422
- if (Array.isArray(routes)) {
10423
- for (const route of routes) {
10424
- const id2 = route?.port;
10425
- if (typeof id2 !== "string" || id2.trim() === "" || seen.has(id2)) continue;
10426
- seen.add(id2);
10427
- ports.push({ id: id2, label: id2 });
10428
- }
10429
- }
10430
- if (fallback !== false && !seen.has("fallback")) {
10431
- ports.push({ id: "fallback", label: "fallback" });
10432
- }
10433
- if (ports.length === 0) ports.push({ id: "out" });
10434
- return ports;
10435
- }
10436
- var HTTP_METHODS = [
10437
- { type: "select", key: "method", label: "Method", options: [
10438
- { value: "GET", label: "GET" },
10439
- { value: "POST", label: "POST" },
10440
- { value: "PUT", label: "PUT" },
10441
- { value: "PATCH", label: "PATCH" },
10442
- { value: "DELETE", label: "DELETE" }
10443
- ], default: "GET", required: true }
10444
- ];
10445
- var KINDS = [
10446
- // ───────────── Triggers ─────────────
10447
- {
10448
- name: "@particle-academy/manual_trigger",
10449
- // Returns the raw inputs MAP, not the `in` port -- flat at an entry
10450
- // point, port-keyed the moment the node has an inbound edge.
10451
- emits: "input-map-merged",
10452
- aliases: ["manual_trigger", "@fancy/manual_trigger"],
10453
- category: "trigger",
10454
- label: "Manual",
10455
- description: "Entry point fired when the user clicks Run.",
10456
- icon: "\u26A1",
10457
- inputs: [],
10458
- outputs: [{ id: "out" }]
10459
- },
10460
- {
10461
- name: "@particle-academy/webhook_trigger",
10462
- aliases: ["webhook_trigger", "@fancy/webhook_trigger"],
10463
- category: "trigger",
10464
- label: "Webhook",
10465
- description: "Triggered by an inbound HTTP request to a host-provided URL.",
10466
- icon: "\u{1F4E1}",
10467
- inputs: [],
10468
- outputs: [{ id: "out", label: "payload" }],
10469
- configSchema: [
10470
- { type: "text", key: "path", label: "Path", placeholder: "/hooks/my-flow", required: true },
10471
- { type: "select", key: "method", label: "Method", options: [
10472
- { value: "POST", label: "POST" },
10473
- { value: "GET", label: "GET" }
10474
- ], default: "POST" },
10475
- { type: "credential", key: "secret", label: "Verifying secret", credentialType: "webhook_secret" }
10476
- ]
10477
- },
10478
- {
10479
- name: "@particle-academy/schedule_trigger",
10480
- outputShape: [
10481
- { path: "cron", type: "string", description: "The cron expression that fired." },
10482
- { path: "timezone", type: "string", description: "The timezone it was evaluated in." }
10483
- ],
10484
- // Merges $ctx->inputs ITSELF beside cron/timezone -- the MAP, whose
10485
- // shape depends on position, not each port's payload the way `merge` does.
10486
- emits: "input-map-merged",
10487
- aliases: ["schedule_trigger", "@fancy/schedule_trigger"],
10488
- category: "trigger",
10489
- label: "Schedule",
10490
- description: "Fires on a cron schedule (host-implemented).",
10491
- icon: "\u23F1",
10492
- inputs: [],
10493
- outputs: [{ id: "out" }],
10494
- configSchema: [
10495
- {
10496
- type: "text",
10497
- key: "cron",
10498
- label: "Cron",
10499
- placeholder: "*/5 * * * *",
10500
- required: true,
10501
- description: "Standard 5-field cron expression."
10502
- },
10503
- { type: "text", key: "timezone", label: "Timezone", placeholder: "UTC", default: "UTC" }
10504
- ]
10505
- },
10506
- {
10507
- name: "@particle-academy/user_input",
10508
- // The keys an author declared on THIS node — the case a static list cannot
10509
- // express, and the one issue #5 named.
10510
- //
10511
- // The TYPE comes from the same normalizer the form renders with, so the
10512
- // variable picker agrees with what the run actually resolves. It used to say
10513
- // `string` for every field, which was wrong the moment a field was a number
10514
- // or a switch — the picker told an author `{{ $json.age }}` was text while
10515
- // the form handed the next node a number.
10516
- outputShape: (config) => (config.fields ?? []).filter((f) => typeof f.key === "string" && f.key !== "").map((f) => ({
10517
- path: f.key,
10518
- type: HUMAN_FIELD_OUTPUT_TYPE[humanFieldType(f.type)],
10519
- description: f.label
10520
- })),
10521
- aliases: ["user_input", "@fancy/user_input"],
10522
- pausesForHuman: "input",
10523
- category: "human",
10524
- label: "User Input",
10525
- description: "Pause the flow until the user submits the configured form.",
10526
- icon: "\u270E",
10527
- inputs: [{ id: "in" }],
10528
- outputs: [{ id: "out", label: "values" }],
10529
- configSchema: [
10530
- { type: "text", key: "title", label: "Form title", default: "Need your input" },
10531
- {
10532
- type: "repeater",
10533
- key: "fields",
10534
- label: "Fields",
10535
- description: "The form the run pauses on.",
10536
- titleKey: "label",
10537
- addLabel: "Add field",
10538
- minItems: 1,
10539
- fields: [
10540
- { type: "text", key: "key", label: "Key", required: true, placeholder: "answer" },
10541
- { type: "text", key: "label", label: "Label", required: true, placeholder: "Your answer" },
10542
- {
10543
- type: "select",
10544
- key: "type",
10545
- label: "Type",
10546
- default: "text",
10547
- // Every control `HumanPrompt` can render. A type the form supports
10548
- // but the panel cannot select is reachable only by hand-editing the
10549
- // workflow JSON — which is the audience this panel exists for.
10550
- options: [
10551
- { value: "text", label: "Text" },
10552
- { value: "textarea", label: "Long text" },
10553
- { value: "number", label: "Number" },
10554
- { value: "select", label: "Select" },
10555
- { value: "switch", label: "Switch (yes / no)" },
10556
- { value: "date", label: "Date" },
10557
- { value: "datetime", label: "Date + time" },
10558
- { value: "time", label: "Time" },
10559
- { value: "email", label: "Email" },
10560
- { value: "url", label: "URL" },
10561
- { value: "tel", label: "Phone" },
10562
- { value: "password", label: "Password" }
10563
- ]
10564
- },
10565
- {
10566
- // Without this a panel-authored select had nothing to choose from,
10567
- // so it rendered an empty dropdown — the type was declarable and
10568
- // unusable in the same breath.
10569
- type: "keyvalue",
10570
- key: "options",
10571
- label: "Choices",
10572
- description: "Select fields only. Left is the value the flow receives, right is what the person sees.",
10573
- keyLabel: "Value",
10574
- valueLabel: "Label",
10575
- keyPlaceholder: "small",
10576
- valuePlaceholder: "Small",
10577
- addLabel: "Add choice"
10578
- },
10579
- { type: "switch", key: "required", label: "Required", default: false }
10580
- ],
10581
- default: [{ key: "answer", label: "Your answer", type: "textarea", required: true }]
10582
- }
10583
- ]
10584
- },
10585
- {
10586
- name: "@particle-academy/rich_user_input",
10587
- aliases: ["rich_user_input", "@fancy/rich_user_input"],
10588
- pausesForHuman: "input",
10589
- category: "human",
10590
- label: "Rich User Input",
10591
- description: "Pause the flow on a fully authored page \u2014 content, required reading, multi-section forms.",
10592
- icon: "\u25A4",
10593
- inputs: [{ id: "in" }],
10594
- outputs: [{ id: "out", label: "values" }],
10595
- configSchema: [
10596
- { type: "text", key: "title", label: "Step title", default: "Please review" },
10597
- {
10598
- type: "document",
10599
- key: "document",
10600
- label: "Page content",
10601
- documentType: "stages",
10602
- description: "Authored with the host's document editor (fancy-cms Stages)."
10603
- },
10604
- { type: "switch", key: "requireConfirm", label: "Require explicit confirmation", default: true },
10605
- { type: "text", key: "submitLabel", label: "Submit button", default: "Continue" }
10606
- ],
10607
- // Preview the authored page inside a FauxClient frame, so the canvas shows
10608
- // what the person hitting this step will actually see.
10609
- renderBody: (ctx) => createElement(RichInputPreview, { config: ctx.config ?? {} })
10610
- },
10611
- {
10612
- name: "@particle-academy/subflow",
10613
- aliases: ["subflow", "@fancy/subflow"],
10614
- category: "logic",
10615
- label: "SubFlow",
10616
- description: "Run another workflow and bring its result \u2014 or its live progress \u2014 back into this one.",
10617
- icon: "\u29C9",
10618
- inputs: [{ id: "in" }],
10619
- // The stream port only exists when something actually streams.
10620
- outputs: (config) => subflowPorts(config ?? {}),
10621
- // Core, not marketplace: it runs a child graph through this same engine and
10622
- // needs nothing from outside except where workflows live.
10623
- executor: subflowExecutor,
10624
- configSchema: [
10625
- {
10626
- type: "text",
10627
- key: "workflow",
10628
- label: "Workflow",
10629
- required: true,
10630
- placeholder: "onboarding-v2",
10631
- description: "Reference resolved by the host's registerWorkflowResolver()."
10632
- },
10633
- {
10634
- type: "number",
10635
- key: "version",
10636
- label: "Pin to version",
10637
- description: "Optional. Leave blank to always run the child's current version. Pinning fails the run loudly if the child has moved on \u2014 without it, someone edits the child and this flow silently runs different logic."
10638
- },
10639
- {
10640
- type: "select",
10641
- key: "mode",
10642
- label: "Return",
10643
- default: "output",
10644
- options: [
10645
- { value: "output", label: "Output when it finishes" },
10646
- { value: "stream", label: "Stream progress as it runs" },
10647
- { value: "both", label: "Both \u2014 stream, then output" }
10648
- ],
10649
- description: "Streaming adds a second port so a parent can show progress instead of a spinner."
10650
- },
10651
- {
10652
- type: "keyvalue",
10653
- key: "inputs",
10654
- label: "Input mapping",
10655
- description: "Values handed to the child's entry points. Omit to pass this node's inputs straight through.",
10656
- keyLabel: "Name",
10657
- valueLabel: "Value",
10658
- addLabel: "Add input"
10659
- },
10660
- {
10661
- type: "number",
10662
- key: "maxDepth",
10663
- label: "Max nesting depth",
10664
- default: DEFAULT_MAX_DEPTH,
10665
- min: 1,
10666
- max: 32,
10667
- description: "Guards against a workflow referencing itself."
10668
- }
10669
- ]
10670
- },
10671
- // ───────────── Logic ─────────────
10672
- {
10673
- name: "@particle-academy/branch",
10674
- // returns its input on the chosen port
10675
- emits: "input",
10676
- aliases: ["branch", "@fancy/branch"],
10677
- // Pure logic: no I/O to choose, so a default is safe. A host
10678
- // executor still wins -- pickExecutor consults the registry first.
10679
- executor: branchExecutor,
10680
- category: "logic",
10681
- label: "Branch",
10682
- description: "Multi-way branch on a condition or value.",
10683
- icon: "\u25C7",
10684
- inputs: [{ id: "in" }],
10685
- outputs: [{ id: "true", label: "true" }, { id: "false", label: "false" }],
10686
- configSchema: [
10687
- {
10688
- type: "select",
10689
- key: "match",
10690
- label: "Match",
10691
- default: "all",
10692
- options: [
10693
- { value: "all", label: "All conditions (AND)" },
10694
- { value: "any", label: "Any condition (OR)" }
10695
- ]
10696
- },
10697
- {
10698
- type: "repeater",
10699
- key: "conditions",
10700
- label: "Conditions",
10701
- description: "Routes to `true` when these match, otherwise `false`.",
10702
- titleKey: "left",
10703
- addLabel: "Add condition",
10704
- minItems: 1,
10705
- fields: [
10706
- { type: "expression", key: "left", label: "Value", example: "{{ $json.status }}", required: true },
10707
- {
10708
- type: "select",
10709
- key: "operator",
10710
- label: "Is",
10711
- default: "eq",
10712
- options: [
10713
- { value: "eq", label: "equal to" },
10714
- { value: "neq", label: "not equal to" },
10715
- { value: "contains", label: "contains" },
10716
- { value: "not_contains", label: "does not contain" },
10717
- { value: "gt", label: "greater than" },
10718
- { value: "gte", label: "greater than or equal to" },
10719
- { value: "lt", label: "less than" },
10720
- { value: "lte", label: "less than or equal to" },
10721
- { value: "truthy", label: "true" },
10722
- { value: "falsy", label: "false" },
10723
- { value: "empty", label: "empty" },
10724
- { value: "not_empty", label: "not empty" }
10725
- ]
10726
- },
10727
- { type: "text", key: "right", label: "Compared to", placeholder: "active" }
10728
- ],
10729
- default: [{ left: "", operator: "eq", right: "" }]
10730
- },
10731
- {
10732
- type: "expression",
10733
- key: "condition",
10734
- label: "Raw expression (advanced)",
10735
- example: "{{ $json.active && $json.score > 10 }}",
10736
- description: "Escape hatch for logic the builder can't express. Overrides the conditions above when set."
10737
- }
10738
- ]
10739
- },
10740
- {
10741
- name: "@particle-academy/switch_case",
10742
- // returns its input on the chosen port
10743
- emits: "input",
10744
- aliases: ["switch_case", "@fancy/switch_case"],
10745
- category: "logic",
10746
- label: "Switch",
10747
- description: "Route to one of N labelled outputs based on a key.",
10748
- icon: "\u2933",
10749
- inputs: [{ id: "in" }],
10750
- // Ports ARE the config: every distinct port a case routes to becomes an
10751
- // output handle, plus the always-present `default`. Editing the cases map
10752
- // moves the ports on the canvas and the ports the runtime activates.
10753
- outputs: (config) => casePorts(config?.cases),
10754
- configSchema: [
10755
- { type: "expression", key: "value", label: "Switch on", example: "{{ $json.kind }}", required: true },
10756
- {
10757
- type: "keyvalue",
10758
- key: "cases",
10759
- label: "Cases",
10760
- description: "Match value \u2192 output port. Unmatched input takes `default`.",
10761
- keyLabel: "When value is",
10762
- valueLabel: "Route to port",
10763
- keyPlaceholder: "a",
10764
- valuePlaceholder: "case_a",
10765
- addLabel: "Add case",
10766
- default: { a: "case_a", b: "case_b" }
10767
- }
10768
- ]
10769
- },
10770
- {
10771
- name: "@particle-academy/for_each",
10772
- outputShape: [
10773
- { path: "items", type: "array" },
10774
- { path: "count", type: "number" }
10775
- ],
10776
- aliases: ["for_each", "@fancy/for_each"],
10777
- // Pure logic: no I/O to choose, so a default is safe. A host
10778
- // executor still wins -- pickExecutor consults the registry first.
10779
- executor: forEachExecutor,
10780
- category: "logic",
10781
- label: "For Each",
10782
- description: "Iterate over a list, emitting each item on `item`.",
10783
- icon: "\u21BB",
10784
- inputs: [{ id: "in" }],
10785
- outputs: [{ id: "item", label: "item" }, { id: "done", label: "done" }],
10786
- configSchema: [
10787
- { type: "expression", key: "source", label: "List", example: "{{ $json.users }}", required: true },
10788
- { type: "number", key: "concurrency", label: "Concurrency", default: 1, min: 1, max: 50 }
10789
- ]
10790
- },
10791
- {
10792
- name: "@particle-academy/merge",
10793
- // `merge` mode unions every object input at the TOP level; `concat` builds
10794
- // a list instead, whose elements are not addressable as fields. So concat
10795
- // declares NOTHING rather than an empty list -- `[]` would claim "emits no
10796
- // fields" of a kind that emits a list, which is false and refuses every
10797
- // reference.
10798
- emits: (config) => (config?.mode ?? "merge") === "concat" ? null : "inputs-merged",
10799
- aliases: ["merge", "@fancy/merge"],
10800
- // Pure logic: no I/O to choose, so a default is safe. A host
10801
- // executor still wins -- pickExecutor consults the registry first.
10802
- executor: mergeExecutor,
10803
- category: "logic",
10804
- label: "Merge",
10805
- description: "Combine multiple inputs into one object or array.",
10806
- icon: "\u2295",
10807
- inputs: [{ id: "a" }, { id: "b" }],
10808
- outputs: [{ id: "out" }],
10809
- configSchema: [
10810
- {
10811
- type: "select",
10812
- key: "mode",
10813
- label: "Mode",
10814
- default: "merge",
10815
- options: [{ value: "merge", label: "Object merge" }, { value: "concat", label: "Array concat" }]
10816
- }
10817
- ]
10818
- },
10819
- {
10820
- name: "@particle-academy/wait",
10821
- outputShape: [
10822
- { path: "waited", type: "string", description: "Which wait mode ran." },
10823
- { path: "duration", type: "number", description: "How long it waited." },
10824
- { path: "input", type: "unknown", description: "The value that arrived, carried forward." }
10825
- ],
10826
- aliases: ["wait", "@fancy/wait"],
10827
- category: "logic",
10828
- label: "Wait",
10829
- description: "Sleep or wait for an external event.",
10830
- icon: "\u23F8",
10831
- configSchema: [
10832
- {
10833
- type: "select",
10834
- key: "mode",
10835
- label: "Mode",
10836
- default: "duration",
10837
- options: [{ value: "duration", label: "Duration" }, { value: "until", label: "Until timestamp" }, { value: "event", label: "External event" }]
10838
- },
10839
- { type: "text", key: "duration", label: "Duration", placeholder: "5s, 10m, 1h", description: "Used when mode = duration." }
10840
- ]
10841
- },
10842
- {
10843
- name: "@particle-academy/transform",
10844
- // Two behaviours: the input unchanged when no expression is configured,
10845
- // else the shape that expression names. So the RELATION is config-dependent.
10846
- emits: (config) => (config?.expression ?? "") === "" ? "input" : "expression:expression",
10847
- aliases: ["transform", "@fancy/transform"],
10848
- // Pure logic: no I/O to choose, so a default is safe. A host
10849
- // executor still wins -- pickExecutor consults the registry first.
10850
- executor: transformExecutor,
10851
- category: "logic",
10852
- label: "Transform",
10853
- description: "Reshape data with an expression.",
10854
- icon: "\u0192",
10855
- configSchema: [
10856
- {
10857
- type: "select",
10858
- key: "mode",
10859
- label: "Build the output",
10860
- default: "fields",
10861
- options: [
10862
- { value: "fields", label: "Field by field" },
10863
- { value: "expression", label: "One expression" }
10864
- ]
10865
- },
10866
- {
10867
- type: "repeater",
10868
- key: "fields",
10869
- label: "Output fields",
10870
- description: "Each row becomes a key on the result.",
10871
- titleKey: "key",
10872
- addLabel: "Add field",
10873
- fields: [
10874
- { type: "text", key: "key", label: "Key", required: true, placeholder: "name" },
10875
- { type: "expression", key: "value", label: "Value", example: "{{ $json.first }}", required: true }
10876
- ],
10877
- default: [{ key: "", value: "" }]
10878
- },
10879
- {
10880
- type: "expression",
10881
- key: "expression",
10882
- label: "Expression (advanced)",
10883
- example: "{{ { id: $json.id, name: $json.first + ' ' + $json.last } }}",
10884
- description: "Used when the mode above is set to one expression."
10885
- }
10886
- ]
10887
- },
10888
- // ───────────── Data ─────────────
10889
- {
10890
- name: "@particle-academy/memory_store",
10891
- aliases: ["memory_store", "@fancy/memory_store"],
10892
- category: "data",
10893
- label: "Memory Store",
10894
- description: "Read or write per-conversation memory.",
10895
- icon: "\u{1F9E0}",
10896
- configSchema: [
10897
- {
10898
- type: "select",
10899
- key: "operation",
10900
- label: "Operation",
10901
- required: true,
10902
- default: "read",
10903
- options: [{ value: "read", label: "Read" }, { value: "write", label: "Write" }, { value: "append", label: "Append" }]
10904
- },
10905
- { type: "text", key: "key", label: "Key", placeholder: "user.preferences", required: true },
10906
- { type: "expression", key: "value", label: "Value (write/append only)", example: "{{ $json }}" },
10907
- { type: "credential", key: "store", label: "Memory store", credentialType: "memory_store" }
10908
- ]
10909
- },
10910
- {
10911
- name: "@particle-academy/data_store",
10912
- aliases: ["data_store", "@fancy/data_store"],
10913
- category: "data",
10914
- label: "Data Store",
10915
- description: "Key-value or table read/write against a host store.",
10916
- icon: "\u{1F5C3}",
10917
- configSchema: [
10918
- {
10919
- type: "select",
10920
- key: "operation",
10921
- label: "Operation",
10922
- required: true,
10923
- default: "get",
10924
- options: [
10925
- { value: "get", label: "Get" },
10926
- { value: "set", label: "Set" },
10927
- { value: "delete", label: "Delete" },
10928
- { value: "query", label: "Query" },
10929
- { value: "list", label: "List" }
10930
- ]
10931
- },
10932
- { type: "text", key: "table", label: "Table / collection", required: true },
10933
- { type: "text", key: "key", label: "Key" },
10934
- {
10935
- type: "keyvalue",
10936
- key: "where",
10937
- label: "Where",
10938
- description: "Field/value pairs to match. For query and list operations.",
10939
- keyLabel: "Field",
10940
- valueLabel: "Equals",
10941
- addLabel: "Add filter"
10942
- },
10943
- { type: "expression", key: "value", label: "Value (set only)", example: "{{ $json }}" },
10944
- { type: "credential", key: "store", label: "Data store", credentialType: "data_store" }
10945
- ]
10946
- },
10947
- {
10948
- name: "@particle-academy/variable",
10949
- // evaluates the expression in config.value
10950
- emits: "expression:value",
10951
- aliases: ["variable", "@fancy/variable"],
10952
- category: "data",
10953
- label: "Variable",
10954
- description: "Workflow-scoped value used by other nodes.",
10955
- icon: "\u{1D4CD}",
10956
- configSchema: [
10957
- { type: "text", key: "name", label: "Name", required: true },
10958
- { type: "expression", key: "value", label: "Value", required: true }
10959
- ]
10960
- },
10961
- // ───────────── AI ─────────────
10962
- {
10963
- name: "@particle-academy/llm_call",
10964
- // LlmClient::complete() -> array{text:string,data?:mixed,usage?:array,raw?:mixed}
10965
- //
10966
- // A FUNCTION of config, because `data` exists only when this node was asked
10967
- // for a schema. Declaring it statically would offer `{{ $json.data }}` on
10968
- // every llm_call in the kit, including the ones that emit nothing of the
10969
- // sort — and a suggestion that resolves to null at runtime is worse than no
10970
- // suggestion, since the picker is exactly what gave the author confidence.
10971
- outputShape: (config) => {
10972
- const asked = config?.response_schema != null && config.response_schema !== "" && !(Array.isArray(config.response_schema) && config.response_schema.length === 0);
10973
- return [
10974
- { path: "text", type: "string", description: "The model's completion." },
10975
- ...asked ? [{ path: "data", type: "unknown", description: "The parsed, schema-checked result." }] : [],
10976
- { path: "usage", type: "object", description: "Token counts, when the provider reports them." },
10977
- { path: "raw", type: "unknown", description: "The provider's untouched response." }
10978
- ];
10979
- },
10980
- aliases: ["llm_call", "@fancy/llm_call"],
10981
- category: "ai",
10982
- label: "LLM Call",
10983
- description: "Send a prompt + context to a model and receive a response.",
10984
- icon: "\u2726",
10985
- configSchema: [
10986
- {
10987
- type: "select",
10988
- key: "provider",
10989
- label: "Provider",
10990
- default: "anthropic",
10991
- options: [
10992
- { value: "anthropic", label: "Anthropic" },
10993
- { value: "openai", label: "OpenAI" },
10994
- { value: "custom", label: "Custom" }
10995
- ]
10996
- },
10997
- { type: "text", key: "model", label: "Model", placeholder: "claude-sonnet-4-5", required: true },
10998
- { type: "textarea", key: "system", label: "System prompt", rows: 4 },
10999
- { type: "expression", key: "prompt", label: "User prompt", example: "{{ $json.question }}", required: true },
11000
- { type: "number", key: "temperature", label: "Temperature", min: 0, max: 2, step: 0.1, default: 0.7 },
11001
- { type: "number", key: "max_tokens", label: "Max tokens", min: 1, max: 8192, default: 1024 },
11002
- {
11003
- type: "repeater",
11004
- key: "tools",
11005
- label: "Tools",
11006
- description: "Tools the model may call.",
11007
- titleKey: "name",
11008
- addLabel: "Add tool",
11009
- fields: [
11010
- { type: "text", key: "name", label: "Name", required: true, placeholder: "search_index" },
11011
- { type: "text", key: "description", label: "When to use it" },
11012
- {
11013
- type: "json",
11014
- key: "input_schema",
11015
- label: "Input schema",
11016
- description: "JSON Schema for the tool's arguments."
11017
- }
11018
- ]
11019
- },
11020
- {
11021
- type: "json",
11022
- key: "response_schema",
11023
- label: "Response schema",
11024
- description: "Optional JSON Schema. When set, the runtime asks the provider for schema-valid JSON and the node emits the parsed value as `data` \u2014 reference it as {{ $json.data }}. A response that cannot be parsed or does not match FAILS the node rather than passing an empty value downstream."
11025
- },
11026
- { type: "credential", key: "credential", label: "API credential", credentialType: "llm_credential" }
11027
- ]
11028
- },
11029
- {
11030
- name: "@particle-academy/llm_router",
11031
- outputShape: [
11032
- { path: "route", type: "string", description: "The port the model chose." },
11033
- { path: "reason", type: "string", description: "Why the model chose it." },
11034
- { path: "input", type: "unknown", description: "The value that arrived, carried forward." }
11035
- ],
11036
- // Every id this node has ever shipped under keeps resolving — MOIC's saved
11037
- // flows carry the bare `llm_branch`.
11038
- aliases: ["llm_router", "llm_branch", "@fancy/llm_branch", "@fancy/llm_router"],
11039
- category: "ai",
11040
- label: "LLM Router",
11041
- description: "Let a model choose which route the flow takes.",
11042
- icon: "\u2727",
11043
- inputs: [{ id: "in" }],
11044
- // Each declared route is a port. The executor returns `{ __port: id }`
11045
- // (or `Port.only(id)` on the PHP runtime) to pick one.
11046
- outputs: (config) => routePorts(config?.routes, config?.fallback),
11047
- // A shuttle, not an engine: it carries the routes out to whatever LLM
11048
- // client the host registered and carries the choice back. No provider SDK
11049
- // reaches core, so this stays a builtin without adding a dependency.
11050
- executor: llmRouterExecutor,
11051
- configSchema: [
11052
- {
11053
- type: "textarea",
11054
- key: "system",
11055
- label: "System prompt",
11056
- rows: 3,
11057
- description: "Optional framing for the routing decision."
11058
- },
11059
- {
11060
- type: "expression",
11061
- key: "prompt",
11062
- label: "What to route on",
11063
- example: "{{ $json.message }}",
11064
- required: true
11065
- },
11066
- {
11067
- type: "repeater",
11068
- key: "routes",
11069
- label: "Routes",
11070
- description: "The model picks exactly one. Descriptions are what it chooses between \u2014 make them distinct.",
11071
- titleKey: "port",
11072
- addLabel: "Add route",
11073
- minItems: 2,
11074
- fields: [
11075
- { type: "text", key: "port", label: "Port", required: true, placeholder: "billing" },
11076
- {
11077
- type: "text",
11078
- key: "description",
11079
- label: "When to choose it",
11080
- required: true,
11081
- placeholder: "The user is asking about an invoice, refund, or payment."
11082
- }
11083
- ],
11084
- default: [
11085
- { port: "a", description: "Describe when the model should pick this route." },
11086
- { port: "b", description: "Describe when the model should pick this route." }
11087
- ]
11088
- },
11089
- {
11090
- type: "select",
11091
- key: "provider",
11092
- label: "Provider",
11093
- default: "anthropic",
11094
- options: [
11095
- { value: "anthropic", label: "Anthropic" },
11096
- { value: "openai", label: "OpenAI" },
11097
- { value: "custom", label: "Custom" }
11098
- ]
11099
- },
11100
- { type: "text", key: "model", label: "Model", placeholder: "claude-sonnet-4-5" },
11101
- {
11102
- type: "switch",
11103
- key: "fallback",
11104
- label: "Add a `fallback` port",
11105
- default: true,
11106
- description: "Where the flow goes if the model returns no usable route."
11107
- },
11108
- { type: "credential", key: "credential", label: "API credential", credentialType: "llm_credential" }
11109
- ]
11110
- },
11111
- {
11112
- name: "@particle-academy/tool_use",
11113
- aliases: ["tool_use", "@fancy/tool_use"],
11114
- category: "ai",
11115
- label: "Tool Use",
11116
- description: "Hand control to a host-registered tool by name.",
11117
- icon: "\u{1F6E0}",
11118
- configSchema: [
11119
- { type: "text", key: "tool", label: "Tool name", placeholder: "search_index", required: true },
11120
- { type: "expression", key: "args", label: "Arguments", example: "{{ { query: $json.q } }}" }
11121
- ]
11122
- },
11123
- {
11124
- name: "@particle-academy/embed_search",
11125
- outputShape: [
11126
- { path: "query", type: "string" },
11127
- { path: "matches", type: "array", description: "Ranked results from the vector store." }
11128
- ],
11129
- aliases: ["embed_search", "@fancy/embed_search"],
11130
- category: "ai",
11131
- label: "Embed & Search",
11132
- description: "Embed a query and search a vector store.",
11133
- icon: "\u273A",
11134
- configSchema: [
11135
- { type: "expression", key: "query", label: "Query", required: true, example: "{{ $json.question }}" },
11136
- { type: "number", key: "topK", label: "Top K", default: 5, min: 1, max: 50 },
11137
- { type: "credential", key: "vectorStore", label: "Vector store", credentialType: "vector_store" }
11138
- ]
11139
- },
11140
- // ───────────── IO ─────────────
11141
- {
11142
- name: "@particle-academy/api_request",
11143
- // HttpClient::send() -> array{status:int,headers:array,body:mixed}
11144
- outputShape: [
11145
- { path: "status", type: "number", description: "HTTP status code." },
11146
- { path: "headers", type: "object" },
11147
- { path: "body", type: "unknown", description: "Decoded JSON when the response is JSON, otherwise the raw body." }
11148
- ],
11149
- aliases: ["api_request", "@fancy/api_request"],
11150
- category: "io",
11151
- label: "API Request",
11152
- description: "HTTP request to any URL.",
11153
- icon: "\u2194",
11154
- configSchema: [
11155
- ...HTTP_METHODS,
11156
- { type: "text", key: "url", label: "URL", placeholder: "https://api.example.com/...", required: true },
11157
- {
11158
- type: "keyvalue",
11159
- key: "headers",
11160
- label: "Headers",
11161
- keyLabel: "Header",
11162
- valueLabel: "Value",
11163
- keyPlaceholder: "content-type",
11164
- valuePlaceholder: "application/json",
11165
- addLabel: "Add header",
11166
- default: { "content-type": "application/json" }
11167
- },
11168
- { type: "json", key: "body", label: "Body" },
11169
- { type: "credential", key: "auth", label: "Auth", credentialType: "api_credential" }
11170
- ]
11171
- },
11172
- {
11173
- name: "@particle-academy/webhook_out",
11174
- outputShape: [
11175
- { path: "sent", type: "boolean", description: "True once the request was made." },
11176
- { path: "status", type: "number", description: "HTTP status, when the transport reported one." },
11177
- { path: "response", type: "unknown", description: "The response body, when there was one." }
11178
- ],
11179
- aliases: ["webhook_out", "@fancy/webhook_out"],
11180
- category: "io",
11181
- label: "Send Webhook",
11182
- description: "POST a payload to a configured URL.",
11183
- icon: "\u2197",
11184
- configSchema: [
11185
- { type: "text", key: "url", label: "URL", required: true },
11186
- {
11187
- type: "keyvalue",
11188
- key: "headers",
11189
- label: "Headers",
11190
- keyLabel: "Header",
11191
- valueLabel: "Value",
11192
- addLabel: "Add header"
11193
- },
11194
- { type: "expression", key: "payload", label: "Payload", required: true, example: "{{ $json }}" }
11195
- ]
11196
- },
11197
- // ───────────── Human ─────────────
11198
- {
11199
- name: "@particle-academy/human_approval",
11200
- // returns its input on approved/denied
11201
- emits: "input",
11202
- aliases: ["human_approval", "@fancy/human_approval"],
11203
- pausesForHuman: "approval",
11204
- category: "human",
11205
- label: "Human Approval",
11206
- description: "Pause until a human approves or denies.",
11207
- icon: "\u2713",
11208
- inputs: [{ id: "in" }],
11209
- outputs: [{ id: "approved", label: "approved" }, { id: "denied", label: "denied" }],
11210
- configSchema: [
11211
- { type: "text", key: "title", label: "Approval title", default: "Approve action" },
11212
- { type: "textarea", key: "description", label: "Description for approver", rows: 3 },
11213
- { type: "credential", key: "channel", label: "Notify channel", credentialType: "notify_channel" }
11214
- ]
11215
- },
11216
- {
11217
- name: "@particle-academy/notify",
11218
- outputShape: [
11219
- { path: "sent", type: "boolean", description: "True once the message was handed to the channel." },
11220
- { path: "channel", type: "string", description: "The channel it went to." },
11221
- { path: "to", type: "string", description: "The recipient." },
11222
- { path: "message", type: "string", description: "The rendered message." }
11223
- ],
11224
- aliases: ["notify", "@fancy/notify"],
11225
- category: "human",
11226
- label: "Notify",
11227
- description: "Send a message via Slack / email / SMS / etc.",
11228
- icon: "\u{1F514}",
11229
- configSchema: [
11230
- {
11231
- type: "select",
11232
- key: "channel",
11233
- label: "Channel",
11234
- default: "slack",
11235
- options: [
11236
- { value: "slack", label: "Slack" },
11237
- { value: "email", label: "Email" },
11238
- { value: "sms", label: "SMS" },
11239
- { value: "discord", label: "Discord" }
11240
- ]
11241
- },
11242
- { type: "text", key: "to", label: "To", required: true },
11243
- { type: "expression", key: "message", label: "Message", required: true, example: "{{ $json.summary }}" }
11244
- ]
11245
- },
11246
- // ───────────── Output ─────────────
11247
- {
11248
- name: "@particle-academy/output",
11249
- // returns its input unchanged
11250
- emits: "input",
11251
- aliases: ["output", "@fancy/output"],
11252
- category: "output",
11253
- label: "Output",
11254
- description: "Terminal node \u2014 captures the workflow's result.",
11255
- icon: "\u25CF",
11256
- inputs: [{ id: "in" }],
11257
- outputs: []
11258
- },
11259
- {
11260
- name: "@particle-academy/log",
11261
- outputShape: [
11262
- { path: "logged", type: "string", description: "The message that was written." },
11263
- { path: "level", type: "string", description: "The level it was written at." }
11264
- ],
11265
- aliases: ["log", "@fancy/log"],
11266
- category: "output",
11267
- label: "Log",
11268
- description: "Send to the run feed.",
11269
- icon: "\u2261",
11270
- inputs: [{ id: "in" }],
11271
- outputs: [],
11272
- configSchema: [
11273
- {
11274
- type: "select",
11275
- key: "level",
11276
- label: "Level",
11277
- default: "info",
11278
- options: [{ value: "info", label: "info" }, { value: "warn", label: "warn" }, { value: "error", label: "error" }]
11279
- },
11280
- { type: "expression", key: "message", label: "Message", required: true, example: "{{ $json }}" }
11281
- ]
11282
- },
11283
- {
11284
- // Swimlane — a portless, resizable container. Child nodes are parented into
11285
- // it; it never runs (the runtime skips the `layout` category). Uses its own
11286
- // renderer (LaneNode) instead of the default card.
11287
- name: "@particle-academy/lane",
11288
- aliases: ["lane", "@fancy/lane"],
11289
- category: "layout",
11290
- label: "Lane",
11291
- description: "A resizable swimlane \u2014 drop nodes into it to group them.",
11292
- icon: "\u25A4",
11293
- inputs: [],
11294
- outputs: [],
11295
- configSchema: [
11296
- { type: "text", key: "title", label: "Title", default: "Lane" },
11297
- {
11298
- type: "select",
11299
- key: "orientation",
11300
- label: "Orientation",
11301
- default: "horizontal",
11302
- options: [{ value: "horizontal", label: "Row" }, { value: "vertical", label: "Column" }]
11303
- }
11304
- ],
11305
- defaultConfig: { title: "Lane", orientation: "horizontal" },
11306
- resizable: { minWidth: 160, minHeight: 72 },
11307
- component: LaneNode
11308
- },
11309
- {
11310
- // Terminal lane — a lane that OWNS a terminal for the length of the run.
11311
- //
11312
- // Visually a swimlane, and `layout` for the same reason the plain lane is:
11313
- // a lane is not a step, so it never executes and never appears in topo
11314
- // order. What is new is that it DECLARES a resource. The runtime opens its
11315
- // terminal lazily, when the first terminal node inside it runs, and closes
11316
- // it in the run's `finally` — so a graph that never reaches a terminal node
11317
- // never spawns a process, and one that does gets exactly one session no
11318
- // matter how many nodes use it.
11319
- //
11320
- // Membership is `parentId`, which already persists into the WorkflowSchema.
11321
- // That is what lets a headless runtime resolve the same grouping the canvas
11322
- // shows, without a second association to keep in sync.
11323
- name: "@particle-academy/terminal_lane",
11324
- aliases: ["terminal_lane", "@fancy/terminal_lane"],
11325
- category: "layout",
11326
- label: "Terminal lane",
11327
- description: "A lane that owns one terminal. Opens at the first terminal node, closes when the run ends.",
11328
- icon: "\u25A3",
11329
- inputs: [],
11330
- outputs: [],
11331
- configSchema: [
11332
- { type: "text", key: "title", label: "Title", default: "Terminal" },
11333
- {
11334
- type: "text",
11335
- key: "command",
11336
- label: "Command",
11337
- placeholder: "Leave empty for the default shell"
11338
- },
11339
- { type: "text", key: "cwd", label: "Working directory", placeholder: "Host default" },
11340
- { type: "keyvalue", key: "env", label: "Environment" },
11341
- {
11342
- type: "select",
11343
- key: "orientation",
11344
- label: "Orientation",
11345
- default: "horizontal",
11346
- options: [
11347
- { value: "horizontal", label: "Row" },
11348
- { value: "vertical", label: "Column" }
11349
- ]
11350
- }
11351
- ],
11352
- defaultConfig: { title: "Terminal", orientation: "horizontal" },
11353
- resizable: { minWidth: 220, minHeight: 120 },
11354
- component: LaneNode
11355
- },
11356
- {
11357
- // Terminal nodes. All three live inside a terminal lane and talk to the
11358
- // session that lane owns; outside one they abort by name rather than
11359
- // opening a shell of their own.
11360
- name: "@particle-academy/terminal_run",
11361
- aliases: ["terminal_run", "@fancy/terminal_run"],
11362
- category: "io",
11363
- label: "Run in terminal",
11364
- description: "Run a shell command in the lane's terminal and wait for its exit code.",
11365
- icon: "$",
11366
- inputs: [{ id: "in" }],
11367
- outputs: [{ id: "out", label: "output" }],
11368
- executor: terminalRunExecutor,
11369
- configSchema: [
11370
- {
11371
- type: "textarea",
11372
- key: "command",
11373
- label: "Command",
11374
- rows: 3,
11375
- required: true,
11376
- placeholder: "npm test",
11377
- description: "Runs in the lane's shell, so `cd` and exported variables persist between nodes. SHELL ONLY \u2014 a TUI never returns to a prompt, so use Send + Await for one."
11378
- },
11379
- {
11380
- type: "number",
11381
- key: "timeoutMs",
11382
- label: "Timeout (ms)",
11383
- default: 12e4,
11384
- description: "How long to wait for the command to finish before failing the run."
11385
- },
11386
- {
11387
- type: "switch",
11388
- key: "failOnNonZero",
11389
- label: "Fail the run on a non-zero exit",
11390
- default: true,
11391
- description: "On by default. Turning it off means a failed command lets the run report success \u2014 read the exit code on the output port and branch on it instead."
11392
- }
11393
- ],
11394
- defaultConfig: { command: "", timeoutMs: 12e4, failOnNonZero: true }
11395
- },
11396
- {
11397
- name: "@particle-academy/terminal_send",
11398
- aliases: ["terminal_send", "@fancy/terminal_send"],
11399
- category: "io",
11400
- label: "Send to terminal",
11401
- description: "Type text at whatever is running in the lane's terminal, without waiting.",
11402
- icon: "\u2328",
11403
- inputs: [{ id: "in" }],
11404
- outputs: [{ id: "out", label: "sent" }],
11405
- executor: terminalSendExecutor,
11406
- configSchema: [
11407
- {
11408
- type: "textarea",
11409
- key: "text",
11410
- label: "Text",
11411
- rows: 4,
11412
- placeholder: "Summarise the failing test and propose a fix.",
11413
- description: "What to type. This is how a graph prompts an agent TUI such as Claude Code or Codex."
11414
- },
11415
- {
11416
- type: "switch",
11417
- key: "submit",
11418
- label: "Press Enter",
11419
- default: true,
11420
- description: "Off leaves the text on the input line \u2014 useful for building one up across several nodes."
11421
- },
11422
- {
11423
- type: "switch",
11424
- key: "clearFirst",
11425
- label: "Forget earlier output first",
11426
- default: false,
11427
- description: "Discards anything the terminal said before this send, so a following Await cannot match a prompt left over from the previous exchange."
11428
- }
11429
- ],
11430
- defaultConfig: { text: "", submit: true, clearFirst: false }
11431
- },
11432
- {
11433
- name: "@particle-academy/terminal_await",
11434
- aliases: ["terminal_await", "@fancy/terminal_await"],
11435
- category: "io",
11436
- label: "Await terminal output",
11437
- description: "Wait until the lane's terminal prints something that matches.",
11438
- icon: "\u23F1",
11439
- inputs: [{ id: "in" }],
11440
- outputs: [{ id: "out", label: "output" }],
11441
- executor: terminalAwaitExecutor,
11442
- configSchema: [
11443
- {
11444
- type: "text",
11445
- key: "pattern",
11446
- label: "Wait for",
11447
- required: true,
11448
- placeholder: "esc to interrupt",
11449
- description: "Matched against the output with colour codes already stripped, so match what you SEE."
11450
- },
11451
- {
11452
- type: "select",
11453
- key: "mode",
11454
- label: "Match as",
11455
- default: "text",
11456
- options: [
11457
- { value: "text", label: "Plain text" },
11458
- { value: "regex", label: "Regular expression" }
11459
- ],
11460
- description: "Regex mode also returns capture groups, which is how a value gets out of a prompt."
11461
- },
11462
- {
11463
- type: "number",
11464
- key: "timeoutMs",
11465
- label: "Timeout (ms)",
11466
- default: 12e4
11467
- },
11468
- {
11469
- type: "select",
11470
- key: "onTimeout",
11471
- label: "If it never appears",
11472
- default: "fail",
11473
- options: [
11474
- { value: "fail", label: "Fail the run" },
11475
- { value: "continue", label: "Continue with matched: false" }
11476
- ],
11477
- description: "Failing is the default. Continuing lets the next node type at a process that never became ready while the run still reports success, so it has to be asked for."
11478
- }
11479
- ],
11480
- defaultConfig: { pattern: "", mode: "text", timeoutMs: 12e4, onTimeout: "fail" }
11481
- },
11482
- {
11483
- // Note — a sticky-note annotation. Portless + visual-only: the runtime skips
11484
- // the `annotation` category, so a note's text NEVER reaches a runner — it
11485
- // rides in the document purely for people, editors, and MCP tools. Uses its
11486
- // own renderer (NoteNode); double-click on the canvas to edit in place.
11487
- name: "@particle-academy/note",
11488
- aliases: ["note", "@fancy/note"],
11489
- category: "annotation",
11490
- label: "Note",
11491
- description: "A sticky note that documents the canvas. Never runs \u2014 editor + agent only.",
11492
- icon: "\u{1F5D2}",
11493
- inputs: [],
11494
- outputs: [],
11495
- configSchema: [
11496
- { type: "text", key: "title", label: "Title", placeholder: "Optional heading" },
11497
- { type: "textarea", key: "text", label: "Note", rows: 5, placeholder: "What does this part of the flow do?" },
11498
- { type: "select", key: "color", label: "Color", default: "amber", options: [
11499
- { value: "amber", label: "Amber" },
11500
- { value: "sky", label: "Sky" },
11501
- { value: "violet", label: "Violet" },
11502
- { value: "emerald", label: "Emerald" },
11503
- { value: "rose", label: "Rose" },
11504
- { value: "slate", label: "Slate" }
11505
- ] }
11506
- ],
11507
- defaultConfig: { text: "", color: "amber" },
11508
- resizable: { minWidth: 140, minHeight: 80 },
11509
- component: NoteNode
11510
- }
11511
- ];
11512
- function registerBuiltinKinds() {
11513
- for (const k of KINDS) registerNodeKind(k);
11514
- }
11515
- var BUILTIN_KINDS = KINDS;
11516
-
11517
- // src/registry/registry.ts
11518
- var kinds = /* @__PURE__ */ new Map();
11519
- var aliases = /* @__PURE__ */ new Map();
11520
- var listeners = /* @__PURE__ */ new Set();
11521
- var overrides = /* @__PURE__ */ new Map();
11522
- var builtinsEnsured = false;
11523
- function ensureBuiltinKinds() {
11524
- if (builtinsEnsured) return;
11525
- builtinsEnsured = true;
11526
- registerBuiltinKinds();
11527
- }
11528
- function registerNodeKind(definition) {
11529
- ensureBuiltinKinds();
11530
- kinds.set(definition.name, definition);
11531
- for (const alias of definition.aliases ?? []) aliases.set(alias, definition.name);
11532
- notify();
11533
- return () => {
11534
- if (kinds.get(definition.name) === definition) {
11535
- kinds.delete(definition.name);
11536
- for (const alias of definition.aliases ?? []) {
11537
- if (aliases.get(alias) === definition.name) aliases.delete(alias);
11538
- }
11539
- notify();
11540
- }
11541
- };
11542
- }
11543
- function resolveKindId(id2) {
11544
- ensureBuiltinKinds();
11545
- if (kinds.has(id2)) return id2;
11546
- const canonical = aliases.get(id2);
11547
- return canonical && kinds.has(canonical) ? canonical : null;
11548
- }
11549
- function overrideNodeKind(name, patch) {
11550
- const canonical = resolveKindId(name) ?? name;
11551
- const previous = overrides.get(canonical);
11552
- overrides.set(canonical, { ...previous, ...patch });
11553
- notify();
11554
- return () => {
11555
- if (previous) {
11556
- overrides.set(canonical, previous);
11557
- } else {
11558
- overrides.delete(canonical);
11559
- }
11560
- notify();
11561
- };
11562
- }
11563
- function clearNodeKindOverrides() {
11564
- if (overrides.size === 0) return;
11565
- overrides.clear();
11566
- notify();
11567
- }
11568
- function withOverride(kind) {
11569
- if (!kind) return null;
11570
- const patch = overrides.get(kind.name);
11571
- return patch ? { ...kind, ...patch } : kind;
11572
- }
11573
- function getNodeKind(name) {
11574
- const canonical = resolveKindId(name);
11575
- return canonical ? withOverride(kinds.get(canonical)) : null;
11576
- }
11577
- function kindIds(kind) {
11578
- return [kind.name, ...kind.aliases ?? []];
11579
- }
11580
- function listNodeKinds(category) {
11581
- ensureBuiltinKinds();
11582
- const all = Array.from(kinds.values()).map(
11583
- (k) => withOverride(k)
11584
- );
11585
- return category ? all.filter((k) => k.category === category) : all;
11586
- }
11587
- function onNodeKindsChanged(listener) {
11588
- listeners.add(listener);
11589
- return () => listeners.delete(listener);
11590
- }
11591
- function notify() {
11592
- for (const l of listeners) l();
11593
- }
11594
- function defaultConfigFor(kind) {
11595
- const fromKind = kind.defaultConfig ? { ...kind.defaultConfig } : {};
11596
- for (const field of kind.configSchema ?? []) {
11597
- if (fromKind[field.key] !== void 0) continue;
11598
- if ("default" in field && field.default !== void 0) {
11599
- fromKind[field.key] = field.default;
11600
- }
11601
- }
11602
- return fromKind;
11603
- }
11604
- function validateConfig(kind, config) {
11605
- const issues = [];
11606
- for (const field of kind.configSchema ?? []) {
11607
- const value = config[field.key];
11608
- if (field.required && (value === void 0 || value === null || value === "")) {
11609
- issues.push({ key: field.key, message: `${field.label} is required` });
11610
- continue;
11611
- }
11612
- if (value === void 0 || value === null) continue;
11613
- const issue = validateField(field, value);
11614
- if (issue) issues.push({ key: field.key, message: issue });
11615
- }
11616
- return issues;
11617
- }
11618
- function validateField(field, value) {
11619
- switch (field.type) {
11620
- case "text":
11621
- case "textarea":
11622
- case "expression":
11623
- case "credential":
11624
- return typeof value === "string" ? null : `${field.label} must be a string`;
11625
- case "number": {
11626
- if (typeof value !== "number" || !Number.isFinite(value)) return `${field.label} must be a number`;
11627
- if (field.min !== void 0 && value < field.min) return `${field.label} must be >= ${field.min}`;
11628
- if (field.max !== void 0 && value > field.max) return `${field.label} must be <= ${field.max}`;
11629
- return null;
11630
- }
11631
- case "switch":
11632
- return typeof value === "boolean" ? null : `${field.label} must be a boolean`;
11633
- case "select": {
11634
- const allowed = field.options.map((o) => o.value);
11635
- return allowed.includes(String(value)) ? null : `${field.label} must be one of ${allowed.join(", ")}`;
11636
- }
11637
- case "json":
11638
- return null;
11639
- // permissive — just JSON-shaped
11640
- case "repeater": {
11641
- if (!Array.isArray(value)) return `${field.label} must be a list`;
11642
- if (field.minItems !== void 0 && value.length < field.minItems) {
11643
- return `${field.label} needs at least ${field.minItems}`;
11644
- }
11645
- if (field.maxItems !== void 0 && value.length > field.maxItems) {
11646
- return `${field.label} allows at most ${field.maxItems}`;
11647
- }
11648
- for (let i = 0; i < value.length; i++) {
11649
- const row = value[i];
11650
- if (!row || typeof row !== "object" || Array.isArray(row)) {
11651
- return `${field.label} item ${i + 1} must be an object`;
11652
- }
11653
- for (const sub of field.fields) {
11654
- const cell = row[sub.key];
11655
- if (sub.required && (cell === void 0 || cell === null || cell === "")) {
11656
- return `${field.label} item ${i + 1}: ${sub.label} is required`;
11657
- }
11658
- if (cell === void 0 || cell === null) continue;
11659
- const issue = validateField(sub, cell);
11660
- if (issue) return `${field.label} item ${i + 1}: ${issue}`;
11661
- }
11662
- }
11663
- return null;
11664
- }
11665
- case "keyvalue": {
11666
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
11667
- return `${field.label} must be a key/value map`;
11668
- }
11669
- const allowed = field.valueOptions?.map((o) => o.value);
11670
- for (const [k, v] of Object.entries(value)) {
11671
- if (typeof v !== "string") return `${field.label}: "${k}" must be a string`;
11672
- if (allowed && !allowed.includes(v)) {
11673
- return `${field.label}: "${k}" must be one of ${allowed.join(", ")}`;
11674
- }
11675
- }
11676
- return null;
11677
- }
11678
- case "document":
11679
- return null;
11680
- // opaque to fancy-flow — the host's editor owns its shape
11681
- default:
11682
- return null;
11683
- }
11684
- }
11685
- function categoryAccent(category) {
11686
- switch (category) {
11687
- case "trigger":
11688
- return "#10b981";
11689
- case "logic":
11690
- return "#f59e0b";
11691
- case "data":
11692
- return "#0ea5e9";
11693
- case "ai":
11694
- return "#8b5cf6";
11695
- case "io":
11696
- return "#3b82f6";
11697
- case "human":
11698
- return "#ec4899";
11699
- case "output":
11700
- return "#a855f7";
11701
- case "layout":
11702
- return "#64748b";
11703
- case "annotation":
11704
- return "#eab308";
11705
- default:
11706
- return "#71717a";
11707
- }
11708
- }
11709
- function LaneNodeInner(props) {
11710
- const data = props.data;
11711
- const config = data.config ?? {};
11712
- const title = config.title ?? data.label ?? "Lane";
11713
- const orientation = config.orientation ?? "horizontal";
11714
- const accent = config.color ?? data.color ?? categoryAccent("layout");
11715
- return /* @__PURE__ */ jsxs(
11716
- "div",
11717
- {
11718
- className: ["ff-lane", `ff-lane--${orientation}`, props.selected ? "ff-lane--selected" : ""].filter(Boolean).join(" "),
11719
- style: { borderColor: props.selected ? accent : void 0 },
11720
- children: [
11721
- /* @__PURE__ */ jsx(NodeResizer, { isVisible: props.selected ?? false, color: accent, minWidth: 160, minHeight: 72 }),
11722
- /* @__PURE__ */ jsx("div", { className: "ff-lane__header", style: { background: accent }, children: /* @__PURE__ */ jsx("span", { className: "ff-lane__title", children: title }) })
11723
- ]
11724
- }
11725
- );
11726
- }
11727
- var LaneNode = memo(LaneNodeInner);
11728
-
11729
- export { BUILTIN_KINDS, Background, BackgroundVariant, Controls, DEFAULT_MAX_DEPTH, FlowEditorProvider, Handle, LaneNode, MiniMap, NodeResizer, NodeToolbar, NoteNode, Position, ReactFlowProvider, RunIdentity, UnresolvedPathError, ViewportPortal, addEdge2 as addEdge, applyEdgeChanges, applyNodeChanges, categoryAccent, clearNodeKindOverrides, declaredRoutes, defaultConfigFor, ensureBuiltinKinds, escapeSegment, evaluateConfig, evaluateExpression, getNodeKind, humanInputFields, index, kindIds, listNodeKinds, llmRouterExecutor, nodeConfig, onNodeKindsChanged, overrideNodeKind, reconnectEdge2 as reconnectEdge, registerBuiltinKinds, registerNodeKind, resolveFallbackPort, resolveKindId, resolveNodePorts, resolvePath, resolvePortSpec, runFlow, subflowExecutor, subflowMode, subflowPorts, text, truthy, tryResolvePath, useFlowEditor, useFlowEditorOptional, useReactFlow, validateConfig };
11730
- //# sourceMappingURL=chunk-HQGOFGAL.js.map
11731
- //# sourceMappingURL=chunk-HQGOFGAL.js.map
9039
+ export { Background, BackgroundVariant, Controls, Handle, MiniMap, NodeResizer, NodeToolbar, Position, ReactFlowProvider, ViewportPortal, addEdge2 as addEdge, applyEdgeChanges, applyNodeChanges, index, reconnectEdge2 as reconnectEdge, useReactFlow };
9040
+ //# sourceMappingURL=chunk-OWENS2H5.js.map
9041
+ //# sourceMappingURL=chunk-OWENS2H5.js.map