@bpmnkit/core 1.2.0 → 1.4.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 (51) hide show
  1. package/README.md +26 -0
  2. package/dist/bpmn/bpmn-builder.d.ts +8 -0
  3. package/dist/bpmn/bpmn-builder.js +6 -2
  4. package/dist/bpmn/compact.d.ts +39 -5
  5. package/dist/bpmn/compact.js +151 -29
  6. package/dist/bpmn/connector-line.d.ts +46 -0
  7. package/dist/bpmn/connector-line.js +135 -0
  8. package/dist/bpmn/full-operations.js +8 -1
  9. package/dist/bpmn/optimize/patterns.js +1 -3
  10. package/dist/bpmn/process-delta.d.ts +7 -0
  11. package/dist/bpmn/process-delta.js +34 -2
  12. package/dist/bpmn/process-text-writer.d.ts +12 -2
  13. package/dist/bpmn/process-text-writer.js +16 -1
  14. package/dist/bpmn/process-text.d.ts +36 -1
  15. package/dist/bpmn/process-text.js +412 -17
  16. package/dist/bpmn/rest-connector.d.ts +6 -0
  17. package/dist/bpmn/rest-connector.js +6 -0
  18. package/dist/bpmn/secrets.d.ts +15 -0
  19. package/dist/bpmn/secrets.js +59 -0
  20. package/dist/bpmn/utils.js +4 -0
  21. package/dist/bpmn/zeebe-extensions.d.ts +10 -0
  22. package/dist/bpmn/zeebe-extensions.js +7 -0
  23. package/dist/connectors/aliases.d.ts +21 -0
  24. package/dist/connectors/aliases.js +272 -0
  25. package/dist/connectors/api.d.ts +118 -0
  26. package/dist/connectors/api.js +280 -0
  27. package/dist/connectors/apply-element.d.ts +59 -0
  28. package/dist/connectors/apply-element.js +385 -0
  29. package/dist/connectors/apply.d.ts +136 -0
  30. package/dist/connectors/apply.js +352 -0
  31. package/dist/connectors/cards.d.ts +96 -0
  32. package/dist/connectors/cards.js +306 -0
  33. package/dist/connectors/catalog.d.ts +79 -0
  34. package/dist/connectors/catalog.js +209 -0
  35. package/dist/connectors/index.d.ts +33 -0
  36. package/dist/connectors/index.js +24 -0
  37. package/dist/connectors/lines.d.ts +108 -0
  38. package/dist/connectors/lines.js +568 -0
  39. package/dist/connectors/select.d.ts +85 -0
  40. package/dist/connectors/select.js +419 -0
  41. package/dist/connectors/template-types.d.ts +188 -0
  42. package/dist/connectors/template-types.js +6 -0
  43. package/dist/connectors/templates/bpmnkit.d.ts +12 -0
  44. package/dist/connectors/templates/bpmnkit.js +186 -0
  45. package/dist/connectors/templates/generated.d.ts +3 -0
  46. package/dist/connectors/templates/generated.js +95885 -0
  47. package/dist/connectors/validate.d.ts +66 -0
  48. package/dist/connectors/validate.js +271 -0
  49. package/dist/index.d.ts +7 -3
  50. package/dist/index.js +2 -0
  51. package/package.json +5 -1
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Picks the connector cards a model sees when it connects a diagram.
3
+ *
4
+ * The connect pass runs after the diagram has its shape, so every task already
5
+ * has a name: "Post summary to Slack", "List open issues". Cards are picked per
6
+ * task from that name, with the user's request as context for the systems it
7
+ * names, and capped so the prompt stays small. No model is involved: when no
8
+ * task matches anything, there is nothing to ask a model.
9
+ */
10
+ import type { BpmnElementType } from "../index.js";
11
+ import { type ApiCard, type ApiService } from "./api.js";
12
+ import { type ConnectorCard } from "./cards.js";
13
+ /** A node that could carry a connector. */
14
+ export interface ConnectorTask {
15
+ id: string;
16
+ name?: string;
17
+ type: BpmnElementType;
18
+ }
19
+ /** The cards picked for one task, best first. */
20
+ export interface TaskCards {
21
+ id: string;
22
+ name?: string;
23
+ cards: ConnectorCard[];
24
+ /** Endpoints of services the task names that no dedicated connector covers, for `http`. */
25
+ apis?: ApiCard[];
26
+ }
27
+ /**
28
+ * Picks cards for each task that could carry a connector: tasks, and events a
29
+ * connector template can attach to. A card is a candidate for a task when:
30
+ *
31
+ * - the task's name names the card's system ("Post to **Slack**"), or
32
+ * - the task is a task (not an event), the request names the system, no
33
+ * other task's name does, and the card fits the task, or
34
+ * - the task's name shares a word other than a common verb with the
35
+ * connector's name ("Publish **event**" and an event-bus connector).
36
+ *
37
+ * Ranking:
38
+ * - A few words requests use for what templates call something else rank the
39
+ * candidates: "notify" prefers a connector's message-sending operation.
40
+ * - A connector naming a system nobody asked for ranks lower: "Azure OpenAI"
41
+ * for a request that says OpenAI.
42
+ * - Each further card of one template ranks lower, so one connector's
43
+ * operations do not crowd out another the request names.
44
+ * - Deprecated templates are never offered.
45
+ *
46
+ * The REST connector is offered for a task whose name asks for an HTTP call
47
+ * ("Fetch order", "Call endpoint") when nothing else fits, and for a task with
48
+ * no connector of its own when the request asks for a REST call. Tasks with no
49
+ * candidate are left out, so an empty answer means there is nothing to connect.
50
+ *
51
+ * With `options.apis`, services of the API index: a task (not an event) that
52
+ * names a service, or whose request does as above, gets the REST connector
53
+ * first and an API card with the service's best-fitting operations — unless a
54
+ * dedicated connector for that system has an operation the task's name
55
+ * mentions. A dedicated connector comes first; the index is for the rest.
56
+ * - A task that names only the service ("Call Stripe REST API") is matched to
57
+ * operations by the request's words.
58
+ * - A service only the request names goes to the one task it fits best.
59
+ *
60
+ * @param options.perTask - Cards per task, at most (default 3).
61
+ * @param options.total - Cards in all, at most (default 8). Every task keeps
62
+ * its best card before any task gets a second.
63
+ * @param options.apis - Services of `@bpmnkit/connector-gen/api-index` the
64
+ * request or the task names named, loaded.
65
+ */
66
+ export declare function selectConnectors(input: {
67
+ text?: string;
68
+ tasks: readonly ConnectorTask[];
69
+ }, options?: {
70
+ perTask?: number;
71
+ total?: number;
72
+ apis?: readonly ApiService[];
73
+ }): TaskCards[];
74
+ /**
75
+ * The picked cards as a prompt block, one task per paragraph:
76
+ *
77
+ * ```
78
+ * notify (Notify ops):
79
+ * slack chat.postMessage — … | token*(secret) data.text* data.channel* | …
80
+ * ```
81
+ *
82
+ * API cards follow a task's connector cards.
83
+ */
84
+ export declare function formatConnectorSelection(selection: readonly TaskCards[]): string;
85
+ //# sourceMappingURL=select.d.ts.map
@@ -0,0 +1,419 @@
1
+ /**
2
+ * Picks the connector cards a model sees when it connects a diagram.
3
+ *
4
+ * The connect pass runs after the diagram has its shape, so every task already
5
+ * has a name: "Post summary to Slack", "List open issues". Cards are picked per
6
+ * task from that name, with the user's request as context for the systems it
7
+ * names, and capped so the prompt stays small. No model is involved: when no
8
+ * task matches anything, there is nothing to ask a model.
9
+ */
10
+ import { apiBrand, formatApiCard, rankApiOperations } from "./api.js";
11
+ import { cardScore, connectorCards, formatConnectorCard, listConnectorCards, searchTerms, } from "./cards.js";
12
+ import { getTemplate } from "./catalog.js";
13
+ /** Element types a connector template can be applied to, by the BPMN name templates use. */
14
+ const BPMN_TYPE = {
15
+ task: "bpmn:Task",
16
+ serviceTask: "bpmn:ServiceTask",
17
+ sendTask: "bpmn:SendTask",
18
+ scriptTask: "bpmn:ScriptTask",
19
+ receiveTask: "bpmn:ReceiveTask",
20
+ startEvent: "bpmn:StartEvent",
21
+ endEvent: "bpmn:EndEvent",
22
+ intermediateCatchEvent: "bpmn:IntermediateCatchEvent",
23
+ intermediateThrowEvent: "bpmn:IntermediateThrowEvent",
24
+ boundaryEvent: "bpmn:BoundaryEvent",
25
+ };
26
+ /** Tasks a template written for `bpmn:Task` turns into its own type. */
27
+ const TASKS = new Set(["task", "serviceTask", "sendTask", "scriptTask"]);
28
+ /** Template element types that turn a task into an outbound call. */
29
+ const OUTBOUND_TASKS = new Set(["bpmn:ServiceTask", "bpmn:SendTask", "bpmn:Task"]);
30
+ /**
31
+ * A request's words, each whole and split at case changes: "GitHub" is both
32
+ * `github`, the system, and `git hub`, as operation names are split.
33
+ */
34
+ function termsOf(text) {
35
+ const whole = text
36
+ .toLowerCase()
37
+ .split(/[^a-z0-9]+/)
38
+ .filter((w) => w.length > 1);
39
+ return [...new Set([...searchTerms(text), ...searchTerms(whole.join(" "))])];
40
+ }
41
+ /** Whether a card's template can be applied to an element of this type. */
42
+ function fits(card, type) {
43
+ const bpmn = BPMN_TYPE[type];
44
+ const template = getTemplate(card.templateId);
45
+ if (!bpmn || !template)
46
+ return false;
47
+ const target = template.elementType?.value;
48
+ if (target !== undefined) {
49
+ // An outbound task template converts any task; any other keeps to its own element type
50
+ return target === bpmn || (TASKS.has(type) && OUTBOUND_TASKS.has(target));
51
+ }
52
+ return (template.appliesTo.includes(bpmn) ||
53
+ (TASKS.has(type) && template.appliesTo.includes("bpmn:Task")));
54
+ }
55
+ /** Alias parts that say how a connector attaches, not which system it talks to. */
56
+ const NOT_A_SYSTEM = new Set([
57
+ "start",
58
+ "catch",
59
+ "boundary",
60
+ "receive",
61
+ "message",
62
+ "throw",
63
+ "end",
64
+ "send",
65
+ "legacy",
66
+ "remote",
67
+ "subprocess",
68
+ "polling",
69
+ "tools",
70
+ "schema",
71
+ "adhoc",
72
+ "kb",
73
+ "code",
74
+ "memory",
75
+ "flow",
76
+ "incident",
77
+ "chat",
78
+ "api",
79
+ ]);
80
+ /** The systems a card's alias names: `github-webhook-start` → github, webhook. */
81
+ function systems(card) {
82
+ return card.alias.split("-").filter((part) => !NOT_A_SYSTEM.has(part) && !/^v\d+$/.test(part));
83
+ }
84
+ /** Verbs every connector has an operation for; a match on them alone says nothing. */
85
+ const VERBS = new Set([
86
+ "create",
87
+ "get",
88
+ "list",
89
+ "update",
90
+ "delete",
91
+ "send",
92
+ "add",
93
+ "remove",
94
+ "read",
95
+ "write",
96
+ "find",
97
+ "search",
98
+ "check",
99
+ "run",
100
+ "post",
101
+ "put",
102
+ "set",
103
+ "new",
104
+ "all",
105
+ "open",
106
+ ]);
107
+ /** Words requests use for what templates call something else: "Notify ops" is a message. */
108
+ const SYNONYMS = {
109
+ append: ["add"],
110
+ notify: ["message", "send"],
111
+ inform: ["message", "send"],
112
+ alert: ["message", "send"],
113
+ tell: ["message", "send"],
114
+ mail: ["email"],
115
+ text: ["message"],
116
+ sms: ["message"],
117
+ };
118
+ function withSynonyms(terms) {
119
+ return [...new Set(terms.flatMap((t) => [t, ...(SYNONYMS[t] ?? [])]))];
120
+ }
121
+ /** Words of a task name that mean a plain REST call when no connector names the system. */
122
+ const HTTP_WORDS = new Set(["http", "https", "rest", "endpoint", "fetch", "url", "webhook"]);
123
+ /**
124
+ * Nouns every business process has, which a connector's name may share without being
125
+ * asked for: "Request rework" is no SOAP request, "Save document" no Textract call.
126
+ */
127
+ const GENERIC = new Set(["request", "document", "file", "data", "report", "record", "form"]);
128
+ /** Whether a request's terms name a system: one word, singular or plural ("Google Sheet"). */
129
+ function askedFor(system, requested) {
130
+ return [system, system.replace(/s$/, ""), `${system}s`].some((form) => requested.has(form));
131
+ }
132
+ /** A word without its plural ending: issues → issue, repositories → repository. */
133
+ function singular(word) {
134
+ if (word.length > 4 && word.endsWith("ies"))
135
+ return `${word.slice(0, -3)}y`;
136
+ return word.length > 3 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word;
137
+ }
138
+ /** What each further card of a template costs in the ranking. */
139
+ const REPEAT_COST = 8;
140
+ /**
141
+ * Ranks each further card of a template lower: the Email connector's IMAP operations must
142
+ * not crowd out SendGrid, which the request names, while a strong second operation of
143
+ * one template still beats a weak other one.
144
+ */
145
+ function varied(sorted) {
146
+ const count = new Map();
147
+ return sorted
148
+ .map((entry) => {
149
+ const n = count.get(entry.card.templateId) ?? 0;
150
+ count.set(entry.card.templateId, n + 1);
151
+ return { entry, score: entry.score - n * REPEAT_COST };
152
+ })
153
+ .sort((a, b) => b.score - a.score)
154
+ .map(({ entry }) => entry);
155
+ }
156
+ /** Words of a request that ask for a plain REST call somewhere in the process. */
157
+ const REST_WORDS = new Set(["rest", "http", "https", "endpoint", "url"]);
158
+ /**
159
+ * Picks cards for each task that could carry a connector: tasks, and events a
160
+ * connector template can attach to. A card is a candidate for a task when:
161
+ *
162
+ * - the task's name names the card's system ("Post to **Slack**"), or
163
+ * - the task is a task (not an event), the request names the system, no
164
+ * other task's name does, and the card fits the task, or
165
+ * - the task's name shares a word other than a common verb with the
166
+ * connector's name ("Publish **event**" and an event-bus connector).
167
+ *
168
+ * Ranking:
169
+ * - A few words requests use for what templates call something else rank the
170
+ * candidates: "notify" prefers a connector's message-sending operation.
171
+ * - A connector naming a system nobody asked for ranks lower: "Azure OpenAI"
172
+ * for a request that says OpenAI.
173
+ * - Each further card of one template ranks lower, so one connector's
174
+ * operations do not crowd out another the request names.
175
+ * - Deprecated templates are never offered.
176
+ *
177
+ * The REST connector is offered for a task whose name asks for an HTTP call
178
+ * ("Fetch order", "Call endpoint") when nothing else fits, and for a task with
179
+ * no connector of its own when the request asks for a REST call. Tasks with no
180
+ * candidate are left out, so an empty answer means there is nothing to connect.
181
+ *
182
+ * With `options.apis`, services of the API index: a task (not an event) that
183
+ * names a service, or whose request does as above, gets the REST connector
184
+ * first and an API card with the service's best-fitting operations — unless a
185
+ * dedicated connector for that system has an operation the task's name
186
+ * mentions. A dedicated connector comes first; the index is for the rest.
187
+ * - A task that names only the service ("Call Stripe REST API") is matched to
188
+ * operations by the request's words.
189
+ * - A service only the request names goes to the one task it fits best.
190
+ *
191
+ * @param options.perTask - Cards per task, at most (default 3).
192
+ * @param options.total - Cards in all, at most (default 8). Every task keeps
193
+ * its best card before any task gets a second.
194
+ * @param options.apis - Services of `@bpmnkit/connector-gen/api-index` the
195
+ * request or the task names named, loaded.
196
+ */
197
+ export function selectConnectors(input, options = {}) {
198
+ const perTask = options.perTask ?? 3;
199
+ const total = options.total ?? 8;
200
+ const apis = options.apis ?? [];
201
+ const requested = new Set(termsOf(input.text ?? ""));
202
+ const requestTerms = withSynonyms([...requested]);
203
+ // A deprecated template has a successor in the catalog: offer that one
204
+ const cards = listConnectorCards().filter((card) => !getTemplate(card.templateId)?.name.includes("(Deprecated)"));
205
+ const http = connectorCards("io.camunda.connectors.HttpJson.v2")[0];
206
+ // A system some task's name names belongs to that task: "Notify ops in Slack"
207
+ // takes Slack, and "Record failure" does not get it from the request
208
+ const claimed = new Set();
209
+ for (const task of input.tasks) {
210
+ const named = new Set(termsOf(task.name ?? ""));
211
+ for (const card of cards) {
212
+ for (const system of systems(card))
213
+ if (named.has(system))
214
+ claimed.add(system);
215
+ }
216
+ for (const service of apis) {
217
+ if (named.has(apiBrand(service.id)))
218
+ claimed.add(apiBrand(service.id));
219
+ }
220
+ }
221
+ const ranked = input.tasks.map((task) => {
222
+ const terms = termsOf(task.name ?? "");
223
+ const named = new Set(terms);
224
+ const content = terms.filter((t) => !VERBS.has(t) && !GENERIC.has(t));
225
+ // Synonyms only rank: "Notify ops" prefers a connector's send-message operation,
226
+ // but does not make every messaging connector a candidate
227
+ const synonyms = withSynonyms(terms).filter((t) => !named.has(t));
228
+ const scored = [];
229
+ // "Post summary to Slack" in a request that says Teams: the draft named the wrong
230
+ // system, and the request's own ranks first
231
+ const misnamed = requested.size > 0 &&
232
+ cards.some((card) => fits(card, task.type) &&
233
+ systems(card).some((s) => named.has(s) && !askedFor(s, requested)));
234
+ /** Whether a card fits by the task's own name, not only by the request. */
235
+ let ownCard = false;
236
+ for (const card of cards) {
237
+ if (!fits(card, task.type))
238
+ continue;
239
+ const own = systems(card);
240
+ const inName = own.some((s) => named.has(s));
241
+ // An event only carries a connector its own name asks for: a request that
242
+ // mentions Slack does not make "Every hour" a Slack trigger
243
+ const inRequest = TASKS.has(task.type) && own.some((s) => requested.has(s) && !claimed.has(s));
244
+ // A word of the connector's name, not only of one of its operations
245
+ const byWord = cardScore(card, content) >= 4;
246
+ if (!inName && !inRequest && !byWord)
247
+ continue;
248
+ if (inName || byWord)
249
+ ownCard = true;
250
+ // "Azure OpenAI" for a request that only says OpenAI names a system nobody asked for
251
+ const asked = (s) => [s, s.replace(/s$/, ""), `${s}s`].some((form) => named.has(form) || requested.has(form));
252
+ // "Google Sheet" asks for the sheets connector: one word, singular or plural
253
+ const unasked = own.filter((s) => !asked(s)).length;
254
+ const score = cardScore(card, terms) * 2 +
255
+ cardScore(card, synonyms) +
256
+ (inName ? 10 : 0) +
257
+ (inRequest ? 4 : 0) +
258
+ // The request's system ranks first, by what the request asks of it
259
+ (inRequest && misnamed ? 30 + cardScore(card, requestTerms) : 0) -
260
+ unasked * 8;
261
+ scored.push(inName || inRequest ? { card, score } : { card, score, byWordOnly: true });
262
+ }
263
+ // "Send message to SQS" names its system: Camunda's own Send message connector, which
264
+ // only shares a word with it, is a distraction
265
+ if (scored.some((s) => !s.byWordOnly && systems(s.card).some((x) => named.has(x)))) {
266
+ for (let k = scored.length - 1; k >= 0; k--)
267
+ if (scored[k]?.byWordOnly)
268
+ scored.splice(k, 1);
269
+ }
270
+ const apiCards = [];
271
+ if (http && TASKS.has(task.type) && fits(http, task.type)) {
272
+ for (const service of apis) {
273
+ const brand = apiBrand(service.id);
274
+ const inName = named.has(brand);
275
+ if (!inName && !(requested.has(brand) && !claimed.has(brand)))
276
+ continue;
277
+ // "Post list to Slack" names its own system: the request's GitHub is not its call
278
+ if (!inName && scored.some((s) => systems(s.card).some((x) => named.has(x))))
279
+ continue;
280
+ const dedicated = scored.some((s) => systems(s.card).includes(brand));
281
+ // "Call Stripe REST API" says which service, and only the request says what for
282
+ let ranked = rankApiOperations(service, task.name ?? "");
283
+ if (ranked.length === 0 && inName && !dedicated) {
284
+ ranked = rankApiOperations(service, input.text ?? "");
285
+ }
286
+ const best = ranked[0];
287
+ if (!best)
288
+ continue;
289
+ // A dedicated connector wins unless the index has an operation that fits more
290
+ // of the name: GitHub's connector creates issues, the index lists workflow runs
291
+ const wordsOf = (text) => text
292
+ .toLowerCase()
293
+ .split(/[^a-z0-9]+/)
294
+ .filter((w) => w.length > 1 && w !== brand && !VERBS.has(w));
295
+ // An operation covers the task's words only when it does what the task's verb says:
296
+ // GitHub's createIssue says nothing for "List open issues"
297
+ const verb = (task.name ?? "").toLowerCase().split(/[^a-z]+/)[0] ?? "";
298
+ const does = (card) => {
299
+ const own = /^(?:[a-z]+\.)?([a-z]+)/.exec(card.operation ?? "")?.[1];
300
+ return !VERBS.has(verb) || own === undefined || !VERBS.has(own) || own === verb;
301
+ };
302
+ // …and is about the word: listIssueComments lists comments, not issues
303
+ const resource = (card) => {
304
+ const parts = (card.operation ?? "")
305
+ .replace(/^[a-z]+\./, "")
306
+ .split(/(?=[A-Z])/)
307
+ .map((p) => p.toLowerCase());
308
+ return parts.length > 1 && VERBS.has(parts[0] ?? "") ? parts.at(-1) : undefined;
309
+ };
310
+ // "issues" asks for many: getIssue, about one, does not cover it
311
+ const covers = (card, word) => {
312
+ const own = resource(card);
313
+ if (own === undefined)
314
+ return cardScore(card, [word]) >= 3;
315
+ const many = (w) => singular(w) !== w;
316
+ return singular(own) === singular(word) && (!many(word) || many(own));
317
+ };
318
+ const coverage = (text) => Math.max(0, ...scored
319
+ .filter((s) => systems(s.card).includes(brand) && does(s.card))
320
+ .map((s) => wordsOf(text).filter((w) => covers(s.card, w)).length));
321
+ const covered = coverage(task.name ?? "");
322
+ // The request decides too: "a confirmation email with SendGrid" is SendGrid's mail
323
+ // operation whatever the task is called, while "failed workflow runs" is the index's.
324
+ // The connector wins when it covers every word of the request the index's best
325
+ // endpoint has
326
+ const asked = input.text ? rankApiOperations(service, input.text)[0]?.op : undefined;
327
+ if (dedicated && asked) {
328
+ const text = `${asked.summary ?? ""} ${asked.path}`.toLowerCase();
329
+ const hit = wordsOf(input.text ?? "").filter((w) => text.includes(singular(w)));
330
+ const mine = scored.filter((s) => systems(s.card).includes(brand) && does(s.card));
331
+ if (hit.length > 0 && hit.every((w) => mine.some((s) => covers(s.card, w))))
332
+ continue;
333
+ }
334
+ if (best.hits <= covered)
335
+ continue;
336
+ apiCards.push({
337
+ service,
338
+ operations: ranked.slice(0, 3).map((r) => r.op),
339
+ fromRequest: !inName,
340
+ score: best.score,
341
+ });
342
+ }
343
+ }
344
+ if (http && fits(http, task.type) && !scored.some((s) => s.card === http)) {
345
+ if (scored.length === 0 && terms.some((t) => HTTP_WORDS.has(t))) {
346
+ scored.push({ card: http, score: 1 });
347
+ }
348
+ else if (TASKS.has(task.type) &&
349
+ !ownCard &&
350
+ [...requested].some((t) => REST_WORDS.has(t))) {
351
+ // "check the stock with a REST call": Check stock names no system, the request says how
352
+ scored.push({ card: http, score: 5 });
353
+ }
354
+ }
355
+ scored.sort((a, b) => b.score - a.score);
356
+ return { task, scored: varied(scored), apiCards };
357
+ });
358
+ // A service only the request names goes to the one task that fits it best: in "refund the
359
+ // payment with Stripe, then notify the customer", Notify customer is not a Stripe call
360
+ for (const service of apis) {
361
+ const offers = ranked.flatMap(({ apiCards }) => apiCards.filter((c) => c.service === service && c.fromRequest));
362
+ const best = offers.reduce((a, b) => (a === undefined || b.score > a.score ? b : a), undefined);
363
+ for (const entry of ranked) {
364
+ entry.apiCards = entry.apiCards.filter((c) => c.service !== service || !c.fromRequest || c === best);
365
+ }
366
+ }
367
+ const picks = ranked.map(({ task, scored, apiCards }) => {
368
+ // With an API card, the REST connector it is for comes first
369
+ const ordered = apiCards.length > 0 && http
370
+ ? [http, ...scored.map((s) => s.card).filter((card) => card !== http)]
371
+ : scored.map((s) => s.card);
372
+ const apiPicked = apiCards
373
+ .slice(0, 2)
374
+ .map(({ service, operations }) => ({ service, operations }));
375
+ return { task, cards: ordered.slice(0, perTask), apis: apiPicked };
376
+ });
377
+ // Every task's best card first, then second-best cards, and so on, up to the total
378
+ const kept = new Map();
379
+ let budget = total;
380
+ for (let rank = 0; rank < perTask && budget > 0; rank++) {
381
+ for (const { task, cards: candidates } of picks) {
382
+ const card = candidates[rank];
383
+ if (card === undefined || budget === 0)
384
+ continue;
385
+ kept.set(task.id, [...(kept.get(task.id) ?? []), card]);
386
+ budget--;
387
+ }
388
+ }
389
+ return picks
390
+ .filter(({ task }) => kept.has(task.id))
391
+ .map(({ task, apis: apiCards }) => {
392
+ const picked = { id: task.id, cards: kept.get(task.id) ?? [] };
393
+ if (task.name !== undefined)
394
+ picked.name = task.name;
395
+ if (apiCards.length > 0 && http && picked.cards.includes(http))
396
+ picked.apis = apiCards;
397
+ return picked;
398
+ });
399
+ }
400
+ /**
401
+ * The picked cards as a prompt block, one task per paragraph:
402
+ *
403
+ * ```
404
+ * notify (Notify ops):
405
+ * slack chat.postMessage — … | token*(secret) data.text* data.channel* | …
406
+ * ```
407
+ *
408
+ * API cards follow a task's connector cards.
409
+ */
410
+ export function formatConnectorSelection(selection) {
411
+ return selection
412
+ .map(({ id, name, cards, apis }) => [
413
+ `${id}${name ? ` (${name})` : ""}:`,
414
+ ...cards.map((c) => formatConnectorCard(c)),
415
+ ...(apis ?? []).map(formatApiCard),
416
+ ].join("\n"))
417
+ .join("\n\n");
418
+ }
419
+ //# sourceMappingURL=select.js.map