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