@simple-ai-lab/sdk 0.4.0 → 0.8.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 (78) hide show
  1. package/README.md +79 -1
  2. package/dist/actions.cjs +452 -0
  3. package/dist/actions.d.cts +348 -0
  4. package/dist/actions.d.ts +348 -0
  5. package/dist/actions.js +443 -0
  6. package/dist/agents.cjs +1176 -0
  7. package/dist/agents.d.cts +1138 -0
  8. package/dist/agents.d.ts +1138 -0
  9. package/dist/agents.js +1166 -0
  10. package/dist/built-in-actions.cjs +456 -0
  11. package/dist/built-in-actions.d.cts +53 -0
  12. package/dist/built-in-actions.d.ts +53 -0
  13. package/dist/built-in-actions.js +453 -0
  14. package/dist/client.cjs +29 -0
  15. package/dist/client.d.cts +15 -0
  16. package/dist/client.d.ts +15 -0
  17. package/dist/client.js +25 -0
  18. package/dist/code-action/defaults.cjs +11 -0
  19. package/dist/code-action/defaults.d.cts +7 -0
  20. package/dist/code-action/defaults.d.ts +7 -0
  21. package/dist/code-action/defaults.js +8 -0
  22. package/dist/code-action/define-action.cjs +78 -0
  23. package/dist/code-action/define-action.d.cts +99 -0
  24. package/dist/code-action/define-action.d.ts +99 -0
  25. package/dist/code-action/define-action.js +73 -0
  26. package/dist/code-action/index.cjs +11 -0
  27. package/dist/code-action/index.d.cts +4 -0
  28. package/dist/code-action/index.d.ts +4 -0
  29. package/dist/code-action/index.js +3 -0
  30. package/dist/code-action/llm.cjs +34 -0
  31. package/dist/code-action/llm.d.cts +28 -0
  32. package/dist/code-action/llm.d.ts +28 -0
  33. package/dist/code-action/llm.js +31 -0
  34. package/dist/code-action/types.cjs +14 -0
  35. package/dist/code-action/types.d.cts +19 -0
  36. package/dist/code-action/types.d.ts +19 -0
  37. package/dist/code-action/types.js +11 -0
  38. package/dist/code-action/workflow.cjs +29 -0
  39. package/dist/code-action/workflow.d.cts +53 -0
  40. package/dist/code-action/workflow.d.ts +53 -0
  41. package/dist/code-action/workflow.js +26 -0
  42. package/dist/data.cjs +98 -0
  43. package/dist/data.d.cts +44 -0
  44. package/dist/data.d.ts +44 -0
  45. package/dist/data.js +94 -0
  46. package/dist/http.cjs +72 -0
  47. package/dist/http.d.cts +14 -0
  48. package/dist/http.d.ts +14 -0
  49. package/dist/http.js +69 -0
  50. package/dist/index.cjs +71 -1597
  51. package/dist/index.d.cts +12 -780
  52. package/dist/index.d.ts +12 -780
  53. package/dist/index.js +10 -1311
  54. package/dist/projects.cjs +234 -0
  55. package/dist/projects.d.cts +24 -0
  56. package/dist/projects.d.ts +24 -0
  57. package/dist/projects.js +228 -0
  58. package/dist/schemas.cjs +50 -0
  59. package/dist/schemas.d.cts +81 -0
  60. package/dist/schemas.d.ts +81 -0
  61. package/dist/schemas.js +47 -0
  62. package/dist/shared/errors.cjs +31 -0
  63. package/dist/shared/errors.d.cts +22 -0
  64. package/dist/shared/errors.d.ts +22 -0
  65. package/dist/shared/errors.js +26 -0
  66. package/package.json +27 -31
  67. package/dist/chunk-V4E5PSKB.js +0 -267
  68. package/dist/chunk-V4E5PSKB.js.map +0 -1
  69. package/dist/code-action-CDt77m7I.d.cts +0 -191
  70. package/dist/code-action-CDt77m7I.d.ts +0 -191
  71. package/dist/code-action.cjs +0 -282
  72. package/dist/code-action.cjs.map +0 -1
  73. package/dist/code-action.d.cts +0 -2
  74. package/dist/code-action.d.ts +0 -2
  75. package/dist/code-action.js +0 -9
  76. package/dist/code-action.js.map +0 -1
  77. package/dist/index.cjs.map +0 -1
  78. package/dist/index.js.map +0 -1
@@ -0,0 +1,1176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_PER_TURN_RETRIEVAL_RECENT_TURNS = exports.DEFAULT_PER_TURN_RETRIEVAL_TOP_K = exports.prompt = exports.node = exports.MAX_CONTAINMENT_RULE_DEPTH = exports.CONTAINMENT_CONTAINED_CONDITION_TYPES = exports.CONTAINMENT_CONTAINABLE_CONDITION_TYPES = exports.CONTAINMENT_RULE_MATCHES = exports.FIVE9_SIP_BYE_HEADER_NAMES = exports.SOP_TOOL_REF_TYPES = exports.DEFAULT_CHECK_IN_AFTER_SILENCE_DELAY_SECONDS = exports.DEFAULT_TRANSITION_MESSAGE = exports.TRANSITION_FILTER_MAX_CONDITIONS = exports.TRANSITION_FILTER_MAX_DEPTH = exports.TRANSITION_FILTER_EXISTENCE_OPERATORS = exports.TRANSITION_FILTER_STRING_OPERATORS = exports.TRANSITION_FILTER_CONTAINS_OPERATORS = exports.TRANSITION_FILTER_NUMERIC_OPERATORS = exports.TRANSITION_FILTER_EQUALITY_OPERATORS = void 0;
4
+ exports.defaultBackgroundNoise = defaultBackgroundNoise;
5
+ exports.defineAgent = defineAgent;
6
+ exports.reference = reference;
7
+ exports.canonicalAuthoringKey = canonicalAuthoringKey;
8
+ exports.canonicalAuthoringKeys = canonicalAuthoringKeys;
9
+ exports.resolveExtractionFields = resolveExtractionFields;
10
+ exports.compileAgent = compileAgent;
11
+ const node_crypto_1 = require("node:crypto");
12
+ const zod_1 = require("zod");
13
+ const actions_1 = require("./actions.cjs");
14
+ /**
15
+ * The tool parameter the platform adds when a callable asks the model to phrase
16
+ * its background message. Mirrors `MODEL_BACKGROUND_MESSAGE_PARAMETER` in
17
+ * `@simple-ai-lab/shared` (`serialization/actions.ts`), which this package
18
+ * cannot depend on. An Action input of the same name would take the same slot.
19
+ */
20
+ const MODEL_BACKGROUND_MESSAGE_PARAMETER = 'background_message';
21
+ exports.TRANSITION_FILTER_EQUALITY_OPERATORS = ['equals', 'not_equals'];
22
+ exports.TRANSITION_FILTER_NUMERIC_OPERATORS = [
23
+ 'greater_than',
24
+ 'greater_than_or_equals',
25
+ 'less_than',
26
+ 'less_than_or_equals',
27
+ ];
28
+ exports.TRANSITION_FILTER_CONTAINS_OPERATORS = ['contains', 'not_contains'];
29
+ exports.TRANSITION_FILTER_STRING_OPERATORS = ['starts_with', 'ends_with'];
30
+ exports.TRANSITION_FILTER_EXISTENCE_OPERATORS = ['exists', 'not_exists'];
31
+ exports.TRANSITION_FILTER_MAX_DEPTH = 8;
32
+ exports.TRANSITION_FILTER_MAX_CONDITIONS = 100;
33
+ /** Speaking on a transition is opt-in per edge. */
34
+ exports.DEFAULT_TRANSITION_MESSAGE = { source: 'disabled', text: '' };
35
+ /**
36
+ * The `call.backgroundNoise` a definition that says nothing about it compiles
37
+ * to, taken from `voice.backgroundNoise`. The CLI renders against this to tell
38
+ * a block it has to write from one `defineAgent` produces on its own.
39
+ */
40
+ function defaultBackgroundNoise({ voiceBackgroundNoise, }) {
41
+ return { trackName: voiceBackgroundNoise, gainMultiplier: 1 };
42
+ }
43
+ /** How long the agent waits before checking in on a silent caller. Matches the product default. */
44
+ exports.DEFAULT_CHECK_IN_AFTER_SILENCE_DELAY_SECONDS = 30;
45
+ function llmOverrideWire(override) {
46
+ return { model: override.model, llmModelUuid: override.modelUuid, temperature: override.temperature };
47
+ }
48
+ /** A tool a SOP section may use, by the uuid the graph already assigns it. */
49
+ exports.SOP_TOOL_REF_TYPES = ['http', 'knowledge-base', 'action'];
50
+ /**
51
+ * The only headers Five9's SIP trunk contract forwards on the BYE, and so the
52
+ * only ones the platform accepts. Mirrors `FIVE9_SIP_ATTRIBUTES_TO_HEADERS` in
53
+ * `@simple-ai-lab/shared` (`public/sip-bye-headers.ts`), which this package
54
+ * cannot depend on; the platform rejects any other name at publish.
55
+ */
56
+ exports.FIVE9_SIP_BYE_HEADER_NAMES = ['X-RouteReason', 'X-RouteType', 'X-RouteValue', 'X-MetaData'];
57
+ function isFive9SipByeHeaderName(name) {
58
+ return exports.FIVE9_SIP_BYE_HEADER_NAMES.some((supported) => supported === name);
59
+ }
60
+ exports.CONTAINMENT_RULE_MATCHES = ['all', 'any'];
61
+ exports.CONTAINMENT_CONTAINABLE_CONDITION_TYPES = ['parameter', 'tag', 'visited_node'];
62
+ exports.CONTAINMENT_CONTAINED_CONDITION_TYPES = ['parameter', 'visited_node', 'ended_by'];
63
+ exports.MAX_CONTAINMENT_RULE_DEPTH = 5;
64
+ function defaultTransferCapability() {
65
+ return {
66
+ enabled: false,
67
+ phoneNumber: null,
68
+ timeout: 120,
69
+ mode: 'cold',
70
+ description: null,
71
+ voicemailMessage: null,
72
+ };
73
+ }
74
+ /**
75
+ * Fills a transfer capability from what was authored.
76
+ *
77
+ * A transfer node, a prompt node's transfer tool, and the Agent-level
78
+ * capability are the same six fields with the same defaults, so one place fills
79
+ * them and the three cannot disagree.
80
+ */
81
+ function transferCapabilityFrom(authored) {
82
+ const defaults = defaultTransferCapability();
83
+ return {
84
+ enabled: authored?.enabled ?? defaults.enabled,
85
+ phoneNumber: authored?.phoneNumber ?? defaults.phoneNumber,
86
+ timeout: authored?.timeout ?? defaults.timeout,
87
+ mode: authored?.mode ?? defaults.mode,
88
+ description: authored?.description ?? defaults.description,
89
+ voicemailMessage: authored?.voicemailMessage ?? defaults.voicemailMessage,
90
+ };
91
+ }
92
+ function defineAgent(input) {
93
+ const voiceBackgroundNoise = input.voice?.backgroundNoise ?? 'off';
94
+ return {
95
+ kind: 'agent-definition',
96
+ key: input.key,
97
+ name: input.name,
98
+ description: input.description ?? null,
99
+ branch: input.branch,
100
+ modality: input.modality ?? 'voice',
101
+ folderUuid: input.folderUuid ?? null,
102
+ analyzerUuids: input.analyzerUuids ?? [],
103
+ tagUuids: input.tagUuids ?? [],
104
+ containmentConfig: input.containmentConfig ?? null,
105
+ voice: {
106
+ voiceUuid: input.voice?.voiceUuid ?? null,
107
+ backgroundNoise: voiceBackgroundNoise,
108
+ },
109
+ llm: {
110
+ model: input.llm?.model ?? 'gpt-4.1',
111
+ modelUuid: input.llm?.modelUuid ?? null,
112
+ temperature: input.llm?.temperature ?? 0.65,
113
+ },
114
+ speech: {
115
+ language: input.speech?.language ?? 'en',
116
+ keyterms: input.speech?.keyterms ?? [],
117
+ voiceFormattingEnabled: input.speech?.voiceFormattingEnabled ?? false,
118
+ pronunciations: input.speech?.pronunciations ?? [],
119
+ },
120
+ ...(input.toneGuidelines === undefined ? {} : { toneGuidelines: input.toneGuidelines }),
121
+ ...(input.cart === undefined ? {} : { cart: input.cart }),
122
+ call: {
123
+ agentSpeaksFirst: input.call?.agentSpeaksFirst ?? false,
124
+ firstSentence: input.call?.firstSentence ?? null,
125
+ maxCallLengthSeconds: input.call?.maxCallLengthSeconds ?? 1800,
126
+ record: input.call?.record ?? true,
127
+ checkInAfterSilence: {
128
+ enabled: input.call?.checkInAfterSilence?.enabled ?? false,
129
+ prompt: input.call?.checkInAfterSilence?.prompt ?? null,
130
+ // Left absent when unauthored so a commit that never carried the key
131
+ // keeps it that way; the runtime already falls back to the default.
132
+ ...(input.call?.checkInAfterSilence?.delaySeconds === undefined
133
+ ? {}
134
+ : { delaySeconds: input.call.checkInAfterSilence.delaySeconds }),
135
+ },
136
+ endCallAfterExtendedSilence: input.call?.endCallAfterExtendedSilence ?? false,
137
+ pciEnabled: input.call?.pciEnabled ?? false,
138
+ backgroundNoise: input.call?.backgroundNoise === undefined
139
+ ? defaultBackgroundNoise({ voiceBackgroundNoise })
140
+ : input.call.backgroundNoise,
141
+ interruptionEagerness: input.call?.interruptionEagerness === undefined ? 3 : input.call.interruptionEagerness,
142
+ eotEagerness: input.call?.eotEagerness ?? null,
143
+ },
144
+ preCallWebhook: {
145
+ enabled: input.preCallWebhook?.enabled ?? false,
146
+ url: input.preCallWebhook?.url ?? null,
147
+ authToken: input.preCallWebhook?.authToken ?? null,
148
+ timeout: input.preCallWebhook?.timeout ?? 5,
149
+ parameters: input.preCallWebhook?.parameters ?? [],
150
+ },
151
+ capabilities: {
152
+ dtmf: {
153
+ enabled: input.capabilities?.dtmf?.enabled ?? false,
154
+ description: input.capabilities?.dtmf?.description ?? null,
155
+ },
156
+ hangup: {
157
+ enabled: input.capabilities?.hangup?.enabled ?? true,
158
+ description: input.capabilities?.hangup?.description ?? null,
159
+ message: input.capabilities?.hangup?.message ?? null,
160
+ },
161
+ transfer: transferCapabilityFrom(input.capabilities?.transfer),
162
+ },
163
+ tools: input.tools ?? [],
164
+ knowledgeBases: input.knowledgeBases ?? [],
165
+ beforeCallAction: input.beforeCallAction ?? null,
166
+ summaryPrompt: input.summaryPrompt ?? null,
167
+ abTestGroupIds: input.abTestGroupIds ?? null,
168
+ actions: input.actions ?? null,
169
+ nodes: input.nodes,
170
+ };
171
+ }
172
+ exports.node = {
173
+ global(config) {
174
+ return { type: 'global', ...config };
175
+ },
176
+ prompt(config) {
177
+ return { type: 'prompt', ...config };
178
+ },
179
+ action(config) {
180
+ return { type: 'action', ...config };
181
+ },
182
+ http(config) {
183
+ return { type: 'http', ...config };
184
+ },
185
+ extract(config) {
186
+ return { type: 'extract', ...config };
187
+ },
188
+ say(config) {
189
+ return { type: 'say', ...config };
190
+ },
191
+ endCall(config) {
192
+ return { type: 'end-call', ...config };
193
+ },
194
+ abTest(config) {
195
+ return { type: 'ab-test', ...config };
196
+ },
197
+ updateParameters(config) {
198
+ return { type: 'update-parameters', ...config };
199
+ },
200
+ staticRouter(config) {
201
+ return { type: 'static-router', ...config };
202
+ },
203
+ collectCreditCard(config) {
204
+ return { type: 'collect-credit-card', ...config };
205
+ },
206
+ transfer(config) {
207
+ return { type: 'transfer', ...config };
208
+ },
209
+ transferChat(config) {
210
+ return { type: 'transfer-chat', ...config };
211
+ },
212
+ };
213
+ exports.prompt = {
214
+ inline(text, example = null, generatedExamples) {
215
+ return { kind: 'inline', text, example, ...(generatedExamples === undefined ? {} : { generatedExamples }) };
216
+ },
217
+ file(path, example = null) {
218
+ return { kind: 'file', path, example };
219
+ },
220
+ version(versionId) {
221
+ return { kind: 'version', versionId };
222
+ },
223
+ };
224
+ function reference(uuid) {
225
+ return { uuid };
226
+ }
227
+ function isRecord(value) {
228
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
229
+ }
230
+ function deterministicUuid(input) {
231
+ const bytes = Buffer.from((0, node_crypto_1.createHash)('sha256').update(`${input.kind}:${input.key}`).digest().subarray(0, 16));
232
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
233
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
234
+ const hex = bytes.toString('hex');
235
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
236
+ }
237
+ function resolveIdentity({ options, kind, key, fallbackKeys = [], }) {
238
+ for (const candidateKey of [key, ...fallbackKeys]) {
239
+ const identity = options.identity?.({ kind, key: candidateKey });
240
+ if (identity !== undefined) {
241
+ return identity;
242
+ }
243
+ }
244
+ return deterministicUuid({ kind, key });
245
+ }
246
+ function canonicalAuthoringKey(value, fallback) {
247
+ const normalizedCharacters = [];
248
+ let needsSeparator = false;
249
+ for (const character of value.toLowerCase()) {
250
+ const characterCode = character.charCodeAt(0);
251
+ const isLowercaseLetter = characterCode >= 97 && characterCode <= 122;
252
+ const isDigit = characterCode >= 48 && characterCode <= 57;
253
+ if (isLowercaseLetter || isDigit) {
254
+ if (needsSeparator && normalizedCharacters.length > 0) {
255
+ normalizedCharacters.push('-');
256
+ }
257
+ normalizedCharacters.push(character);
258
+ needsSeparator = false;
259
+ }
260
+ else if (normalizedCharacters.length > 0) {
261
+ needsSeparator = true;
262
+ }
263
+ }
264
+ const normalized = normalizedCharacters.join('');
265
+ return normalized === '' ? fallback : normalized;
266
+ }
267
+ function canonicalAuthoringKeys(values) {
268
+ const used = new Set();
269
+ return values.map(({ value, fallback }) => {
270
+ const base = canonicalAuthoringKey(value, fallback);
271
+ let candidate = base;
272
+ let sequence = 2;
273
+ while (used.has(candidate)) {
274
+ candidate = `${base}-${sequence}`;
275
+ sequence += 1;
276
+ }
277
+ used.add(candidate);
278
+ return candidate;
279
+ });
280
+ }
281
+ function jsonSchemaDescription(value) {
282
+ return typeof value.description === 'string' ? value.description : '';
283
+ }
284
+ function extractionFieldFromJsonSchema({ name, value, required, path, }) {
285
+ if (!isRecord(value)) {
286
+ throw new Error(`${path} is not a representable extraction field`);
287
+ }
288
+ const enumValues = Array.isArray(value.enum)
289
+ ? value.enum.filter((item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean')
290
+ : undefined;
291
+ if (value.type === 'object') {
292
+ const rawProperties = isRecord(value.properties) ? value.properties : {};
293
+ const requiredNames = new Set(Array.isArray(value.required) ? value.required.filter((item) => typeof item === 'string') : []);
294
+ return {
295
+ name,
296
+ type: 'object',
297
+ description: jsonSchemaDescription(value),
298
+ required,
299
+ properties: Object.entries(rawProperties).map(([childName, child]) => extractionFieldFromJsonSchema({
300
+ name: childName,
301
+ value: child,
302
+ required: requiredNames.has(childName),
303
+ path: `${path}.${childName}`,
304
+ })),
305
+ };
306
+ }
307
+ if (value.type === 'array') {
308
+ if (value.items === undefined) {
309
+ throw new Error(`${path} must declare an array item schema`);
310
+ }
311
+ return {
312
+ name,
313
+ type: 'array',
314
+ description: jsonSchemaDescription(value),
315
+ required,
316
+ items: extractionFieldFromJsonSchema({
317
+ name: 'item',
318
+ value: value.items,
319
+ required: true,
320
+ path: `${path}[]`,
321
+ }),
322
+ };
323
+ }
324
+ if (!['string', 'number', 'integer', 'boolean'].includes(String(value.type))) {
325
+ throw new Error(`${path} uses unsupported extraction type "${String(value.type)}"`);
326
+ }
327
+ return {
328
+ name,
329
+ type: value.type === 'integer' ? 'number' : String(value.type),
330
+ description: jsonSchemaDescription(value),
331
+ required,
332
+ ...(enumValues === undefined ? {} : { enum: enumValues }),
333
+ };
334
+ }
335
+ function resolveExtractionFields(schema) {
336
+ if (Array.isArray(schema)) {
337
+ return schema;
338
+ }
339
+ if (schema instanceof zod_1.z.ZodType) {
340
+ return extractionFieldsFromZod(schema);
341
+ }
342
+ throw new Error('Extraction schemas must be Zod 4 objects or ExtractionField arrays');
343
+ }
344
+ function extractionFieldsFromZod(schema) {
345
+ const jsonSchema = zod_1.z.toJSONSchema(schema);
346
+ if (!isRecord(jsonSchema) || jsonSchema.type !== 'object') {
347
+ throw new Error('Extraction schemas must be Zod objects');
348
+ }
349
+ const rawProperties = isRecord(jsonSchema.properties) ? jsonSchema.properties : {};
350
+ const requiredNames = new Set(Array.isArray(jsonSchema.required)
351
+ ? jsonSchema.required.filter((item) => typeof item === 'string')
352
+ : []);
353
+ return Object.entries(rawProperties).map(([name, value]) => extractionFieldFromJsonSchema({
354
+ name,
355
+ value,
356
+ required: requiredNames.has(name),
357
+ path: `schema.${name}`,
358
+ }));
359
+ }
360
+ function readPromptText({ path, options }) {
361
+ if (options.readPromptFile === undefined) {
362
+ throw new Error(`Prompt file "${path}" requires a readPromptFile compiler option`);
363
+ }
364
+ return options.readPromptFile(path);
365
+ }
366
+ /** An example is prompt text too, so a file-backed one goes through the same reader as the prompt. */
367
+ function compilePromptExample({ example, options }) {
368
+ return typeof example === 'string' || example === null ? example : readPromptText({ path: example.path, options });
369
+ }
370
+ function compilePrompt(referenceValue, options) {
371
+ switch (referenceValue.kind) {
372
+ case 'inline':
373
+ return {
374
+ type: 'inline',
375
+ prompt: referenceValue.text,
376
+ example: compilePromptExample({ example: referenceValue.example, options }),
377
+ // Product-generated; preserved verbatim so pulled prompts round-trip.
378
+ ...(referenceValue.generatedExamples === undefined
379
+ ? {}
380
+ : { generatedExamples: referenceValue.generatedExamples }),
381
+ };
382
+ case 'file':
383
+ return {
384
+ type: 'inline',
385
+ prompt: readPromptText({ path: referenceValue.path, options }),
386
+ example: compilePromptExample({ example: referenceValue.example, options }),
387
+ };
388
+ case 'version':
389
+ return { type: 'reference', promptVersionId: referenceValue.versionId };
390
+ }
391
+ }
392
+ function resolveActionVersion({ definition, options, }) {
393
+ if (definition.kind === 'reference') {
394
+ return definition.versionUuid;
395
+ }
396
+ const resolved = options.actionVersionUuids?.[definition.key];
397
+ if (resolved !== undefined) {
398
+ return resolved;
399
+ }
400
+ if (options.allowUnresolvedActionVersions === true) {
401
+ return resolveIdentity({
402
+ options,
403
+ kind: 'action-version-placeholder',
404
+ key: definition.key,
405
+ });
406
+ }
407
+ throw new Error(`Action "${definition.key}" does not have a resolved version UUID`);
408
+ }
409
+ function pointerForInputName(name) {
410
+ return `/${name.replace(/~/g, '~0').replace(/\//g, '~1')}`;
411
+ }
412
+ /**
413
+ * The stored mappings, from whichever field was set. The two hold the same type
414
+ * and mean opposite things, so only one may be set.
415
+ */
416
+ function compileOutputParameterMappings({ key, outputParameters, outputParameterMappings, }) {
417
+ if (outputParameterMappings !== undefined) {
418
+ if (outputParameters !== undefined) {
419
+ throw new Error(`Action use site "${key}" sets both outputParameters and outputParameterMappings; they describe the same thing in opposite directions`);
420
+ }
421
+ return outputParameterMappings;
422
+ }
423
+ const mappedParameters = new Set();
424
+ const mappings = [];
425
+ for (const [outputName, parameterName] of Object.entries(outputParameters ?? {})) {
426
+ if (mappedParameters.has(parameterName)) {
427
+ throw new Error(`Agent parameter "${parameterName}" is mapped from more than one Action output`);
428
+ }
429
+ mappedParameters.add(parameterName);
430
+ mappings.push([parameterName, `{{ outputs.${outputName} }}`]);
431
+ }
432
+ return Object.fromEntries(mappings);
433
+ }
434
+ function compileCallableUseSite({ callable, canonicalKey, options, }) {
435
+ const inputMappings = {};
436
+ // Store only explicit overrides. Agent v2 inherits omitted descriptions from
437
+ // the Action input schema when building the runtime tool schema.
438
+ const inputDescriptions = {};
439
+ for (const [name, input] of Object.entries(callable.inputs)) {
440
+ const pointer = pointerForInputName(name);
441
+ if (input.source === 'agent') {
442
+ inputDescriptions[pointer] = input.description;
443
+ continue;
444
+ }
445
+ inputMappings[pointer] = input.value;
446
+ // The two records are independent on the wire: a prefilled input keeps its
447
+ // agent-facing description rather than losing it to the mapping.
448
+ if (input.description !== undefined) {
449
+ inputDescriptions[pointer] = input.description;
450
+ }
451
+ }
452
+ // The text is trimmed because the platform trims what it stores, so an
453
+ // authored message padded with whitespace would publish in a different form
454
+ // than the source it came from and the next pull would disagree with it.
455
+ const authoredMessage = callable.backgroundMessage;
456
+ const backgroundMessage = authoredMessage === null ? null : { ...authoredMessage, text: authoredMessage.text.trim() };
457
+ // Both rules below are the server's, checked here so an author hears about
458
+ // them from `compileAgent` rather than from a rejected publish.
459
+ if (backgroundMessage !== null && backgroundMessage.text === '') {
460
+ throw new Error(`Callable Action "${callable.key}" has a blank background message`);
461
+ }
462
+ // Only reachable when the Action's inputs are known. `action.ref(...)` may be
463
+ // written without a `contract`, and then this cannot tell a collision from a
464
+ // clean use site, so the server decides at publish. Refusing outright would
465
+ // make the SDK stricter than the platform and block a legal Agent.
466
+ const contractProperties = callable.action.contract?.inputSchema.properties ?? {};
467
+ if (backgroundMessage?.source === 'model' &&
468
+ contractProperties[MODEL_BACKGROUND_MESSAGE_PARAMETER] !== undefined &&
469
+ inputMappings[pointerForInputName(MODEL_BACKGROUND_MESSAGE_PARAMETER)] === undefined) {
470
+ throw new Error(`Callable Action "${callable.key}" cannot ask the model for a background message because the Action already declares an input named "${MODEL_BACKGROUND_MESSAGE_PARAMETER}"; prefill it with action.from(...) or use an authored message`);
471
+ }
472
+ return {
473
+ actionUseSiteUuid: resolveIdentity({
474
+ options,
475
+ kind: 'action-use-site',
476
+ key: callable.key,
477
+ fallbackKeys: [canonicalKey],
478
+ }),
479
+ actionVersionUuid: resolveActionVersion({ definition: callable.action, options }),
480
+ name: callable.name,
481
+ description: callable.description,
482
+ inputDescriptions,
483
+ inputMappings,
484
+ outputParameterMappings: compileOutputParameterMappings({
485
+ key: callable.key,
486
+ outputParameters: callable.outputParameters,
487
+ outputParameterMappings: callable.outputParameterMappings,
488
+ }),
489
+ backgroundMessage,
490
+ };
491
+ }
492
+ function compileActionRun({ run, trigger, canonicalKey, options, }) {
493
+ return {
494
+ actionUseSiteUuid: resolveIdentity({
495
+ options,
496
+ kind: 'action-use-site',
497
+ key: run.key,
498
+ fallbackKeys: [canonicalKey],
499
+ }),
500
+ actionVersionUuid: resolveActionVersion({ definition: run.action, options }),
501
+ inputMappings: Object.fromEntries(Object.entries(run.inputs).map(([name, value]) => [
502
+ name.startsWith('/') ? name : pointerForInputName(name),
503
+ value,
504
+ ])),
505
+ outputParameterMappings: compileOutputParameterMappings({
506
+ key: run.key,
507
+ outputParameters: run.outputParameters,
508
+ outputParameterMappings: run.outputParameterMappings,
509
+ }),
510
+ trigger,
511
+ };
512
+ }
513
+ /** Product defaults for retrieval settings the author leaves out. */
514
+ exports.DEFAULT_PER_TURN_RETRIEVAL_TOP_K = 3;
515
+ exports.DEFAULT_PER_TURN_RETRIEVAL_RECENT_TURNS = 4;
516
+ function compilePerTurnRetrieval(definition) {
517
+ return {
518
+ enabled: definition.enabled ?? true,
519
+ knowledgeBaseUuids: definition.knowledgeBases.map((item) => item.uuid),
520
+ topK: definition.topK ?? exports.DEFAULT_PER_TURN_RETRIEVAL_TOP_K,
521
+ recentTurns: definition.recentTurns ?? exports.DEFAULT_PER_TURN_RETRIEVAL_RECENT_TURNS,
522
+ minScore: definition.minScore ?? null,
523
+ };
524
+ }
525
+ /**
526
+ * Node kinds that can invoke Callable Actions: prompt nodes and card collectors. Action
527
+ * discovery, declaration validation and inline-Action collection all gate on this, so a
528
+ * collector's Actions are declared and created wherever a prompt node's are.
529
+ */
530
+ function nodeCarriesCallableActions(definition) {
531
+ return definition.type === 'prompt' || definition.type === 'collect-credit-card';
532
+ }
533
+ function collectCallableActions(nodes) {
534
+ const byKey = new Map();
535
+ for (const definition of nodes) {
536
+ if (!nodeCarriesCallableActions(definition)) {
537
+ continue;
538
+ }
539
+ for (const callable of definition.actions ?? []) {
540
+ const existing = byKey.get(callable.key);
541
+ if (existing !== undefined && existing !== callable) {
542
+ throw new Error(`Callable Action key "${callable.key}" is defined more than once`);
543
+ }
544
+ byKey.set(callable.key, callable);
545
+ }
546
+ }
547
+ return [...byKey.values()];
548
+ }
549
+ /**
550
+ * A node may only point at a use site the Agent declares, and no two entries may
551
+ * share a key. Either would compile a `toolUseSiteUuid` the commit's
552
+ * `toolUseSites` does not define, which Agent v2's validation rejects.
553
+ */
554
+ function validateDeclaredActions({ declared, nodes, }) {
555
+ if (declared === null) {
556
+ return;
557
+ }
558
+ // Identities resolve from the key, so two entries sharing one would compile to
559
+ // a single `actionUseSiteUuid` for two different use sites.
560
+ const declaredByKey = new Map();
561
+ for (const callable of declared) {
562
+ if (declaredByKey.has(callable.key)) {
563
+ throw new Error(`Callable Action key "${callable.key}" is defined more than once`);
564
+ }
565
+ declaredByKey.set(callable.key, callable);
566
+ }
567
+ for (const definitionNode of nodes) {
568
+ if (!nodeCarriesCallableActions(definitionNode)) {
569
+ continue;
570
+ }
571
+ for (const callable of definitionNode.actions ?? []) {
572
+ const declaredCallable = declaredByKey.get(callable.key);
573
+ if (declaredCallable === undefined) {
574
+ throw new Error(`Node "${definitionNode.key}" uses Callable Action "${callable.key}", which the Agent's actions list does not declare`);
575
+ }
576
+ // The declared entry is what compiles, so a node holding a different
577
+ // object under the same key would have its version dropped.
578
+ if (declaredCallable !== callable) {
579
+ throw new Error(`Node "${definitionNode.key}" uses a different Callable Action "${callable.key}" than the Agent's actions list declares`);
580
+ }
581
+ }
582
+ }
583
+ }
584
+ function collectInlineActions(definition) {
585
+ const byKey = new Map();
586
+ const visit = (actionDefinition) => {
587
+ if (actionDefinition.kind !== 'inline') {
588
+ return;
589
+ }
590
+ const existing = byKey.get(actionDefinition.key);
591
+ if (existing !== undefined && existing !== actionDefinition) {
592
+ throw new Error(`Inline Action key "${actionDefinition.key}" is defined more than once`);
593
+ }
594
+ byKey.set(actionDefinition.key, actionDefinition);
595
+ };
596
+ for (const callable of definition.actions ?? collectCallableActions(definition.nodes)) {
597
+ visit(callable.action);
598
+ }
599
+ if (definition.beforeCallAction !== null) {
600
+ visit(definition.beforeCallAction.action);
601
+ }
602
+ for (const definitionNode of definition.nodes) {
603
+ if (definitionNode.type === 'action') {
604
+ visit(definitionNode.action);
605
+ }
606
+ if (definitionNode.type === 'prompt' &&
607
+ definitionNode.perTurnAction !== null &&
608
+ definitionNode.perTurnAction !== undefined) {
609
+ visit(definitionNode.perTurnAction.action);
610
+ }
611
+ }
612
+ return [...byKey.values()];
613
+ }
614
+ function compileEdges({ definition, canonicalNodeKey, nodeUuids, options, }) {
615
+ return (definition.edges ?? []).map((edgeDefinition, index) => {
616
+ const targetUuid = nodeUuids.get(edgeDefinition.to);
617
+ if (targetUuid === undefined) {
618
+ throw new Error(`Node "${definition.key}" points to unknown node "${edgeDefinition.to}"`);
619
+ }
620
+ const edgeKey = edgeDefinition.key ?? `${definition.key}:${index}`;
621
+ if (edgeDefinition.condition != null && edgeDefinition.filter != null) {
622
+ throw new Error(`Edge "${edgeKey}" cannot define both a static condition and an availability filter`);
623
+ }
624
+ return {
625
+ uuid: resolveIdentity({
626
+ options,
627
+ kind: 'edge',
628
+ key: edgeKey,
629
+ fallbackKeys: [`${canonicalNodeKey}:${index}`],
630
+ }),
631
+ toNodeUuid: targetUuid,
632
+ description: edgeDefinition.when,
633
+ priority: edgeDefinition.priority ?? index,
634
+ condition: edgeDefinition.condition ?? null,
635
+ filter: edgeDefinition.filter ?? null,
636
+ message: edgeDefinition.message ?? exports.DEFAULT_TRANSITION_MESSAGE,
637
+ agentContext: edgeDefinition.agentContext ?? null,
638
+ };
639
+ });
640
+ }
641
+ function baseNodeWire({ definition, canonicalNodeKey, index, nodeUuids, options, }) {
642
+ const uuid = nodeUuids.get(definition.key);
643
+ if (uuid === undefined) {
644
+ throw new Error(`Node "${definition.key}" has no compiled identity`);
645
+ }
646
+ return {
647
+ uuid,
648
+ name: definition.name,
649
+ isRoot: definition.root ?? false,
650
+ position: definition.position ?? { x: (index % 4) * 320, y: Math.floor(index / 4) * 220 },
651
+ behavior: { waitAfterExecuting: definition.waitAfterExecuting ?? 0 },
652
+ edges: compileEdges({ definition, canonicalNodeKey, nodeUuids, options }),
653
+ };
654
+ }
655
+ /**
656
+ * Takes the capability rather than the node: the update-parameters and
657
+ * collect-credit-card nodes have no slot for one, so there is nothing to read
658
+ * off them.
659
+ */
660
+ function nodeCapabilities(alwaysAvailable) {
661
+ if (alwaysAvailable === undefined) {
662
+ return {};
663
+ }
664
+ return {
665
+ alwaysAvailable: {
666
+ enabled: alwaysAvailable.enabled,
667
+ description: alwaysAvailable.description,
668
+ filter: alwaysAvailable.filter ?? null,
669
+ },
670
+ };
671
+ }
672
+ function promptNodeCapabilities(definition) {
673
+ const base = nodeCapabilities(definition.alwaysAvailable);
674
+ if (definition.transfer === undefined) {
675
+ return base;
676
+ }
677
+ return {
678
+ ...base,
679
+ transfer: transferCapabilityFrom(definition.transfer),
680
+ };
681
+ }
682
+ /**
683
+ * Checked here so an unsupported header name fails at `compileAgent` rather
684
+ * than at publish, where the platform's allowlist would reject the whole commit.
685
+ * The authoring type already rules these out, so this catches the cases the type
686
+ * cannot: a value built as a plain record, or a JavaScript caller.
687
+ */
688
+ function compileSipByeHeaders({ headers, nodeKey, }) {
689
+ const compiled = {};
690
+ for (const [name, value] of Object.entries(headers ?? {})) {
691
+ if (value === undefined) {
692
+ continue;
693
+ }
694
+ if (!isFive9SipByeHeaderName(name)) {
695
+ throw new Error(`End-call node "${nodeKey}" sets unsupported SIP BYE header "${name}"; Five9 forwards only ${exports.FIVE9_SIP_BYE_HEADER_NAMES.join(', ')}`);
696
+ }
697
+ compiled[name] = value;
698
+ }
699
+ return compiled;
700
+ }
701
+ function compileNode({ definition, canonicalNodeKey, canonicalCallableKeys, index, nodeUuids, options, }) {
702
+ const base = baseNodeWire({ definition, canonicalNodeKey, index, nodeUuids, options });
703
+ const builtInTools = nodeCapabilities('alwaysAvailable' in definition ? definition.alwaysAvailable : undefined);
704
+ switch (definition.type) {
705
+ case 'global':
706
+ return {
707
+ ...base,
708
+ type: 'global',
709
+ prompt: compilePrompt(definition.prompt, options),
710
+ };
711
+ case 'prompt': {
712
+ const perTurnAction = definition.perTurnAction === null || definition.perTurnAction === undefined
713
+ ? null
714
+ : compileActionRun({
715
+ run: definition.perTurnAction,
716
+ trigger: 'every_turn',
717
+ canonicalKey: `${canonicalNodeKey}:every-turn`,
718
+ options,
719
+ });
720
+ return {
721
+ ...base,
722
+ type: 'standard',
723
+ prompt: compilePrompt(definition.prompt, options),
724
+ toolUuids: (definition.tools ?? []).map((item) => item.uuid),
725
+ // Present whenever `actions` is declared, even when empty, so an
726
+ // explicit empty list survives the round trip.
727
+ ...(definition.actions === undefined
728
+ ? {}
729
+ : {
730
+ toolUseSiteUuids: definition.actions.map((callable) => resolveIdentity({
731
+ options,
732
+ kind: 'action-use-site',
733
+ key: callable.key,
734
+ fallbackKeys: [canonicalCallableKeys.get(callable.key) ?? callable.key],
735
+ })),
736
+ }),
737
+ knowledgeBaseUuids: (definition.knowledgeBases ?? []).map((item) => item.uuid),
738
+ customDataTableNames: definition.customDataTables ?? [],
739
+ builtInTools: promptNodeCapabilities(definition),
740
+ sopSpec: definition.sopSpec ?? null,
741
+ overrides: {
742
+ ...(definition.voiceOverride === undefined ? {} : { voice: definition.voiceOverride }),
743
+ ...(definition.llmOverride === undefined ? {} : { llm: llmOverrideWire(definition.llmOverride) }),
744
+ },
745
+ behavior: {
746
+ ...base.behavior,
747
+ ...(definition.vadMinSilenceDuration === undefined
748
+ ? {}
749
+ : { vadMinSilenceDuration: definition.vadMinSilenceDuration }),
750
+ ...(definition.waitAfterTransfer === undefined ? {} : { waitAfterTransfer: definition.waitAfterTransfer }),
751
+ },
752
+ // These four round-trip three states each: absent, explicit null, or a
753
+ // value. The product emits all three across different nodes, so
754
+ // `undefined` means "omit the key" and `null` means "write null".
755
+ ...(definition.perTurnWebhook === undefined ? {} : { perTurnWebhook: definition.perTurnWebhook }),
756
+ ...(definition.perTurnExtraction === undefined
757
+ ? {}
758
+ : {
759
+ perTurnExtractionFields: definition.perTurnExtraction === null ? null : resolveExtractionFields(definition.perTurnExtraction),
760
+ }),
761
+ ...(definition.perTurnRetrieval === undefined
762
+ ? {}
763
+ : {
764
+ perTurnRetrieval: definition.perTurnRetrieval === null ? null : compilePerTurnRetrieval(definition.perTurnRetrieval),
765
+ }),
766
+ ...(definition.perTurnAction === undefined ? {} : { perTurnAction }),
767
+ };
768
+ }
769
+ case 'action':
770
+ return {
771
+ ...base,
772
+ type: 'action_node',
773
+ actionVersionUuid: resolveActionVersion({ definition: definition.action, options }),
774
+ inputMappings: Object.fromEntries(Object.entries(definition.inputs).map(([name, value]) => [
775
+ name.startsWith('/') ? name : pointerForInputName(name),
776
+ value,
777
+ ])),
778
+ outputParameterMappings: compileOutputParameterMappings({
779
+ key: definition.key,
780
+ outputParameters: definition.outputParameters,
781
+ outputParameterMappings: definition.outputParameterMappings,
782
+ }),
783
+ runInBackground: definition.runInBackground ?? false,
784
+ backgroundMessage: definition.backgroundMessage ?? null,
785
+ executionMessage: definition.executionMessage ?? null,
786
+ mockResponseData: definition.mockResponseData ?? null,
787
+ builtInTools,
788
+ };
789
+ case 'http':
790
+ return {
791
+ ...base,
792
+ type: 'http',
793
+ url: definition.url,
794
+ method: definition.method,
795
+ headers: definition.headers ?? {},
796
+ body: definition.body ?? null,
797
+ responseSelectors: definition.responseSelectors ?? [],
798
+ runInBackground: definition.runInBackground ?? false,
799
+ backgroundMessage: definition.backgroundMessage ?? null,
800
+ executionMessage: definition.executionMessage ?? null,
801
+ mockResponseData: definition.mockResponseData ?? null,
802
+ builtInTools,
803
+ };
804
+ case 'extract': {
805
+ // A shared Schema and inline fields are exclusive: the platform rejects a
806
+ // node carrying both, so a reference compiles to an empty field list.
807
+ const schema = definition.schema;
808
+ const extraction = 'uuid' in schema
809
+ ? { fields: [], schemaUuid: schema.uuid }
810
+ : { fields: resolveExtractionFields(schema), schemaUuid: null };
811
+ return {
812
+ ...base,
813
+ type: 'extract',
814
+ ...extraction,
815
+ executionMessage: definition.message ?? null,
816
+ builtInTools,
817
+ };
818
+ }
819
+ case 'say':
820
+ return {
821
+ ...base,
822
+ type: 'say',
823
+ executionMessage: definition.text,
824
+ overrides: definition.voiceUuid === undefined ? {} : { voice: { voiceUuid: definition.voiceUuid } },
825
+ behavior: {
826
+ ...base.behavior,
827
+ ...(definition.waitAfterSay === undefined ? {} : { waitAfterSay: definition.waitAfterSay }),
828
+ },
829
+ builtInTools,
830
+ };
831
+ case 'end-call':
832
+ return {
833
+ ...base,
834
+ type: 'end_call',
835
+ executionMessage: definition.message ?? null,
836
+ sipByeHeaders: compileSipByeHeaders({ headers: definition.sipByeHeaders, nodeKey: definition.key }),
837
+ builtInTools,
838
+ };
839
+ case 'ab-test':
840
+ return {
841
+ ...base,
842
+ type: 'ab_test',
843
+ abTestGroupUuid: definition.abTestGroupUuid,
844
+ builtInTools,
845
+ };
846
+ case 'update-parameters':
847
+ return {
848
+ ...base,
849
+ type: 'update_parameters',
850
+ parameterUpdates: definition.parameterUpdates,
851
+ };
852
+ case 'static-router':
853
+ return {
854
+ ...base,
855
+ type: 'static_router',
856
+ builtInTools,
857
+ };
858
+ case 'collect-credit-card':
859
+ return {
860
+ ...base,
861
+ type: 'collect_credit_card',
862
+ instructions: definition.instructions ?? null,
863
+ ...(definition.overridePrompt === undefined ? {} : { overrideCollectorPrompt: definition.overridePrompt }),
864
+ // Present whenever `actions` is declared, even when empty, so an explicit empty
865
+ // list survives the round trip.
866
+ ...(definition.actions === undefined
867
+ ? {}
868
+ : {
869
+ toolUseSiteUuids: definition.actions.map((callable) => resolveIdentity({
870
+ options,
871
+ kind: 'action-use-site',
872
+ key: callable.key,
873
+ fallbackKeys: [canonicalCallableKeys.get(callable.key) ?? callable.key],
874
+ })),
875
+ }),
876
+ overrides: definition.llmOverride === undefined ? {} : { llm: llmOverrideWire(definition.llmOverride) },
877
+ behavior: {
878
+ ...base.behavior,
879
+ ...(definition.vadMinSilenceDuration === undefined
880
+ ? {}
881
+ : { vadMinSilenceDuration: definition.vadMinSilenceDuration }),
882
+ },
883
+ };
884
+ case 'transfer': {
885
+ const transfer = transferCapabilityFrom({ ...definition, enabled: definition.enabled ?? true });
886
+ return {
887
+ ...base,
888
+ type: 'transfer',
889
+ executionMessage: definition.message ?? null,
890
+ behavior: {
891
+ ...base.behavior,
892
+ ...(definition.waitAfterTransfer === undefined ? {} : { waitAfterTransfer: definition.waitAfterTransfer }),
893
+ },
894
+ builtInTools: { ...builtInTools, transfer },
895
+ };
896
+ }
897
+ case 'transfer-chat':
898
+ return {
899
+ ...base,
900
+ type: 'transfer_chat',
901
+ ...(definition.message === undefined ? {} : { executionMessage: definition.message }),
902
+ ...(definition.mode === undefined ? {} : { mode: definition.mode }),
903
+ five9TenantName: definition.five9TenantName ?? '',
904
+ five9CampaignName: definition.five9CampaignName ?? '',
905
+ five9ContactMapping: definition.five9ContactMapping ?? {},
906
+ five9AttributesMapping: definition.five9AttributesMapping ?? [],
907
+ builtInTools,
908
+ };
909
+ }
910
+ }
911
+ function describeCartActionRef(ref) {
912
+ if ('callable' in ref)
913
+ return `callable Action "${ref.callable}"`;
914
+ if ('actionNode' in ref)
915
+ return `Action node "${ref.actionNode}"`;
916
+ if ('perTurnAction' in ref)
917
+ return `the per-turn Action on node "${ref.perTurnAction}"`;
918
+ return 'the before-call Action';
919
+ }
920
+ /**
921
+ * Resolves the cart's authoring keys to the uuids the compiled commit uses. A reference to
922
+ * something the Agent doesn't have fails here, rather than at publish.
923
+ */
924
+ function compileCart({ cart, callables, toolUseSites, definitionNodes, nodes, beforeCallStart, }) {
925
+ const nodeAt = (key) => {
926
+ const index = definitionNodes.findIndex((definitionNode) => definitionNode.key === key);
927
+ return index === -1 ? null : { definition: definitionNodes[index], wire: nodes[index] };
928
+ };
929
+ const resolveAction = (ref) => {
930
+ let uuid;
931
+ if ('callable' in ref) {
932
+ const index = callables.findIndex((callable) => callable.key === ref.callable);
933
+ uuid = index === -1 ? undefined : toolUseSites[index]?.actionUseSiteUuid;
934
+ }
935
+ else if ('actionNode' in ref) {
936
+ const found = nodeAt(ref.actionNode);
937
+ uuid = found?.definition?.type === 'action' ? found.wire?.uuid : undefined;
938
+ }
939
+ else if ('perTurnAction' in ref) {
940
+ const wire = nodeAt(ref.perTurnAction)?.wire;
941
+ uuid =
942
+ wire !== undefined && 'perTurnAction' in wire
943
+ ? (wire.perTurnAction?.actionUseSiteUuid ?? undefined)
944
+ : undefined;
945
+ }
946
+ else {
947
+ uuid = beforeCallStart?.actionUseSiteUuid;
948
+ }
949
+ if (uuid === undefined) {
950
+ throw new Error(`The cart refers to ${describeCartActionRef(ref)}, which this Agent does not have`);
951
+ }
952
+ return uuid;
953
+ };
954
+ const checkout = compileCartCheckout({ checkout: cart.checkout ?? null, resolveAction, nodeAt });
955
+ return {
956
+ parameter: cart.parameter,
957
+ view: cart.view,
958
+ reasonArgument: cart.reasonArgument ?? null,
959
+ actions: (cart.actions ?? []).map((entry) => ({
960
+ actionUseSiteUuid: resolveAction(entry.action),
961
+ label: entry.label,
962
+ })),
963
+ checkout,
964
+ };
965
+ }
966
+ function compileCartCheckout({ checkout, resolveAction, nodeAt, }) {
967
+ if (checkout === null) {
968
+ return null;
969
+ }
970
+ switch (checkout.when.kind) {
971
+ case 'action_succeeded': {
972
+ if (checkout.when.actions.length === 0) {
973
+ throw new Error('The cart checkout needs at least one Action');
974
+ }
975
+ return {
976
+ when: { kind: 'action_succeeded', actionUseSiteUuids: checkout.when.actions.map(resolveAction) },
977
+ orderIds: checkout.orderIds ?? null,
978
+ };
979
+ }
980
+ case 'node_reached': {
981
+ if (checkout.when.nodes.length === 0) {
982
+ throw new Error('The cart checkout needs at least one node');
983
+ }
984
+ assertNoCheckoutOrderIds(checkout);
985
+ return {
986
+ when: {
987
+ kind: 'node_reached',
988
+ nodeUuids: checkout.when.nodes.map((key) => {
989
+ const uuid = nodeAt(key)?.wire?.uuid;
990
+ if (uuid === undefined) {
991
+ throw new Error(`The cart checkout refers to node "${key}", which this Agent does not have`);
992
+ }
993
+ return uuid;
994
+ }),
995
+ },
996
+ orderIds: null,
997
+ };
998
+ }
999
+ case 'parameter_equals': {
1000
+ assertNoCheckoutOrderIds(checkout);
1001
+ return { when: checkout.when, orderIds: null };
1002
+ }
1003
+ default: {
1004
+ checkout.when;
1005
+ throw new Error('Unhandled cart checkout rule');
1006
+ }
1007
+ }
1008
+ }
1009
+ /** Plain JavaScript callers aren't held to the types; order ids only come from an Action's outputs. */
1010
+ function assertNoCheckoutOrderIds(checkout) {
1011
+ if (checkout.orderIds != null) {
1012
+ throw new Error(`Only an action_succeeded cart checkout can name order ids, not ${checkout.when.kind}`);
1013
+ }
1014
+ }
1015
+ function validateDefinition(definition) {
1016
+ const keys = definition.nodes.map((definitionNode) => definitionNode.key);
1017
+ if (new Set(keys).size !== keys.length) {
1018
+ throw new Error('Every node key must be unique');
1019
+ }
1020
+ // An Agent with no nodes is a real product state — a freshly created Agent
1021
+ // before any graph is drawn — so it is representable rather than rejected.
1022
+ // The root-node invariant still applies to every Agent that has nodes.
1023
+ if (definition.nodes.length === 0) {
1024
+ return;
1025
+ }
1026
+ const roots = definition.nodes.filter((definitionNode) => definitionNode.root === true);
1027
+ if (roots.length !== 1) {
1028
+ throw new Error(`An agent with nodes must contain exactly one root node; received ${roots.length}`);
1029
+ }
1030
+ if (definition.nodes.some((definitionNode) => definitionNode.type === 'global' && definitionNode.root === true)) {
1031
+ throw new Error('The global node cannot be the root node');
1032
+ }
1033
+ }
1034
+ function compileAgent(definition, options = {}) {
1035
+ validateDefinition(definition);
1036
+ const canonicalNodeKeys = canonicalAuthoringKeys(definition.nodes.map((definitionNode, index) => ({
1037
+ value: definitionNode.name,
1038
+ fallback: `node-${index + 1}`,
1039
+ })));
1040
+ const canonicalNodeKeysByDefinitionKey = new Map(definition.nodes.map((definitionNode, index) => [
1041
+ definitionNode.key,
1042
+ canonicalNodeKeys[index] ?? definitionNode.key,
1043
+ ]));
1044
+ const nodeUuids = new Map(definition.nodes.map((definitionNode, index) => [
1045
+ definitionNode.key,
1046
+ resolveIdentity({
1047
+ options,
1048
+ kind: 'node',
1049
+ key: definitionNode.key,
1050
+ fallbackKeys: [canonicalNodeKeys[index] ?? definitionNode.key],
1051
+ }),
1052
+ ]));
1053
+ // Deriving from nodes is what an Agent written without a list means; it
1054
+ // cannot express order, sharing, or a use site no node references.
1055
+ const callables = definition.actions ?? collectCallableActions(definition.nodes);
1056
+ validateDeclaredActions({ declared: definition.actions, nodes: definition.nodes });
1057
+ const canonicalCallableKeys = canonicalAuthoringKeys(callables.map((callable, index) => ({
1058
+ value: callable.name,
1059
+ fallback: `action-${index + 1}`,
1060
+ })));
1061
+ const canonicalCallableKeysByDefinitionKey = new Map(callables.map((callable, index) => [callable.key, canonicalCallableKeys[index] ?? callable.key]));
1062
+ const toolUseSites = callables.map((callable) => compileCallableUseSite({
1063
+ callable,
1064
+ canonicalKey: canonicalCallableKeysByDefinitionKey.get(callable.key) ?? callable.key,
1065
+ options,
1066
+ }));
1067
+ const inlineActions = collectInlineActions(definition);
1068
+ const abTestGroupIds = [
1069
+ ...new Set(definition.nodes.flatMap((definitionNode) => definitionNode.type === 'ab-test' ? [definitionNode.abTestGroupUuid] : [])),
1070
+ ];
1071
+ const compiledNodes = definition.nodes.map((definitionNode, index) => compileNode({
1072
+ definition: definitionNode,
1073
+ canonicalNodeKey: canonicalNodeKeysByDefinitionKey.get(definitionNode.key) ?? definitionNode.key,
1074
+ canonicalCallableKeys: canonicalCallableKeysByDefinitionKey,
1075
+ index,
1076
+ nodeUuids,
1077
+ options,
1078
+ }));
1079
+ const beforeCallStart = definition.beforeCallAction === null
1080
+ ? null
1081
+ : compileActionRun({
1082
+ run: definition.beforeCallAction,
1083
+ trigger: 'before_call_start',
1084
+ canonicalKey: 'before-call-start',
1085
+ options,
1086
+ });
1087
+ const cart = definition.cart === undefined || definition.cart === null
1088
+ ? definition.cart
1089
+ : compileCart({
1090
+ cart: definition.cart,
1091
+ callables,
1092
+ toolUseSites,
1093
+ definitionNodes: definition.nodes,
1094
+ nodes: compiledNodes,
1095
+ beforeCallStart,
1096
+ });
1097
+ return {
1098
+ agent: {
1099
+ key: definition.key,
1100
+ name: definition.name,
1101
+ description: definition.description,
1102
+ modality: definition.modality,
1103
+ folderUuid: definition.folderUuid,
1104
+ analyzerUuids: definition.analyzerUuids,
1105
+ tagUuids: definition.tagUuids,
1106
+ containmentConfig: definition.containmentConfig,
1107
+ },
1108
+ branch: { name: definition.branch },
1109
+ actions: inlineActions.map((definitionAction) => ({
1110
+ key: definitionAction.key,
1111
+ versionUuid: resolveActionVersion({
1112
+ definition: definitionAction,
1113
+ options,
1114
+ }),
1115
+ values: (0, actions_1.compileAction)(definitionAction, {
1116
+ ...(options.readActionSourceFile === undefined ? {} : { readSourceFile: options.readActionSourceFile }),
1117
+ }),
1118
+ })),
1119
+ content: {
1120
+ config: {
1121
+ voice: {
1122
+ voiceUuid: definition.voice.voiceUuid,
1123
+ backgroundNoise: definition.voice.backgroundNoise,
1124
+ },
1125
+ llm: {
1126
+ model: definition.llm.model,
1127
+ llmModelUuid: definition.llm.modelUuid,
1128
+ temperature: definition.llm.temperature,
1129
+ },
1130
+ speech: definition.speech,
1131
+ ...(definition.toneGuidelines === undefined ? {} : { toneGuidelines: definition.toneGuidelines }),
1132
+ call: {
1133
+ agentSpeaksFirst: definition.call.agentSpeaksFirst,
1134
+ firstSentence: definition.call.firstSentence,
1135
+ maxCallLengthSeconds: definition.call.maxCallLengthSeconds,
1136
+ record: definition.call.record,
1137
+ checkInAfterSilence: definition.call.checkInAfterSilence,
1138
+ endCallAfterExtendedSilence: definition.call.endCallAfterExtendedSilence,
1139
+ pciEnabled: definition.call.pciEnabled,
1140
+ ...(definition.call.backgroundNoise === null ? {} : { backgroundNoise: definition.call.backgroundNoise }),
1141
+ // Absent and a value are the only two states the product writes, so
1142
+ // `null` means omit rather than sending an invented default. The platform derives the
1143
+ // legacy `interruptionConfig` / `eotEagerness` from this, so neither is sent here.
1144
+ ...(definition.call.interruptionEagerness === null && definition.call.eotEagerness === null
1145
+ ? {}
1146
+ : {
1147
+ voiceAnalysisConfig: {
1148
+ ...(definition.call.interruptionEagerness === null
1149
+ ? {}
1150
+ : { interruptionEagerness: definition.call.interruptionEagerness }),
1151
+ ...(definition.call.eotEagerness === null
1152
+ ? {}
1153
+ : { endOfTurnEagerness: definition.call.eotEagerness }),
1154
+ },
1155
+ }),
1156
+ },
1157
+ preCallWebhook: definition.preCallWebhook,
1158
+ builtInTools: definition.capabilities,
1159
+ assignedToolIds: definition.tools.map((item) => item.uuid),
1160
+ // Emitted whenever any node declares an `actions` array, so an Agent
1161
+ // that once had callable Actions keeps its explicit empty list rather
1162
+ // than dropping the key.
1163
+ ...(definition.actions !== null ||
1164
+ definition.nodes.some((definitionNode) => nodeCarriesCallableActions(definitionNode) && definitionNode.actions !== undefined)
1165
+ ? { toolUseSites }
1166
+ : {}),
1167
+ automaticActions: { beforeCallStart },
1168
+ knowledgeBaseIds: definition.knowledgeBases.map((item) => item.uuid),
1169
+ abTestGroupIds: definition.abTestGroupIds ?? abTestGroupIds,
1170
+ ...(cart === undefined ? {} : { cart }),
1171
+ },
1172
+ nodes: compiledNodes,
1173
+ summaryPrompt: definition.summaryPrompt,
1174
+ },
1175
+ };
1176
+ }