@xyne/workflow-sdk 3.2.45 → 3.2.47

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 (109) hide show
  1. package/dist/agents/agent-step.d.ts +5 -5
  2. package/dist/agents/contract.d.ts +5 -5
  3. package/dist/agents/host-agent-step.d.ts +7 -7
  4. package/dist/agents/pi-session-runtime.d.ts +4 -4
  5. package/dist/common/credentials.d.ts +43 -0
  6. package/dist/common/credentials.d.ts.map +1 -1
  7. package/dist/common/credentials.js +34 -0
  8. package/dist/common/credentials.js.map +1 -1
  9. package/dist/connectors/builtin/builtin-connector.d.ts +1 -1
  10. package/dist/connectors/builtin/builtin-connector.d.ts.map +1 -1
  11. package/dist/connectors/builtin/builtin-connector.js +6 -4
  12. package/dist/connectors/builtin/builtin-connector.js.map +1 -1
  13. package/dist/connectors/builtin/credentials.d.ts +8 -0
  14. package/dist/connectors/builtin/credentials.d.ts.map +1 -1
  15. package/dist/connectors/builtin/credentials.js +14 -0
  16. package/dist/connectors/builtin/credentials.js.map +1 -1
  17. package/dist/connectors/builtin/steps/classifier-agent.step.d.ts +176 -0
  18. package/dist/connectors/builtin/steps/classifier-agent.step.d.ts.map +1 -0
  19. package/dist/connectors/builtin/steps/classifier-agent.step.js +248 -0
  20. package/dist/connectors/builtin/steps/classifier-agent.step.js.map +1 -0
  21. package/dist/connectors/builtin/steps/cycle.step.d.ts +4 -4
  22. package/dist/connectors/builtin/steps/http-request.step.d.ts +4 -4
  23. package/dist/connectors/builtin/steps/map.step.d.ts +15 -4
  24. package/dist/connectors/builtin/steps/map.step.d.ts.map +1 -1
  25. package/dist/connectors/builtin/steps/map.step.js +51 -18
  26. package/dist/connectors/builtin/steps/map.step.js.map +1 -1
  27. package/dist/connectors/builtin/steps/parallel.step.d.ts +4 -4
  28. package/dist/conversational-flow/create.d.ts +15 -2
  29. package/dist/conversational-flow/create.d.ts.map +1 -1
  30. package/dist/conversational-flow/create.js +29 -10
  31. package/dist/conversational-flow/create.js.map +1 -1
  32. package/dist/conversational-flow/edit.d.ts +21 -20
  33. package/dist/conversational-flow/edit.d.ts.map +1 -1
  34. package/dist/conversational-flow/edit.js +204 -286
  35. package/dist/conversational-flow/edit.js.map +1 -1
  36. package/dist/conversational-flow/index.d.ts +8 -3
  37. package/dist/conversational-flow/index.d.ts.map +1 -1
  38. package/dist/conversational-flow/index.js +7 -2
  39. package/dist/conversational-flow/index.js.map +1 -1
  40. package/dist/conversational-flow/internals.d.ts +51 -0
  41. package/dist/conversational-flow/internals.d.ts.map +1 -0
  42. package/dist/conversational-flow/internals.js +163 -0
  43. package/dist/conversational-flow/internals.js.map +1 -0
  44. package/dist/conversational-flow/lookup-edit.d.ts +96 -0
  45. package/dist/conversational-flow/lookup-edit.d.ts.map +1 -0
  46. package/dist/conversational-flow/lookup-edit.js +266 -0
  47. package/dist/conversational-flow/lookup-edit.js.map +1 -0
  48. package/dist/conversational-flow/lookups.d.ts +46 -0
  49. package/dist/conversational-flow/lookups.d.ts.map +1 -0
  50. package/dist/conversational-flow/lookups.js +145 -0
  51. package/dist/conversational-flow/lookups.js.map +1 -0
  52. package/dist/conversational-flow/read.d.ts.map +1 -1
  53. package/dist/conversational-flow/read.js +48 -7
  54. package/dist/conversational-flow/read.js.map +1 -1
  55. package/dist/conversational-flow/router-edit.d.ts +53 -0
  56. package/dist/conversational-flow/router-edit.d.ts.map +1 -0
  57. package/dist/conversational-flow/router-edit.js +191 -0
  58. package/dist/conversational-flow/router-edit.js.map +1 -0
  59. package/dist/conversational-flow/routers.d.ts +92 -0
  60. package/dist/conversational-flow/routers.d.ts.map +1 -0
  61. package/dist/conversational-flow/routers.js +286 -0
  62. package/dist/conversational-flow/routers.js.map +1 -0
  63. package/dist/conversational-flow/settle.d.ts +26 -0
  64. package/dist/conversational-flow/settle.d.ts.map +1 -0
  65. package/dist/conversational-flow/settle.js +59 -0
  66. package/dist/conversational-flow/settle.js.map +1 -0
  67. package/dist/conversational-flow/tree.d.ts +15 -1
  68. package/dist/conversational-flow/tree.d.ts.map +1 -1
  69. package/dist/conversational-flow/tree.js +28 -0
  70. package/dist/conversational-flow/tree.js.map +1 -1
  71. package/dist/conversational-flow/turn.d.ts +2 -0
  72. package/dist/conversational-flow/turn.d.ts.map +1 -1
  73. package/dist/conversational-flow/turn.js +26 -7
  74. package/dist/conversational-flow/turn.js.map +1 -1
  75. package/dist/conversational-flow/types.d.ts +50 -3
  76. package/dist/conversational-flow/types.d.ts.map +1 -1
  77. package/dist/conversational-flow/types.js +35 -0
  78. package/dist/conversational-flow/types.js.map +1 -1
  79. package/dist/engine/config-validator.js +2 -2
  80. package/dist/engine/config-validator.js.map +1 -1
  81. package/dist/engine/variable-resolver.js +1 -1
  82. package/dist/engine/variable-resolver.js.map +1 -1
  83. package/dist/engine/workflow-executor.d.ts.map +1 -1
  84. package/dist/engine/workflow-executor.js +10 -0
  85. package/dist/engine/workflow-executor.js.map +1 -1
  86. package/dist/index.d.ts +2 -0
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +1 -0
  89. package/dist/index.js.map +1 -1
  90. package/dist/runtime/workflow-runtime.d.ts.map +1 -1
  91. package/dist/runtime/workflow-runtime.js +3 -0
  92. package/dist/runtime/workflow-runtime.js.map +1 -1
  93. package/dist/steps/base-step.d.ts.map +1 -1
  94. package/dist/steps/base-step.js +1 -0
  95. package/dist/steps/base-step.js.map +1 -1
  96. package/dist/testing/mock-context.d.ts.map +1 -1
  97. package/dist/testing/mock-context.js +1 -0
  98. package/dist/testing/mock-context.js.map +1 -1
  99. package/dist/types/context.d.ts +15 -0
  100. package/dist/types/context.d.ts.map +1 -1
  101. package/dist/types/known-types.d.ts +1 -0
  102. package/dist/types/known-types.d.ts.map +1 -1
  103. package/dist/types/known-types.js +1 -0
  104. package/dist/types/known-types.js.map +1 -1
  105. package/dist/util/variable-ref.d.ts +1 -1
  106. package/dist/util/variable-ref.d.ts.map +1 -1
  107. package/dist/util/variable-ref.js +1 -1
  108. package/dist/util/variable-ref.js.map +1 -1
  109. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
- import { HANDOFF_SECTION, QUESTION_SEPARATOR, readConversationalFlow } from './read.js';
2
- import { treeOrder } from './tree.js';
3
- import { AGENT_STEP_TYPE, optionsOf } from './types.js';
4
- export class ConversationalFlowEditError extends Error {
5
- name = 'ConversationalFlowEditError';
6
- }
1
+ import { HANDOFF_SECTION, QUESTION_SEPARATOR } from './read.js';
2
+ import { linkerOf, mainMenuLabel } from './tree.js';
3
+ import { AGENT_STEP_TYPE, END_MESSAGE_KEY, optionsOf } from './types.js';
4
+ import { allStepIds, asArray, asRec, asSteps, caseOf, clamp, clone, containerOf, ConversationalFlowEditError, fieldOf, findStep, firstBackIndex, formFields, list, mutate, optionAt, promptIn, requireFlow, requireScreen, retarget, routerCases, selectOptions, slug, uniqueName, } from './internals.js';
5
+ import { agentRouter, pointSubtreeAt, routerFor } from './routers.js';
6
+ import { settle } from './settle.js';
7
7
  // ─── Screens ───
8
8
  /** Rename a screen. Breadcrumb headers and the router's list follow the new name. */
9
9
  export function renameScreen(config, screenId, title) {
@@ -53,6 +53,9 @@ export function addScreen(config, args) {
53
53
  // Keep system screens (routers, ends, hand offs) last, where authors expect them.
54
54
  const firstSystem = flow.screens.find((s) => s.kind === 'router' || s.kind === 'end' || s.kind === 'handoff');
55
55
  cases.splice(firstSystem ? firstSystem.caseIndex : cases.length, 0, entry);
56
+ // Typed text goes where its parent's does — into the section's router when
57
+ // the parent is inside a scoped one, and to the flow's router otherwise.
58
+ pointTypedAt(entry['steps'], flow.routeKey, routerFor(flow, parent.id)?.id);
56
59
  });
57
60
  // Link from the parent, above its way-back options.
58
61
  const updated = requireFlow(next);
@@ -78,8 +81,10 @@ export function setScreenType(config, screenId, type) {
78
81
  if (screen.kind === 'questions' && type !== 'questions' && screen.prompts.length > 1) {
79
82
  throw new ConversationalFlowEditError('Remove the follow-up questions first — they only exist inside this screen.');
80
83
  }
81
- const parent = screen.parent ? requireScreen(flow, screen.parent) : undefined;
82
- const prompt = screen.prompts[0]?.text ?? screen.askAi?.intro ?? '';
84
+ // A Finish sits outside the tree, so on the way back to a screen with options
85
+ // its way back comes from whoever leads to it.
86
+ const parent = screen.parent ? requireScreen(flow, screen.parent) : linkerOf(flow, screen.id);
87
+ const prompt = screen.prompts[0]?.text ?? screen.askAi?.intro ?? screen.endMessage ?? '';
83
88
  return settle(config, (draft) => {
84
89
  const entry = routerCases(draft, flow)[screen.caseIndex];
85
90
  const hadOptions = screen.kind === 'menu' || screen.kind === 'message' || screen.kind === 'questions';
@@ -105,6 +110,7 @@ export function removeScreen(config, screenId) {
105
110
  if (orphaned.length > 0) {
106
111
  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}”.`);
107
112
  }
113
+ const scoped = flow.screens.find((s) => s.router?.scope === screenId);
108
114
  return settle(config, (draft) => {
109
115
  for (const other of flow.screens) {
110
116
  if (other.id === screenId)
@@ -118,7 +124,12 @@ export function removeScreen(config, screenId) {
118
124
  }
119
125
  }
120
126
  }
121
- routerCases(draft, flow).splice(screen.caseIndex, 1);
127
+ // Its own case, and the router that served only it. Highest index first,
128
+ // so removing one doesn't move the other.
129
+ const cases = routerCases(draft, flow);
130
+ for (const at of [screen.caseIndex, scoped?.caseIndex].filter((i) => i !== undefined).sort((a, b) => b - a)) {
131
+ cases.splice(at, 1);
132
+ }
122
133
  });
123
134
  }
124
135
  /**
@@ -151,6 +162,12 @@ export function moveScreen(config, screenId, newParentId) {
151
162
  }
152
163
  });
153
164
  next = addOption(next, target.id, { label: screen.title, screen: screenId }, firstBackIndex(target));
165
+ // It has joined another part of the tree, so its typed text follows the
166
+ // router that serves its new home — as its way back follows its new parent.
167
+ next = mutate(next, (draft) => {
168
+ const moved = requireFlow(next);
169
+ pointSubtreeAt(draft, moved, screenId, routerFor(moved, newParentId)?.id ?? '');
170
+ });
154
171
  // The old way back (↑ the old parent, …) no longer leads back once moved, so
155
172
  // it has to be recognised from before the move to be replaced.
156
173
  const formerlyBack = new Map();
@@ -183,6 +200,138 @@ export function setWayBack(config, screenId, on) {
183
200
  }
184
201
  });
185
202
  }
203
+ /**
204
+ * Whether a screen takes typed text, or only its options.
205
+ *
206
+ * Nothing records this: a screen takes typing because its WAIT has a text field
207
+ * and a CONDITIONAL sends what was typed to the router. Turning it off removes
208
+ * both, which is what every layer below already reads — the turn answers
209
+ * `reply.text.allowed: false`, and text sent anyway is refused.
210
+ *
211
+ * Turning it back on copies the field and the typed branch from a screen that
212
+ * still has them, the way a new screen is built; with none left, both are
213
+ * rebuilt from the CYCLE's own input keys.
214
+ */
215
+ export function setTypingAllowed(config, screenId, on) {
216
+ const flow = requireFlow(config);
217
+ const screen = requireScreen(flow, screenId);
218
+ if (screen.kind === 'ask-ai') {
219
+ throw new ConversationalFlowEditError('An Ask AI screen is typing — that is what it does. Change the screen’s type instead.');
220
+ }
221
+ if (screen.prompts.length === 0)
222
+ throw new ConversationalFlowEditError(`“${screen.title}” asks nothing, so there is nothing to type into.`);
223
+ if (!on && optionsOf(screen).length === 0) {
224
+ throw new ConversationalFlowEditError(`“${screen.title}” offers no options, so turning typing off would leave no way to answer it.`);
225
+ }
226
+ return mutate(config, (draft) => {
227
+ const taken = allStepIds(draft);
228
+ for (const prompt of screen.prompts) {
229
+ if (on === (prompt.textField !== undefined))
230
+ continue;
231
+ const wait = findStep(draft, prompt.id, 'WAIT');
232
+ const fields = formFields(wait);
233
+ const around = containerOf(draft, prompt.id);
234
+ const at = around.findIndex((step) => asRec(step)['id'] === prompt.id);
235
+ if (!on) {
236
+ // The gate tests a field that is about to go, so what it guarded moves up.
237
+ const gate = asRec(around[at + 1]);
238
+ if (gate['type'] === 'CONDITIONAL')
239
+ around.splice(at + 1, 1, ...asArray(asRec(gate['config'])['if_false']).map(asRec));
240
+ fields.splice(0, Infinity, ...fields.filter((f) => f['type'] !== 'text' && f['type'] !== 'textarea'));
241
+ continue;
242
+ }
243
+ const typing = typedShape(draft, flow, prompt.id);
244
+ // Copied from another screen, so it may name another section's router.
245
+ pointTypedAt([typing.typedJump], flow.routeKey, routerFor(flow, screen.id)?.id);
246
+ fields.push(typing.field);
247
+ const gate = typing.gate;
248
+ gate.id = uniqueName(`typed_${screen.id}`, taken);
249
+ if (typing.typedJump) {
250
+ typing.typedJump.id = uniqueName(`route_${screen.id}`, taken);
251
+ gate.config['if_true'] = [typing.typedJump];
252
+ }
253
+ else {
254
+ gate.config['if_true'] = [];
255
+ }
256
+ gate.config['if_false'] = around.splice(at + 1);
257
+ around.push(gate);
258
+ }
259
+ });
260
+ }
261
+ /**
262
+ * Point whichever GO_TO carries a typed message at `routerId` — a screen's
263
+ * typed branch names the router that serves it, and a copied branch names
264
+ * whichever router the screen it was copied from used.
265
+ */
266
+ function pointTypedAt(steps, routeKey, routerId) {
267
+ if (!routerId)
268
+ return;
269
+ for (const step of asSteps(steps)) {
270
+ if (step.type === 'GO_TO') {
271
+ // A literal screen id is a router link. An expression is a screen taking
272
+ // the person where their own answer said — an Ask AI's way out, say.
273
+ const carried = asRec(step.config['with']);
274
+ const current = carried[routeKey];
275
+ if (typeof current === 'string' && !current.includes('{{'))
276
+ carried[routeKey] = routerId;
277
+ continue;
278
+ }
279
+ if (step.type === 'CONDITIONAL')
280
+ pointTypedAt(asRec(step.config)['if_true'], routeKey, routerId);
281
+ }
282
+ }
283
+ /**
284
+ * What a screen that takes typing is made of, built for `waitId`: the text
285
+ * field, the CONDITIONAL that splits typed from tapped, and the GO_TO carrying
286
+ * the message to the router.
287
+ *
288
+ * Copied from a screen that still takes typing, so the flow's own field names
289
+ * and keys are kept. With none left to copy — the author turned typing off
290
+ * everywhere — the same shape is built from the CYCLE's input keys and the
291
+ * router's id, which is all it ever depended on.
292
+ */
293
+ function typedShape(draft, flow, waitId) {
294
+ for (const s of flow.screens) {
295
+ for (const p of s.prompts) {
296
+ if (!p.textField || p.freeText?.kind !== 'screen' || p.id === waitId)
297
+ continue;
298
+ const gate = asSteps(containerOf(draft, p.id)).find((step) => step.type === 'CONDITIONAL');
299
+ const field = formFields(findStep(draft, p.id, 'WAIT')).find((f) => f['name'] === p.textField);
300
+ if (!gate || !field)
301
+ continue;
302
+ const copy = retarget(clone(gate), p.id, waitId);
303
+ const typedJump = asSteps(asRec(copy.config)['if_true'])[0];
304
+ copy.config['if_true'] = [];
305
+ copy.config['if_false'] = [];
306
+ return { field: clone(field), gate: copy, typedJump };
307
+ }
308
+ }
309
+ const router = flow.screens.find((s) => s.kind === 'router');
310
+ if (!router)
311
+ throw new ConversationalFlowEditError('This flow has no router, so typed messages would have nowhere to go.');
312
+ const textKey = Object.keys(asRec(findStep(draft, flow.cycleId, 'CYCLE').config['input'])).find((k) => k !== flow.routeKey);
313
+ if (!textKey)
314
+ throw new ConversationalFlowEditError('This flow carries no typed text, so a screen cannot take any.');
315
+ const name = 'message';
316
+ const ref = `{{steps.${waitId}.output.resumeData.data.${name}}}`;
317
+ return {
318
+ field: { type: 'text', name, label: 'Or type your question' },
319
+ gate: {
320
+ id: '',
321
+ type: 'CONDITIONAL',
322
+ config: {
323
+ condition: { all: [{ variable: ref, operator: 'exists' }, { variable: ref, operator: 'neq', value: '' }] },
324
+ if_true: [],
325
+ if_false: [],
326
+ },
327
+ },
328
+ typedJump: {
329
+ id: '',
330
+ type: 'GO_TO',
331
+ config: { target: flow.cycleId, with: { [flow.routeKey]: router.id, [textKey]: ref } },
332
+ },
333
+ };
334
+ }
186
335
  /** What a Finish screen returns as the run's outcome. */
187
336
  export function setEndResult(config, screenId, value) {
188
337
  const flow = requireFlow(config);
@@ -191,34 +340,32 @@ export function setEndResult(config, screenId, value) {
191
340
  throw new ConversationalFlowEditError(`“${screen.title}” isn’t a Finish screen.`);
192
341
  return mutate(config, (draft) => {
193
342
  const finish = asSteps(routerCases(draft, flow)[screen.caseIndex]['steps'])[0];
194
- finish.config['with'] = value;
343
+ // The farewell rides in the same object, so editing the result keeps it.
344
+ const { [END_MESSAGE_KEY]: message } = asRec(finish.config['with']);
345
+ finish.config['with'] = { ...value, ...(typeof message === 'string' && message ? { [END_MESSAGE_KEY]: message } : {}) };
195
346
  });
196
347
  }
197
- // ─── The AI router and Ask AI ───
198
- export function setRouterAgent(config, agentSlug) {
348
+ /**
349
+ * What a Finish screen says as it closes the conversation. Empty for a silent
350
+ * one — the conversation simply ends, as it always did.
351
+ */
352
+ export function setEndMessage(config, screenId, message) {
199
353
  const flow = requireFlow(config);
200
- const router = agentRouter(flow);
201
- if (!router?.router)
202
- throw new ConversationalFlowEditError('This flow has no AI router.');
354
+ const screen = requireScreen(flow, screenId);
355
+ if (screen.kind !== 'end')
356
+ throw new ConversationalFlowEditError(`“${screen.title}” isn’t a Finish screen.`);
203
357
  return mutate(config, (draft) => {
204
- findStep(draft, router.router.stepId, AGENT_STEP_TYPE).config['agentSlug'] = agentSlug.trim();
205
- });
206
- }
207
- /** The author's own instructions to the router, put before the generated screen list. */
208
- export function setRouterGuidance(config, guidance) {
209
- const flow = requireFlow(config);
210
- const router = agentRouter(flow);
211
- if (!router?.router)
212
- throw new ConversationalFlowEditError('This flow has no AI router.');
213
- return settle(config, (draft) => {
214
- const step = findStep(draft, router.router.stepId, AGENT_STEP_TYPE);
215
- const text = guidance.trim();
358
+ const finish = asSteps(routerCases(draft, flow)[screen.caseIndex]['steps'])[0];
359
+ const carried = asRec(finish.config['with']);
360
+ const text = message.trim();
216
361
  if (text)
217
- step.description = text;
362
+ carried[END_MESSAGE_KEY] = text;
218
363
  else
219
- delete step.description;
364
+ delete carried[END_MESSAGE_KEY];
365
+ finish.config['with'] = carried;
220
366
  });
221
367
  }
368
+ // ─── The AI router and Ask AI ───
222
369
  export function setAskAi(config, screenId, patch) {
223
370
  const flow = requireFlow(config);
224
371
  const screen = requireScreen(flow, screenId);
@@ -383,10 +530,13 @@ function buildSteps(draft, flow, type, args) {
383
530
  const taken = allStepIds(draft);
384
531
  const back = args.parent ? wayBack(flow, args.parent) : [];
385
532
  if (type === 'end') {
533
+ // Whatever the screen said becomes its last word, so turning a Message into
534
+ // a Finish keeps its wording instead of silently dropping it.
535
+ const carried = { ...(args.prompt ? { [END_MESSAGE_KEY]: args.prompt } : {}), outcome: args.screenId };
386
536
  return [{
387
537
  id: uniqueName(`finish_${args.screenId}`, taken),
388
538
  type: 'FINISH',
389
- config: { target: flow.cycleId, with: { outcome: args.screenId } },
539
+ config: { target: flow.cycleId, with: carried },
390
540
  }];
391
541
  }
392
542
  const template = templateScreen(draft, flow);
@@ -453,7 +603,7 @@ function buildSteps(draft, flow, type, args) {
453
603
  }
454
604
  const options = [...back];
455
605
  if (type === 'message') {
456
- const end = flow.screens.find((s) => s.kind === 'end');
606
+ const end = sharedExit(flow, args.screenId);
457
607
  if (end)
458
608
  options.push({ label: 'That’s all', value: end.id });
459
609
  }
@@ -498,6 +648,25 @@ function buildPromptSteps(t, args) {
498
648
  gate.config['if_false'] = picked;
499
649
  return [wait, gate];
500
650
  }
651
+ /**
652
+ * The ending a new Message screen offers as "That's all": a way out of the
653
+ * conversation that belongs to no branch in particular.
654
+ *
655
+ * A Finish that says something ("Your driver is 3 minutes away") is that
656
+ * branch's own ending, and offering it from an unrelated screen would put words
657
+ * in its mouth. So: a silent Finish first, then whichever ending the most
658
+ * screens already lead to, and none at all when every ending belongs to
659
+ * somewhere — the screen simply keeps its way back.
660
+ */
661
+ function sharedExit(flow, exclude) {
662
+ const ends = flow.screens.filter((s) => s.kind === 'end' && s.id !== exclude);
663
+ const silent = ends.filter((s) => s.endMessage === undefined);
664
+ if (silent.length > 0)
665
+ return silent[0];
666
+ const leads = (id) => flow.screens.filter((s) => optionsOf(s).some((o) => o.to.kind === 'screen' && o.to.screen === id)).length;
667
+ const shared = ends.filter((s) => leads(s.id) > 1).sort((a, b) => leads(b.id) - leads(a.id));
668
+ return shared[0];
669
+ }
501
670
  /**
502
671
  * The options that lead back from a new child of `parent`: back to the parent
503
672
  * itself, then whatever way back the parent already offers. Labels follow the
@@ -523,15 +692,6 @@ function wayBack(flow, parent) {
523
692
  ...inherited.map((o) => ({ label: o.label, value: o.value })),
524
693
  ];
525
694
  }
526
- /** How this flow words the way back to its first screen ("Main menu"), if it has one. */
527
- function mainMenuLabel(flow) {
528
- for (const s of flow.screens) {
529
- const o = optionsOf(s).find((x) => x.back && x.to.kind === 'screen' && x.to.screen === flow.rootScreen);
530
- if (o)
531
- return o.label;
532
- }
533
- return undefined;
534
- }
535
695
  /**
536
696
  * Rewrite the way-back options of `screenId` — and, by default, of everything
537
697
  * beneath it — from its current place in the tree. Top-down, so each screen
@@ -568,156 +728,8 @@ function refreshWayBack(config, screenId, opts = {}) {
568
728
  }
569
729
  return next;
570
730
  }
571
- /** Rewrite every `steps.<from>.` reference inside a step to `steps.<to>.`. */
572
- function retarget(value, from, to) {
573
- const pattern = new RegExp(`(\\{\\{\\s*steps\\.)${escapeRegExp(from)}(\\.)`, 'g');
574
- return JSON.parse(JSON.stringify(value).replace(pattern, `$1${to}$2`));
575
- }
576
731
  // ─── Derived: headers and the router ───
577
- /** Recompute what is derived from the screens (headers, the router) without any other change. */
578
- export function refreshDerived(config) {
579
- return settle(config, () => { });
580
- }
581
- /**
582
- * Apply `edit`, then refresh what is derived from the screens: breadcrumb
583
- * headers (only those that were the generated breadcrumb — a header the author
584
- * wrote is left alone) and the AI router's list of screens.
585
- */
586
- function settle(config, edit,
587
- /** The config as the author last saw it, when `config` is already part-way through a multi-step edit. */
588
- baseline = config) {
589
- const before = requireFlow(baseline);
590
- const wasGenerated = new Set();
591
- for (const s of before.screens) {
592
- const crumb = breadcrumb(before, s);
593
- for (const p of s.prompts)
594
- if (p.header === crumb)
595
- wasGenerated.add(p.id);
596
- }
597
- const edited = mutate(config, edit);
598
- const after = requireFlow(edited);
599
- return mutate(edited, (draft) => {
600
- for (const s of after.screens) {
601
- const crumb = breadcrumb(after, s);
602
- for (const p of s.prompts) {
603
- if (wasGenerated.has(p.id) || p.header === undefined)
604
- findStep(draft, p.id, 'WAIT').config['reason'] = crumb;
605
- }
606
- }
607
- writeRouter(draft, after);
608
- writeHandoffs(draft, after);
609
- });
610
- }
611
- /**
612
- * Where a hand off can go once the person is done: a Finish closes the
613
- * conversation; any other screen hands it back. Finishes first, then the
614
- * screens as the menu reads — never another hand off.
615
- */
616
- function writeHandoffs(draft, flow) {
617
- const handoffs = flow.screens.filter((s) => s.kind === 'handoff' && s.prompts[0]);
618
- if (handoffs.length === 0)
619
- return;
620
- const ends = flow.screens.filter((s) => s.kind === 'end');
621
- const screens = [...treeOrder(flow), ...flow.screens.filter((s) => s.depth === -1 && (s.kind === 'menu' || s.kind === 'message' || s.kind === 'questions' || s.kind === 'ask-ai'))];
622
- const options = [
623
- ...ends.map((s) => ({ label: s.title, value: s.id })),
624
- ...screens.map((s) => ({ label: s.id === flow.rootScreen ? (mainMenuLabel(flow) ?? s.title) : breadcrumb(flow, s), value: s.id })),
625
- ];
626
- for (const h of handoffs)
627
- selectOptions(findStep(draft, h.prompts[0].id, 'WAIT')).splice(0, Infinity, ...options);
628
- }
629
- /** "Payments › Charges › Charged twice" — ancestors below the root, then the screen. */
630
- export function breadcrumb(flow, screen) {
631
- const byId = new Map(flow.screens.map((s) => [s.id, s]));
632
- const chain = [];
633
- for (let at = screen; at; at = at.parent ? byId.get(at.parent) : undefined)
634
- chain.unshift(at);
635
- const titles = chain.filter((s) => s.id !== flow.rootScreen).map((s) => s.title);
636
- return titles.length > 0 ? titles.join(' › ') : screen.title;
637
- }
638
- /** Screens the router may send people to: everything they can be shown. */
639
- export function routableScreens(flow) {
640
- return flow.screens.filter((s) => s.kind !== 'router' && s.kind !== 'end');
641
- }
642
- /**
643
- * The AI router's instructions and output contract, generated from the screens.
644
- * The author's own guidance (the router step's description) goes first; the
645
- * `enum` is what stops the agent naming a screen that doesn't exist.
646
- */
647
- function writeRouter(draft, flow) {
648
- const router = agentRouter(flow)?.router;
649
- if (!router)
650
- return;
651
- const step = findStep(draft, router.stepId, AGENT_STEP_TYPE);
652
- const screens = routableScreens(flow);
653
- const textKey = typedTextKey(draft, flow);
654
- const lines = screens.map((s) => {
655
- const section = flow.screens.some((c) => c.parent === s.id) ? ' [section]' : '';
656
- const about = s.about ?? `the ${breadcrumb(flow, s)} screen`;
657
- return `${s.id} (${breadcrumb(flow, s)})${section} — ${about}`;
658
- });
659
- step.config['task'] = [
660
- ...(router.guidance ? [router.guidance, ''] : []),
661
- textKey
662
- ? `Someone in this conversation typed: "{{steps.__loop.output.input.${textKey}}}"`
663
- : 'Someone in this conversation typed a message.',
664
- '',
665
- 'Send them to the screen that best answers it. The screens, with where each sits:',
666
- ...lines,
667
- '',
668
- 'Prefer the most specific screen. Only choose a [section] when the message is too vague for any of its screens.',
669
- `If nothing fits, choose "${flow.rootScreen}".`,
670
- `Answer with JSON only: {"${flow.routeKey}": "<id from the list>", "reason": "<one short sentence>"}.`,
671
- ].join('\n');
672
- step.config['outputType'] = 'json';
673
- step.config['outputSchema'] = {
674
- type: 'object',
675
- properties: {
676
- [flow.routeKey]: { type: 'string', enum: screens.map((s) => s.id) },
677
- reason: { type: 'string' },
678
- },
679
- required: [flow.routeKey, 'reason'],
680
- };
681
- }
682
- /** The cycle input that carries what they typed — read from a typed-text GO_TO. */
683
- function typedTextKey(draft, flow) {
684
- for (const s of flow.screens) {
685
- for (const p of s.prompts) {
686
- if (p.freeText?.kind !== 'screen' || !p.textField)
687
- continue;
688
- 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}`)));
689
- const carried = asRec(jump?.config['with']);
690
- const key = Object.keys(carried).find((k) => k !== flow.routeKey && typeof carried[k] === 'string' && carried[k].includes('{{'));
691
- if (key)
692
- return key;
693
- }
694
- }
695
- return undefined;
696
- }
697
- function agentRouter(flow) {
698
- return flow.screens.find((s) => s.router?.mode === 'agent');
699
- }
700
732
  // ─── Lookups ───
701
- function requireFlow(config) {
702
- const flow = readConversationalFlow(config);
703
- if (!flow)
704
- throw new ConversationalFlowEditError('This workflow is not a conversational flow.');
705
- return flow;
706
- }
707
- function requireScreen(flow, id) {
708
- const screen = flow.screens.find((s) => s.id === id);
709
- if (!screen)
710
- throw new ConversationalFlowEditError(`There is no screen "${id}".`);
711
- return screen;
712
- }
713
- function promptIn(flow, id) {
714
- for (const s of flow.screens) {
715
- const prompt = s.prompts.find((p) => p.id === id);
716
- if (prompt)
717
- return prompt;
718
- }
719
- throw new ConversationalFlowEditError(`There is no question "${id}".`);
720
- }
721
733
  const HANDOFF_OPTIONS = 'A hand off can be sent to every screen; its options follow the flow on their own.';
722
734
  /** A hand off's options are generated; they aren't edited one by one. */
723
735
  function requireNotHandoff(flow, promptId) {
@@ -751,6 +763,10 @@ function requireNotSoleLink(flow, promptId, option) {
751
763
  function aboutCarrier(draft, screen) {
752
764
  if (screen.prompts[0])
753
765
  return findStep(draft, screen.prompts[0].id, 'WAIT');
766
+ // A Finish has no question to carry it; its own step does. Writing one is
767
+ // also what lets the router end a conversation here — see `endsByTyping`.
768
+ if (screen.kind === 'end')
769
+ return asSteps(caseOf(draft, screen.id)['steps'])[0];
754
770
  throw new ConversationalFlowEditError(`The AI router doesn’t send people to “${screen.title}”.`);
755
771
  }
756
772
  function kindMatches(kind, type) {
@@ -765,103 +781,5 @@ function isBeneath(flow, id, ancestor) {
765
781
  return true;
766
782
  return false;
767
783
  }
768
- function routerCases(draft, flow) {
769
- const router = findStep(draft, flow.routerId, 'SWITCH');
770
- const cases = router.config['cases'];
771
- if (!Array.isArray(cases))
772
- throw new ConversationalFlowEditError('The router has no cases.');
773
- return cases;
774
- }
775
- function caseOf(draft, screenId) {
776
- const flow = requireFlow(draft);
777
- return routerCases(draft, flow)[requireScreen(flow, screenId).caseIndex];
778
- }
779
- function findStep(draft, id, type) {
780
- const found = walk(asSteps(draft.steps)).find((s) => s.id === id);
781
- if (!found || (type && found.type !== type))
782
- throw new ConversationalFlowEditError(`Step "${id}" is missing.`);
783
- return found;
784
- }
785
- function walk(steps, out = []) {
786
- for (const step of steps) {
787
- out.push(step);
788
- for (const value of Object.values(step.config ?? {})) {
789
- if (Array.isArray(value)) {
790
- walk(asSteps(value), out);
791
- for (const entry of value)
792
- walk(asSteps(asRec(entry)['steps']), out);
793
- }
794
- else if (value && typeof value === 'object') {
795
- for (const branch of Object.values(value))
796
- walk(asSteps(branch), out);
797
- }
798
- }
799
- }
800
- return out;
801
- }
802
- function allStepIds(draft) {
803
- return new Set(walk(asSteps(draft.steps)).map((s) => s.id));
804
- }
805
- function selectOptions(wait) {
806
- const fields = asRec(wait.config['form'])['fields'];
807
- const select = Array.isArray(fields) ? fields.find((f) => f['type'] === 'select') : undefined;
808
- if (!select)
809
- throw new ConversationalFlowEditError(`"${wait.id}" has no options field.`);
810
- if (!Array.isArray(select['options']))
811
- select['options'] = [];
812
- return select['options'];
813
- }
814
- function optionAt(wait, index) {
815
- const option = selectOptions(wait)[index];
816
- if (!option)
817
- throw new ConversationalFlowEditError('No such option.');
818
- return option;
819
- }
820
- function firstBackIndex(prompt) {
821
- const i = prompt.options.findIndex((o) => o.back);
822
- return i === -1 ? prompt.options.length : i;
823
- }
824
784
  // ─── Utilities ───
825
- function mutate(config, edit) {
826
- const draft = clone(config);
827
- edit(draft);
828
- return draft;
829
- }
830
- /** The name of a WAIT's field of this kind (`text` covers textarea). */
831
- function fieldOf(wait, kind) {
832
- const fields = asArray(asRec(wait.config['form'])['fields']).map(asRec);
833
- const field = fields.find((f) => (kind === 'text' ? f['type'] === 'text' || f['type'] === 'textarea' : f['type'] === 'select'));
834
- return typeof field?.['name'] === 'string' ? field['name'] : undefined;
835
- }
836
- function clone(value) {
837
- return JSON.parse(JSON.stringify(value));
838
- }
839
- function slug(title) {
840
- return title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'screen';
841
- }
842
- function uniqueName(base, taken) {
843
- let name = base;
844
- for (let n = 2; taken.has(name); n++)
845
- name = `${base}_${n}`;
846
- taken.add(name);
847
- return name;
848
- }
849
- function list(titles) {
850
- return titles.map((t) => `“${t}”`).join(', ');
851
- }
852
- function clamp(n, lo, hi) {
853
- return Math.min(Math.max(n, lo), hi);
854
- }
855
- function escapeRegExp(s) {
856
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
857
- }
858
- function asRec(value) {
859
- return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
860
- }
861
- function asArray(value) {
862
- return Array.isArray(value) ? value : [];
863
- }
864
- function asSteps(value) {
865
- return asArray(value).filter((s) => !!s && typeof s === 'object' && typeof s['id'] === 'string' && typeof s['type'] === 'string');
866
- }
867
785
  //# sourceMappingURL=edit.js.map