@didit-protocol/mcp-server 3.0.3 → 5.1.33

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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +582 -178
  3. package/dist/audit-log.d.ts +22 -0
  4. package/dist/audit-log.d.ts.map +1 -0
  5. package/dist/audit-log.js +77 -0
  6. package/dist/audit-log.js.map +1 -0
  7. package/dist/auth/introspection-verifier.d.ts +16 -0
  8. package/dist/auth/introspection-verifier.d.ts.map +1 -0
  9. package/dist/auth/introspection-verifier.js +77 -0
  10. package/dist/auth/introspection-verifier.js.map +1 -0
  11. package/dist/auth/verifier.d.ts +19 -0
  12. package/dist/auth/verifier.d.ts.map +1 -0
  13. package/dist/auth/verifier.js +88 -0
  14. package/dist/auth/verifier.js.map +1 -0
  15. package/dist/blank-args.d.ts +10 -0
  16. package/dist/blank-args.d.ts.map +1 -0
  17. package/dist/blank-args.js +34 -0
  18. package/dist/blank-args.js.map +1 -0
  19. package/dist/chatgpt-app.d.ts +44 -0
  20. package/dist/chatgpt-app.d.ts.map +1 -0
  21. package/dist/chatgpt-app.js +52 -0
  22. package/dist/chatgpt-app.js.map +1 -0
  23. package/dist/config.d.ts +115 -2
  24. package/dist/config.d.ts.map +1 -1
  25. package/dist/config.js +251 -15
  26. package/dist/config.js.map +1 -1
  27. package/dist/dates.d.ts +2 -0
  28. package/dist/dates.d.ts.map +1 -0
  29. package/dist/dates.js +23 -0
  30. package/dist/dates.js.map +1 -0
  31. package/dist/feature-config-schema.d.ts +66 -0
  32. package/dist/feature-config-schema.d.ts.map +1 -0
  33. package/dist/feature-config-schema.js +192 -0
  34. package/dist/feature-config-schema.js.map +1 -0
  35. package/dist/http.d.ts +4 -0
  36. package/dist/http.d.ts.map +1 -0
  37. package/dist/http.js +230 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/index.d.ts +20 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +2986 -440
  42. package/dist/index.js.map +1 -1
  43. package/dist/internal-tools.d.ts +17 -0
  44. package/dist/internal-tools.d.ts.map +1 -0
  45. package/dist/internal-tools.js +26 -0
  46. package/dist/internal-tools.js.map +1 -0
  47. package/dist/mcp-modern.d.ts +36 -0
  48. package/dist/mcp-modern.d.ts.map +1 -0
  49. package/dist/mcp-modern.js +152 -0
  50. package/dist/mcp-modern.js.map +1 -0
  51. package/dist/orgapp.d.ts +34 -0
  52. package/dist/orgapp.d.ts.map +1 -0
  53. package/dist/orgapp.js +93 -0
  54. package/dist/orgapp.js.map +1 -0
  55. package/dist/permissions.d.ts +24 -0
  56. package/dist/permissions.d.ts.map +1 -0
  57. package/dist/permissions.js +210 -0
  58. package/dist/permissions.js.map +1 -0
  59. package/dist/privileged-tools.d.ts +14 -0
  60. package/dist/privileged-tools.d.ts.map +1 -0
  61. package/dist/privileged-tools.js +21 -0
  62. package/dist/privileged-tools.js.map +1 -0
  63. package/dist/schema/feature-config-schema.json +4446 -0
  64. package/dist/security.d.ts +168 -0
  65. package/dist/security.d.ts.map +1 -0
  66. package/dist/security.js +858 -0
  67. package/dist/security.js.map +1 -0
  68. package/dist/session-pdf-download.d.ts +8 -0
  69. package/dist/session-pdf-download.d.ts.map +1 -0
  70. package/dist/session-pdf-download.js +91 -0
  71. package/dist/session-pdf-download.js.map +1 -0
  72. package/dist/tools/analytics.d.ts +13 -0
  73. package/dist/tools/analytics.d.ts.map +1 -0
  74. package/dist/tools/analytics.js +171 -0
  75. package/dist/tools/analytics.js.map +1 -0
  76. package/dist/tools/auth.d.ts +11 -2
  77. package/dist/tools/auth.d.ts.map +1 -1
  78. package/dist/tools/auth.js +93 -19
  79. package/dist/tools/auth.js.map +1 -1
  80. package/dist/tools/billing.d.ts +2 -2
  81. package/dist/tools/billing.d.ts.map +1 -1
  82. package/dist/tools/billing.js +38 -12
  83. package/dist/tools/billing.js.map +1 -1
  84. package/dist/tools/blocklist.d.ts +2 -1
  85. package/dist/tools/blocklist.d.ts.map +1 -1
  86. package/dist/tools/blocklist.js +10 -19
  87. package/dist/tools/blocklist.js.map +1 -1
  88. package/dist/tools/businesses.d.ts +7 -0
  89. package/dist/tools/businesses.d.ts.map +1 -0
  90. package/dist/tools/businesses.js +57 -0
  91. package/dist/tools/businesses.js.map +1 -0
  92. package/dist/tools/cases.d.ts +6 -0
  93. package/dist/tools/cases.d.ts.map +1 -0
  94. package/dist/tools/cases.js +63 -0
  95. package/dist/tools/cases.js.map +1 -0
  96. package/dist/tools/compliance.d.ts +8 -0
  97. package/dist/tools/compliance.d.ts.map +1 -0
  98. package/dist/tools/compliance.js +95 -0
  99. package/dist/tools/compliance.js.map +1 -0
  100. package/dist/tools/context.d.ts +2 -0
  101. package/dist/tools/context.d.ts.map +1 -0
  102. package/dist/tools/context.js +37 -0
  103. package/dist/tools/context.js.map +1 -0
  104. package/dist/tools/customization.d.ts +18 -0
  105. package/dist/tools/customization.d.ts.map +1 -0
  106. package/dist/tools/customization.js +35 -0
  107. package/dist/tools/customization.js.map +1 -0
  108. package/dist/tools/feature-config.d.ts +53 -0
  109. package/dist/tools/feature-config.d.ts.map +1 -0
  110. package/dist/tools/feature-config.js +432 -0
  111. package/dist/tools/feature-config.js.map +1 -0
  112. package/dist/tools/lists.d.ts +3 -0
  113. package/dist/tools/lists.d.ts.map +1 -1
  114. package/dist/tools/lists.js +29 -26
  115. package/dist/tools/lists.js.map +1 -1
  116. package/dist/tools/members.d.ts +7 -0
  117. package/dist/tools/members.d.ts.map +1 -0
  118. package/dist/tools/members.js +60 -0
  119. package/dist/tools/members.js.map +1 -0
  120. package/dist/tools/observability.d.ts +4 -0
  121. package/dist/tools/observability.d.ts.map +1 -0
  122. package/dist/tools/observability.js +17 -0
  123. package/dist/tools/observability.js.map +1 -0
  124. package/dist/tools/questionnaires.d.ts +61 -3
  125. package/dist/tools/questionnaires.d.ts.map +1 -1
  126. package/dist/tools/questionnaires.js +128 -24
  127. package/dist/tools/questionnaires.js.map +1 -1
  128. package/dist/tools/reports.d.ts +5 -0
  129. package/dist/tools/reports.d.ts.map +1 -0
  130. package/dist/tools/reports.js +89 -0
  131. package/dist/tools/reports.js.map +1 -0
  132. package/dist/tools/search.d.ts +30 -0
  133. package/dist/tools/search.d.ts.map +1 -0
  134. package/dist/tools/search.js +317 -0
  135. package/dist/tools/search.js.map +1 -0
  136. package/dist/tools/session-explain-levers.d.ts +17 -0
  137. package/dist/tools/session-explain-levers.d.ts.map +1 -0
  138. package/dist/tools/session-explain-levers.js +139 -0
  139. package/dist/tools/session-explain-levers.js.map +1 -0
  140. package/dist/tools/session-explain.d.ts +3 -0
  141. package/dist/tools/session-explain.d.ts.map +1 -0
  142. package/dist/tools/session-explain.js +180 -0
  143. package/dist/tools/session-explain.js.map +1 -0
  144. package/dist/tools/sessions.d.ts +16 -3
  145. package/dist/tools/sessions.d.ts.map +1 -1
  146. package/dist/tools/sessions.js +150 -64
  147. package/dist/tools/sessions.js.map +1 -1
  148. package/dist/tools/settings.d.ts +15 -1
  149. package/dist/tools/settings.d.ts.map +1 -1
  150. package/dist/tools/settings.js +141 -22
  151. package/dist/tools/settings.js.map +1 -1
  152. package/dist/tools/standalone.d.ts +9 -6
  153. package/dist/tools/standalone.d.ts.map +1 -1
  154. package/dist/tools/standalone.js +47 -102
  155. package/dist/tools/standalone.js.map +1 -1
  156. package/dist/tools/transactions.d.ts +14 -0
  157. package/dist/tools/transactions.d.ts.map +1 -0
  158. package/dist/tools/transactions.js +93 -0
  159. package/dist/tools/transactions.js.map +1 -0
  160. package/dist/tools/users.d.ts +3 -1
  161. package/dist/tools/users.d.ts.map +1 -1
  162. package/dist/tools/users.js +35 -22
  163. package/dist/tools/users.js.map +1 -1
  164. package/dist/tools/webhooks.d.ts +6 -0
  165. package/dist/tools/webhooks.d.ts.map +1 -0
  166. package/dist/tools/webhooks.js +41 -0
  167. package/dist/tools/webhooks.js.map +1 -0
  168. package/dist/tools/workflow-graph.d.ts +65 -0
  169. package/dist/tools/workflow-graph.d.ts.map +1 -0
  170. package/dist/tools/workflow-graph.js +686 -0
  171. package/dist/tools/workflow-graph.js.map +1 -0
  172. package/package.json +23 -6
@@ -0,0 +1,686 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KYB_REGISTRY_MANUAL_ENTRY_PRICE_USD = void 0;
4
+ exports.annotateAgeAssurance = annotateAgeAssurance;
5
+ exports.getWorkflowGraph = getWorkflowGraph;
6
+ exports.getWorkflowFieldDefinitions = getWorkflowFieldDefinitions;
7
+ exports.getIdVerificationMethodsCatalog = getIdVerificationMethodsCatalog;
8
+ exports.getKybRegistryCatalog = getKybRegistryCatalog;
9
+ exports.getWorkflowBranchFields = getWorkflowBranchFields;
10
+ exports.validateWorkflowGraph = validateWorkflowGraph;
11
+ exports.createWorkflowDraft = createWorkflowDraft;
12
+ exports.publishWorkflow = publishWorkflow;
13
+ exports.setWorkflowGraph = setWorkflowGraph;
14
+ exports.editWorkflowGraph = editWorkflowGraph;
15
+ const node_util_1 = require("node:util");
16
+ const config_1 = require("../config");
17
+ const orgapp_1 = require("../orgapp");
18
+ const search_1 = require("./search");
19
+ const security_1 = require("../security");
20
+ const feature_config_1 = require("./feature-config");
21
+ // Real workflows carry huge feature configs (OCR `documents_allowed` ~157KB, POA
22
+ // `poa_documents_allowed` ~49KB, phone-country lists, …). Returning or requiring those verbatim
23
+ // overflows the model's context and makes edits fragile. We (a) summarize big config values when
24
+ // returning a graph, and (b) edit graphs by applying small ops to the FULL graph SERVER-SIDE, so
25
+ // the allow-lists never round-trip through a tool parameter and are preserved byte-for-byte.
26
+ const MAX_VALUE_CHARS = 800;
27
+ function summarizeValue(v) {
28
+ const s = (() => {
29
+ try {
30
+ return JSON.stringify(v);
31
+ }
32
+ catch {
33
+ return "";
34
+ }
35
+ })();
36
+ if (s.length <= MAX_VALUE_CHARS)
37
+ return v;
38
+ if (Array.isArray(v))
39
+ return { _omitted: true, _type: "array", _items: v.length, _bytes: s.length };
40
+ if (v && typeof v === "object") {
41
+ return { _omitted: true, _type: "object", _keys: Object.keys(v).length, _bytes: s.length, _sample_keys: Object.keys(v).slice(0, 8) };
42
+ }
43
+ return { _omitted: true, _bytes: s.length };
44
+ }
45
+ function summarizeConfig(config) {
46
+ if (!config || typeof config !== "object")
47
+ return config;
48
+ const out = {};
49
+ for (const [k, v] of Object.entries(config))
50
+ out[k] = summarizeValue(v);
51
+ return out;
52
+ }
53
+ /** A structure-only view: node ids/types/features/labels/next/branches kept; large config values
54
+ * replaced with `{_omitted, _bytes, …}` markers so the response stays small. */
55
+ function summarizeGraph(graph) {
56
+ if (!graph || typeof graph !== "object")
57
+ return graph;
58
+ const nodes = {};
59
+ for (const [id, node] of Object.entries(graph.nodes || {})) {
60
+ const n = { ...node };
61
+ if (n.config)
62
+ n.config = summarizeConfig(n.config);
63
+ nodes[id] = n;
64
+ }
65
+ return { start_node: graph.start_node, nodes };
66
+ }
67
+ function requireNode(graph, id) {
68
+ if (!id || !graph.nodes?.[id]) {
69
+ throw new Error(`Graph op references node '${id}' which does not exist. Existing nodes: ` +
70
+ `${Object.keys(graph.nodes || {}).join(", ")}.`);
71
+ }
72
+ }
73
+ /** Apply edit operations to a (full) graph in memory. Small deltas only — never the big config. */
74
+ function applyGraphOps(graph, operations) {
75
+ const g = JSON.parse(JSON.stringify(graph ?? {}));
76
+ g.nodes = g.nodes || {};
77
+ const changes = [];
78
+ for (const op of operations || []) {
79
+ switch (op.op) {
80
+ case "set_node":
81
+ case "add_node":
82
+ if (!op.node_id || !op.node)
83
+ throw new Error("set_node requires node_id + node.");
84
+ g.nodes[op.node_id] = op.node;
85
+ changes.push(`set node ${op.node_id} (${op.node.node_type}${op.node.feature ? ":" + op.node.feature : ""})`);
86
+ break;
87
+ case "remove_node":
88
+ requireNode(g, op.node_id);
89
+ delete g.nodes[op.node_id];
90
+ changes.push(`removed node ${op.node_id}`);
91
+ break;
92
+ case "set_next":
93
+ requireNode(g, op.node_id);
94
+ g.nodes[op.node_id].next = op.next ?? null;
95
+ changes.push(`${op.node_id}.next = ${op.next ?? "null"}`);
96
+ break;
97
+ case "set_branches":
98
+ requireNode(g, op.node_id);
99
+ g.nodes[op.node_id].branches = op.branches ?? [];
100
+ changes.push(`${op.node_id}.branches (${(op.branches ?? []).length})`);
101
+ break;
102
+ case "set_start":
103
+ if (!op.start_node)
104
+ throw new Error("set_start requires start_node.");
105
+ g.start_node = op.start_node;
106
+ changes.push(`start_node = ${op.start_node}`);
107
+ break;
108
+ case "merge_node_config":
109
+ requireNode(g, op.node_id);
110
+ g.nodes[op.node_id].config = { ...(g.nodes[op.node_id].config || {}), ...(op.config || {}) };
111
+ changes.push(`${op.node_id}.config merged (${Object.keys(op.config || {}).join(", ")})`);
112
+ break;
113
+ default:
114
+ throw new Error(`Unknown graph op '${op.op}'. Use one of: set_node, remove_node, set_next, ` +
115
+ `set_branches, set_start, merge_node_config.`);
116
+ }
117
+ }
118
+ return { graph: g, changes };
119
+ }
120
+ /** Branch nodes must express their catch-all as an EXPLICIT else branch (empty rules), not a bare
121
+ * `next` fallback — a bare `next` renders ambiguously in the builder and is easy to omit. Convert
122
+ * each branch node's `next` into an else branch so a branch always carries a visible else path.
123
+ * (Mirrors the backend's own normalization; applied client-side so validate/save reflect it now.) */
124
+ function normalizeBranchElse(graph) {
125
+ if (!graph || typeof graph !== "object" || !graph.nodes)
126
+ return graph;
127
+ for (const node of Object.values(graph.nodes)) {
128
+ if (!node || node.node_type !== "branch")
129
+ continue;
130
+ const branches = Array.isArray(node.branches) ? node.branches : [];
131
+ const hasElse = branches.some((b) => !b?.rules || b.rules.length === 0);
132
+ if (node.next && !hasElse) {
133
+ branches.push({ id: "else", logic: "and", rules: [], goto: node.next });
134
+ }
135
+ node.branches = branches;
136
+ delete node.next; // the catch-all is now the else branch
137
+ }
138
+ return graph;
139
+ }
140
+ async function inScope(workflowId, scope, fn) {
141
+ const resolved = await (0, search_1.resolveWorkflowScope)(workflowId, scope.organization_id, scope.application_id);
142
+ const { organizationId, applicationId, workflow } = resolved;
143
+ const result = await (0, orgapp_1.runForScope)(organizationId, applicationId, () => fn(workflow));
144
+ return (0, search_1.withWorkflowResolution)(result, resolved);
145
+ }
146
+ /** Returned data (data minimization): which data points the client/relying party receives in the
147
+ * decision API and webhooks. The graph endpoint does not carry `response_attributes`, and an
148
+ * agent that cannot see it fills the gap by guessing from which features run ("it has OCR, so
149
+ * the client gets kyc.*") — the exact hallucination this block exists to prevent. The resolved
150
+ * `wf` only carries the field when it came from the settings-detail endpoint, so fall back to
151
+ * fetching it; if even that fails, say so explicitly instead of implying the default. */
152
+ async function returnedData(wf) {
153
+ const settings = wf && typeof wf === "object" && "response_attributes" in wf
154
+ ? wf
155
+ : await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${wf.uuid}/`)).catch(() => null);
156
+ // A payload that omits the key is NOT an explicit null: null means "all data
157
+ // points", and that permissive default must never be implied on uncertain data.
158
+ if (!settings || typeof settings !== "object" || !("response_attributes" in settings)) {
159
+ return {
160
+ unavailable: true,
161
+ hint: "The returned-data config could not be read this turn — tell the user you cannot see it; do NOT guess.",
162
+ };
163
+ }
164
+ return {
165
+ response_attributes: settings.response_attributes ?? null,
166
+ semantics: "The ONLY source of truth for what the client/relying party receives in the decision API " +
167
+ "and webhooks. null or missing (the whole object or a feature key) = ALL data points " +
168
+ "returned; [] = NONE (the client only sees status/warnings/node id); [names] = only " +
169
+ "those fields. Never infer this from which features the workflow runs. When the value is " +
170
+ "null/missing ('all data points'), do NOT enumerate field names — you do not have the " +
171
+ "field catalogue here: say the client receives everything those features produce, " +
172
+ "including document data and, when a selfie/liveness step runs, the selfie image and " +
173
+ "liveness video, and point at the workflow's Returned data panel for the exact list. " +
174
+ "Only an explicit [names] list may be enumerated.",
175
+ };
176
+ }
177
+ /** Age assurance is an umbrella PURPOSE, not a feature: verifying age from a document (the OCR
178
+ * node's age restrictions) and estimating it from a selfie (AGE_ESTIMATION) both count, and
179
+ * neither shows up in the workflow's NAME. Asked "what do my age assurance workflows return?",
180
+ * an agent that can only substring-match the label finds nothing and answers for whichever
181
+ * workflow looked closest — the failure this block exists to prevent. Derived from the FULL
182
+ * graph (before summarizing, which collapses the big `age_restrictions_by_country` map). */
183
+ const AGE_VERIFICATION_FIELDS = ["kyc.age"];
184
+ const AGE_ESTIMATION_FIELDS = ["face.estimated_age", "age_estimation."];
185
+ const AGE_ASSURANCE_SEMANTICS = "Age assurance is the UMBRELLA: verifying age from a document (OCR age restrictions) and " +
186
+ "estimating it from a selfie (AGE_ESTIMATION) both count, as does inferring it. This " +
187
+ "workflow does age assurance if `does_age_assurance` is true — decide from THIS, never " +
188
+ "from the workflow's name, and never narrow the question to age estimation alone. When " +
189
+ "it is false the workflow does NOT do age assurance: if that is what the user asked " +
190
+ "about, tell them they have none rather than answering for this workflow instead.";
191
+ const matchesAny = (field, prefixes) => prefixes.some((prefix) => field === prefix || field.startsWith(prefix));
192
+ /** The age fields a branch rule reads, deduped. `field@node_id` is the console's encoding. */
193
+ function ageConditionFields(nodes) {
194
+ const fields = nodes
195
+ .flatMap((node) => (Array.isArray(node?.branches) ? node.branches : []))
196
+ .flatMap((branch) => Array.isArray(branch?.rules) ? branch.rules : [])
197
+ .map((rule) => String(rule?.field ?? "").split("@")[0])
198
+ .filter((field) => matchesAny(field, [...AGE_VERIFICATION_FIELDS, ...AGE_ESTIMATION_FIELDS]));
199
+ return [...new Set(fields)];
200
+ }
201
+ function ageAssurance(graph) {
202
+ // No graph read, no verdict: "does_age_assurance: false" on missing data would
203
+ // deny a capability the workflow may well have — the same permissive-default
204
+ // trap `returned_data` guards against.
205
+ if (!graph || typeof graph !== "object" || !graph.nodes) {
206
+ return {
207
+ unavailable: true,
208
+ hint: "The graph could not be read this turn — say you cannot tell whether this workflow does age assurance; do NOT report that it does not.",
209
+ };
210
+ }
211
+ const nodes = Object.values(graph.nodes);
212
+ const ocr_age_restrictions = nodes.some((n) => n?.config?.is_age_restrictions_enabled === true);
213
+ const age_estimation_feature = nodes.some((n) => n?.feature === "AGE_ESTIMATION");
214
+ const age_conditions = ageConditionFields(nodes);
215
+ const verifies = ocr_age_restrictions ||
216
+ age_conditions.some((f) => matchesAny(f, AGE_VERIFICATION_FIELDS));
217
+ const estimates = age_estimation_feature ||
218
+ age_conditions.some((f) => matchesAny(f, AGE_ESTIMATION_FIELDS));
219
+ const methods = [
220
+ ...(verifies ? ["age_verification"] : []),
221
+ ...(estimates ? ["age_estimation"] : []),
222
+ ];
223
+ return {
224
+ methods,
225
+ does_age_assurance: methods.length > 0,
226
+ signals: { ocr_age_restrictions, age_estimation_feature, age_conditions },
227
+ semantics: AGE_ASSURANCE_SEMANTICS,
228
+ };
229
+ }
230
+ /** Age assurance on a LIST row. The listing endpoint returns `features` but no graph, so the
231
+ * document route (age restrictions on the OCR step) is invisible there — asked which workflows
232
+ * do age assurance, the agent can only preselect by the AGE_ESTIMATION feature it can see and
233
+ * silently misses the rest (observed 2026-08-17 against a real account). Reading every graph is
234
+ * the only way to know, so it happens SERVER-side, in parallel, behind an opt-in flag. Rows stay
235
+ * TINY on purpose: the verdict and its methods, never the shared semantics (repeating that
236
+ * string per row cost 20KB of context on a 40-row list) and never the signals, which
237
+ * didit_workflow_get_graph already carries for the one workflow the agent drills into. */
238
+ const AGE_ANNOTATION_CAP = 50; // matches searchWorkflows' default limit, so no row is left unjudged
239
+ const AGE_ANNOTATION_CONCURRENCY = 8;
240
+ /** One encoding of "unknown", carrying its own instruction: an unreadable row that merely went
241
+ * missing from the verdict list would re-open the false negative this whole flag exists to close. */
242
+ const AGE_UNREADABLE = {
243
+ does_age_assurance: null,
244
+ age_assurance_note: "Graph unreadable this turn: say you could not check this workflow — never leave it out of " +
245
+ "the answer and never report it as not doing age assurance.",
246
+ };
247
+ async function rowAgeAssurance(row) {
248
+ const read = () => (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${row.uuid}/workflow-graph/`));
249
+ const inRowScope = row.organization_id && row.application_id
250
+ ? () => (0, orgapp_1.runForScope)(row.organization_id, row.application_id, read)
251
+ : read;
252
+ const res = await inRowScope().catch(() => null);
253
+ const verdict = res?.graph ? ageAssurance(res.graph) : null;
254
+ Object.assign(row, verdict ? { does_age_assurance: verdict.does_age_assurance, methods: verdict.methods } : AGE_UNREADABLE);
255
+ }
256
+ function listRows(payload) {
257
+ if (Array.isArray(payload))
258
+ return payload;
259
+ const rows = payload?.results ?? payload?.workflows;
260
+ return Array.isArray(rows) ? rows : [];
261
+ }
262
+ /** Annotate each non-archived row with its age-assurance verdict, in place. */
263
+ async function annotateAgeAssurance(payload) {
264
+ // Only `uuid` addresses the graph endpoint: a stable workflow_id needs the extra
265
+ // resolve probe and would 404 into a spurious "unreadable".
266
+ const targets = listRows(payload).filter((r) => r && !r.is_archived && r.uuid);
267
+ const checked = targets.slice(0, AGE_ANNOTATION_CAP);
268
+ await (0, orgapp_1.mapWithConcurrency)(checked, AGE_ANNOTATION_CONCURRENCY, rowAgeAssurance);
269
+ // Spreading an ARRAY payload into an object literal would hand back {"0":…,"1":…}, so the
270
+ // truncation note only rides on an object; the per-row verdicts survive either way.
271
+ if (checked.length === targets.length || Array.isArray(payload) || !payload)
272
+ return payload;
273
+ return {
274
+ ...payload,
275
+ age_assurance_note: `Only the first ${AGE_ANNOTATION_CAP} of ${targets.length} non-archived workflows were checked; the rest carry no verdict, so do not report them as not doing age assurance.`,
276
+ };
277
+ }
278
+ /** GET the current graph for a workflow, plus its status/version and whether it's editable.
279
+ * Large feature configs are SUMMARIZED by default (set includeConfig to get them verbatim) so
280
+ * the response never overflows context. */
281
+ async function getWorkflowGraph(workflowId, scope = {}, includeConfig = false) {
282
+ return inScope(workflowId, scope, async (wf) => {
283
+ const [res, returned_data] = await Promise.all([
284
+ (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${wf.uuid}/workflow-graph/`)),
285
+ returnedData(wf),
286
+ ]);
287
+ if (!res || typeof res !== "object")
288
+ return res;
289
+ const age_assurance = ageAssurance(res.graph);
290
+ if (includeConfig || !res.graph)
291
+ return { ...res, returned_data, age_assurance };
292
+ return {
293
+ ...res,
294
+ returned_data,
295
+ age_assurance,
296
+ graph: summarizeGraph(res.graph),
297
+ config_summarized: true,
298
+ hint: "Large feature configs (documents_allowed, poa_documents_allowed, phone countries, …) are " +
299
+ "summarized to keep this small. To CHANGE the graph, use didit_workflow_edit_graph with small " +
300
+ "ops (set_next / set_node / set_branches / merge_node_config) — it merges them into the full " +
301
+ "graph server-side, so you never resend those lists. Pass include_config:true to see them.",
302
+ };
303
+ });
304
+ }
305
+ /** The full catalog of branchable fields + the operators valid on each (so the agent builds
306
+ * valid rules — e.g. kyc.extra_fields.profession supports `fuzzy_match`). */
307
+ async function getWorkflowFieldDefinitions(workflowId, scope = {}) {
308
+ return inScope(workflowId, scope, async () => {
309
+ const result = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/workflow-graph/field-definitions/`));
310
+ const feature = scope.feature?.trim().toUpperCase();
311
+ if (!feature)
312
+ return result;
313
+ return {
314
+ feature,
315
+ fields: result?.fields_by_feature?.[feature] ?? [],
316
+ operators_by_field_type: result?.operators_by_field_type ?? {},
317
+ filtered: true,
318
+ };
319
+ });
320
+ }
321
+ /** The ID verification methods capability and pricing catalog: which countries support
322
+ * non-doc lookup, which digital-identity wallets each country offers, their availability
323
+ * (available / coming_soon), plain-language request and response fields, and catalog prices.
324
+ * Served by the backend with integration routes and costs already stripped. */
325
+ async function getIdVerificationMethodsCatalog(workflowId, scope = {}) {
326
+ return inScope(workflowId, scope, async () => {
327
+ const result = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/workflow-graph/id-verification-methods-catalog/`));
328
+ const country = scope.country?.trim().toUpperCase();
329
+ if (!country)
330
+ return result;
331
+ const wallets = Object.fromEntries(Object.entries(result?.wallets ?? {}).filter(([, w]) => (w?.countries ?? []).includes(country)));
332
+ return {
333
+ country,
334
+ document: result?.document,
335
+ id_lookup: result?.id_lookup?.[country] ?? null,
336
+ wallets,
337
+ fallback_actions: result?.fallback_actions,
338
+ max_attempts: result?.max_attempts,
339
+ filtered: true,
340
+ };
341
+ });
342
+ }
343
+ /** Retail names the console shows for the KYB registry data tiers (its i18n keys
344
+ * kyb-registry-tier-basic / -shareholders / -ubo). */
345
+ const KYB_REGISTRY_TIER_NAMES = { basic: "Lite", shareholders: "Shareholders", ubo: "UBOs" };
346
+ /** Flat fee for a company the applicant types in by hand. The pricing endpoint does not
347
+ * serve it; this mirrors the backend's KYB_REGISTRY_MANUAL_ENTRY_PRICE_USD, and the
348
+ * contract test pins it to the number the contract's description prints. */
349
+ exports.KYB_REGISTRY_MANUAL_ENTRY_PRICE_USD = "0.75";
350
+ const KYB_REGISTRY_TIERS = Object.keys(KYB_REGISTRY_TIER_NAMES);
351
+ const ISO2 = /^[A-Z]{2}$/;
352
+ /** The backend's normalize_registry_catalog_country: upper-case, `_` → `-`, and keep
353
+ * only the country part of a subdivision key ("es_md" → "ES"). */
354
+ function normalizeCountryKey(value) {
355
+ return String(value).trim().toUpperCase().replace(/_/g, "-").split("-")[0] ?? "";
356
+ }
357
+ /** A model often sends one code as a bare string; anything else non-array is ignored. */
358
+ function requestedCountries(countries) {
359
+ const list = Array.isArray(countries) ? countries : typeof countries === "string" ? [countries] : [];
360
+ return [...new Set(list.filter((c) => typeof c === "string").map(normalizeCountryKey))].filter(Boolean);
361
+ }
362
+ function offers(country, tier) {
363
+ return country.tiers?.[tier]?.available === true;
364
+ }
365
+ const byAmount = (a, b) => Number(a) - Number(b);
366
+ const distinctPrices = (prices) => [...new Set(prices.filter((p) => typeof p === "string"))].sort(byAmount);
367
+ function summarizeTier(rows, tier) {
368
+ const offering = rows.filter(([, c]) => offers(c, tier));
369
+ return {
370
+ name: KYB_REGISTRY_TIER_NAMES[tier],
371
+ available_in: offering.length,
372
+ price_usd: distinctPrices(offering.map(([, c]) => c.tiers?.[tier]?.price_usd)),
373
+ };
374
+ }
375
+ /** Counts plus the SHORT exception lists: which countries have no registry at all and which
376
+ * stop at Lite. The full per-country table is ~250 rows, so it only travels on request. */
377
+ function summarizeKybRegistryCatalog(rows) {
378
+ const monitored = rows.filter(([, c]) => c.monitoring?.available === true);
379
+ return {
380
+ countries_total: rows.length,
381
+ tiers: Object.fromEntries(KYB_REGISTRY_TIERS.map((tier) => [tier, summarizeTier(rows, tier)])),
382
+ no_registry: rows.filter(([, c]) => !offers(c, "basic")).map(([code]) => code),
383
+ lite_only: rows.filter(([, c]) => offers(c, "basic") && !offers(c, "shareholders") && !offers(c, "ubo")).map(([code]) => code),
384
+ monitoring: {
385
+ available_in: monitored.length,
386
+ price_usd_per_company_per_year: distinctPrices(monitored.map(([, c]) => c.monitoring?.price_usd)),
387
+ },
388
+ note: "Pass `countries` (ISO-2) for a country's exact tiers, prices and monitoring availability.",
389
+ };
390
+ }
391
+ /** The KYB registry catalog: per ISO-2 country, which data tiers the
392
+ * registries offer (basic = Lite, shareholders, ubo), their retail price, and whether continuous
393
+ * monitoring is sold there. Public endpoint: no org/app scope, no provider identity. */
394
+ async function getKybRegistryCatalog(countries) {
395
+ const catalog = (await (0, config_1.apiRequest)("/organization/kyb-registry-pricing/"));
396
+ const rows = catalog && typeof catalog === "object" && !Array.isArray(catalog)
397
+ ? Object.entries(catalog).filter(([code]) => ISO2.test(code))
398
+ : [];
399
+ if (!rows.length) {
400
+ // A maintenance page, an empty body or a redirect would otherwise read as
401
+ // "no country has a registry"; say the catalog could not be read instead.
402
+ throw new security_1.DiditError({
403
+ code: "server_error",
404
+ message: "The KYB registry pricing catalog could not be read (unexpected response shape).",
405
+ hint: "Retry in a moment; if it keeps failing, tell the user the catalog is unavailable rather than guessing tiers.",
406
+ });
407
+ }
408
+ const shared = { tier_names: KYB_REGISTRY_TIER_NAMES, manual_entry_price_usd: exports.KYB_REGISTRY_MANUAL_ENTRY_PRICE_USD };
409
+ const wanted = requestedCountries(countries);
410
+ if (!wanted.length)
411
+ return { ...summarizeKybRegistryCatalog(rows), ...shared };
412
+ const known = new Map(rows);
413
+ const unknown = wanted.filter((code) => !known.has(code));
414
+ return {
415
+ countries: Object.fromEntries(wanted.filter((code) => known.has(code)).map((code) => [code, known.get(code)])),
416
+ ...(unknown.length ? { unknown_countries: unknown, unknown_hint: "Not an ISO 3166-1 alpha-2 code in the catalog (Spain is ES, Germany is DE)." } : {}),
417
+ ...shared,
418
+ filtered: true,
419
+ };
420
+ }
421
+ /** Fields available at a specific branch point given a candidate graph (incl. dynamically-derived
422
+ * Document-AI / questionnaire fields from earlier nodes). Both inputs are checked here, before
423
+ * any network call: the backend reads `branch_node_id` (the old `node_id` wire key was silently
424
+ * dropped, so every call answered "Both 'graph' and 'branch_node_id' are required"). */
425
+ async function getWorkflowBranchFields(workflowId, graph, branchNodeId, scope = {}) {
426
+ requireBranchFieldsArgs(graph, branchNodeId);
427
+ (0, feature_config_1.normalizeFeatureConfigs)(graph);
428
+ return inScope(workflowId, scope, (wf) => (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${wf.uuid}/workflow-graph/branch-fields/`), {
429
+ method: "POST",
430
+ json: { graph, branch_node_id: branchNodeId },
431
+ }));
432
+ }
433
+ function requireBranchFieldsArgs(graph, branchNodeId) {
434
+ const field = !graph?.nodes ? "graph" : !branchNodeId ? "branch_node_id" : "";
435
+ if (!field)
436
+ return;
437
+ throw new security_1.DiditError({
438
+ code: "bad_request",
439
+ field,
440
+ message: "Both 'graph' and 'branch_node_id' are required.",
441
+ hint: "graph is the object returned by didit_workflow_get_graph / ui_workflow_get_graph; branch_node_id is the id of a branch node inside that graph's nodes.",
442
+ });
443
+ }
444
+ /** Dry-run validate a graph without saving. Call this BEFORE set_graph and fix any per-node errors. */
445
+ async function validateWorkflowGraph(workflowId, graph, scope = {}, includeConfig = false) {
446
+ (0, feature_config_1.normalizeFeatureConfigs)(graph);
447
+ normalizeBranchElse(graph);
448
+ (0, feature_config_1.resolveBranchRuleNodeIds)(graph);
449
+ (0, feature_config_1.assertKycKybSegregation)(graph);
450
+ // The backend endpoint is application-scoped: workflow_uuid only feeds the
451
+ // KYC/KYB segregation check for EXISTING workflows. A graph for a workflow
452
+ // that does not exist yet (an unsaved editor canvas) is validated without it.
453
+ const workflowType = scope.workflow_type;
454
+ const validate = async (identity) => {
455
+ const result = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/workflow-graph/validate/`), {
456
+ method: "POST",
457
+ json: { graph, ...identity },
458
+ });
459
+ if (includeConfig || !result?.graph)
460
+ return result;
461
+ return {
462
+ ...result,
463
+ graph: summarizeGraph(result.graph),
464
+ config_summarized: true,
465
+ hint: "Large feature config values are summarized. Pass include_config:true to return them verbatim.",
466
+ };
467
+ };
468
+ if (!workflowId)
469
+ return validate(workflowType ? { workflow_type: workflowType } : {});
470
+ return inScope(workflowId, scope, (wf) => validate({ workflow_uuid: wf.uuid }));
471
+ }
472
+ /** Create an editable DRAFT version from a (published) workflow. */
473
+ async function createWorkflowDraft(workflowId, scope = {}) {
474
+ return inScope(workflowId, scope, (wf) => (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${wf.uuid}/create-draft/`), { method: "POST" }));
475
+ }
476
+ /** The graph as the backend STORED it, or null when it could not be re-read. Deliberately has no
477
+ * fallback to the graph we sent: returning the intent as if it were the result is how "I removed
478
+ * those fields" survived a save that kept them. */
479
+ async function persistedGraph(uuid) {
480
+ try {
481
+ const res = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${uuid}/workflow-graph/`));
482
+ return res?.graph ?? res ?? null;
483
+ }
484
+ catch {
485
+ return null;
486
+ }
487
+ }
488
+ /** Config keys a merge_node_config op asked for that the STORED graph does not match. Reported as
489
+ * UNCONFIRMED rather than dropped: the backend may legitimately normalise a value it accepted, so
490
+ * the honest claim is "re-read this before telling the user it changed" — which is the check that
491
+ * was missing when seven registry fields were reported removed and were still being collected. */
492
+ function unconfirmedConfigKeys(stored, operations) {
493
+ const nodes = stored?.nodes ?? {};
494
+ return operations.flatMap((op) => op.op !== "merge_node_config" || !op.config || !op.node_id
495
+ ? []
496
+ : Object.keys(op.config)
497
+ .filter((key) => !(0, node_util_1.isDeepStrictEqual)(nodes[op.node_id]?.config?.[key], op.config[key]))
498
+ .map((key) => `${op.node_id}.config.${key}`));
499
+ }
500
+ /** What the caller may claim about a save. Names the version_uuid a publish has to target, because
501
+ * the stable workflow_id resolves to the already-published version and telling the caller to
502
+ * "call didit_workflow_publish" without naming the version is what sent it to the wrong one. */
503
+ function readBackNote(stored, published, versionUuid) {
504
+ if (stored === null) {
505
+ return (`The save was accepted but the stored graph could NOT be re-read, so what is actually in ` +
506
+ `version ${versionUuid} is unverified. Re-read it with didit_workflow_get_graph before ` +
507
+ `telling the user what changed.`);
508
+ }
509
+ if (published)
510
+ return `Saved and published — version ${versionUuid} is live for new sessions.`;
511
+ return (`Saved to DRAFT version ${versionUuid}, which is NOT live. Publish it with ` +
512
+ `didit_workflow_publish({ workflow_id: "${versionUuid}" }) — passing the stable workflow_id ` +
513
+ `instead targets the version that is already published. Existing sessions are unaffected.`);
514
+ }
515
+ /** PATCH one version to published and report the status the API CONFIRMS, never the one we asked
516
+ * for. A body carrying no status (204, bare success) means the PATCH did not error but nothing
517
+ * read it back, so it is reported as unconfirmed instead of being dressed up as a read-back. */
518
+ async function publishVersion(uuid) {
519
+ const res = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${uuid}/`), {
520
+ method: "PATCH",
521
+ json: { status: "published" },
522
+ });
523
+ const status = typeof res?.status === "string" ? res.status.toLowerCase() : null;
524
+ return { status: status ?? "published", confirmed: status !== null };
525
+ }
526
+ /** The version a publish must target. A draft publishes itself; a PUBLISHED version can never
527
+ * carry an edit, because set_graph/edit_graph apply to a draft — so its pending changes live in
528
+ * that draft and publishing the published version again makes nothing live. create-draft is
529
+ * idempotent (max 1 draft per workflow group), so it hands back the draft that holds the edits
530
+ * rather than making another one. */
531
+ async function versionToPublish(wf) {
532
+ if (String(wf.status ?? "").toLowerCase() === "draft")
533
+ return wf.uuid;
534
+ // Requires a POSITIVE signal that a draft exists (list rows carry has_draft). Without one,
535
+ // create-draft would clone the live version and publishing that clone is a new version that
536
+ // changes nothing — a no-op dressed up as a publish, which is the whole defect.
537
+ if (wf.has_draft !== true) {
538
+ throw new Error(`Workflow version ${wf.uuid} is already published, with no draft version to publish, so ` +
539
+ `there is nothing to publish and nothing changed. Edit the workflow first ` +
540
+ `(didit_workflow_edit_graph) and publish the version_uuid that edit returns.`);
541
+ }
542
+ const draft = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${wf.uuid}/create-draft/`), {
543
+ method: "POST",
544
+ });
545
+ const uuid = draft?.uuid ?? draft?.workflow_id;
546
+ if (!uuid)
547
+ throw new Error(`Could not resolve the draft version of ${wf.uuid} to publish.`);
548
+ return uuid;
549
+ }
550
+ /** Publish the version that actually holds the pending changes (makes it live for new sessions).
551
+ * Accepts a draft version uuid or the stable workflow_id: the stable id resolves to the LISTED
552
+ * version, which is the published one, so publishing it verbatim republished a version nobody had
553
+ * edited and reported success. */
554
+ async function publishWorkflow(workflowId, scope = {}) {
555
+ return inScope(workflowId, scope, async (wf) => {
556
+ const target = await versionToPublish(wf);
557
+ const { status, confirmed } = await publishVersion(target);
558
+ const live = status === "published";
559
+ return {
560
+ workflow_id: wf.workflow_id ?? workflowId,
561
+ version_uuid: target,
562
+ status,
563
+ published: live,
564
+ status_confirmed: confirmed,
565
+ note: live
566
+ ? `Version ${target} is live for new sessions. Existing sessions are unaffected.`
567
+ : `The API reports status "${status}" for version ${target} after the publish — it is NOT ` +
568
+ `live. Say so; do not report this workflow as published.`,
569
+ };
570
+ });
571
+ }
572
+ /** Replace a workflow's graph. If the resolved version is published, a DRAFT is auto-created and
573
+ * the graph applied there (a live version is never mutated). `publish=true` publishes afterwards;
574
+ * otherwise it stays a reviewable DRAFT. */
575
+ async function setWorkflowGraph(workflowId, graph, publish = false, scope = {}) {
576
+ (0, feature_config_1.normalizeFeatureConfigs)(graph);
577
+ normalizeBranchElse(graph);
578
+ (0, feature_config_1.resolveBranchRuleNodeIds)(graph);
579
+ (0, feature_config_1.assertKycKybSegregation)(graph);
580
+ const { organizationId, applicationId, workflow } = await (0, search_1.resolveWorkflowScope)(workflowId, scope.organization_id, scope.application_id);
581
+ return (0, orgapp_1.runForScope)(organizationId, applicationId, async () => {
582
+ let targetUuid = workflow.uuid;
583
+ let createdDraft = false;
584
+ const status = String(workflow.status ?? "").toLowerCase();
585
+ if (status && status !== "draft") {
586
+ const draft = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${workflow.uuid}/create-draft/`), { method: "POST" });
587
+ targetUuid = draft?.uuid ?? draft?.workflow_id ?? targetUuid;
588
+ createdDraft = true;
589
+ }
590
+ await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${targetUuid}/workflow-graph/`), {
591
+ method: "PUT",
592
+ json: { graph },
593
+ });
594
+ const stored = await persistedGraph(targetUuid);
595
+ const published = publish ? (await publishVersion(targetUuid)).status === "published" : false;
596
+ return {
597
+ workflow_id: workflowId,
598
+ version_uuid: targetUuid,
599
+ organization_id: organizationId,
600
+ application_id: applicationId,
601
+ created_draft: createdDraft,
602
+ published,
603
+ status: published ? "published" : "draft",
604
+ graph_read_back: stored !== null,
605
+ ...(stored ? { graph: summarizeGraph(stored) } : {}),
606
+ note: readBackNote(stored, published, targetUuid),
607
+ };
608
+ });
609
+ }
610
+ /** Edit a workflow's graph with small OPERATIONS instead of resending the whole thing. The MCP
611
+ * fetches the full current graph SERVER-SIDE, applies the ops, validates, and (auto-drafting a
612
+ * published workflow) saves it — so huge feature configs (documents_allowed, poa lists, phone
613
+ * countries) are preserved byte-for-byte and never pass through a tool parameter. This is the way
614
+ * to modify an EXISTING workflow; `set_graph` (full replace) is only for building one from scratch. */
615
+ async function editWorkflowGraph(workflowId, operations, publish = false, scope = {}) {
616
+ if (!Array.isArray(operations) || operations.length === 0) {
617
+ throw new Error("edit_graph requires a non-empty `operations` array.");
618
+ }
619
+ const { organizationId, applicationId, workflow } = await (0, search_1.resolveWorkflowScope)(workflowId, scope.organization_id, scope.application_id);
620
+ return (0, orgapp_1.runForScope)(organizationId, applicationId, async () => {
621
+ // 1. Fetch the FULL current graph server-side (allow-lists included; never sent by the model).
622
+ const current = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${workflow.uuid}/workflow-graph/`));
623
+ const baseGraph = current?.graph ?? current;
624
+ // 2. Apply the small ops in memory, then normalize branch catch-alls to explicit else branches.
625
+ const { graph: merged, changes } = applyGraphOps(baseGraph, operations);
626
+ (0, feature_config_1.normalizeFeatureConfigs)(merged);
627
+ normalizeBranchElse(merged);
628
+ (0, feature_config_1.resolveBranchRuleNodeIds)(merged);
629
+ (0, feature_config_1.assertKycKybSegregation)(merged);
630
+ // 3. Dry-run validate server-side. Return cleanly on failure — never save a broken graph.
631
+ let validation;
632
+ try {
633
+ validation = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/workflow-graph/validate/`), {
634
+ method: "POST",
635
+ json: { graph: merged, workflow_uuid: workflow.uuid },
636
+ });
637
+ }
638
+ catch (e) {
639
+ validation = { is_valid: false, error: e?.message ?? String(e) };
640
+ }
641
+ if (validation && validation.is_valid === false) {
642
+ return {
643
+ applied: false,
644
+ changes,
645
+ validation,
646
+ note: "Validation failed — nothing was saved. Fix the reported issues and retry.",
647
+ };
648
+ }
649
+ // 4. Apply to a DRAFT (the live published version is never mutated).
650
+ let targetUuid = workflow.uuid;
651
+ let createdDraft = false;
652
+ if (String(workflow.status ?? "").toLowerCase() !== "draft") {
653
+ const draft = await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${workflow.uuid}/create-draft/`), { method: "POST" });
654
+ targetUuid = draft?.uuid ?? draft?.workflow_id ?? targetUuid;
655
+ createdDraft = true;
656
+ }
657
+ await (0, config_1.apiRequest)((0, config_1.orgAppPath)(`/verification-settings/${targetUuid}/workflow-graph/`), {
658
+ method: "PUT",
659
+ json: { graph: merged },
660
+ });
661
+ const stored = await persistedGraph(targetUuid);
662
+ const unconfirmed = stored ? unconfirmedConfigKeys(stored, operations) : [];
663
+ const published = publish ? (await publishVersion(targetUuid)).status === "published" : false;
664
+ return {
665
+ applied: true,
666
+ changes,
667
+ workflow_id: workflowId,
668
+ version_uuid: targetUuid,
669
+ organization_id: organizationId,
670
+ application_id: applicationId,
671
+ created_draft: createdDraft,
672
+ published,
673
+ status: published ? "published" : "draft",
674
+ node_count: Object.keys(merged.nodes || {}).length,
675
+ graph_read_back: stored !== null,
676
+ ...(stored ? { graph: summarizeGraph(stored) } : {}),
677
+ ...(unconfirmed.length > 0 ? { unconfirmed_config_keys: unconfirmed } : {}),
678
+ note: unconfirmed.length > 0
679
+ ? `The stored graph does NOT match what was requested for ${unconfirmed.join(", ")}. ` +
680
+ `Re-read those with didit_workflow_get_graph before telling the user they changed. ` +
681
+ readBackNote(stored, published, targetUuid)
682
+ : readBackNote(stored, published, targetUuid),
683
+ };
684
+ });
685
+ }
686
+ //# sourceMappingURL=workflow-graph.js.map