@leitwerk-dev/process-sdk 0.1.0

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 (199) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/browser-ui-extension.d.ts +27 -0
  3. package/dist/browser-ui-extension.d.ts.map +1 -0
  4. package/dist/browser-ui-extension.js +2 -0
  5. package/dist/browser-ui-extension.js.map +1 -0
  6. package/dist/capabilities.d.ts +9 -0
  7. package/dist/capabilities.d.ts.map +1 -0
  8. package/dist/capabilities.js +7 -0
  9. package/dist/capabilities.js.map +1 -0
  10. package/dist/chunk-5RJZ2E7D.js +58 -0
  11. package/dist/chunk-5RJZ2E7D.js.map +1 -0
  12. package/dist/chunk-ITPH65G6.js +197 -0
  13. package/dist/chunk-ITPH65G6.js.map +1 -0
  14. package/dist/chunk-LIIP7FMU.js +48 -0
  15. package/dist/chunk-LIIP7FMU.js.map +1 -0
  16. package/dist/codecs.d.ts +3 -0
  17. package/dist/codecs.d.ts.map +1 -0
  18. package/dist/codecs.js +9 -0
  19. package/dist/codecs.js.map +1 -0
  20. package/dist/commit-message.d.ts +7 -0
  21. package/dist/commit-message.d.ts.map +1 -0
  22. package/dist/commit-message.js +3 -0
  23. package/dist/commit-message.js.map +1 -0
  24. package/dist/core-capabilities.d.ts +393 -0
  25. package/dist/core-capabilities.d.ts.map +1 -0
  26. package/dist/core-capabilities.js +6 -0
  27. package/dist/core-capabilities.js.map +1 -0
  28. package/dist/define-process.d.ts +269 -0
  29. package/dist/define-process.d.ts.map +1 -0
  30. package/dist/define-process.js +1040 -0
  31. package/dist/define-process.js.map +1 -0
  32. package/dist/event-bus.d.ts +3 -0
  33. package/dist/event-bus.d.ts.map +1 -0
  34. package/dist/event-bus.js +31 -0
  35. package/dist/event-bus.js.map +1 -0
  36. package/dist/extension-api-CnlL69Tu.d.ts +1281 -0
  37. package/dist/extension-api.d.ts +425 -0
  38. package/dist/extension-api.d.ts.map +1 -0
  39. package/dist/extension-api.js +5 -0
  40. package/dist/extension-api.js.map +1 -0
  41. package/dist/flow.d.ts +456 -0
  42. package/dist/flow.d.ts.map +1 -0
  43. package/dist/flow.js +1557 -0
  44. package/dist/flow.js.map +1 -0
  45. package/dist/form-contract.d.ts +2 -0
  46. package/dist/form-contract.d.ts.map +1 -0
  47. package/dist/form-contract.js +2 -0
  48. package/dist/form-contract.js.map +1 -0
  49. package/dist/fs-utils.d.ts +3 -0
  50. package/dist/fs-utils.d.ts.map +1 -0
  51. package/dist/fs-utils.js +23 -0
  52. package/dist/fs-utils.js.map +1 -0
  53. package/dist/git-binary.d.ts +11 -0
  54. package/dist/git-binary.d.ts.map +1 -0
  55. package/dist/git-binary.js +38 -0
  56. package/dist/git-binary.js.map +1 -0
  57. package/dist/graph-fragments.d.ts +23 -0
  58. package/dist/graph-fragments.d.ts.map +1 -0
  59. package/dist/graph-fragments.js +57 -0
  60. package/dist/graph-fragments.js.map +1 -0
  61. package/dist/host-capabilities.d.ts +12 -0
  62. package/dist/host-capabilities.d.ts.map +1 -0
  63. package/dist/host-capabilities.js +42 -0
  64. package/dist/host-capabilities.js.map +1 -0
  65. package/dist/index.d.ts +35 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +29 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/launcher-contract.d.ts +2 -0
  70. package/dist/launcher-contract.d.ts.map +1 -0
  71. package/dist/launcher-contract.js +2 -0
  72. package/dist/launcher-contract.js.map +1 -0
  73. package/dist/leaf-outcome-renderer.d.ts +48 -0
  74. package/dist/leaf-outcome-renderer.d.ts.map +1 -0
  75. package/dist/leaf-outcome-renderer.js +69 -0
  76. package/dist/leaf-outcome-renderer.js.map +1 -0
  77. package/dist/leaf-outcomes.d.ts +5 -0
  78. package/dist/leaf-outcomes.d.ts.map +1 -0
  79. package/dist/leaf-outcomes.js +52 -0
  80. package/dist/leaf-outcomes.js.map +1 -0
  81. package/dist/model-provider.d.ts +210 -0
  82. package/dist/model-provider.d.ts.map +1 -0
  83. package/dist/model-provider.js +171 -0
  84. package/dist/model-provider.js.map +1 -0
  85. package/dist/pi-config.d.ts +59 -0
  86. package/dist/pi-config.d.ts.map +1 -0
  87. package/dist/pi-config.js +182 -0
  88. package/dist/pi-config.js.map +1 -0
  89. package/dist/process-definition-internals.d.ts +7 -0
  90. package/dist/process-definition-internals.d.ts.map +1 -0
  91. package/dist/process-definition-internals.js +25 -0
  92. package/dist/process-definition-internals.js.map +1 -0
  93. package/dist/process-flow-view.d.ts +20 -0
  94. package/dist/process-flow-view.d.ts.map +1 -0
  95. package/dist/process-flow-view.js +418 -0
  96. package/dist/process-flow-view.js.map +1 -0
  97. package/dist/process-graph.d.ts +45 -0
  98. package/dist/process-graph.d.ts.map +1 -0
  99. package/dist/process-graph.js +213 -0
  100. package/dist/process-graph.js.map +1 -0
  101. package/dist/process-launcher-builder.d.ts +9 -0
  102. package/dist/process-launcher-builder.d.ts.map +1 -0
  103. package/dist/process-launcher-builder.js +43 -0
  104. package/dist/process-launcher-builder.js.map +1 -0
  105. package/dist/process-watcher-builder.d.ts +10 -0
  106. package/dist/process-watcher-builder.d.ts.map +1 -0
  107. package/dist/process-watcher-builder.js +40 -0
  108. package/dist/process-watcher-builder.js.map +1 -0
  109. package/dist/registry-utils.d.ts +8 -0
  110. package/dist/registry-utils.d.ts.map +1 -0
  111. package/dist/registry-utils.js +18 -0
  112. package/dist/registry-utils.js.map +1 -0
  113. package/dist/repository-git-env.d.ts +8 -0
  114. package/dist/repository-git-env.d.ts.map +1 -0
  115. package/dist/repository-git-env.js +26 -0
  116. package/dist/repository-git-env.js.map +1 -0
  117. package/dist/review-flow.d.ts +10 -0
  118. package/dist/review-flow.d.ts.map +1 -0
  119. package/dist/review-flow.js +44 -0
  120. package/dist/review-flow.js.map +1 -0
  121. package/dist/runtime-internals.d.ts +3 -0
  122. package/dist/runtime-internals.d.ts.map +1 -0
  123. package/dist/runtime-internals.js +3 -0
  124. package/dist/runtime-internals.js.map +1 -0
  125. package/dist/server-events.d.ts +84 -0
  126. package/dist/server-events.d.ts.map +1 -0
  127. package/dist/server-events.js +2 -0
  128. package/dist/server-events.js.map +1 -0
  129. package/dist/server-process-builder.d.ts +11 -0
  130. package/dist/server-process-builder.d.ts.map +1 -0
  131. package/dist/server-process-builder.js +52 -0
  132. package/dist/server-process-builder.js.map +1 -0
  133. package/dist/state-helpers.d.ts +9 -0
  134. package/dist/state-helpers.d.ts.map +1 -0
  135. package/dist/state-helpers.js +20 -0
  136. package/dist/state-helpers.js.map +1 -0
  137. package/dist/subprocess-env.d.ts +12 -0
  138. package/dist/subprocess-env.d.ts.map +1 -0
  139. package/dist/subprocess-env.js +34 -0
  140. package/dist/subprocess-env.js.map +1 -0
  141. package/dist/tool-renderers.d.ts +10 -0
  142. package/dist/tool-renderers.d.ts.map +1 -0
  143. package/dist/tool-renderers.js +63 -0
  144. package/dist/tool-renderers.js.map +1 -0
  145. package/dist/turn-semantics.d.ts +22 -0
  146. package/dist/turn-semantics.d.ts.map +1 -0
  147. package/dist/turn-semantics.js +339 -0
  148. package/dist/turn-semantics.js.map +1 -0
  149. package/dist/types.d.ts +295 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/dist/types.js +12 -0
  152. package/dist/types.js.map +1 -0
  153. package/dist/ui-process-builder.d.ts +9 -0
  154. package/dist/ui-process-builder.d.ts.map +1 -0
  155. package/dist/ui-process-builder.js +30 -0
  156. package/dist/ui-process-builder.js.map +1 -0
  157. package/dist/worker-process-builder.d.ts +10 -0
  158. package/dist/worker-process-builder.d.ts.map +1 -0
  159. package/dist/worker-process-builder.js +22 -0
  160. package/dist/worker-process-builder.js.map +1 -0
  161. package/package.json +72 -0
  162. package/src/browser-ui-extension.ts +32 -0
  163. package/src/capabilities.ts +16 -0
  164. package/src/codecs.ts +10 -0
  165. package/src/commit-message.ts +9 -0
  166. package/src/core-capabilities.ts +526 -0
  167. package/src/define-process.ts +1879 -0
  168. package/src/event-bus.ts +35 -0
  169. package/src/extension-api.ts +600 -0
  170. package/src/flow.ts +2268 -0
  171. package/src/form-contract.ts +11 -0
  172. package/src/fs-utils.ts +28 -0
  173. package/src/git-binary.ts +40 -0
  174. package/src/graph-fragments.ts +110 -0
  175. package/src/host-capabilities.ts +60 -0
  176. package/src/index.ts +468 -0
  177. package/src/launcher-contract.ts +8 -0
  178. package/src/leaf-outcome-renderer.ts +112 -0
  179. package/src/leaf-outcomes.ts +74 -0
  180. package/src/model-provider.ts +461 -0
  181. package/src/pi-config.ts +268 -0
  182. package/src/process-definition-internals.ts +46 -0
  183. package/src/process-flow-view.ts +479 -0
  184. package/src/process-graph.ts +309 -0
  185. package/src/process-launcher-builder.ts +59 -0
  186. package/src/process-watcher-builder.ts +72 -0
  187. package/src/registry-utils.ts +31 -0
  188. package/src/repository-git-env.ts +35 -0
  189. package/src/review-flow.ts +66 -0
  190. package/src/runtime-internals.ts +7 -0
  191. package/src/server-events.ts +105 -0
  192. package/src/server-process-builder.ts +90 -0
  193. package/src/state-helpers.ts +36 -0
  194. package/src/subprocess-env.ts +48 -0
  195. package/src/tool-renderers.ts +92 -0
  196. package/src/turn-semantics.ts +554 -0
  197. package/src/types.ts +391 -0
  198. package/src/ui-process-builder.ts +46 -0
  199. package/src/worker-process-builder.ts +33 -0
@@ -0,0 +1,182 @@
1
+ import { homedir } from "node:os";
2
+ import Mustache from "mustache";
3
+ import { PI_BUILT_IN_TOOL_NAMES, } from "./types.js";
4
+ function isScalarValue(value) {
5
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
6
+ }
7
+ function toTemplateContextRecord(value) {
8
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
9
+ return {};
10
+ }
11
+ const context = {};
12
+ for (const [key, candidate] of Object.entries(value)) {
13
+ if (isScalarValue(candidate)) {
14
+ context[key] = candidate;
15
+ }
16
+ }
17
+ return context;
18
+ }
19
+ export function createTemplateContext(input) {
20
+ const context = {
21
+ ...toTemplateContextRecord(input.params),
22
+ };
23
+ if (input.process) {
24
+ context.processId = input.process.processId ?? undefined;
25
+ context.externalId = input.process.externalId ?? undefined;
26
+ context.externalUrl = input.process.externalUrl ?? undefined;
27
+ context.selectedTurnId = input.process.selectedTurnId ?? undefined;
28
+ }
29
+ const firstProject = input.projects?.[0];
30
+ if (firstProject) {
31
+ context.projectKey = firstProject.key;
32
+ context.repositoryUrl = firstProject.repoLocator;
33
+ context.baseBranch = firstProject.baseBranch;
34
+ context.workBranch = firstProject.workBranch ?? undefined;
35
+ }
36
+ return context;
37
+ }
38
+ export function interpolateTemplate(template, context) {
39
+ return Mustache.render(template, context);
40
+ }
41
+ function isTurnDefinitionSource(source) {
42
+ return "kind" in source;
43
+ }
44
+ function resolveToolSourceDefinition(source) {
45
+ return isTurnDefinitionSource(source) ? source : source.definition;
46
+ }
47
+ export function validatePiBuiltInToolArray(toolNames, context) {
48
+ const errors = [];
49
+ const seen = new Set();
50
+ for (const rawName of toolNames) {
51
+ if (typeof rawName !== "string") {
52
+ errors.push(`${context} must contain only string tool names`);
53
+ continue;
54
+ }
55
+ const name = rawName.trim();
56
+ if (name === "") {
57
+ errors.push(`${context} must not contain empty tool names`);
58
+ continue;
59
+ }
60
+ if (name !== rawName) {
61
+ errors.push(`${context} must use canonical Pi tool names without surrounding whitespace`);
62
+ continue;
63
+ }
64
+ if (!PI_BUILT_IN_TOOL_NAMES.includes(name)) {
65
+ errors.push(`${context} references unknown Pi tool '${name}'. Expected one of ${PI_BUILT_IN_TOOL_NAMES.join(", ")}`);
66
+ continue;
67
+ }
68
+ if (seen.has(name)) {
69
+ errors.push(`${context} must not contain duplicate Pi tool '${name}'`);
70
+ continue;
71
+ }
72
+ seen.add(name);
73
+ }
74
+ return errors;
75
+ }
76
+ export function resolveTurnAvailableToolNames(input) {
77
+ const errors = validatePiBuiltInToolArray(input.turnDef.availableTools, `turn '${input.turnId}' availableTools`);
78
+ if (errors.length > 0) {
79
+ throw new Error(errors.join("; "));
80
+ }
81
+ return [...input.turnDef.availableTools];
82
+ }
83
+ export function collectProcessAvailableToolNames(turns) {
84
+ const usedToolNames = new Set();
85
+ for (const source of turns ?? []) {
86
+ const definition = resolveToolSourceDefinition(source);
87
+ if (definition.kind !== "llm" || !("availableTools" in definition)) {
88
+ continue;
89
+ }
90
+ const errors = validatePiBuiltInToolArray(definition.availableTools, "LLM turn availableTools");
91
+ if (errors.length > 0) {
92
+ throw new Error(errors.join("; "));
93
+ }
94
+ for (const toolName of definition.availableTools) {
95
+ usedToolNames.add(toolName);
96
+ }
97
+ }
98
+ return PI_BUILT_IN_TOOL_NAMES.filter((toolName) => usedToolNames.has(toolName));
99
+ }
100
+ const DEFAULT_TOOL_DESCRIPTIONS = {
101
+ read: "Read file contents",
102
+ bash: "Execute bash commands (ls, grep, find, etc.)",
103
+ edit: "Make surgical edits to files (find exact text and replace)",
104
+ write: "Create or overwrite files",
105
+ grep: "Search file contents",
106
+ find: "Find files by name/path",
107
+ ls: "List directory contents",
108
+ };
109
+ function buildDefaultSystemPrompt(availableToolNames) {
110
+ const toolList = availableToolNames.length > 0
111
+ ? availableToolNames
112
+ .map((toolName) => {
113
+ const description = DEFAULT_TOOL_DESCRIPTIONS[toolName] ?? "Built-in Pi tool";
114
+ return `- ${toolName}: ${description}`;
115
+ })
116
+ .join("\n")
117
+ : "- No built-in tools are available for this process unless a turn registers custom tools.";
118
+ return `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by using the tools made available for the active turn.
119
+
120
+ Available built-in tools for this process:
121
+ ${toolList}
122
+
123
+ In addition to the tools above, you may have access to other custom tools depending on the active turn.
124
+
125
+ Guidelines:
126
+ - Use only tools that are available in the active turn.
127
+ - Use read/search tools to examine files before editing.
128
+ - Use edit for precise changes when it is available (old text must match exactly).
129
+ - Use write only for new files or complete rewrites when it is available.
130
+ - When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did.
131
+ - Be concise in your responses.
132
+ - Show file paths clearly when working with files.`;
133
+ }
134
+ export function resolveProcessPiConfig(input) {
135
+ const processConfig = input.configSnapshot?.process_configs?.[input.processId];
136
+ const processPiOverride = processConfig?.pi;
137
+ const availableToolNames = collectProcessAvailableToolNames(input.turns);
138
+ const configSystemPromptTemplate = input.configSnapshot?.pi?.system_prompt_template;
139
+ const systemPromptTemplate = processPiOverride?.system_prompt_template ??
140
+ input.processPiConfig?.systemPromptTemplate ??
141
+ configSystemPromptTemplate;
142
+ const appendSystemPromptTemplate = processPiOverride?.append_system_prompt_template ??
143
+ input.processPiConfig?.appendSystemPromptTemplate;
144
+ const resolvedSystemPrompt = systemPromptTemplate
145
+ ? interpolateTemplate(systemPromptTemplate, input.templateContext)
146
+ : buildDefaultSystemPrompt(availableToolNames);
147
+ const sessionCwd = input.processPiConfig?.sessionCwdTemplate
148
+ ? interpolateTemplate(input.processPiConfig.sessionCwdTemplate, input.templateContext).trim()
149
+ : undefined;
150
+ return {
151
+ systemPrompt: resolvedSystemPrompt,
152
+ appendSystemPrompt: appendSystemPromptTemplate
153
+ ? interpolateTemplate(appendSystemPromptTemplate, input.templateContext)
154
+ : undefined,
155
+ ...(sessionCwd ? { sessionCwd } : {}),
156
+ availableToolNames,
157
+ };
158
+ }
159
+ export function resolveTurnActiveToolNames(input) {
160
+ return resolveTurnAvailableToolNames(input);
161
+ }
162
+ // Mirror Pi's PI_CODING_AGENT_DIR expansion semantics from
163
+ // pi-mono/packages/coding-agent/src/config.ts.
164
+ export function expandPiAgentDir(agentDir) {
165
+ if (agentDir === "~") {
166
+ return homedir();
167
+ }
168
+ if (agentDir.startsWith("~/")) {
169
+ return homedir() + agentDir.slice(1);
170
+ }
171
+ return agentDir;
172
+ }
173
+ export function resolvePiAgentDir(options) {
174
+ const configuredAgentDir = typeof options.agentDir === "string" && options.agentDir.trim() !== ""
175
+ ? options.agentDir
176
+ : typeof options.configSnapshot?.pi?.agent_dir === "string" &&
177
+ options.configSnapshot.pi.agent_dir.trim() !== ""
178
+ ? options.configSnapshot.pi.agent_dir
179
+ : options.fallbackDir;
180
+ return expandPiAgentDir(configuredAgentDir);
181
+ }
182
+ //# sourceMappingURL=pi-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi-config.js","sourceRoot":"","sources":["../src/pi-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,QAAQ,MAAM,UAAU,CAAC;AAEhC,OAAO,EACN,sBAAsB,GAItB,MAAM,YAAY,CAAC;AASpB,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,SAAS,CAAC;AAC7F,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAc;IAC9C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzE,OAAO,EAAE,CAAC;IACX,CAAC;IACD,MAAM,OAAO,GAAoB,EAAE,CAAC;IACpC,KAAK,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACtD,IAAI,aAAa,CAAC,SAAS,CAAC,EAAE,CAAC;YAC9B,OAAO,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;QAC1B,CAAC;IACF,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAcrC;IACA,MAAM,OAAO,GAAoB;QAChC,GAAG,uBAAuB,CAAC,KAAK,CAAC,MAAM,CAAC;KACxC,CAAC;IACF,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,SAAS,IAAI,SAAS,CAAC;QACzD,OAAO,CAAC,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,IAAI,SAAS,CAAC;QAC3D,OAAO,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AG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrC,kBAAkB;KAClB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAC,KAG1C;IACA,OAAO,6BAA6B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC;AAED,2DAA2D;AAC3D,+CAA+C;AAC/C,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAChD,IAAI,QAAQ,KAAK,GAAG,EAAE,CAAC;QACtB,OAAO,OAAO,EAAE,CAAC;IAClB,CAAC;IACD,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/B,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,OAIjC;IACA,MAAM,kBAAkB,GACvB,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE;QACrE,CAAC,CAAC,OAAO,CAAC,QAAQ;QAClB,CAAC,CAAC,OAAO,OAAO,CAAC,cAAc,EAAE,EAAE,EAAE,SAAS,KAAK,QAAQ;YACzD,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE;YAClD,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC,SAAS;YACrC,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC;IACzB,OAAO,gBAAgB,CAAC,kBAAkB,CAAC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { ProcessTurnTransition } from "@leitwerk-dev/domain";
2
+ import type { ProcessTurnBinding } from "./extension-api.js";
3
+ export declare function markDefinedProcess(value: object): void;
4
+ export declare function isDefinedProcess(value: unknown): boolean;
5
+ export declare function setProcessTurnTransitions(binding: object, transitions: readonly ProcessTurnTransition[]): void;
6
+ export declare function getProcessTurnTransitions(binding: ProcessTurnBinding<unknown> | undefined): readonly ProcessTurnTransition[];
7
+ //# sourceMappingURL=process-definition-internals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-definition-internals.d.ts","sourceRoot":"","sources":["../src/process-definition-internals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAmB7D,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAEtD;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAExD;AAED,wBAAgB,yBAAyB,CACxC,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,SAAS,qBAAqB,EAAE,GAC3C,IAAI,CAKN;AAED,wBAAgB,yBAAyB,CACxC,OAAO,EAAE,kBAAkB,CAAC,OAAO,CAAC,GAAG,SAAS,GAC9C,SAAS,qBAAqB,EAAE,CAKlC"}
@@ -0,0 +1,25 @@
1
+ const registryKey = Symbol.for("@leitwerk-dev/process-sdk/internal-registry");
2
+ const registryHolder = globalThis;
3
+ if (!registryHolder[registryKey]) {
4
+ registryHolder[registryKey] = {
5
+ definedProcesses: new WeakSet(),
6
+ turnTransitions: new WeakMap(),
7
+ };
8
+ }
9
+ const registry = registryHolder[registryKey];
10
+ export function markDefinedProcess(value) {
11
+ registry.definedProcesses.add(value);
12
+ }
13
+ export function isDefinedProcess(value) {
14
+ return typeof value === "object" && value !== null && registry.definedProcesses.has(value);
15
+ }
16
+ export function setProcessTurnTransitions(binding, transitions) {
17
+ registry.turnTransitions.set(binding, transitions.map((transition) => ({ ...transition })));
18
+ }
19
+ export function getProcessTurnTransitions(binding) {
20
+ if (!binding) {
21
+ return [];
22
+ }
23
+ return registry.turnTransitions.get(binding)?.map((transition) => ({ ...transition })) ?? [];
24
+ }
25
+ //# sourceMappingURL=process-definition-internals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-definition-internals.js","sourceRoot":"","sources":["../src/process-definition-internals.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,6CAA6C,CAAC,CAAC;AAC9E,MAAM,cAAc,GAAG,UAEtB,CAAC;AACF,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,EAAE,CAAC;IAClC,cAAc,CAAC,WAAW,CAAC,GAAG;QAC7B,gBAAgB,EAAE,IAAI,OAAO,EAAU;QACvC,eAAe,EAAE,IAAI,OAAO,EAA4C;KACxE,CAAC;AACH,CAAC;AACD,MAAM,QAAQ,GAAG,cAAc,CAAC,WAAW,CAAC,CAAC;AAE7C,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC/C,QAAQ,CAAC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,QAAQ,CAAC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAC5F,CAAC;AAED,MAAM,UAAU,yBAAyB,CACxC,OAAe,EACf,WAA6C;IAE7C,QAAQ,CAAC,eAAe,CAAC,GAAG,CAC3B,OAAO,EACP,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC,CACpD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,yBAAyB,CACxC,OAAgD;IAEhD,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;AAC9F,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { type ProcessFlowView } from "@leitwerk-dev/domain";
2
+ import type { ProcessGraphView } from "./process-graph.js";
3
+ /**
4
+ * Removes routing (human) turns from a process graph by merging each one into a
5
+ * single anchor work node (see {@link computeRoutingAnchors}). Edges into a
6
+ * decision are redirected to its anchor, and the decision's action edges are
7
+ * re-emitted from that anchor. Self-loops produced by the merge are left in place
8
+ * here and dropped later during edge construction. Entry turns and the declared
9
+ * happy path are remapped/filtered to stay consistent.
10
+ */
11
+ export declare function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView;
12
+ /**
13
+ * Projects a process graph into a spine-first flow view for operator-facing
14
+ * diagrams. The spine is the declared happy path (or a derived best-effort path
15
+ * when none is declared); every other turn hangs off the spine as a branch.
16
+ * The `aborted` end state is always present because abort is reachable from any
17
+ * active turn, even when no explicit transition targets it.
18
+ */
19
+ export declare function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowView;
20
+ //# sourceMappingURL=process-flow-view.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-flow-view.d.ts","sourceRoot":"","sources":["../src/process-flow-view.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,KAAK,eAAe,EAIpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAwB,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AA8KjF;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,gBAAgB,GAAG,gBAAgB,CAgE9E;AA4HD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,CA2FhF"}
@@ -0,0 +1,418 @@
1
+ import { humanizeProcessLabel, } from "@leitwerk-dev/domain";
2
+ function trimToNull(value) {
3
+ if (typeof value !== "string") {
4
+ return null;
5
+ }
6
+ const trimmed = value.trim();
7
+ return trimmed === "" ? null : trimmed;
8
+ }
9
+ /**
10
+ * Human/operator turns are routing decisions: they pick which path the process
11
+ * takes but perform no work themselves. They are collapsed out of the flow graph
12
+ * so the chart shows only work nodes (LLM/automatic/server) and end states, with
13
+ * the operator's decision surfaced as the edge label between the real nodes.
14
+ */
15
+ function isRoutingTurn(turn) {
16
+ return turn.turnType === "human";
17
+ }
18
+ /**
19
+ * Picks the work turn an operator decision is *about* — its anchor. A decision is
20
+ * both a join (many work turns lead into it) and a split (the operator picks one
21
+ * of several actions). Folding the split onto every join predecessor would invent
22
+ * an N×M mesh of work→work edges that no single step actually connects (e.g. a
23
+ * "review implementation → simplify" edge that does not exist in the process).
24
+ *
25
+ * Instead, every operator decision collapses into exactly one anchor work node:
26
+ * - edges that lead *into* the decision are redirected to the anchor, and
27
+ * - the decision's action edges are emitted *from* the anchor.
28
+ *
29
+ * That yields N+M edges around one real node instead of N×M fabricated ones, and
30
+ * every surviving edge still maps to a single declared transition with one human
31
+ * hop folded into the work node that owns the decision.
32
+ *
33
+ * The anchor is the work predecessor the decision belongs to, preferring a
34
+ * predecessor on the declared happy path (earliest position), then the earliest
35
+ * declared work predecessor. Decisions reached only from other decisions inherit
36
+ * their predecessor decision's anchor.
37
+ */
38
+ function computeRoutingAnchors(graph, routingIds) {
39
+ const declarationIndex = new Map();
40
+ [...graph.turns.keys()].forEach((turnId, index) => {
41
+ declarationIndex.set(turnId, index);
42
+ });
43
+ const happyIndex = new Map();
44
+ (graph.happyPath ?? []).forEach((turnId, index) => {
45
+ if (!happyIndex.has(turnId)) {
46
+ happyIndex.set(turnId, index);
47
+ }
48
+ });
49
+ const workPredecessors = new Map();
50
+ const routingPredecessors = new Map();
51
+ for (const routingId of routingIds) {
52
+ workPredecessors.set(routingId, []);
53
+ routingPredecessors.set(routingId, []);
54
+ }
55
+ for (const [turnId, turn] of graph.turns) {
56
+ for (const transition of turn.transitions) {
57
+ const next = transition.nextTurnId;
58
+ if (next === undefined || !routingIds.has(next) || next === turnId) {
59
+ continue;
60
+ }
61
+ if (routingIds.has(turnId)) {
62
+ routingPredecessors.get(next)?.push(turnId);
63
+ }
64
+ else {
65
+ workPredecessors.get(next)?.push(turnId);
66
+ }
67
+ }
68
+ }
69
+ const preferenceKey = (turnId) => [
70
+ happyIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
71
+ declarationIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
72
+ ];
73
+ const pickPreferred = (candidates) => {
74
+ let best;
75
+ let bestKey;
76
+ for (const candidate of candidates) {
77
+ const key = preferenceKey(candidate);
78
+ if (bestKey === undefined ||
79
+ key[0] < bestKey[0] ||
80
+ (key[0] === bestKey[0] && key[1] < bestKey[1])) {
81
+ best = candidate;
82
+ bestKey = key;
83
+ }
84
+ }
85
+ return best;
86
+ };
87
+ const anchors = new Map();
88
+ for (const routingId of routingIds) {
89
+ const preferred = pickPreferred(workPredecessors.get(routingId) ?? []);
90
+ if (preferred !== undefined) {
91
+ anchors.set(routingId, preferred);
92
+ }
93
+ }
94
+ // Decisions reached only from other decisions resolve transitively to the
95
+ // anchor of a predecessor decision. Iterate to a fixpoint.
96
+ let changed = true;
97
+ while (changed) {
98
+ changed = false;
99
+ for (const routingId of routingIds) {
100
+ if (anchors.has(routingId)) {
101
+ continue;
102
+ }
103
+ for (const predecessor of routingPredecessors.get(routingId) ?? []) {
104
+ const predecessorAnchor = anchors.get(predecessor);
105
+ if (predecessorAnchor !== undefined) {
106
+ anchors.set(routingId, predecessorAnchor);
107
+ changed = true;
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ }
113
+ // Any decision still unresolved (an isolated decision-only cluster) falls back
114
+ // to the first declared work turn so the graph stays connected and deterministic.
115
+ const fallbackWork = [...graph.turns.keys()].find((turnId) => !routingIds.has(turnId));
116
+ if (fallbackWork !== undefined) {
117
+ for (const routingId of routingIds) {
118
+ if (!anchors.has(routingId)) {
119
+ anchors.set(routingId, fallbackWork);
120
+ }
121
+ }
122
+ }
123
+ return anchors;
124
+ }
125
+ function redirectTransition(transition, resolveWork) {
126
+ const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
127
+ if (transition.lifecycleStatus !== undefined) {
128
+ return {
129
+ lifecycleStatus: transition.lifecycleStatus,
130
+ ...(label ? { outcome: label } : {}),
131
+ };
132
+ }
133
+ const next = transition.nextTurnId;
134
+ if (next === undefined) {
135
+ return { ...(label ? { outcome: label } : {}) };
136
+ }
137
+ return {
138
+ nextTurnId: resolveWork(next),
139
+ ...(label ? { outcome: label } : {}),
140
+ };
141
+ }
142
+ function dedupeTransitions(transitions) {
143
+ const seen = new Set();
144
+ const result = [];
145
+ for (const transition of transitions) {
146
+ const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
147
+ const key = `${transition.nextTurnId ?? ""}|${transition.lifecycleStatus ?? ""}|${label ?? ""}`;
148
+ if (seen.has(key)) {
149
+ continue;
150
+ }
151
+ seen.add(key);
152
+ result.push(transition);
153
+ }
154
+ return result;
155
+ }
156
+ /**
157
+ * Removes routing (human) turns from a process graph by merging each one into a
158
+ * single anchor work node (see {@link computeRoutingAnchors}). Edges into a
159
+ * decision are redirected to its anchor, and the decision's action edges are
160
+ * re-emitted from that anchor. Self-loops produced by the merge are left in place
161
+ * here and dropped later during edge construction. Entry turns and the declared
162
+ * happy path are remapped/filtered to stay consistent.
163
+ */
164
+ export function collapseRoutingTurns(graph) {
165
+ const routingIds = new Set();
166
+ for (const [turnId, turn] of graph.turns) {
167
+ if (isRoutingTurn(turn)) {
168
+ routingIds.add(turnId);
169
+ }
170
+ }
171
+ if (routingIds.size === 0) {
172
+ return graph;
173
+ }
174
+ if (routingIds.size === graph.turns.size) {
175
+ return graph;
176
+ }
177
+ const anchors = computeRoutingAnchors(graph, routingIds);
178
+ const resolveWork = (turnId) => routingIds.has(turnId) ? (anchors.get(turnId) ?? turnId) : turnId;
179
+ // Group each decision's action transitions onto its anchor work turn.
180
+ const inheritedByAnchor = new Map();
181
+ for (const routingId of routingIds) {
182
+ const anchor = anchors.get(routingId);
183
+ if (anchor === undefined) {
184
+ continue;
185
+ }
186
+ const routingTurn = graph.turns.get(routingId);
187
+ if (!routingTurn) {
188
+ continue;
189
+ }
190
+ const bucket = inheritedByAnchor.get(anchor) ?? [];
191
+ for (const transition of routingTurn.transitions) {
192
+ bucket.push(redirectTransition(transition, resolveWork));
193
+ }
194
+ inheritedByAnchor.set(anchor, bucket);
195
+ }
196
+ const turns = new Map();
197
+ for (const [turnId, turn] of graph.turns) {
198
+ if (routingIds.has(turnId)) {
199
+ continue;
200
+ }
201
+ const transitions = [
202
+ ...turn.transitions.map((transition) => redirectTransition(transition, resolveWork)),
203
+ ...(inheritedByAnchor.get(turnId) ?? []),
204
+ ];
205
+ turns.set(turnId, { ...turn, transitions: dedupeTransitions(transitions) });
206
+ }
207
+ const entryTurnIds = new Set();
208
+ for (const entry of graph.entryTurnIds) {
209
+ if (graph.turns.has(entry)) {
210
+ entryTurnIds.add(resolveWork(entry));
211
+ }
212
+ }
213
+ const filteredHappyPath = graph.happyPath?.filter((turnId) => !routingIds.has(turnId)) ?? null;
214
+ return {
215
+ id: graph.id,
216
+ primaryEntryTurnId: resolveWork(graph.primaryEntryTurnId),
217
+ entryTurnIds,
218
+ happyPath: filteredHappyPath && filteredHappyPath.length > 0 ? filteredHappyPath : null,
219
+ turns,
220
+ };
221
+ }
222
+ /**
223
+ * Best-effort spine when a process does not declare an explicit happy path.
224
+ * Walks `nextTurnId` edges breadth-first from the entry turn to the nearest turn
225
+ * that can reach a `completed` terminal, preferring the shortest forward path and
226
+ * breaking ties by transition declaration order. Returns `[entry]` when no
227
+ * completing path exists.
228
+ */
229
+ function deriveSpine(graph, entry) {
230
+ const turnsWithCompletedTerminal = new Set();
231
+ for (const [turnId, turn] of graph.turns) {
232
+ if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
233
+ turnsWithCompletedTerminal.add(turnId);
234
+ }
235
+ }
236
+ if (turnsWithCompletedTerminal.size === 0) {
237
+ return [entry];
238
+ }
239
+ const predecessor = new Map([[entry, null]]);
240
+ const queue = [entry];
241
+ let goal = null;
242
+ while (queue.length > 0) {
243
+ const current = queue.shift();
244
+ if (turnsWithCompletedTerminal.has(current)) {
245
+ goal = current;
246
+ break;
247
+ }
248
+ const turn = graph.turns.get(current);
249
+ if (!turn) {
250
+ continue;
251
+ }
252
+ for (const transition of turn.transitions) {
253
+ const next = transition.nextTurnId;
254
+ if (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {
255
+ continue;
256
+ }
257
+ predecessor.set(next, current);
258
+ queue.push(next);
259
+ }
260
+ }
261
+ if (goal === null) {
262
+ return [entry];
263
+ }
264
+ const reversed = [];
265
+ let cursor = goal;
266
+ while (cursor !== null) {
267
+ reversed.push(cursor);
268
+ cursor = predecessor.get(cursor) ?? null;
269
+ }
270
+ return reversed.reverse();
271
+ }
272
+ /**
273
+ * Assigns each non-spine turn to the spine node it hangs off. A branch is anchored
274
+ * to the lowest-index spine node that can reach it without passing through another
275
+ * spine node, so offshoots attach to the earliest spine step that launches them.
276
+ */
277
+ function deriveBranchAnchors(graph, spineIndexByTurn) {
278
+ const anchorByTurn = new Map();
279
+ const orderedSpine = [...spineIndexByTurn.entries()]
280
+ .sort((left, right) => left[1] - right[1])
281
+ .map(([turnId]) => turnId);
282
+ for (const spineTurnId of orderedSpine) {
283
+ const stack = [spineTurnId];
284
+ const visited = new Set([spineTurnId]);
285
+ while (stack.length > 0) {
286
+ const current = stack.pop();
287
+ const turn = graph.turns.get(current);
288
+ if (!turn) {
289
+ continue;
290
+ }
291
+ for (const transition of turn.transitions) {
292
+ const next = transition.nextTurnId;
293
+ if (next === undefined || !graph.turns.has(next) || visited.has(next)) {
294
+ continue;
295
+ }
296
+ visited.add(next);
297
+ if (spineIndexByTurn.has(next)) {
298
+ // Stop at spine nodes; do not traverse through them.
299
+ continue;
300
+ }
301
+ if (!anchorByTurn.has(next)) {
302
+ anchorByTurn.set(next, spineTurnId);
303
+ }
304
+ stack.push(next);
305
+ }
306
+ }
307
+ }
308
+ return anchorByTurn;
309
+ }
310
+ function transitionLabel(transition) {
311
+ // Route every operator-facing edge label through the shared humanizer so the
312
+ // diagram shows nice Title Case names (e.g. `approve_plan` -> `Approve Plan`),
313
+ // consistent with action forms and ready for future localization.
314
+ const raw = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
315
+ return raw === null ? null : humanizeProcessLabel(raw);
316
+ }
317
+ function buildNode(input) {
318
+ return {
319
+ turnId: input.turnId,
320
+ description: trimToNull(input.turn.description) ?? input.turnId,
321
+ turnType: input.turn.turnType,
322
+ role: input.spineIndex === null ? "branch" : "spine",
323
+ spineIndex: input.spineIndex,
324
+ anchorTurnId: input.spineIndex === null ? input.anchorTurnId : null,
325
+ isEntry: input.isEntry,
326
+ };
327
+ }
328
+ /**
329
+ * Projects a process graph into a spine-first flow view for operator-facing
330
+ * diagrams. The spine is the declared happy path (or a derived best-effort path
331
+ * when none is declared); every other turn hangs off the spine as a branch.
332
+ * The `aborted` end state is always present because abort is reachable from any
333
+ * active turn, even when no explicit transition targets it.
334
+ */
335
+ export function buildProcessFlowView(rawGraph) {
336
+ const graph = collapseRoutingTurns(rawGraph);
337
+ const entryTurnIds = [...graph.entryTurnIds].filter((turnId) => graph.turns.has(turnId));
338
+ const primaryEntry = graph.turns.has(graph.primaryEntryTurnId)
339
+ ? graph.primaryEntryTurnId
340
+ : [...graph.turns.keys()][0];
341
+ const declaredSpine = graph.happyPath?.filter((turnId) => graph.turns.has(turnId)) ?? null;
342
+ const spine = declaredSpine && declaredSpine.length > 0
343
+ ? [...declaredSpine]
344
+ : primaryEntry !== undefined
345
+ ? deriveSpine(graph, primaryEntry)
346
+ : [];
347
+ const spineIndexByTurn = new Map();
348
+ spine.forEach((turnId, index) => {
349
+ spineIndexByTurn.set(turnId, index);
350
+ });
351
+ const anchorByTurn = deriveBranchAnchors(graph, spineIndexByTurn);
352
+ const entrySet = new Set(entryTurnIds);
353
+ const nodes = [];
354
+ for (const [turnId, turn] of graph.turns) {
355
+ const spineIndex = spineIndexByTurn.get(turnId) ?? null;
356
+ nodes.push(buildNode({
357
+ turnId,
358
+ turn,
359
+ spineIndex,
360
+ anchorTurnId: anchorByTurn.get(turnId) ?? null,
361
+ isEntry: entrySet.has(turnId),
362
+ }));
363
+ }
364
+ const edges = [];
365
+ const terminalStatuses = new Set();
366
+ for (const [turnId, turn] of graph.turns) {
367
+ for (const transition of turn.transitions) {
368
+ const label = transitionLabel(transition);
369
+ if (transition.lifecycleStatus !== undefined) {
370
+ terminalStatuses.add(transition.lifecycleStatus);
371
+ edges.push({
372
+ from: turnId,
373
+ to: null,
374
+ lifecycleStatus: transition.lifecycleStatus,
375
+ kind: "terminal",
376
+ label,
377
+ });
378
+ continue;
379
+ }
380
+ const next = transition.nextTurnId;
381
+ if (next === undefined) {
382
+ continue;
383
+ }
384
+ // Skip self-loops: an edge that leaves and re-enters the same box adds
385
+ // clutter without conveying additional flow.
386
+ if (next === turnId) {
387
+ continue;
388
+ }
389
+ const fromIndex = spineIndexByTurn.get(turnId);
390
+ const toIndex = spineIndexByTurn.get(next);
391
+ let kind;
392
+ if (fromIndex !== undefined && toIndex !== undefined) {
393
+ kind = toIndex === fromIndex + 1 ? "forward" : "loopback";
394
+ }
395
+ else {
396
+ kind = "branch";
397
+ }
398
+ edges.push({ from: turnId, to: next, lifecycleStatus: null, kind, label });
399
+ }
400
+ }
401
+ const endStates = [];
402
+ for (const status of terminalStatuses) {
403
+ endStates.push({ lifecycleStatus: status, synthetic: false });
404
+ }
405
+ if (!terminalStatuses.has("aborted")) {
406
+ endStates.push({ lifecycleStatus: "aborted", synthetic: true });
407
+ }
408
+ endStates.sort((left, right) => left.lifecycleStatus.localeCompare(right.lifecycleStatus));
409
+ return {
410
+ processId: graph.id,
411
+ entryTurnIds,
412
+ spine,
413
+ nodes,
414
+ edges,
415
+ endStates,
416
+ };
417
+ }
418
+ //# sourceMappingURL=process-flow-view.js.map