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