@xyne/workflow-sdk 3.2.40 → 3.2.42

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 (240) hide show
  1. package/README.md +1 -0
  2. package/dist/agents/agent-step.d.ts.map +1 -1
  3. package/dist/agents/agent-step.js +8 -5
  4. package/dist/agents/agent-step.js.map +1 -1
  5. package/dist/agents/contract.d.ts +21 -4
  6. package/dist/agents/contract.d.ts.map +1 -1
  7. package/dist/agents/contract.js +95 -5
  8. package/dist/agents/contract.js.map +1 -1
  9. package/dist/agents/host-agent-step.d.ts +20 -4
  10. package/dist/agents/host-agent-step.d.ts.map +1 -1
  11. package/dist/agents/host-agent-step.js +77 -18
  12. package/dist/agents/host-agent-step.js.map +1 -1
  13. package/dist/agents/provider.d.ts +17 -0
  14. package/dist/agents/provider.d.ts.map +1 -1
  15. package/dist/agents/provider.js.map +1 -1
  16. package/dist/client/index.d.ts +3 -1
  17. package/dist/client/index.d.ts.map +1 -1
  18. package/dist/client/types.d.ts +50 -0
  19. package/dist/client/types.d.ts.map +1 -1
  20. package/dist/client/workflow-client.d.ts.map +1 -1
  21. package/dist/client/workflow-client.js +48 -0
  22. package/dist/client/workflow-client.js.map +1 -1
  23. package/dist/common/expression-eval.d.ts +35 -0
  24. package/dist/common/expression-eval.d.ts.map +1 -0
  25. package/dist/common/expression-eval.js +214 -0
  26. package/dist/common/expression-eval.js.map +1 -0
  27. package/dist/common/principal.d.ts +45 -0
  28. package/dist/common/principal.d.ts.map +1 -0
  29. package/dist/common/principal.js +9 -0
  30. package/dist/common/principal.js.map +1 -0
  31. package/dist/connectors/builtin/builtin-connector.d.ts.map +1 -1
  32. package/dist/connectors/builtin/builtin-connector.js +5 -0
  33. package/dist/connectors/builtin/builtin-connector.js.map +1 -1
  34. package/dist/connectors/builtin/steps/cycle.step.d.ts +126 -0
  35. package/dist/connectors/builtin/steps/cycle.step.d.ts.map +1 -0
  36. package/dist/connectors/builtin/steps/cycle.step.js +144 -0
  37. package/dist/connectors/builtin/steps/cycle.step.js.map +1 -0
  38. package/dist/connectors/builtin/steps/jump.step.d.ts +64 -0
  39. package/dist/connectors/builtin/steps/jump.step.d.ts.map +1 -0
  40. package/dist/connectors/builtin/steps/jump.step.js +57 -0
  41. package/dist/connectors/builtin/steps/jump.step.js.map +1 -0
  42. package/dist/connectors/builtin/steps/loop.step.d.ts +5 -0
  43. package/dist/connectors/builtin/steps/loop.step.d.ts.map +1 -1
  44. package/dist/connectors/builtin/steps/loop.step.js +16 -0
  45. package/dist/connectors/builtin/steps/loop.step.js.map +1 -1
  46. package/dist/connectors/builtin/steps/map.step.d.ts +6 -0
  47. package/dist/connectors/builtin/steps/map.step.d.ts.map +1 -1
  48. package/dist/connectors/builtin/steps/map.step.js +21 -0
  49. package/dist/connectors/builtin/steps/map.step.js.map +1 -1
  50. package/dist/connectors/builtin/steps/parallel.step.d.ts +7 -0
  51. package/dist/connectors/builtin/steps/parallel.step.d.ts.map +1 -1
  52. package/dist/connectors/builtin/steps/parallel.step.js +19 -1
  53. package/dist/connectors/builtin/steps/parallel.step.js.map +1 -1
  54. package/dist/connectors/builtin/steps/repeat.step.d.ts +126 -0
  55. package/dist/connectors/builtin/steps/repeat.step.d.ts.map +1 -0
  56. package/dist/connectors/builtin/steps/repeat.step.js +144 -0
  57. package/dist/connectors/builtin/steps/repeat.step.js.map +1 -0
  58. package/dist/conversational-flow/create.d.ts +31 -0
  59. package/dist/conversational-flow/create.d.ts.map +1 -0
  60. package/dist/conversational-flow/create.js +94 -0
  61. package/dist/conversational-flow/create.js.map +1 -0
  62. package/dist/conversational-flow/edit.d.ts +98 -0
  63. package/dist/conversational-flow/edit.d.ts.map +1 -0
  64. package/dist/conversational-flow/edit.js +814 -0
  65. package/dist/conversational-flow/edit.js.map +1 -0
  66. package/dist/conversational-flow/index.d.ts +17 -0
  67. package/dist/conversational-flow/index.d.ts.map +1 -0
  68. package/dist/conversational-flow/index.js +7 -0
  69. package/dist/conversational-flow/index.js.map +1 -0
  70. package/dist/conversational-flow/read.d.ts +22 -0
  71. package/dist/conversational-flow/read.d.ts.map +1 -0
  72. package/dist/conversational-flow/read.js +418 -0
  73. package/dist/conversational-flow/read.js.map +1 -0
  74. package/dist/conversational-flow/server/conversation-service.d.ts +70 -0
  75. package/dist/conversational-flow/server/conversation-service.d.ts.map +1 -0
  76. package/dist/conversational-flow/server/conversation-service.js +181 -0
  77. package/dist/conversational-flow/server/conversation-service.js.map +1 -0
  78. package/dist/conversational-flow/server/routes.d.ts +16 -0
  79. package/dist/conversational-flow/server/routes.d.ts.map +1 -0
  80. package/dist/conversational-flow/server/routes.js +140 -0
  81. package/dist/conversational-flow/server/routes.js.map +1 -0
  82. package/dist/conversational-flow/tree.d.ts +11 -0
  83. package/dist/conversational-flow/tree.d.ts.map +1 -0
  84. package/dist/conversational-flow/tree.js +39 -0
  85. package/dist/conversational-flow/tree.js.map +1 -0
  86. package/dist/conversational-flow/turn.d.ts +184 -0
  87. package/dist/conversational-flow/turn.d.ts.map +1 -0
  88. package/dist/conversational-flow/turn.js +408 -0
  89. package/dist/conversational-flow/turn.js.map +1 -0
  90. package/dist/conversational-flow/types.d.ts +152 -0
  91. package/dist/conversational-flow/types.d.ts.map +1 -0
  92. package/dist/conversational-flow/types.js +22 -0
  93. package/dist/conversational-flow/types.js.map +1 -0
  94. package/dist/engine/available-context.js +11 -0
  95. package/dist/engine/available-context.js.map +1 -1
  96. package/dist/engine/branch-signal.d.ts +72 -0
  97. package/dist/engine/branch-signal.d.ts.map +1 -0
  98. package/dist/engine/branch-signal.js +42 -0
  99. package/dist/engine/branch-signal.js.map +1 -0
  100. package/dist/engine/config-validator.d.ts +7 -0
  101. package/dist/engine/config-validator.d.ts.map +1 -1
  102. package/dist/engine/config-validator.js +73 -11
  103. package/dist/engine/config-validator.js.map +1 -1
  104. package/dist/engine/workflow-executor.d.ts.map +1 -1
  105. package/dist/engine/workflow-executor.js +30 -3
  106. package/dist/engine/workflow-executor.js.map +1 -1
  107. package/dist/events/types.d.ts +2 -0
  108. package/dist/events/types.d.ts.map +1 -1
  109. package/dist/events/types.js.map +1 -1
  110. package/dist/index.d.ts +7 -1
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +3 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/ingest/start-policy.d.ts +2 -2
  115. package/dist/router/workflow-router.d.ts.map +1 -1
  116. package/dist/router/workflow-router.js +3 -0
  117. package/dist/router/workflow-router.js.map +1 -1
  118. package/dist/runtime/execution-event-bus.d.ts +38 -0
  119. package/dist/runtime/execution-event-bus.d.ts.map +1 -0
  120. package/dist/runtime/execution-event-bus.js +87 -0
  121. package/dist/runtime/execution-event-bus.js.map +1 -0
  122. package/dist/runtime/workflow-runtime.d.ts.map +1 -1
  123. package/dist/runtime/workflow-runtime.js +5 -0
  124. package/dist/runtime/workflow-runtime.js.map +1 -1
  125. package/dist/steps/base-step.d.ts +40 -3
  126. package/dist/steps/base-step.d.ts.map +1 -1
  127. package/dist/steps/base-step.js +6 -0
  128. package/dist/steps/base-step.js.map +1 -1
  129. package/dist/steps/builtin/code.step.d.ts +99 -0
  130. package/dist/steps/builtin/code.step.d.ts.map +1 -0
  131. package/dist/steps/builtin/code.step.js +152 -0
  132. package/dist/steps/builtin/code.step.js.map +1 -0
  133. package/dist/steps/builtin/conditional.step.d.ts +182 -0
  134. package/dist/steps/builtin/conditional.step.d.ts.map +1 -0
  135. package/dist/steps/builtin/conditional.step.js +82 -0
  136. package/dist/steps/builtin/conditional.step.js.map +1 -0
  137. package/dist/steps/builtin/dedup.step.d.ts +65 -0
  138. package/dist/steps/builtin/dedup.step.d.ts.map +1 -0
  139. package/dist/steps/builtin/dedup.step.js +61 -0
  140. package/dist/steps/builtin/dedup.step.js.map +1 -0
  141. package/dist/steps/builtin/http-request.step.d.ts +1020 -0
  142. package/dist/steps/builtin/http-request.step.d.ts.map +1 -0
  143. package/dist/steps/builtin/http-request.step.js +491 -0
  144. package/dist/steps/builtin/http-request.step.js.map +1 -0
  145. package/dist/steps/builtin/loop.step.d.ts +100 -0
  146. package/dist/steps/builtin/loop.step.d.ts.map +1 -0
  147. package/dist/steps/builtin/loop.step.js +73 -0
  148. package/dist/steps/builtin/loop.step.js.map +1 -0
  149. package/dist/steps/builtin/map.step.d.ts +148 -0
  150. package/dist/steps/builtin/map.step.d.ts.map +1 -0
  151. package/dist/steps/builtin/map.step.js +111 -0
  152. package/dist/steps/builtin/map.step.js.map +1 -0
  153. package/dist/steps/builtin/parallel.step.d.ts +246 -0
  154. package/dist/steps/builtin/parallel.step.d.ts.map +1 -0
  155. package/dist/steps/builtin/parallel.step.js +175 -0
  156. package/dist/steps/builtin/parallel.step.js.map +1 -0
  157. package/dist/steps/builtin/ssrf-guard.d.ts +9 -0
  158. package/dist/steps/builtin/ssrf-guard.d.ts.map +1 -0
  159. package/dist/steps/builtin/ssrf-guard.js +115 -0
  160. package/dist/steps/builtin/ssrf-guard.js.map +1 -0
  161. package/dist/steps/builtin/switch.step.d.ts +235 -0
  162. package/dist/steps/builtin/switch.step.d.ts.map +1 -0
  163. package/dist/steps/builtin/switch.step.js +101 -0
  164. package/dist/steps/builtin/switch.step.js.map +1 -0
  165. package/dist/steps/builtin/transform.step.d.ts +247 -0
  166. package/dist/steps/builtin/transform.step.d.ts.map +1 -0
  167. package/dist/steps/builtin/transform.step.js +135 -0
  168. package/dist/steps/builtin/transform.step.js.map +1 -0
  169. package/dist/steps/builtin/wait.step.d.ts +1072 -0
  170. package/dist/steps/builtin/wait.step.d.ts.map +1 -0
  171. package/dist/steps/builtin/wait.step.js +254 -0
  172. package/dist/steps/builtin/wait.step.js.map +1 -0
  173. package/dist/steps/step-descriptor.d.ts +3 -1
  174. package/dist/steps/step-descriptor.d.ts.map +1 -1
  175. package/dist/steps/step-descriptor.js +1 -1
  176. package/dist/steps/step-descriptor.js.map +1 -1
  177. package/dist/steps/step-registry.d.ts +62 -0
  178. package/dist/steps/step-registry.d.ts.map +1 -0
  179. package/dist/steps/step-registry.js +103 -0
  180. package/dist/steps/step-registry.js.map +1 -0
  181. package/dist/triggers/builtin/default-cron-trigger.d.ts +44 -0
  182. package/dist/triggers/builtin/default-cron-trigger.d.ts.map +1 -0
  183. package/dist/triggers/builtin/default-cron-trigger.js +31 -0
  184. package/dist/triggers/builtin/default-cron-trigger.js.map +1 -0
  185. package/dist/triggers/builtin/default-event-trigger.d.ts +32 -0
  186. package/dist/triggers/builtin/default-event-trigger.d.ts.map +1 -0
  187. package/dist/triggers/builtin/default-event-trigger.js +21 -0
  188. package/dist/triggers/builtin/default-event-trigger.js.map +1 -0
  189. package/dist/triggers/builtin/default-manual-trigger.d.ts +45 -0
  190. package/dist/triggers/builtin/default-manual-trigger.d.ts.map +1 -0
  191. package/dist/triggers/builtin/default-manual-trigger.js +51 -0
  192. package/dist/triggers/builtin/default-manual-trigger.js.map +1 -0
  193. package/dist/triggers/builtin/default-webhook-trigger.d.ts +72 -0
  194. package/dist/triggers/builtin/default-webhook-trigger.d.ts.map +1 -0
  195. package/dist/triggers/builtin/default-webhook-trigger.js +91 -0
  196. package/dist/triggers/builtin/default-webhook-trigger.js.map +1 -0
  197. package/dist/triggers/builtin/default-webhook-v2-trigger.d.ts +29 -0
  198. package/dist/triggers/builtin/default-webhook-v2-trigger.d.ts.map +1 -0
  199. package/dist/triggers/builtin/default-webhook-v2-trigger.js +38 -0
  200. package/dist/triggers/builtin/default-webhook-v2-trigger.js.map +1 -0
  201. package/dist/triggers/trigger-registry.d.ts +48 -0
  202. package/dist/triggers/trigger-registry.d.ts.map +1 -0
  203. package/dist/triggers/trigger-registry.js +83 -0
  204. package/dist/triggers/trigger-registry.js.map +1 -0
  205. package/dist/types/attachment.d.ts +23 -0
  206. package/dist/types/attachment.d.ts.map +1 -0
  207. package/dist/types/attachment.js +2 -0
  208. package/dist/types/attachment.js.map +1 -0
  209. package/dist/types/known-types.d.ts +6 -3
  210. package/dist/types/known-types.d.ts.map +1 -1
  211. package/dist/types/known-types.js +5 -0
  212. package/dist/types/known-types.js.map +1 -1
  213. package/dist/types/resume-payload.d.ts +34 -0
  214. package/dist/types/resume-payload.d.ts.map +1 -0
  215. package/dist/types/resume-payload.js +12 -0
  216. package/dist/types/resume-payload.js.map +1 -0
  217. package/dist/types/validation.d.ts +2 -1
  218. package/dist/types/validation.d.ts.map +1 -1
  219. package/dist/types/validation.js +1 -0
  220. package/dist/types/validation.js.map +1 -1
  221. package/dist/util/executable-check.d.ts +42 -0
  222. package/dist/util/executable-check.d.ts.map +1 -0
  223. package/dist/util/executable-check.js +115 -0
  224. package/dist/util/executable-check.js.map +1 -0
  225. package/dist/util/schema-marks.d.ts.map +1 -1
  226. package/dist/util/schema-marks.js +19 -21
  227. package/dist/util/schema-marks.js.map +1 -1
  228. package/dist/util/variable-ref.d.ts +4 -1
  229. package/dist/util/variable-ref.d.ts.map +1 -1
  230. package/dist/util/variable-ref.js +10 -5
  231. package/dist/util/variable-ref.js.map +1 -1
  232. package/package.json +5 -1
  233. package/dist/types/config-path.d.ts +0 -24
  234. package/dist/types/config-path.d.ts.map +0 -1
  235. package/dist/types/config-path.js +0 -18
  236. package/dist/types/config-path.js.map +0 -1
  237. package/dist/util/option-mark.d.ts +0 -44
  238. package/dist/util/option-mark.d.ts.map +0 -1
  239. package/dist/util/option-mark.js +0 -132
  240. package/dist/util/option-mark.js.map +0 -1
@@ -0,0 +1,814 @@
1
+ import { QUESTION_SEPARATOR, readConversationalFlow } from './read.js';
2
+ import { optionsOf } from './types.js';
3
+ export class ConversationalFlowEditError extends Error {
4
+ name = 'ConversationalFlowEditError';
5
+ }
6
+ // ─── Screens ───
7
+ /** Rename a screen. Breadcrumb headers and the router's list follow the new name. */
8
+ export function renameScreen(config, screenId, title) {
9
+ const trimmed = title.trim();
10
+ if (!trimmed)
11
+ throw new ConversationalFlowEditError('A screen needs a title.');
12
+ return settle(config, (draft) => {
13
+ caseOf(draft, screenId)['label'] = trimmed;
14
+ });
15
+ }
16
+ /** "AI sends people here when…" — what the router reads about this screen. */
17
+ export function setAbout(config, screenId, about) {
18
+ const flow = requireFlow(config);
19
+ const screen = requireScreen(flow, screenId);
20
+ return settle(config, (draft) => {
21
+ const step = aboutCarrier(draft, screen);
22
+ const text = about.trim();
23
+ if (text)
24
+ step.description = text;
25
+ else
26
+ delete step.description;
27
+ });
28
+ }
29
+ /**
30
+ * Add a screen of `type` under `parent` and link the parent to it. It sends
31
+ * typed text wherever the rest of the flow does and offers the way back.
32
+ */
33
+ export function addScreen(config, args) {
34
+ const title = args.title.trim();
35
+ if (!title)
36
+ throw new ConversationalFlowEditError('A screen needs a title.');
37
+ const type = args.type ?? 'menu';
38
+ const flow = requireFlow(config);
39
+ const parent = requireScreen(flow, args.parent);
40
+ const parentPrompt = parent.prompts[0];
41
+ if (!parentPrompt)
42
+ throw new ConversationalFlowEditError(`“${parent.title}” doesn’t show options, so it can’t lead anywhere.`);
43
+ const taken = new Set(flow.screens.map((s) => s.id));
44
+ const screenId = uniqueName(args.id ?? slug(title), taken);
45
+ let next = mutate(config, (draft) => {
46
+ const cases = routerCases(draft, flow);
47
+ const entry = {
48
+ label: title,
49
+ condition: { ...asRec(cases[0]?.['condition']), value: screenId },
50
+ steps: buildSteps(draft, flow, type, { screenId, title, parent, prompt: '' }),
51
+ };
52
+ // Keep system screens (routers, ends) last, where authors expect them.
53
+ const firstSystem = flow.screens.find((s) => s.kind === 'router' || s.kind === 'end');
54
+ cases.splice(firstSystem ? firstSystem.caseIndex : cases.length, 0, entry);
55
+ });
56
+ // Link from the parent, above its way-back options.
57
+ const updated = requireFlow(next);
58
+ next = addOption(next, parentPrompt.id, { label: title, screen: screenId }, firstBackIndex(promptIn(updated, parentPrompt.id)));
59
+ return { config: settle(next, () => { }, config), screenId };
60
+ }
61
+ /**
62
+ * Change what a screen is. The title, "about" and wording carry over. A screen
63
+ * that other screens hang beneath can only become another screen with options.
64
+ */
65
+ export function setScreenType(config, screenId, type) {
66
+ const flow = requireFlow(config);
67
+ const screen = requireScreen(flow, screenId);
68
+ if (screen.kind === 'router')
69
+ throw new ConversationalFlowEditError('The AI router can’t be turned into another kind of screen.');
70
+ if (kindMatches(screen.kind, type))
71
+ return config;
72
+ const children = flow.screens.filter((s) => s.parent === screenId);
73
+ const keepsOptions = type === 'menu' || type === 'message' || type === 'questions';
74
+ if (!keepsOptions && children.length > 0) {
75
+ throw new ConversationalFlowEditError(`Move ${list(children.map((c) => c.title))} somewhere else first — ${children.length === 1 ? 'it is' : 'they are'} only reachable from “${screen.title}”.`);
76
+ }
77
+ if (screen.kind === 'questions' && type !== 'questions' && screen.prompts.length > 1) {
78
+ throw new ConversationalFlowEditError('Remove the follow-up questions first — they only exist inside this screen.');
79
+ }
80
+ const parent = screen.parent ? requireScreen(flow, screen.parent) : undefined;
81
+ const prompt = screen.prompts[0]?.text ?? screen.askAi?.intro ?? '';
82
+ return settle(config, (draft) => {
83
+ const entry = routerCases(draft, flow)[screen.caseIndex];
84
+ const kept = keepsOptions && screen.prompts[0] ? selectOptions(findStep(draft, screen.prompts[0].id, 'WAIT')) : undefined;
85
+ const steps = buildSteps(draft, flow, type, { screenId, title: screen.title, parent, prompt });
86
+ // Converting between the three option screens keeps every option the author made.
87
+ if (kept)
88
+ selectOptions(steps[0]).splice(0, Infinity, ...kept);
89
+ if (screen.about && steps[0])
90
+ steps[0].description = screen.about;
91
+ entry['steps'] = steps;
92
+ });
93
+ }
94
+ /** Remove a screen, every option that led to it, and the router's permission to pick it. */
95
+ export function removeScreen(config, screenId) {
96
+ const flow = requireFlow(config);
97
+ const screen = requireScreen(flow, screenId);
98
+ if (screen.id === flow.rootScreen)
99
+ throw new ConversationalFlowEditError('The first screen can’t be removed.');
100
+ if (screen.kind === 'router')
101
+ throw new ConversationalFlowEditError('The AI router can’t be removed; typed messages would have nowhere to go.');
102
+ const orphaned = flow.screens.filter((s) => s.parent === screenId);
103
+ if (orphaned.length > 0) {
104
+ throw new ConversationalFlowEditError(`Move or remove ${list(orphaned.map((s) => s.title))} first — ${orphaned.length === 1 ? 'it is' : 'they are'} only reachable from “${screen.title}”.`);
105
+ }
106
+ return settle(config, (draft) => {
107
+ for (const other of flow.screens) {
108
+ if (other.id === screenId)
109
+ continue;
110
+ for (const prompt of other.prompts) {
111
+ const options = selectOptions(findStep(draft, prompt.id));
112
+ for (let i = options.length - 1; i >= 0; i--) {
113
+ const to = prompt.options[i]?.to;
114
+ if (to?.kind === 'screen' && to.screen === screenId)
115
+ options.splice(i, 1);
116
+ }
117
+ }
118
+ }
119
+ routerCases(draft, flow).splice(screen.caseIndex, 1);
120
+ });
121
+ }
122
+ /**
123
+ * Hang a screen beneath another. The old parent stops linking to it, the new one
124
+ * starts, and the way back from it — and from everything beneath it — follows.
125
+ */
126
+ export function moveScreen(config, screenId, newParentId) {
127
+ const flow = requireFlow(config);
128
+ const screen = requireScreen(flow, screenId);
129
+ const newParent = requireScreen(flow, newParentId);
130
+ if (screen.id === flow.rootScreen)
131
+ throw new ConversationalFlowEditError('The first screen can’t be moved.');
132
+ if (newParent.id === screenId || isBeneath(flow, newParentId, screenId)) {
133
+ throw new ConversationalFlowEditError('A screen can’t move beneath itself.');
134
+ }
135
+ const target = newParent.prompts[0];
136
+ if (!target)
137
+ throw new ConversationalFlowEditError(`“${newParent.title}” doesn’t show options, so it can’t lead anywhere.`);
138
+ if (screen.parent === newParentId)
139
+ return config;
140
+ let next = mutate(config, (draft) => {
141
+ const old = screen.parent ? requireScreen(flow, screen.parent) : undefined;
142
+ for (const prompt of old?.prompts ?? []) {
143
+ const options = selectOptions(findStep(draft, prompt.id));
144
+ for (let i = options.length - 1; i >= 0; i--) {
145
+ const o = prompt.options[i];
146
+ if (o && !o.back && o.to.kind === 'screen' && o.to.screen === screenId)
147
+ options.splice(i, 1);
148
+ }
149
+ }
150
+ });
151
+ next = addOption(next, target.id, { label: screen.title, screen: screenId }, firstBackIndex(target));
152
+ // The old way back (↑ the old parent, …) no longer leads back once moved, so
153
+ // it has to be recognised from before the move to be replaced.
154
+ const formerlyBack = new Map();
155
+ for (const s of flow.screens) {
156
+ if (s.id !== screenId && !isBeneath(flow, s.id, screenId))
157
+ continue;
158
+ for (const p of s.prompts)
159
+ formerlyBack.set(p.id, new Set(p.options.filter((o) => o.back).map((o) => o.value)));
160
+ }
161
+ next = refreshWayBack(next, screenId, { formerlyBack });
162
+ return settle(next, () => { }, config);
163
+ }
164
+ /** Offer (or stop offering) the way back — ↑ each ancestor, then the first screen. */
165
+ export function setWayBack(config, screenId, on) {
166
+ const flow = requireFlow(config);
167
+ const screen = requireScreen(flow, screenId);
168
+ if (screen.kind === 'ask-ai' && !on) {
169
+ throw new ConversationalFlowEditError('An Ask AI screen needs a way out; its exits are the way back.');
170
+ }
171
+ if (on)
172
+ return refreshWayBack(config, screenId, { subtree: false });
173
+ return mutate(config, (draft) => {
174
+ for (const prompt of screen.prompts) {
175
+ const options = selectOptions(findStep(draft, prompt.id));
176
+ for (let i = prompt.options.length - 1; i >= 0; i--)
177
+ if (prompt.options[i].back)
178
+ options.splice(i, 1);
179
+ }
180
+ });
181
+ }
182
+ /** What a Finish screen returns as the run's outcome. */
183
+ export function setEndResult(config, screenId, value) {
184
+ const flow = requireFlow(config);
185
+ const screen = requireScreen(flow, screenId);
186
+ if (screen.kind !== 'end')
187
+ throw new ConversationalFlowEditError(`“${screen.title}” isn’t a Finish screen.`);
188
+ return mutate(config, (draft) => {
189
+ const finish = asSteps(routerCases(draft, flow)[screen.caseIndex]['steps'])[0];
190
+ finish.config['with'] = value;
191
+ });
192
+ }
193
+ // ─── The AI router and Ask AI ───
194
+ export function setRouterAgent(config, agentSlug) {
195
+ const flow = requireFlow(config);
196
+ const router = agentRouter(flow);
197
+ if (!router?.router)
198
+ throw new ConversationalFlowEditError('This flow has no AI router.');
199
+ return mutate(config, (draft) => {
200
+ findStep(draft, router.router.stepId, 'RUN_AGENT').config['agentSlug'] = agentSlug.trim();
201
+ });
202
+ }
203
+ /** The author's own instructions to the router, put before the generated screen list. */
204
+ export function setRouterGuidance(config, guidance) {
205
+ const flow = requireFlow(config);
206
+ const router = agentRouter(flow);
207
+ if (!router?.router)
208
+ throw new ConversationalFlowEditError('This flow has no AI router.');
209
+ return settle(config, (draft) => {
210
+ const step = findStep(draft, router.router.stepId, 'RUN_AGENT');
211
+ const text = guidance.trim();
212
+ if (text)
213
+ step.description = text;
214
+ else
215
+ delete step.description;
216
+ });
217
+ }
218
+ export function setAskAi(config, screenId, patch) {
219
+ const flow = requireFlow(config);
220
+ const screen = requireScreen(flow, screenId);
221
+ if (!screen.askAi)
222
+ throw new ConversationalFlowEditError(`“${screen.title}” isn’t an Ask AI screen.`);
223
+ return mutate(config, (draft) => {
224
+ const step = findStep(draft, screen.askAi.stepId, 'RUN_AGENT');
225
+ if (patch.agent !== undefined)
226
+ step.config['agentSlug'] = patch.agent.trim();
227
+ if (patch.task !== undefined) {
228
+ // The instructions change; the question the person typed stays appended.
229
+ const task = typeof step.config['task'] === 'string' ? step.config['task'] : '';
230
+ const at = task.lastIndexOf(QUESTION_SEPARATOR);
231
+ step.config['task'] = patch.task + (at === -1 ? '' : task.slice(at));
232
+ }
233
+ if (patch.intro !== undefined)
234
+ findStep(draft, screen.prompts[0].id, 'WAIT').config['prompt'] = patch.intro;
235
+ });
236
+ }
237
+ // ─── Prompts ───
238
+ export function setPromptText(config, promptId, text) {
239
+ return mutate(config, (draft) => {
240
+ findStep(draft, promptId, 'WAIT').config['prompt'] = text;
241
+ });
242
+ }
243
+ /**
244
+ * Add an answer to a question that opens a follow-up question, asked in the
245
+ * same round. The prompt must already branch on its answers (a Questions screen).
246
+ */
247
+ export function addFollowUp(config, promptId, args) {
248
+ const flow = requireFlow(config);
249
+ const prompt = promptIn(flow, promptId);
250
+ if (!prompt.pickSwitchId) {
251
+ throw new ConversationalFlowEditError('Only a Questions screen can ask a follow-up. Change the screen’s type first.');
252
+ }
253
+ const label = args.label.trim();
254
+ if (!label)
255
+ throw new ConversationalFlowEditError('An answer needs a label.');
256
+ const screen = flow.screens.find((s) => s.prompts.some((p) => p.id === promptId));
257
+ const value = uniqueName(slug(label), new Set(prompt.options.map((o) => o.value)));
258
+ let newPromptId = '';
259
+ const next = mutate(config, (draft) => {
260
+ const taken = allStepIds(draft);
261
+ const wait = findStep(draft, promptId, 'WAIT');
262
+ const options = selectOptions(wait);
263
+ options.splice(firstBackIndex(prompt), 0, { label, value });
264
+ const pick = findStep(draft, prompt.pickSwitchId, 'SWITCH');
265
+ const template = templateScreen(draft, flow);
266
+ const followUp = buildPromptSteps(template, {
267
+ waitId: uniqueName(`ask_${screen.id}__${value}`, taken),
268
+ suffix: `${screen.id}__${value}`,
269
+ prompt: args.question,
270
+ options: prompt.options.filter((o) => o.back).map((o) => ({ label: o.label, value: o.value })),
271
+ header: prompt.header,
272
+ branches: true,
273
+ taken,
274
+ });
275
+ newPromptId = followUp[0].id;
276
+ const choiceRef = `{{steps.${promptId}.output.resumeData.data.${prompt.choiceField ?? 'choice'}}}`;
277
+ const cases = asArray(pick.config['cases']);
278
+ cases.push({ label: value, condition: { variable: choiceRef, operator: 'eq', value }, steps: followUp });
279
+ pick.config['cases'] = cases;
280
+ });
281
+ return { config: next, promptId: newPromptId };
282
+ }
283
+ // ─── Options ───
284
+ /** Add an option that goes to a screen. */
285
+ export function addOption(config, promptId, option, at) {
286
+ const flow = requireFlow(config);
287
+ requireScreen(flow, option.screen);
288
+ const prompt = promptIn(flow, promptId);
289
+ requireForwardsPick(prompt);
290
+ if (prompt.options.some((o) => o.value === option.screen)) {
291
+ throw new ConversationalFlowEditError('This question already has an option that goes there.');
292
+ }
293
+ return mutate(config, (draft) => {
294
+ const options = selectOptions(findStep(draft, promptId, 'WAIT'));
295
+ const entry = { label: option.label.trim() || option.screen, value: option.screen };
296
+ options.splice(at === undefined ? options.length : clamp(at, 0, options.length), 0, entry);
297
+ });
298
+ }
299
+ export function relabelOption(config, promptId, index, label) {
300
+ const trimmed = label.trim();
301
+ if (!trimmed)
302
+ throw new ConversationalFlowEditError('An option needs a label.');
303
+ return mutate(config, (draft) => {
304
+ optionAt(findStep(draft, promptId, 'WAIT'), index)['label'] = trimmed;
305
+ });
306
+ }
307
+ /**
308
+ * Point an option at another screen. For a plain screen the option's value *is*
309
+ * its destination, so this rewrites the value. An option that opens a
310
+ * follow-up question can't be repointed — that would drop the question.
311
+ */
312
+ export function retargetOption(config, promptId, index, screen) {
313
+ const flow = requireFlow(config);
314
+ requireScreen(flow, screen);
315
+ const prompt = promptIn(flow, promptId);
316
+ const current = prompt.options[index];
317
+ if (!current)
318
+ throw new ConversationalFlowEditError('No such option.');
319
+ if (current.to.kind !== 'screen') {
320
+ throw new ConversationalFlowEditError('This option opens a follow-up question. Remove the question to point it somewhere else.');
321
+ }
322
+ requireForwardsPick(prompt);
323
+ if (prompt.options.some((o, i) => i !== index && o.value === screen)) {
324
+ throw new ConversationalFlowEditError('Another option already goes there.');
325
+ }
326
+ requireNotSoleLink(flow, promptId, current);
327
+ return settle(config, (draft) => {
328
+ optionAt(findStep(draft, promptId, 'WAIT'), index)['value'] = screen;
329
+ });
330
+ }
331
+ export function removeOption(config, promptId, index) {
332
+ const flow = requireFlow(config);
333
+ const prompt = promptIn(flow, promptId);
334
+ const option = prompt.options[index];
335
+ if (!option)
336
+ throw new ConversationalFlowEditError('No such option.');
337
+ if (option.to.kind === 'prompt') {
338
+ throw new ConversationalFlowEditError('This option opens a follow-up question. Remove the question instead.');
339
+ }
340
+ requireNotSoleLink(flow, promptId, option);
341
+ return mutate(config, (draft) => {
342
+ selectOptions(findStep(draft, promptId, 'WAIT')).splice(index, 1);
343
+ });
344
+ }
345
+ export function moveOption(config, promptId, from, to) {
346
+ return mutate(config, (draft) => {
347
+ const options = selectOptions(findStep(draft, promptId, 'WAIT'));
348
+ if (!options[from])
349
+ throw new ConversationalFlowEditError('No such option.');
350
+ const [moved] = options.splice(from, 1);
351
+ options.splice(clamp(to, 0, options.length), 0, moved);
352
+ });
353
+ }
354
+ /**
355
+ * A plain screen to copy the shape from — the root if it is plain, else the
356
+ * first plain screen. Its WAIT fields, its typed-text gate and the keys its
357
+ * GO_TOs carry all come across; only ids, texts and options change.
358
+ */
359
+ function templateScreen(draft, flow) {
360
+ const plain = [flow.screens.find((s) => s.id === flow.rootScreen), ...flow.screens].find((s) => !!s && (s.kind === 'menu' || s.kind === 'message'));
361
+ if (!plain)
362
+ throw new ConversationalFlowEditError('This flow has no plain screen to model a new one on.');
363
+ const steps = asSteps(routerCases(draft, flow)[plain.caseIndex]['steps']);
364
+ const [wait, second] = steps;
365
+ const gate = second?.type === 'CONDITIONAL' ? second : undefined;
366
+ const picked = gate ? asSteps(gate.config['if_false']) : steps.slice(1);
367
+ const typed = gate ? asSteps(gate.config['if_true']) : [];
368
+ const pickJump = picked.find((s) => s.type === 'GO_TO');
369
+ if (!wait || !pickJump)
370
+ throw new ConversationalFlowEditError('This flow has no plain screen to model a new one on.');
371
+ return { wait, gate, typedJump: typed.find((s) => s.type === 'GO_TO'), pickJump };
372
+ }
373
+ function buildSteps(draft, flow, type, args) {
374
+ const taken = allStepIds(draft);
375
+ const back = args.parent ? wayBack(flow, args.parent) : [];
376
+ if (type === 'end') {
377
+ return [{
378
+ id: uniqueName(`finish_${args.screenId}`, taken),
379
+ type: 'FINISH',
380
+ config: { target: flow.cycleId, with: { outcome: args.screenId } },
381
+ }];
382
+ }
383
+ const template = templateScreen(draft, flow);
384
+ if (type === 'ask-ai') {
385
+ // Opens like any screen — the intro, the ways out, a text box — and a typed
386
+ // question goes to an agent that answers, then waits for a reply
387
+ // (`waitForReply`): a reply continues the conversation; picking one of this
388
+ // screen's ways out ends it and moves on there.
389
+ if (!template.gate)
390
+ throw new ConversationalFlowEditError('Ask AI needs a flow that takes typed messages.');
391
+ const waitId = uniqueName(`ask_${args.screenId}`, taken);
392
+ const steps = buildPromptSteps(template, {
393
+ waitId,
394
+ suffix: args.screenId,
395
+ prompt: args.prompt || `Ask me anything about ${args.title.toLowerCase()}.`,
396
+ options: back,
397
+ header: undefined,
398
+ branches: false,
399
+ taken,
400
+ });
401
+ const textField = fieldOf(template.wait, 'text') ?? 'message';
402
+ const agentId = uniqueName(`ai_${args.screenId}`, taken);
403
+ const leave = retarget(clone(template.pickJump), template.wait.id, agentId);
404
+ leave.id = uniqueName(`leave_${args.screenId}`, taken);
405
+ const carried = asRec(leave.config['with']);
406
+ for (const key of Object.keys(carried))
407
+ if (key !== flow.routeKey)
408
+ carried[key] = '';
409
+ carried[flow.routeKey] = `{{steps.${agentId}.output.choice}}`;
410
+ steps[1].config['if_true'] = [
411
+ {
412
+ id: agentId,
413
+ type: 'RUN_AGENT',
414
+ config: {
415
+ agentSlug: agentRouter(flow)?.router?.agent ?? '',
416
+ task: `Answer their questions about ${args.title}. Use your connected systems and sources, and say so plainly when you are not sure.`
417
+ + QUESTION_SEPARATOR
418
+ + `{{steps.${waitId}.output.resumeData.data.${textField}}}`,
419
+ outputType: 'string',
420
+ waitForReply: true,
421
+ },
422
+ },
423
+ leave,
424
+ ];
425
+ return steps;
426
+ }
427
+ const options = [...back];
428
+ if (type === 'message') {
429
+ const end = flow.screens.find((s) => s.kind === 'end');
430
+ if (end)
431
+ options.push({ label: 'That’s all', value: end.id });
432
+ }
433
+ return buildPromptSteps(template, {
434
+ waitId: uniqueName(`ask_${args.screenId}`, taken),
435
+ suffix: args.screenId,
436
+ prompt: args.prompt,
437
+ options,
438
+ header: undefined,
439
+ branches: type === 'questions',
440
+ taken,
441
+ });
442
+ }
443
+ /**
444
+ * WAIT (+ typed-text gate) + what a pick does: forwarded as the next screen,
445
+ * or — for questions — branched by a SWITCH whose default forwards the pick.
446
+ */
447
+ function buildPromptSteps(t, args) {
448
+ const rename = (step, base) => {
449
+ const copy = retarget(clone(step), t.wait.id, args.waitId);
450
+ copy.id = uniqueName(`${base}_${args.suffix}`, args.taken);
451
+ return copy;
452
+ };
453
+ const wait = clone(t.wait);
454
+ wait.id = args.waitId;
455
+ delete wait.description;
456
+ wait.config['prompt'] = args.prompt;
457
+ // No header unless given: the refresh after insertion writes the breadcrumb.
458
+ if (args.header)
459
+ wait.config['reason'] = args.header;
460
+ else
461
+ delete wait.config['reason'];
462
+ selectOptions(wait).splice(0, Infinity, ...args.options);
463
+ const pick = rename(t.pickJump, args.branches ? 'leave' : 'go');
464
+ const picked = args.branches
465
+ ? [{ id: uniqueName(`pick_${args.suffix}`, args.taken), type: 'SWITCH', config: { cases: [], default: [pick] } }]
466
+ : [pick];
467
+ if (!t.gate)
468
+ return [wait, ...picked];
469
+ const gate = rename(t.gate, 'typed');
470
+ gate.config['if_true'] = t.typedJump ? [rename(t.typedJump, 'route')] : [];
471
+ gate.config['if_false'] = picked;
472
+ return [wait, gate];
473
+ }
474
+ /**
475
+ * The options that lead back from a new child of `parent`: back to the parent
476
+ * itself, then whatever way back the parent already offers. Labels follow the
477
+ * flow's own wording — if the parent writes "↑ Payments", the child writes
478
+ * "↑ <parent>".
479
+ */
480
+ function wayBack(flow, parent) {
481
+ const inherited = optionsOf(parent).filter((o) => o.back);
482
+ if (parent.id === flow.rootScreen) {
483
+ const root = flow.screens.find((s) => s.id === flow.rootScreen);
484
+ return [{ label: mainMenuLabel(flow) ?? root.title, value: root.id }];
485
+ }
486
+ const byId = new Map(flow.screens.map((s) => [s.id, s]));
487
+ const example = inherited.find((o) => {
488
+ const target = o.to.kind === 'screen' ? byId.get(o.to.screen) : undefined;
489
+ return target && target.id !== flow.rootScreen && o.label.endsWith(target.title);
490
+ });
491
+ const prefix = example && example.to.kind === 'screen'
492
+ ? example.label.slice(0, example.label.length - byId.get(example.to.screen).title.length)
493
+ : '↑ ';
494
+ return [
495
+ { label: `${prefix}${parent.title}`, value: parent.id },
496
+ ...inherited.map((o) => ({ label: o.label, value: o.value })),
497
+ ];
498
+ }
499
+ /** How this flow words the way back to its first screen ("Main menu"), if it has one. */
500
+ function mainMenuLabel(flow) {
501
+ for (const s of flow.screens) {
502
+ const o = optionsOf(s).find((x) => x.back && x.to.kind === 'screen' && x.to.screen === flow.rootScreen);
503
+ if (o)
504
+ return o.label;
505
+ }
506
+ return undefined;
507
+ }
508
+ /**
509
+ * Rewrite the way-back options of `screenId` — and, by default, of everything
510
+ * beneath it — from its current place in the tree. Top-down, so each screen
511
+ * inherits the freshly written way back of its parent.
512
+ */
513
+ function refreshWayBack(config, screenId, opts = {}) {
514
+ let next = config;
515
+ const queue = [screenId];
516
+ while (queue.length > 0) {
517
+ const id = queue.shift();
518
+ const flow = requireFlow(next);
519
+ const screen = requireScreen(flow, id);
520
+ const parent = screen.parent ? flow.screens.find((s) => s.id === screen.parent) : undefined;
521
+ if (parent) {
522
+ const fresh = wayBack(flow, parent);
523
+ next = mutate(next, (draft) => {
524
+ for (const prompt of screen.prompts) {
525
+ const options = selectOptions(findStep(draft, prompt.id));
526
+ const stale = opts.formerlyBack?.get(prompt.id);
527
+ const isWayBack = (o) => o.back || (stale?.has(o.value) ?? false);
528
+ const at = Math.min(firstBackIndex(prompt), ...prompt.options.map((o, i) => (isWayBack(o) ? i : Infinity)));
529
+ for (let i = prompt.options.length - 1; i >= 0; i--)
530
+ if (isWayBack(prompt.options[i]))
531
+ options.splice(i, 1);
532
+ const kept = new Set(options.map((o) => o['value']));
533
+ options.splice(Math.min(at, options.length), 0, ...fresh.filter((o) => !kept.has(o['value'])));
534
+ }
535
+ });
536
+ }
537
+ if (opts.subtree !== false) {
538
+ for (const child of requireFlow(next).screens.filter((s) => s.parent === id))
539
+ queue.push(child.id);
540
+ }
541
+ }
542
+ return next;
543
+ }
544
+ /** Rewrite every `steps.<from>.` reference inside a step to `steps.<to>.`. */
545
+ function retarget(value, from, to) {
546
+ const pattern = new RegExp(`(\\{\\{\\s*steps\\.)${escapeRegExp(from)}(\\.)`, 'g');
547
+ return JSON.parse(JSON.stringify(value).replace(pattern, `$1${to}$2`));
548
+ }
549
+ // ─── Derived: headers and the router ───
550
+ /** Recompute what is derived from the screens (headers, the router) without any other change. */
551
+ export function refreshDerived(config) {
552
+ return settle(config, () => { });
553
+ }
554
+ /**
555
+ * Apply `edit`, then refresh what is derived from the screens: breadcrumb
556
+ * headers (only those that were the generated breadcrumb — a header the author
557
+ * wrote is left alone) and the AI router's list of screens.
558
+ */
559
+ function settle(config, edit,
560
+ /** The config as the author last saw it, when `config` is already part-way through a multi-step edit. */
561
+ baseline = config) {
562
+ const before = requireFlow(baseline);
563
+ const wasGenerated = new Set();
564
+ for (const s of before.screens) {
565
+ const crumb = breadcrumb(before, s);
566
+ for (const p of s.prompts)
567
+ if (p.header === crumb)
568
+ wasGenerated.add(p.id);
569
+ }
570
+ const edited = mutate(config, edit);
571
+ const after = requireFlow(edited);
572
+ return mutate(edited, (draft) => {
573
+ for (const s of after.screens) {
574
+ const crumb = breadcrumb(after, s);
575
+ for (const p of s.prompts) {
576
+ if (wasGenerated.has(p.id) || p.header === undefined)
577
+ findStep(draft, p.id, 'WAIT').config['reason'] = crumb;
578
+ }
579
+ }
580
+ writeRouter(draft, after);
581
+ });
582
+ }
583
+ /** "Payments › Charges › Charged twice" — ancestors below the root, then the screen. */
584
+ export function breadcrumb(flow, screen) {
585
+ const byId = new Map(flow.screens.map((s) => [s.id, s]));
586
+ const chain = [];
587
+ for (let at = screen; at; at = at.parent ? byId.get(at.parent) : undefined)
588
+ chain.unshift(at);
589
+ const titles = chain.filter((s) => s.id !== flow.rootScreen).map((s) => s.title);
590
+ return titles.length > 0 ? titles.join(' › ') : screen.title;
591
+ }
592
+ /** Screens the router may send people to: everything they can be shown. */
593
+ export function routableScreens(flow) {
594
+ return flow.screens.filter((s) => s.kind !== 'router' && s.kind !== 'end');
595
+ }
596
+ /**
597
+ * The AI router's instructions and output contract, generated from the screens.
598
+ * The author's own guidance (the router step's description) goes first; the
599
+ * `enum` is what stops the agent naming a screen that doesn't exist.
600
+ */
601
+ function writeRouter(draft, flow) {
602
+ const router = agentRouter(flow)?.router;
603
+ if (!router)
604
+ return;
605
+ const step = findStep(draft, router.stepId, 'RUN_AGENT');
606
+ const screens = routableScreens(flow);
607
+ const textKey = typedTextKey(draft, flow);
608
+ const lines = screens.map((s) => {
609
+ const section = flow.screens.some((c) => c.parent === s.id) ? ' [section]' : '';
610
+ const about = s.about ?? `the ${breadcrumb(flow, s)} screen`;
611
+ return `${s.id} (${breadcrumb(flow, s)})${section} — ${about}`;
612
+ });
613
+ step.config['task'] = [
614
+ ...(router.guidance ? [router.guidance, ''] : []),
615
+ textKey
616
+ ? `Someone in this conversation typed: "{{steps.__loop.output.input.${textKey}}}"`
617
+ : 'Someone in this conversation typed a message.',
618
+ '',
619
+ 'Send them to the screen that best answers it. The screens, with where each sits:',
620
+ ...lines,
621
+ '',
622
+ 'Prefer the most specific screen. Only choose a [section] when the message is too vague for any of its screens.',
623
+ `If nothing fits, choose "${flow.rootScreen}".`,
624
+ `Answer with JSON only: {"${flow.routeKey}": "<id from the list>", "reason": "<one short sentence>"}.`,
625
+ ].join('\n');
626
+ step.config['outputType'] = 'json';
627
+ step.config['outputSchema'] = {
628
+ type: 'object',
629
+ properties: {
630
+ [flow.routeKey]: { type: 'string', enum: screens.map((s) => s.id) },
631
+ reason: { type: 'string' },
632
+ },
633
+ required: [flow.routeKey, 'reason'],
634
+ };
635
+ }
636
+ /** The cycle input that carries what they typed — read from a typed-text GO_TO. */
637
+ function typedTextKey(draft, flow) {
638
+ for (const s of flow.screens) {
639
+ for (const p of s.prompts) {
640
+ if (p.freeText?.kind !== 'screen' || !p.textField)
641
+ continue;
642
+ const jump = walk(asSteps(draft.steps)).find((x) => x.type === 'GO_TO' && Object.values(asRec(x.config['with'])).some((v) => typeof v === 'string' && v.includes(`steps.${p.id}.output.resumeData.data.${p.textField}`)));
643
+ const carried = asRec(jump?.config['with']);
644
+ const key = Object.keys(carried).find((k) => k !== flow.routeKey && typeof carried[k] === 'string' && carried[k].includes('{{'));
645
+ if (key)
646
+ return key;
647
+ }
648
+ }
649
+ return undefined;
650
+ }
651
+ function agentRouter(flow) {
652
+ return flow.screens.find((s) => s.router?.mode === 'agent');
653
+ }
654
+ // ─── Lookups ───
655
+ function requireFlow(config) {
656
+ const flow = readConversationalFlow(config);
657
+ if (!flow)
658
+ throw new ConversationalFlowEditError('This workflow is not a conversational flow.');
659
+ return flow;
660
+ }
661
+ function requireScreen(flow, id) {
662
+ const screen = flow.screens.find((s) => s.id === id);
663
+ if (!screen)
664
+ throw new ConversationalFlowEditError(`There is no screen "${id}".`);
665
+ return screen;
666
+ }
667
+ function promptIn(flow, id) {
668
+ for (const s of flow.screens) {
669
+ const prompt = s.prompts.find((p) => p.id === id);
670
+ if (prompt)
671
+ return prompt;
672
+ }
673
+ throw new ConversationalFlowEditError(`There is no question "${id}".`);
674
+ }
675
+ /** Options can only name a screen when the prompt forwards the pick as the next screen. */
676
+ function requireForwardsPick(prompt) {
677
+ if (!prompt.choiceField)
678
+ throw new ConversationalFlowEditError('This question has no options to choose from.');
679
+ const forwards = prompt.options.length === 0 || prompt.pickSwitchId !== undefined || prompt.options.some((o) => o.to.kind === 'screen');
680
+ if (!forwards) {
681
+ throw new ConversationalFlowEditError('Options on this question each open a follow-up. Edit them in the step view.');
682
+ }
683
+ }
684
+ /**
685
+ * Refuse to drop or repoint the option a child screen hangs from: the screen
686
+ * would be left with no way in.
687
+ */
688
+ function requireNotSoleLink(flow, promptId, option) {
689
+ if (option.to.kind !== 'screen' || option.back)
690
+ return;
691
+ const target = flow.screens.find((s) => s.id === option.to.screen);
692
+ const owner = flow.screens.find((s) => s.prompts.some((p) => p.id === promptId));
693
+ if (target && owner && target.parent === owner.id) {
694
+ throw new ConversationalFlowEditError(`“${target.title}” is only reachable through this option. Move or remove it first.`);
695
+ }
696
+ }
697
+ /** The step that carries a screen's "about": its first WAIT. */
698
+ function aboutCarrier(draft, screen) {
699
+ if (screen.prompts[0])
700
+ return findStep(draft, screen.prompts[0].id, 'WAIT');
701
+ throw new ConversationalFlowEditError(`The AI router doesn’t send people to “${screen.title}”.`);
702
+ }
703
+ function kindMatches(kind, type) {
704
+ if (type === 'menu' || type === 'message')
705
+ return kind === 'menu' || kind === 'message';
706
+ return kind === type;
707
+ }
708
+ function isBeneath(flow, id, ancestor) {
709
+ const parent = new Map(flow.screens.map((s) => [s.id, s.parent]));
710
+ for (let at = parent.get(id); at !== undefined; at = parent.get(at))
711
+ if (at === ancestor)
712
+ return true;
713
+ return false;
714
+ }
715
+ function routerCases(draft, flow) {
716
+ const router = findStep(draft, flow.routerId, 'SWITCH');
717
+ const cases = router.config['cases'];
718
+ if (!Array.isArray(cases))
719
+ throw new ConversationalFlowEditError('The router has no cases.');
720
+ return cases;
721
+ }
722
+ function caseOf(draft, screenId) {
723
+ const flow = requireFlow(draft);
724
+ return routerCases(draft, flow)[requireScreen(flow, screenId).caseIndex];
725
+ }
726
+ function findStep(draft, id, type) {
727
+ const found = walk(asSteps(draft.steps)).find((s) => s.id === id);
728
+ if (!found || (type && found.type !== type))
729
+ throw new ConversationalFlowEditError(`Step "${id}" is missing.`);
730
+ return found;
731
+ }
732
+ function walk(steps, out = []) {
733
+ for (const step of steps) {
734
+ out.push(step);
735
+ for (const value of Object.values(step.config ?? {})) {
736
+ if (Array.isArray(value)) {
737
+ walk(asSteps(value), out);
738
+ for (const entry of value)
739
+ walk(asSteps(asRec(entry)['steps']), out);
740
+ }
741
+ else if (value && typeof value === 'object') {
742
+ for (const branch of Object.values(value))
743
+ walk(asSteps(branch), out);
744
+ }
745
+ }
746
+ }
747
+ return out;
748
+ }
749
+ function allStepIds(draft) {
750
+ return new Set(walk(asSteps(draft.steps)).map((s) => s.id));
751
+ }
752
+ function selectOptions(wait) {
753
+ const fields = asRec(wait.config['form'])['fields'];
754
+ const select = Array.isArray(fields) ? fields.find((f) => f['type'] === 'select') : undefined;
755
+ if (!select)
756
+ throw new ConversationalFlowEditError(`"${wait.id}" has no options field.`);
757
+ if (!Array.isArray(select['options']))
758
+ select['options'] = [];
759
+ return select['options'];
760
+ }
761
+ function optionAt(wait, index) {
762
+ const option = selectOptions(wait)[index];
763
+ if (!option)
764
+ throw new ConversationalFlowEditError('No such option.');
765
+ return option;
766
+ }
767
+ function firstBackIndex(prompt) {
768
+ const i = prompt.options.findIndex((o) => o.back);
769
+ return i === -1 ? prompt.options.length : i;
770
+ }
771
+ // ─── Utilities ───
772
+ function mutate(config, edit) {
773
+ const draft = clone(config);
774
+ edit(draft);
775
+ return draft;
776
+ }
777
+ /** The name of a WAIT's field of this kind (`text` covers textarea). */
778
+ function fieldOf(wait, kind) {
779
+ const fields = asArray(asRec(wait.config['form'])['fields']).map(asRec);
780
+ const field = fields.find((f) => (kind === 'text' ? f['type'] === 'text' || f['type'] === 'textarea' : f['type'] === 'select'));
781
+ return typeof field?.['name'] === 'string' ? field['name'] : undefined;
782
+ }
783
+ function clone(value) {
784
+ return JSON.parse(JSON.stringify(value));
785
+ }
786
+ function slug(title) {
787
+ return title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'screen';
788
+ }
789
+ function uniqueName(base, taken) {
790
+ let name = base;
791
+ for (let n = 2; taken.has(name); n++)
792
+ name = `${base}_${n}`;
793
+ taken.add(name);
794
+ return name;
795
+ }
796
+ function list(titles) {
797
+ return titles.map((t) => `“${t}”`).join(', ');
798
+ }
799
+ function clamp(n, lo, hi) {
800
+ return Math.min(Math.max(n, lo), hi);
801
+ }
802
+ function escapeRegExp(s) {
803
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
804
+ }
805
+ function asRec(value) {
806
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
807
+ }
808
+ function asArray(value) {
809
+ return Array.isArray(value) ? value : [];
810
+ }
811
+ function asSteps(value) {
812
+ return asArray(value).filter((s) => !!s && typeof s === 'object' && typeof s['id'] === 'string' && typeof s['type'] === 'string');
813
+ }
814
+ //# sourceMappingURL=edit.js.map