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