@simple-ai-lab/sdk 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +56 -3
  2. package/dist/actions.cjs +438 -0
  3. package/dist/actions.d.cts +336 -0
  4. package/dist/actions.d.ts +336 -0
  5. package/dist/actions.js +429 -0
  6. package/dist/agents.cjs +1054 -0
  7. package/dist/agents.d.cts +1016 -0
  8. package/dist/agents.d.ts +1016 -0
  9. package/dist/agents.js +1044 -0
  10. package/dist/built-in-actions.cjs +356 -0
  11. package/dist/built-in-actions.d.cts +41 -0
  12. package/dist/built-in-actions.d.ts +41 -0
  13. package/dist/built-in-actions.js +353 -0
  14. package/dist/client.cjs +29 -0
  15. package/dist/client.d.cts +15 -0
  16. package/dist/client.d.ts +15 -0
  17. package/dist/client.js +25 -0
  18. package/dist/code-action/defaults.cjs +11 -0
  19. package/dist/code-action/defaults.d.cts +7 -0
  20. package/dist/code-action/defaults.d.ts +7 -0
  21. package/dist/code-action/defaults.js +8 -0
  22. package/dist/code-action/define-action.cjs +74 -0
  23. package/dist/code-action/define-action.d.cts +94 -0
  24. package/dist/code-action/define-action.d.ts +94 -0
  25. package/dist/code-action/define-action.js +69 -0
  26. package/dist/code-action/index.cjs +11 -0
  27. package/dist/code-action/index.d.cts +4 -0
  28. package/dist/code-action/index.d.ts +4 -0
  29. package/dist/code-action/index.js +3 -0
  30. package/dist/code-action/types.cjs +13 -0
  31. package/dist/code-action/types.d.cts +13 -0
  32. package/dist/code-action/types.d.ts +13 -0
  33. package/dist/code-action/types.js +10 -0
  34. package/dist/code-action/workflow.cjs +29 -0
  35. package/dist/code-action/workflow.d.cts +53 -0
  36. package/dist/code-action/workflow.d.ts +53 -0
  37. package/dist/code-action/workflow.js +26 -0
  38. package/dist/data.cjs +98 -0
  39. package/dist/data.d.cts +44 -0
  40. package/dist/data.d.ts +44 -0
  41. package/dist/data.js +94 -0
  42. package/dist/http.cjs +65 -0
  43. package/dist/http.d.cts +14 -0
  44. package/dist/http.d.ts +14 -0
  45. package/dist/http.js +62 -0
  46. package/dist/index.cjs +68 -1593
  47. package/dist/index.d.cts +12 -961
  48. package/dist/index.d.ts +12 -961
  49. package/dist/index.js +10 -1540
  50. package/dist/projects.cjs +234 -0
  51. package/dist/projects.d.cts +24 -0
  52. package/dist/projects.d.ts +24 -0
  53. package/dist/projects.js +228 -0
  54. package/dist/schemas.cjs +50 -0
  55. package/dist/schemas.d.cts +81 -0
  56. package/dist/schemas.d.ts +81 -0
  57. package/dist/schemas.js +47 -0
  58. package/dist/shared/errors.cjs +31 -0
  59. package/dist/shared/errors.d.cts +22 -0
  60. package/dist/shared/errors.d.ts +22 -0
  61. package/dist/shared/errors.js +26 -0
  62. package/package.json +27 -21
  63. package/dist/index.cjs.map +0 -1
  64. package/dist/index.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,1540 +1,10 @@
1
- // src/actions.ts
2
- import { z } from "zod";
3
- function isRecord(value) {
4
- return value !== null && typeof value === "object" && !Array.isArray(value);
5
- }
6
- function nullableJsonSchema(value) {
7
- const type = value.type;
8
- if (Array.isArray(type)) {
9
- const nonNullTypes = type.filter((item) => item !== "null");
10
- if (nonNullTypes.length === 1 && typeof nonNullTypes[0] === "string") {
11
- return { schema: { ...value, type: nonNullTypes[0] }, nullable: type.includes("null") };
12
- }
13
- }
14
- const anyOf = value.anyOf;
15
- if (Array.isArray(anyOf)) {
16
- const schemas = anyOf.filter(isRecord);
17
- const nonNullSchemas = schemas.filter((schema) => schema.type !== "null");
18
- const containsNull = schemas.some((schema) => schema.type === "null");
19
- if (containsNull && nonNullSchemas.length === 1) {
20
- const nonNullSchema = nonNullSchemas[0] ?? {};
21
- return {
22
- schema: {
23
- ...nonNullSchema,
24
- ...typeof value.description === "string" ? { description: value.description } : {}
25
- },
26
- nullable: true
27
- };
28
- }
29
- }
30
- return { schema: value, nullable: false };
31
- }
32
- function schemaDescription(schema) {
33
- return typeof schema.description === "string" ? schema.description : "";
34
- }
35
- function convertJsonSchemaNode(value, path) {
36
- if (!isRecord(value)) {
37
- throw new Error(`${path} is not a representable Zod schema`);
38
- }
39
- const { schema, nullable } = nullableJsonSchema(value);
40
- if (schema.enum !== void 0 || schema.const !== void 0) {
41
- throw new Error(`${path} uses enum/const, which Actions I/O schemas do not support`);
42
- }
43
- switch (schema.type) {
44
- case "string":
45
- case "number":
46
- case "boolean":
47
- return {
48
- type: schema.type,
49
- description: schemaDescription(schema),
50
- nullable
51
- };
52
- case "object": {
53
- const rawProperties = isRecord(schema.properties) ? schema.properties : {};
54
- const properties = {};
55
- for (const [name, child] of Object.entries(rawProperties)) {
56
- if (!/^[A-Za-z_]\w*$/.test(name) || ["__proto__", "constructor", "prototype"].includes(name)) {
57
- throw new Error(`${path}.${name} is not a valid Actions I/O property name`);
58
- }
59
- properties[name] = convertJsonSchemaNode(child, `${path}.${name}`);
60
- }
61
- const required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name === "string") : [];
62
- const additionalProperties = schema.additionalProperties === true;
63
- return {
64
- type: "object",
65
- description: schemaDescription(schema),
66
- nullable,
67
- properties,
68
- required,
69
- additionalProperties
70
- };
71
- }
72
- case "array":
73
- return {
74
- type: "array",
75
- description: schemaDescription(schema),
76
- nullable,
77
- ...schema.items === void 0 ? {} : { items: convertJsonSchemaNode(schema.items, `${path}[]`) }
78
- };
79
- case "integer":
80
- return {
81
- type: "number",
82
- description: schemaDescription(schema),
83
- nullable
84
- };
85
- default:
86
- throw new Error(`${path} uses unsupported Zod/JSON Schema type "${String(schema.type)}"`);
87
- }
88
- }
89
- function actionsIoSchemaFromZod(schema) {
90
- const converted = convertJsonSchemaNode(z.toJSONSchema(schema), "schema");
91
- if (converted.type !== "object") {
92
- throw new Error("Action input and output schemas must be Zod objects");
93
- }
94
- return {
95
- type: "object",
96
- description: converted.description,
97
- properties: converted.properties,
98
- required: converted.required,
99
- additionalProperties: converted.additionalProperties
100
- };
101
- }
102
- function pointerForName(name) {
103
- const escaped = name.replace(/~/g, "~0").replace(/\//g, "~1");
104
- return `/${escaped}`;
105
- }
106
- function normalizeOutputMappings({
107
- mappings,
108
- outputSchema
109
- }) {
110
- const normalized = Object.fromEntries(
111
- Object.entries(mappings).map(([name, template]) => [name.startsWith("/") ? name : pointerForName(name), template])
112
- );
113
- for (const name of Object.keys(outputSchema.properties)) {
114
- const pointer = pointerForName(name);
115
- if (normalized[pointer] === void 0) {
116
- throw new Error(`Action output "${name}" needs an output mapping`);
117
- }
118
- }
119
- for (const pointer of Object.keys(normalized)) {
120
- const firstToken = pointer.slice(1).split("/")[0]?.replace(/~1/g, "/").replace(/~0/g, "~");
121
- if (firstToken === void 0 || outputSchema.properties[firstToken] === void 0) {
122
- throw new Error(`Action output mapping "${pointer}" does not reference a declared output`);
123
- }
124
- }
125
- return normalized;
126
- }
127
- function compileContracts({
128
- input,
129
- output
130
- }) {
131
- return {
132
- inputSchema: actionsIoSchemaFromZod(input),
133
- outputSchema: actionsIoSchemaFromZod(output)
134
- };
135
- }
136
- function requireSourceFile({
137
- reference: reference2,
138
- options
139
- }) {
140
- if (options.readSourceFile === void 0) {
141
- throw new Error(`Action source file "${reference2.path}" requires a readSourceFile compiler option`);
142
- }
143
- return options.readSourceFile(reference2.path);
144
- }
145
- function compileHttpAction(config) {
146
- const contract = compileContracts(config);
147
- return {
148
- kind: "inline",
149
- key: config.key,
150
- contract,
151
- compile: () => ({
152
- actionType: "http",
153
- name: config.name,
154
- description: config.description,
155
- ...contract,
156
- outputMappings: normalizeOutputMappings({
157
- mappings: config.outputMappings,
158
- outputSchema: contract.outputSchema
159
- }),
160
- operation: {
161
- type: "request",
162
- method: config.request.method,
163
- urlTemplate: config.request.url,
164
- headers: Object.entries(config.request.headers ?? {}).map(([name, valueTemplate]) => ({
165
- name,
166
- valueTemplate
167
- })),
168
- bodyTemplate: config.request.body ?? null
169
- }
170
- })
171
- };
172
- }
173
- function compileCodeAction(config) {
174
- const contract = compileContracts(config);
175
- return {
176
- kind: "inline",
177
- key: config.key,
178
- contract,
179
- compile: (options) => ({
180
- actionType: "code",
181
- name: config.name,
182
- description: config.description,
183
- ...contract,
184
- outputMappings: normalizeOutputMappings({
185
- mappings: config.outputMappings,
186
- outputSchema: contract.outputSchema
187
- }),
188
- operation: {
189
- type: "execute",
190
- language: "typescript",
191
- source: typeof config.source === "string" ? config.source : requireSourceFile({ reference: config.source, options }),
192
- compiledJs: null,
193
- runtime: "node22",
194
- timeoutMs: config.timeoutMs ?? 3e4
195
- }
196
- })
197
- };
198
- }
199
- function compileCustomDataQueryAction(config) {
200
- const contract = compileContracts(config);
201
- return {
202
- kind: "inline",
203
- key: config.key,
204
- contract,
205
- compile: () => ({
206
- actionType: "custom_data",
207
- name: config.name,
208
- description: config.description,
209
- ...contract,
210
- outputMappings: normalizeOutputMappings({
211
- mappings: config.outputMappings,
212
- outputSchema: contract.outputSchema
213
- }),
214
- operation: { type: "query", sql: config.sql }
215
- })
216
- };
217
- }
218
- function compileCustomDataSearchAction(config) {
219
- const contract = compileContracts(config);
220
- return {
221
- kind: "inline",
222
- key: config.key,
223
- contract,
224
- compile: () => ({
225
- actionType: "custom_data",
226
- name: config.name,
227
- description: config.description,
228
- ...contract,
229
- outputMappings: normalizeOutputMappings({
230
- mappings: config.outputMappings,
231
- outputSchema: contract.outputSchema
232
- }),
233
- operation: { type: "search", table: config.table, bodyTemplate: config.body }
234
- })
235
- };
236
- }
237
- function compileKnowledgeBaseSearchAction(config) {
238
- const contract = compileContracts(config);
239
- return {
240
- kind: "inline",
241
- key: config.key,
242
- contract,
243
- compile: () => ({
244
- actionType: "knowledge_base",
245
- name: config.name,
246
- description: config.description,
247
- ...contract,
248
- outputMappings: normalizeOutputMappings({
249
- mappings: config.outputMappings,
250
- outputSchema: contract.outputSchema
251
- }),
252
- operation: {
253
- type: "search",
254
- knowledgeBaseIds: config.knowledgeBaseIds,
255
- bodyTemplate: config.body
256
- }
257
- })
258
- };
259
- }
260
- var action = {
261
- http(config) {
262
- return compileHttpAction(config);
263
- },
264
- code(config) {
265
- return compileCodeAction(config);
266
- },
267
- customDataQuery(config) {
268
- return compileCustomDataQueryAction(config);
269
- },
270
- customDataSearch(config) {
271
- return compileCustomDataSearchAction(config);
272
- },
273
- knowledgeBaseSearch(config) {
274
- return compileKnowledgeBaseSearchAction(config);
275
- },
276
- ref(config) {
277
- return {
278
- kind: "reference",
279
- key: config.key,
280
- versionUuid: config.versionUuid,
281
- contract: config.contract ?? null
282
- };
283
- },
284
- callable(config) {
285
- return { kind: "callable", ...config };
286
- },
287
- run(config) {
288
- return { kind: "run", ...config };
289
- },
290
- fromAgent(description) {
291
- return { source: "agent", description };
292
- },
293
- from(value) {
294
- return { source: "template", value };
295
- }
296
- };
297
- function compileAction(definition, options = {}) {
298
- return definition.compile(options);
299
- }
300
- function sourceFile(path) {
301
- return { kind: "source-file", path };
302
- }
303
-
304
- // src/agents.ts
305
- import { createHash } from "crypto";
306
- import { z as z2 } from "zod";
307
- function defaultTransferCapability() {
308
- return {
309
- enabled: false,
310
- phoneNumber: null,
311
- timeout: 120,
312
- mode: "cold",
313
- description: null,
314
- voicemailMessage: null
315
- };
316
- }
317
- function defineAgent(input) {
318
- const transferDefaults = defaultTransferCapability();
319
- return {
320
- kind: "agent-definition",
321
- key: input.key,
322
- name: input.name,
323
- description: input.description ?? null,
324
- branch: input.branch,
325
- modality: input.modality ?? "voice",
326
- folderUuid: input.folderUuid ?? null,
327
- analyzerUuids: input.analyzerUuids ?? [],
328
- tagUuids: input.tagUuids ?? [],
329
- containmentConfig: input.containmentConfig ?? null,
330
- voice: {
331
- voiceUuid: input.voice?.voiceUuid ?? null,
332
- backgroundNoise: input.voice?.backgroundNoise ?? "off"
333
- },
334
- llm: {
335
- model: input.llm?.model ?? "gpt-4.1",
336
- modelUuid: input.llm?.modelUuid ?? null,
337
- temperature: input.llm?.temperature ?? 0.65
338
- },
339
- speech: {
340
- language: input.speech?.language ?? "en",
341
- keyterms: input.speech?.keyterms ?? []
342
- },
343
- call: {
344
- agentSpeaksFirst: input.call?.agentSpeaksFirst ?? false,
345
- firstSentence: input.call?.firstSentence ?? null,
346
- maxCallLengthSeconds: input.call?.maxCallLengthSeconds ?? 1800,
347
- record: input.call?.record ?? true,
348
- checkInAfterSilence: input.call?.checkInAfterSilence ?? { enabled: false, prompt: null },
349
- endCallAfterExtendedSilence: input.call?.endCallAfterExtendedSilence ?? false,
350
- pciEnabled: input.call?.pciEnabled ?? false,
351
- backgroundNoiseTrack: input.call?.backgroundNoiseTrack ?? null,
352
- backgroundNoiseGain: input.call?.backgroundNoiseGain === void 0 ? 1 : input.call.backgroundNoiseGain,
353
- interruptionMode: input.call?.interruptionMode === void 0 ? "medium" : input.call.interruptionMode
354
- },
355
- preCallWebhook: {
356
- enabled: input.preCallWebhook?.enabled ?? false,
357
- url: input.preCallWebhook?.url ?? null,
358
- authToken: input.preCallWebhook?.authToken ?? null,
359
- timeout: input.preCallWebhook?.timeout ?? 5,
360
- parameters: input.preCallWebhook?.parameters ?? []
361
- },
362
- capabilities: {
363
- dtmf: {
364
- enabled: input.capabilities?.dtmf?.enabled ?? false,
365
- description: input.capabilities?.dtmf?.description ?? null
366
- },
367
- hangup: {
368
- enabled: input.capabilities?.hangup?.enabled ?? true,
369
- description: input.capabilities?.hangup?.description ?? null,
370
- message: input.capabilities?.hangup?.message ?? null
371
- },
372
- transfer: {
373
- enabled: input.capabilities?.transfer?.enabled ?? transferDefaults.enabled,
374
- phoneNumber: input.capabilities?.transfer?.phoneNumber ?? transferDefaults.phoneNumber,
375
- timeout: input.capabilities?.transfer?.timeout ?? transferDefaults.timeout,
376
- mode: input.capabilities?.transfer?.mode ?? transferDefaults.mode,
377
- description: input.capabilities?.transfer?.description ?? transferDefaults.description,
378
- voicemailMessage: input.capabilities?.transfer?.voicemailMessage ?? transferDefaults.voicemailMessage
379
- }
380
- },
381
- knowledgeBases: input.knowledgeBases ?? [],
382
- beforeCallAction: input.beforeCallAction ?? null,
383
- summaryPrompt: input.summaryPrompt ?? null,
384
- abTestGroupIds: input.abTestGroupIds ?? null,
385
- nodes: input.nodes
386
- };
387
- }
388
- var node = {
389
- global(config) {
390
- return { type: "global", ...config };
391
- },
392
- prompt(config) {
393
- return { type: "prompt", ...config };
394
- },
395
- action(config) {
396
- return { type: "action", ...config };
397
- },
398
- http(config) {
399
- return { type: "http", ...config };
400
- },
401
- extract(config) {
402
- return { type: "extract", ...config };
403
- },
404
- say(config) {
405
- return { type: "say", ...config };
406
- },
407
- endCall(config) {
408
- return { type: "end-call", ...config };
409
- },
410
- route(config) {
411
- return { type: "route", ...config };
412
- },
413
- abTest(config) {
414
- return { type: "ab-test", ...config };
415
- },
416
- transfer(config) {
417
- return { type: "transfer", ...config };
418
- },
419
- transferChat(config) {
420
- return { type: "transfer-chat", ...config };
421
- }
422
- };
423
- var prompt = {
424
- inline(text, example = null, generatedExamples) {
425
- return { kind: "inline", text, example, ...generatedExamples === void 0 ? {} : { generatedExamples } };
426
- },
427
- file(path, example = null) {
428
- return { kind: "file", path, example };
429
- },
430
- version(versionId) {
431
- return { kind: "version", versionId };
432
- }
433
- };
434
- function reference(uuid) {
435
- return { uuid };
436
- }
437
- function isRecord2(value) {
438
- return value !== null && typeof value === "object" && !Array.isArray(value);
439
- }
440
- function deterministicUuid(input) {
441
- const bytes = Buffer.from(createHash("sha256").update(`${input.kind}:${input.key}`).digest().subarray(0, 16));
442
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
443
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
444
- const hex = bytes.toString("hex");
445
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
446
- }
447
- function resolveIdentity({
448
- options,
449
- kind,
450
- key,
451
- fallbackKeys = []
452
- }) {
453
- for (const candidateKey of [key, ...fallbackKeys]) {
454
- const identity = options.identity?.({ kind, key: candidateKey });
455
- if (identity !== void 0) {
456
- return identity;
457
- }
458
- }
459
- return deterministicUuid({ kind, key });
460
- }
461
- function canonicalAuthoringKey(value, fallback) {
462
- const normalizedCharacters = [];
463
- let needsSeparator = false;
464
- for (const character of value.toLowerCase()) {
465
- const characterCode = character.charCodeAt(0);
466
- const isLowercaseLetter = characterCode >= 97 && characterCode <= 122;
467
- const isDigit = characterCode >= 48 && characterCode <= 57;
468
- if (isLowercaseLetter || isDigit) {
469
- if (needsSeparator && normalizedCharacters.length > 0) {
470
- normalizedCharacters.push("-");
471
- }
472
- normalizedCharacters.push(character);
473
- needsSeparator = false;
474
- } else if (normalizedCharacters.length > 0) {
475
- needsSeparator = true;
476
- }
477
- }
478
- const normalized = normalizedCharacters.join("");
479
- return normalized === "" ? fallback : normalized;
480
- }
481
- function canonicalAuthoringKeys(values) {
482
- const used = /* @__PURE__ */ new Set();
483
- return values.map(({ value, fallback }) => {
484
- const base = canonicalAuthoringKey(value, fallback);
485
- let candidate = base;
486
- let sequence = 2;
487
- while (used.has(candidate)) {
488
- candidate = `${base}-${sequence}`;
489
- sequence += 1;
490
- }
491
- used.add(candidate);
492
- return candidate;
493
- });
494
- }
495
- function jsonSchemaDescription(value) {
496
- return typeof value.description === "string" ? value.description : "";
497
- }
498
- function extractionFieldFromJsonSchema({
499
- name,
500
- value,
501
- required,
502
- path
503
- }) {
504
- if (!isRecord2(value)) {
505
- throw new Error(`${path} is not a representable extraction field`);
506
- }
507
- const enumValues = Array.isArray(value.enum) ? value.enum.filter(
508
- (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean"
509
- ) : void 0;
510
- if (value.type === "object") {
511
- const rawProperties = isRecord2(value.properties) ? value.properties : {};
512
- const requiredNames = new Set(
513
- Array.isArray(value.required) ? value.required.filter((item) => typeof item === "string") : []
514
- );
515
- return {
516
- name,
517
- type: "object",
518
- description: jsonSchemaDescription(value),
519
- required,
520
- properties: Object.entries(rawProperties).map(
521
- ([childName, child]) => extractionFieldFromJsonSchema({
522
- name: childName,
523
- value: child,
524
- required: requiredNames.has(childName),
525
- path: `${path}.${childName}`
526
- })
527
- )
528
- };
529
- }
530
- if (value.type === "array") {
531
- if (value.items === void 0) {
532
- throw new Error(`${path} must declare an array item schema`);
533
- }
534
- return {
535
- name,
536
- type: "array",
537
- description: jsonSchemaDescription(value),
538
- required,
539
- items: extractionFieldFromJsonSchema({
540
- name: "item",
541
- value: value.items,
542
- required: true,
543
- path: `${path}[]`
544
- })
545
- };
546
- }
547
- if (!["string", "number", "integer", "boolean"].includes(String(value.type))) {
548
- throw new Error(`${path} uses unsupported extraction type "${String(value.type)}"`);
549
- }
550
- return {
551
- name,
552
- type: value.type === "integer" ? "number" : String(value.type),
553
- description: jsonSchemaDescription(value),
554
- required,
555
- ...enumValues === void 0 ? {} : { enum: enumValues }
556
- };
557
- }
558
- function extractionFieldsFromZod(schema) {
559
- const jsonSchema = z2.toJSONSchema(schema);
560
- if (!isRecord2(jsonSchema) || jsonSchema.type !== "object") {
561
- throw new Error("Extraction schemas must be Zod objects");
562
- }
563
- const rawProperties = isRecord2(jsonSchema.properties) ? jsonSchema.properties : {};
564
- const requiredNames = new Set(
565
- Array.isArray(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
566
- );
567
- return Object.entries(rawProperties).map(
568
- ([name, value]) => extractionFieldFromJsonSchema({
569
- name,
570
- value,
571
- required: requiredNames.has(name),
572
- path: `schema.${name}`
573
- })
574
- );
575
- }
576
- function compilePrompt(referenceValue, options) {
577
- switch (referenceValue.kind) {
578
- case "inline":
579
- return {
580
- type: "inline",
581
- prompt: referenceValue.text,
582
- example: referenceValue.example,
583
- // Product-generated; preserved verbatim so pulled prompts round-trip.
584
- ...referenceValue.generatedExamples === void 0 ? {} : { generatedExamples: referenceValue.generatedExamples }
585
- };
586
- case "file": {
587
- if (options.readPromptFile === void 0) {
588
- throw new Error(`Prompt file "${referenceValue.path}" requires a readPromptFile compiler option`);
589
- }
590
- return {
591
- type: "inline",
592
- prompt: options.readPromptFile(referenceValue.path),
593
- example: referenceValue.example
594
- };
595
- }
596
- case "version":
597
- return { type: "reference", promptVersionId: referenceValue.versionId };
598
- }
599
- }
600
- function resolveActionVersion({
601
- definition,
602
- options
603
- }) {
604
- if (definition.kind === "reference") {
605
- return definition.versionUuid;
606
- }
607
- const resolved = options.actionVersionUuids?.[definition.key];
608
- if (resolved !== void 0) {
609
- return resolved;
610
- }
611
- if (options.allowUnresolvedActionVersions === true) {
612
- return resolveIdentity({
613
- options,
614
- kind: "action-version-placeholder",
615
- key: definition.key
616
- });
617
- }
618
- throw new Error(`Action "${definition.key}" does not have a resolved version UUID`);
619
- }
620
- function pointerForInputName(name) {
621
- return `/${name.replace(/~/g, "~0").replace(/\//g, "~1")}`;
622
- }
623
- function compileOutputParameterMappings(outputParameters) {
624
- const mappedParameters = /* @__PURE__ */ new Set();
625
- const mappings = [];
626
- for (const [outputName, parameterName] of Object.entries(outputParameters)) {
627
- if (mappedParameters.has(parameterName)) {
628
- throw new Error(`Agent parameter "${parameterName}" is mapped from more than one Action output`);
629
- }
630
- mappedParameters.add(parameterName);
631
- mappings.push([parameterName, `{{ outputs.${outputName} }}`]);
632
- }
633
- return Object.fromEntries(mappings);
634
- }
635
- function compileCallableUseSite({
636
- callable,
637
- canonicalKey,
638
- options
639
- }) {
640
- const inputMappings = {};
641
- const inputDescriptions = {};
642
- for (const [name, input] of Object.entries(callable.inputs)) {
643
- const pointer = pointerForInputName(name);
644
- if (input.source === "agent") {
645
- inputDescriptions[pointer] = input.description;
646
- } else {
647
- inputMappings[pointer] = input.value;
648
- }
649
- }
650
- const contractProperties = callable.action.contract?.inputSchema.properties ?? {};
651
- for (const [name, schema] of Object.entries(contractProperties)) {
652
- const pointer = pointerForInputName(name);
653
- if (inputMappings[pointer] !== void 0 || inputDescriptions[pointer] !== void 0) {
654
- continue;
655
- }
656
- if (schema.description.trim() === "") {
657
- throw new Error(`Callable Action "${callable.key}" input "${name}" needs an agent-facing description`);
658
- }
659
- inputDescriptions[pointer] = schema.description;
660
- }
661
- return {
662
- actionUseSiteUuid: resolveIdentity({
663
- options,
664
- kind: "action-use-site",
665
- key: callable.key,
666
- fallbackKeys: [canonicalKey]
667
- }),
668
- actionVersionUuid: resolveActionVersion({ definition: callable.action, options }),
669
- name: callable.name,
670
- description: callable.description,
671
- inputDescriptions,
672
- inputMappings,
673
- outputParameterMappings: compileOutputParameterMappings(callable.outputParameters)
674
- };
675
- }
676
- function compileActionRun({
677
- run,
678
- trigger,
679
- canonicalKey,
680
- options
681
- }) {
682
- return {
683
- actionUseSiteUuid: resolveIdentity({
684
- options,
685
- kind: "action-use-site",
686
- key: run.key,
687
- fallbackKeys: [canonicalKey]
688
- }),
689
- actionVersionUuid: resolveActionVersion({ definition: run.action, options }),
690
- inputMappings: Object.fromEntries(
691
- Object.entries(run.inputs).map(([name, value]) => [
692
- name.startsWith("/") ? name : pointerForInputName(name),
693
- value
694
- ])
695
- ),
696
- outputParameterMappings: compileOutputParameterMappings(run.outputParameters),
697
- trigger
698
- };
699
- }
700
- function collectCallableActions(nodes) {
701
- const byKey = /* @__PURE__ */ new Map();
702
- for (const definition of nodes) {
703
- if (definition.type !== "prompt") {
704
- continue;
705
- }
706
- for (const callable of definition.actions ?? []) {
707
- const existing = byKey.get(callable.key);
708
- if (existing !== void 0 && existing !== callable) {
709
- throw new Error(`Callable Action key "${callable.key}" is defined more than once`);
710
- }
711
- byKey.set(callable.key, callable);
712
- }
713
- }
714
- return [...byKey.values()];
715
- }
716
- function collectInlineActions(definition) {
717
- const byKey = /* @__PURE__ */ new Map();
718
- const visit = (actionDefinition) => {
719
- if (actionDefinition.kind !== "inline") {
720
- return;
721
- }
722
- const existing = byKey.get(actionDefinition.key);
723
- if (existing !== void 0 && existing !== actionDefinition) {
724
- throw new Error(`Inline Action key "${actionDefinition.key}" is defined more than once`);
725
- }
726
- byKey.set(actionDefinition.key, actionDefinition);
727
- };
728
- for (const callable of collectCallableActions(definition.nodes)) {
729
- visit(callable.action);
730
- }
731
- if (definition.beforeCallAction !== null) {
732
- visit(definition.beforeCallAction.action);
733
- }
734
- for (const definitionNode of definition.nodes) {
735
- if (definitionNode.type === "action") {
736
- visit(definitionNode.action);
737
- }
738
- if (definitionNode.type === "prompt" && definitionNode.perTurnAction !== null && definitionNode.perTurnAction !== void 0) {
739
- visit(definitionNode.perTurnAction.action);
740
- }
741
- }
742
- return [...byKey.values()];
743
- }
744
- function compileEdges({
745
- definition,
746
- canonicalNodeKey,
747
- nodeUuids,
748
- options
749
- }) {
750
- return (definition.edges ?? []).map((edgeDefinition, index) => {
751
- const targetUuid = nodeUuids.get(edgeDefinition.to);
752
- if (targetUuid === void 0) {
753
- throw new Error(`Node "${definition.key}" points to unknown node "${edgeDefinition.to}"`);
754
- }
755
- const edgeKey = edgeDefinition.key ?? `${definition.key}:${index}`;
756
- return {
757
- uuid: resolveIdentity({
758
- options,
759
- kind: "edge",
760
- key: edgeKey,
761
- fallbackKeys: [`${canonicalNodeKey}:${index}`]
762
- }),
763
- toNodeUuid: targetUuid,
764
- description: edgeDefinition.when,
765
- priority: edgeDefinition.priority ?? index,
766
- condition: edgeDefinition.condition ?? null
767
- };
768
- });
769
- }
770
- function baseNodeWire({
771
- definition,
772
- canonicalNodeKey,
773
- index,
774
- nodeUuids,
775
- options
776
- }) {
777
- const uuid = nodeUuids.get(definition.key);
778
- if (uuid === void 0) {
779
- throw new Error(`Node "${definition.key}" has no compiled identity`);
780
- }
781
- return {
782
- uuid,
783
- name: definition.name,
784
- isRoot: definition.root ?? false,
785
- position: definition.position ?? { x: index % 4 * 320, y: Math.floor(index / 4) * 220 },
786
- behavior: { waitAfterExecuting: definition.waitAfterExecuting ?? 0 },
787
- edges: compileEdges({ definition, canonicalNodeKey, nodeUuids, options })
788
- };
789
- }
790
- function nodeCapabilities(definition) {
791
- return definition.alwaysAvailable === void 0 ? {} : { alwaysAvailable: definition.alwaysAvailable };
792
- }
793
- function promptNodeCapabilities(definition) {
794
- const base = nodeCapabilities(definition);
795
- if (definition.transfer === void 0) {
796
- return base;
797
- }
798
- return {
799
- ...base,
800
- transfer: {
801
- enabled: definition.transfer.enabled,
802
- phoneNumber: definition.transfer.phoneNumber ?? null,
803
- timeout: definition.transfer.timeout ?? 120,
804
- mode: definition.transfer.mode ?? "cold",
805
- description: definition.transfer.description ?? null,
806
- voicemailMessage: definition.transfer.voicemailMessage ?? null
807
- }
808
- };
809
- }
810
- function compileNode({
811
- definition,
812
- canonicalNodeKey,
813
- canonicalCallableKeys,
814
- index,
815
- nodeUuids,
816
- options
817
- }) {
818
- const base = baseNodeWire({ definition, canonicalNodeKey, index, nodeUuids, options });
819
- const builtInTools = nodeCapabilities(definition);
820
- switch (definition.type) {
821
- case "global":
822
- return {
823
- ...base,
824
- type: "global",
825
- prompt: compilePrompt(definition.prompt, options)
826
- };
827
- case "prompt": {
828
- const perTurnAction = definition.perTurnAction === null || definition.perTurnAction === void 0 ? null : compileActionRun({
829
- run: definition.perTurnAction,
830
- trigger: "every_turn",
831
- canonicalKey: `${canonicalNodeKey}:every-turn`,
832
- options
833
- });
834
- return {
835
- ...base,
836
- type: "standard",
837
- prompt: compilePrompt(definition.prompt, options),
838
- toolUuids: [],
839
- // Present whenever `actions` is declared, even when empty, so an
840
- // explicit empty list survives the round trip.
841
- ...definition.actions === void 0 ? {} : {
842
- toolUseSiteUuids: definition.actions.map(
843
- (callable) => resolveIdentity({
844
- options,
845
- kind: "action-use-site",
846
- key: callable.key,
847
- fallbackKeys: [canonicalCallableKeys.get(callable.key) ?? callable.key]
848
- })
849
- )
850
- },
851
- knowledgeBaseUuids: (definition.knowledgeBases ?? []).map((item) => item.uuid),
852
- customDataTableNames: definition.customDataTables ?? [],
853
- builtInTools: promptNodeCapabilities(definition),
854
- sopSpec: definition.sopSpec ?? null,
855
- overrides: {
856
- ...definition.voiceOverride === void 0 ? {} : { voice: definition.voiceOverride },
857
- ...definition.llmOverride === void 0 ? {} : {
858
- llm: {
859
- model: definition.llmOverride.model,
860
- llmModelUuid: definition.llmOverride.modelUuid,
861
- temperature: definition.llmOverride.temperature
862
- }
863
- }
864
- },
865
- behavior: {
866
- ...base.behavior,
867
- ...definition.vadMinSilenceDuration === void 0 ? {} : { vadMinSilenceDuration: definition.vadMinSilenceDuration },
868
- ...definition.waitAfterTransfer === void 0 ? {} : { waitAfterTransfer: definition.waitAfterTransfer }
869
- },
870
- // These three round-trip three states each: absent, explicit null, or a
871
- // value. The product emits all three across different nodes, so
872
- // `undefined` means "omit the key" and `null` means "write null".
873
- ...definition.perTurnWebhook === void 0 ? {} : { perTurnWebhook: definition.perTurnWebhook },
874
- ...definition.perTurnExtraction === void 0 ? {} : {
875
- perTurnExtractionFields: definition.perTurnExtraction === null ? null : extractionFieldsFromZod(definition.perTurnExtraction)
876
- },
877
- ...definition.perTurnAction === void 0 ? {} : { perTurnAction }
878
- };
879
- }
880
- case "action":
881
- return {
882
- ...base,
883
- type: "action_node",
884
- actionVersionUuid: resolveActionVersion({ definition: definition.action, options }),
885
- inputMappings: Object.fromEntries(
886
- Object.entries(definition.inputs).map(([name, value]) => [
887
- name.startsWith("/") ? name : pointerForInputName(name),
888
- value
889
- ])
890
- ),
891
- outputParameterMappings: compileOutputParameterMappings(definition.outputParameters ?? {}),
892
- runInBackground: definition.runInBackground ?? false,
893
- backgroundMessage: definition.backgroundMessage ?? null,
894
- executionMessage: definition.executionMessage ?? null,
895
- mockResponseData: definition.mockResponseData ?? null,
896
- builtInTools
897
- };
898
- case "http":
899
- return {
900
- ...base,
901
- type: "http",
902
- url: definition.url,
903
- method: definition.method,
904
- headers: definition.headers ?? {},
905
- body: definition.body ?? null,
906
- responseSelectors: definition.responseSelectors ?? [],
907
- runInBackground: definition.runInBackground ?? false,
908
- backgroundMessage: definition.backgroundMessage ?? null,
909
- executionMessage: definition.executionMessage ?? null,
910
- mockResponseData: definition.mockResponseData ?? null,
911
- builtInTools
912
- };
913
- case "extract":
914
- return {
915
- ...base,
916
- type: "extract",
917
- fields: extractionFieldsFromZod(definition.schema),
918
- executionMessage: definition.message ?? null,
919
- builtInTools
920
- };
921
- case "say":
922
- return {
923
- ...base,
924
- type: "say",
925
- executionMessage: definition.text,
926
- overrides: definition.voiceUuid === void 0 ? {} : { voice: { voiceUuid: definition.voiceUuid } },
927
- behavior: {
928
- ...base.behavior,
929
- ...definition.waitAfterSay === void 0 ? {} : { waitAfterSay: definition.waitAfterSay }
930
- },
931
- builtInTools
932
- };
933
- case "end-call":
934
- return {
935
- ...base,
936
- type: "end_call",
937
- executionMessage: definition.message ?? null,
938
- builtInTools
939
- };
940
- case "route":
941
- return {
942
- ...base,
943
- type: "routing",
944
- description: definition.description,
945
- builtInTools
946
- };
947
- case "ab-test":
948
- return {
949
- ...base,
950
- type: "ab_test",
951
- abTestGroupUuid: definition.abTestGroupUuid,
952
- builtInTools
953
- };
954
- case "transfer": {
955
- const transfer = {
956
- enabled: true,
957
- phoneNumber: definition.phoneNumber,
958
- timeout: definition.timeout ?? 120,
959
- mode: definition.mode ?? "cold",
960
- description: definition.description ?? null,
961
- voicemailMessage: definition.voicemailMessage ?? null
962
- };
963
- return {
964
- ...base,
965
- type: "transfer",
966
- executionMessage: definition.message ?? null,
967
- behavior: {
968
- ...base.behavior,
969
- ...definition.waitAfterTransfer === void 0 ? {} : { waitAfterTransfer: definition.waitAfterTransfer }
970
- },
971
- builtInTools: { ...builtInTools, transfer }
972
- };
973
- }
974
- case "transfer-chat":
975
- return {
976
- ...base,
977
- type: "transfer_chat",
978
- executionMessage: definition.message ?? null,
979
- mode: definition.mode,
980
- five9TenantName: definition.five9TenantName ?? "",
981
- five9CampaignName: definition.five9CampaignName ?? "",
982
- five9ContactMapping: definition.five9ContactMapping ?? {},
983
- five9AttributesMapping: definition.five9AttributesMapping ?? [],
984
- builtInTools
985
- };
986
- }
987
- }
988
- function validateDefinition(definition) {
989
- const keys = definition.nodes.map((definitionNode) => definitionNode.key);
990
- if (new Set(keys).size !== keys.length) {
991
- throw new Error("Every node key must be unique");
992
- }
993
- if (definition.nodes.length === 0) {
994
- return;
995
- }
996
- const roots = definition.nodes.filter((definitionNode) => definitionNode.root === true);
997
- if (roots.length !== 1) {
998
- throw new Error(`An agent with nodes must contain exactly one root node; received ${roots.length}`);
999
- }
1000
- if (definition.nodes.some((definitionNode) => definitionNode.type === "global" && definitionNode.root === true)) {
1001
- throw new Error("The global node cannot be the root node");
1002
- }
1003
- }
1004
- function compileAgent(definition, options = {}) {
1005
- validateDefinition(definition);
1006
- const canonicalNodeKeys = canonicalAuthoringKeys(
1007
- definition.nodes.map((definitionNode, index) => ({
1008
- value: definitionNode.name,
1009
- fallback: `node-${index + 1}`
1010
- }))
1011
- );
1012
- const canonicalNodeKeysByDefinitionKey = new Map(
1013
- definition.nodes.map((definitionNode, index) => [
1014
- definitionNode.key,
1015
- canonicalNodeKeys[index] ?? definitionNode.key
1016
- ])
1017
- );
1018
- const nodeUuids = new Map(
1019
- definition.nodes.map((definitionNode, index) => [
1020
- definitionNode.key,
1021
- resolveIdentity({
1022
- options,
1023
- kind: "node",
1024
- key: definitionNode.key,
1025
- fallbackKeys: [canonicalNodeKeys[index] ?? definitionNode.key]
1026
- })
1027
- ])
1028
- );
1029
- const callables = collectCallableActions(definition.nodes);
1030
- const canonicalCallableKeys = canonicalAuthoringKeys(
1031
- callables.map((callable, index) => ({
1032
- value: callable.name,
1033
- fallback: `action-${index + 1}`
1034
- }))
1035
- );
1036
- const canonicalCallableKeysByDefinitionKey = new Map(
1037
- callables.map((callable, index) => [callable.key, canonicalCallableKeys[index] ?? callable.key])
1038
- );
1039
- const toolUseSites = callables.map(
1040
- (callable) => compileCallableUseSite({
1041
- callable,
1042
- canonicalKey: canonicalCallableKeysByDefinitionKey.get(callable.key) ?? callable.key,
1043
- options
1044
- })
1045
- );
1046
- const inlineActions = collectInlineActions(definition);
1047
- const abTestGroupIds = [
1048
- ...new Set(
1049
- definition.nodes.flatMap(
1050
- (definitionNode) => definitionNode.type === "ab-test" ? [definitionNode.abTestGroupUuid] : []
1051
- )
1052
- )
1053
- ];
1054
- return {
1055
- agent: {
1056
- key: definition.key,
1057
- name: definition.name,
1058
- description: definition.description,
1059
- modality: definition.modality,
1060
- folderUuid: definition.folderUuid,
1061
- analyzerUuids: definition.analyzerUuids,
1062
- tagUuids: definition.tagUuids,
1063
- containmentConfig: definition.containmentConfig
1064
- },
1065
- branch: { name: definition.branch },
1066
- actions: inlineActions.map((definitionAction) => ({
1067
- key: definitionAction.key,
1068
- versionUuid: resolveActionVersion({
1069
- definition: definitionAction,
1070
- options
1071
- }),
1072
- values: compileAction(definitionAction, {
1073
- ...options.readActionSourceFile === void 0 ? {} : { readSourceFile: options.readActionSourceFile }
1074
- })
1075
- })),
1076
- content: {
1077
- config: {
1078
- voice: {
1079
- voiceUuid: definition.voice.voiceUuid,
1080
- backgroundNoise: definition.voice.backgroundNoise
1081
- },
1082
- llm: {
1083
- model: definition.llm.model,
1084
- llmModelUuid: definition.llm.modelUuid,
1085
- temperature: definition.llm.temperature
1086
- },
1087
- speech: definition.speech,
1088
- call: {
1089
- agentSpeaksFirst: definition.call.agentSpeaksFirst,
1090
- firstSentence: definition.call.firstSentence,
1091
- maxCallLengthSeconds: definition.call.maxCallLengthSeconds,
1092
- record: definition.call.record,
1093
- checkInAfterSilence: definition.call.checkInAfterSilence,
1094
- endCallAfterExtendedSilence: definition.call.endCallAfterExtendedSilence,
1095
- pciEnabled: definition.call.pciEnabled,
1096
- backgroundNoise: {
1097
- trackName: definition.call.backgroundNoiseTrack ?? definition.voice.backgroundNoise,
1098
- ...definition.call.backgroundNoiseGain === null ? {} : { gainMultiplier: definition.call.backgroundNoiseGain }
1099
- },
1100
- ...definition.call.interruptionMode === null ? {} : { interruptionConfig: { mode: definition.call.interruptionMode } }
1101
- },
1102
- preCallWebhook: definition.preCallWebhook,
1103
- builtInTools: definition.capabilities,
1104
- assignedToolIds: [],
1105
- // Emitted whenever any node declares an `actions` array, so an Agent
1106
- // that once had callable Actions keeps its explicit empty list rather
1107
- // than dropping the key.
1108
- ...definition.nodes.some(
1109
- (definitionNode) => definitionNode.type === "prompt" && definitionNode.actions !== void 0
1110
- ) ? { toolUseSites } : {},
1111
- automaticActions: {
1112
- beforeCallStart: definition.beforeCallAction === null ? null : compileActionRun({
1113
- run: definition.beforeCallAction,
1114
- trigger: "before_call_start",
1115
- canonicalKey: "before-call-start",
1116
- options
1117
- })
1118
- },
1119
- knowledgeBaseIds: definition.knowledgeBases.map((item) => item.uuid),
1120
- abTestGroupIds: definition.abTestGroupIds ?? abTestGroupIds
1121
- },
1122
- nodes: definition.nodes.map(
1123
- (definitionNode, index) => compileNode({
1124
- definition: definitionNode,
1125
- canonicalNodeKey: canonicalNodeKeysByDefinitionKey.get(definitionNode.key) ?? definitionNode.key,
1126
- canonicalCallableKeys: canonicalCallableKeysByDefinitionKey,
1127
- index,
1128
- nodeUuids,
1129
- options
1130
- })
1131
- ),
1132
- summaryPrompt: definition.summaryPrompt
1133
- }
1134
- };
1135
- }
1136
-
1137
- // src/schemas.ts
1138
- import { z as z3 } from "zod";
1139
- var MAX_QUERY_SIZE = 50;
1140
- var MAX_BATCH_ROWS = 1e3;
1141
- var tableNameSchema = z3.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
1142
- var filterValueSchema = z3.union([z3.string(), z3.number(), z3.boolean()]);
1143
- var dataColumnPathSchema = z3.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
1144
- message: "Must be a dot-separated column path with no empty segments"
1145
- });
1146
- var dataFilterSchema = z3.object({
1147
- column: dataColumnPathSchema,
1148
- values: z3.array(filterValueSchema)
1149
- });
1150
- var queryInputSchema = z3.object({
1151
- tableName: tableNameSchema,
1152
- filters: z3.array(dataFilterSchema).optional(),
1153
- text: z3.string().max(5e3).optional(),
1154
- size: z3.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
1155
- from: z3.number().int().min(0).optional()
1156
- });
1157
- var listOptionsSchema = z3.object({
1158
- page: z3.number().int().min(1).optional(),
1159
- perPage: z3.number().int().min(1).max(200).optional(),
1160
- orderBy: z3.string().optional(),
1161
- orderDirection: z3.enum(["asc", "desc"]).optional(),
1162
- /** Column-name → value equality filters applied server-side. */
1163
- filters: z3.record(z3.string(), z3.string()).optional()
1164
- });
1165
- var recordPayloadSchema = z3.record(z3.string(), z3.unknown());
1166
- var batchUpsertRowsSchema = z3.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
1167
-
1168
- // src/data.ts
1169
- function encodeTable(tableName) {
1170
- return encodeURIComponent(tableNameSchema.parse(tableName));
1171
- }
1172
- var DataClient = class {
1173
- #http;
1174
- constructor(http) {
1175
- this.#http = http;
1176
- }
1177
- /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
1178
- async query(input) {
1179
- const parsed = queryInputSchema.parse(input);
1180
- const result = await this.#http.request({ method: "POST", path: "/data/query", body: parsed });
1181
- return result;
1182
- }
1183
- /** Facet values for an indexed table. */
1184
- async facets(tableName) {
1185
- const result = await this.#http.request({ method: "GET", path: `/data/facets/${encodeTable(tableName)}` });
1186
- return result;
1187
- }
1188
- /** Paginated listing straight from the relational store. */
1189
- async list(tableName, options = {}) {
1190
- const parsed = listOptionsSchema.parse(options);
1191
- const query = { ...parsed.filters ?? {} };
1192
- if (parsed.page !== void 0) {
1193
- query.page = String(parsed.page);
1194
- }
1195
- if (parsed.perPage !== void 0) {
1196
- query.per_page = String(parsed.perPage);
1197
- }
1198
- if (parsed.orderBy !== void 0) {
1199
- query.order_by = parsed.orderBy;
1200
- }
1201
- if (parsed.orderDirection !== void 0) {
1202
- query.order_direction = parsed.orderDirection;
1203
- }
1204
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}`, query });
1205
- return result;
1206
- }
1207
- async get(tableName, id) {
1208
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}/${id}` });
1209
- return result;
1210
- }
1211
- async create(tableName, payload) {
1212
- const result = await this.#http.request({
1213
- method: "PUT",
1214
- path: `/data/${encodeTable(tableName)}`,
1215
- body: recordPayloadSchema.parse(payload)
1216
- });
1217
- return result;
1218
- }
1219
- async update(tableName, id, payload) {
1220
- const result = await this.#http.request({
1221
- method: "PATCH",
1222
- path: `/data/${encodeTable(tableName)}/${id}`,
1223
- body: recordPayloadSchema.parse(payload)
1224
- });
1225
- return result;
1226
- }
1227
- async delete(tableName, id) {
1228
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}/${id}` });
1229
- return result;
1230
- }
1231
- /** Deletes every record in the table. Irreversible. */
1232
- async deleteAll(tableName) {
1233
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}` });
1234
- return result;
1235
- }
1236
- /**
1237
- * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
1238
- * REPLACE on key conflict — omitted columns are cleared, not preserved.
1239
- * Returns a batch handle; poll `getBatch` for completion.
1240
- */
1241
- async batchUpsert(tableName, rows) {
1242
- const result = await this.#http.request({
1243
- method: "PUT",
1244
- path: `/data/${encodeTable(tableName)}/batch`,
1245
- body: { rows: batchUpsertRowsSchema.parse(rows) }
1246
- });
1247
- return result;
1248
- }
1249
- /** Status of an async upsert batch created by `batchUpsert`. */
1250
- async getBatch(ingestBatchId) {
1251
- const result = await this.#http.request({
1252
- method: "GET",
1253
- path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`
1254
- });
1255
- return result;
1256
- }
1257
- };
1258
-
1259
- // src/errors.ts
1260
- var SimpleAIError = class extends Error {
1261
- /** HTTP status code, or 0 when the request never reached the API. */
1262
- status;
1263
- /** Machine-readable error code from the API body, when present. */
1264
- code;
1265
- /** The parsed response body (JSON when possible, otherwise raw text). */
1266
- body;
1267
- constructor({
1268
- message,
1269
- status,
1270
- code,
1271
- body,
1272
- cause
1273
- }) {
1274
- super(message, cause === void 0 ? void 0 : { cause });
1275
- this.name = "SimpleAIError";
1276
- this.status = status;
1277
- this.code = code;
1278
- this.body = body;
1279
- }
1280
- };
1281
-
1282
- // src/http.ts
1283
- function parseBody(text) {
1284
- if (text.length === 0) {
1285
- return null;
1286
- }
1287
- try {
1288
- return JSON.parse(text);
1289
- } catch {
1290
- return text;
1291
- }
1292
- }
1293
- function errorDetails(body) {
1294
- if (body !== null && typeof body === "object") {
1295
- const record = body;
1296
- const code = typeof record.code === "string" ? record.code : null;
1297
- const message = typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : null;
1298
- return { code, message };
1299
- }
1300
- return { code: null, message: typeof body === "string" && body.length > 0 ? body : null };
1301
- }
1302
- function createHttpClient({
1303
- baseUrl,
1304
- apiKey,
1305
- fetchImplementation
1306
- }) {
1307
- const normalizedBase = baseUrl.replace(/\/+$/, "");
1308
- return {
1309
- request: async ({ method, path, query, body }) => {
1310
- const queryString = query === void 0 || Object.keys(query).length === 0 ? "" : `?${new URLSearchParams(query).toString()}`;
1311
- const url = `${normalizedBase}${path}${queryString}`;
1312
- let response;
1313
- try {
1314
- response = await fetchImplementation(url, {
1315
- method,
1316
- headers: {
1317
- authorization: `Bearer ${apiKey}`,
1318
- "content-type": "application/json",
1319
- accept: "application/json"
1320
- },
1321
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
1322
- });
1323
- } catch (e) {
1324
- throw new SimpleAIError({
1325
- message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
1326
- status: 0,
1327
- code: "network_error",
1328
- body: null,
1329
- cause: e
1330
- });
1331
- }
1332
- const parsed = parseBody(await response.text());
1333
- if (!response.ok) {
1334
- const { code, message } = errorDetails(parsed);
1335
- throw new SimpleAIError({
1336
- message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,
1337
- status: response.status,
1338
- code,
1339
- body: parsed
1340
- });
1341
- }
1342
- return parsed;
1343
- }
1344
- };
1345
- }
1346
-
1347
- // src/client.ts
1348
- var DEFAULT_BASE_URL = "https://api.prod.usesimple.ai/api/v1";
1349
- function envVar(name) {
1350
- if (typeof process === "undefined" || process.env === void 0) {
1351
- return void 0;
1352
- }
1353
- const value = process.env[name];
1354
- return value === void 0 || value === "" ? void 0 : value;
1355
- }
1356
- var SimpleAI = class {
1357
- /** Custom data tables — query, read, and write records. */
1358
- data;
1359
- constructor(options = {}) {
1360
- const apiKey = options.apiKey ?? envVar("SIMPLE_API_KEY");
1361
- if (apiKey === void 0) {
1362
- throw new Error(
1363
- "Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. Inside Simple AI code actions the key is injected automatically."
1364
- );
1365
- }
1366
- const baseUrl = options.baseUrl ?? envVar("SIMPLE_BASE_URL") ?? DEFAULT_BASE_URL;
1367
- const fetchImplementation = options.fetch ?? ((url, init) => fetch(url, init));
1368
- const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });
1369
- this.data = new DataClient(http);
1370
- }
1371
- };
1372
-
1373
- // src/define-action.ts
1374
- var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
1375
- function defineAction(handler) {
1376
- const wrapped = async ({ inputs, config }) => {
1377
- const client = new SimpleAI();
1378
- return handler({ inputs, config, client });
1379
- };
1380
- return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
1381
- }
1382
-
1383
- // src/projects.ts
1384
- function defineAgentSnapshot(definition) {
1385
- return { kind: "agent-snapshot", ...definition };
1386
- }
1387
- function replaceActionVersionUuid({
1388
- versionUuid,
1389
- actions,
1390
- options
1391
- }) {
1392
- const actionDefinition = actions.find((item) => item.sourceVersionUuid === versionUuid);
1393
- if (actionDefinition === void 0) {
1394
- return versionUuid;
1395
- }
1396
- return options.actionVersionUuids?.[actionDefinition.key] ?? versionUuid;
1397
- }
1398
- function compileSnapshotNode({
1399
- node: node2,
1400
- actions,
1401
- options
1402
- }) {
1403
- if (node2.type === "action_node") {
1404
- return {
1405
- ...node2,
1406
- actionVersionUuid: replaceActionVersionUuid({
1407
- versionUuid: node2.actionVersionUuid,
1408
- actions,
1409
- options
1410
- })
1411
- };
1412
- }
1413
- if (node2.type === "standard" && node2.perTurnAction != null) {
1414
- return {
1415
- ...node2,
1416
- perTurnAction: {
1417
- ...node2.perTurnAction,
1418
- actionVersionUuid: replaceActionVersionUuid({
1419
- versionUuid: node2.perTurnAction.actionVersionUuid,
1420
- actions,
1421
- options
1422
- })
1423
- }
1424
- };
1425
- }
1426
- return node2;
1427
- }
1428
- function compileSnapshot(definition, options) {
1429
- const snapshotActionValues = (values) => {
1430
- switch (values.actionType) {
1431
- case "code":
1432
- return {
1433
- ...values,
1434
- operation: {
1435
- ...values.operation,
1436
- compiledJs: null
1437
- }
1438
- };
1439
- case "http":
1440
- case "custom_data":
1441
- case "knowledge_base":
1442
- return values;
1443
- }
1444
- };
1445
- return {
1446
- agent: definition.agent,
1447
- branch: definition.branch,
1448
- actions: definition.actions.map((item) => ({
1449
- key: item.key,
1450
- versionUuid: replaceActionVersionUuid({
1451
- versionUuid: item.sourceVersionUuid,
1452
- actions: definition.actions,
1453
- options
1454
- }),
1455
- values: snapshotActionValues(item.values)
1456
- })),
1457
- content: {
1458
- ...definition.content,
1459
- config: {
1460
- ...definition.content.config,
1461
- ...definition.content.config.toolUseSites === void 0 ? {} : {
1462
- toolUseSites: definition.content.config.toolUseSites.map((useSite) => ({
1463
- ...useSite,
1464
- actionVersionUuid: replaceActionVersionUuid({
1465
- versionUuid: useSite.actionVersionUuid,
1466
- actions: definition.actions,
1467
- options
1468
- })
1469
- }))
1470
- },
1471
- automaticActions: {
1472
- beforeCallStart: definition.content.config.automaticActions.beforeCallStart === null ? null : {
1473
- ...definition.content.config.automaticActions.beforeCallStart,
1474
- actionVersionUuid: replaceActionVersionUuid({
1475
- versionUuid: definition.content.config.automaticActions.beforeCallStart.actionVersionUuid,
1476
- actions: definition.actions,
1477
- options
1478
- })
1479
- }
1480
- }
1481
- },
1482
- nodes: definition.content.nodes.map(
1483
- (node2) => compileSnapshotNode({ node: node2, actions: definition.actions, options })
1484
- )
1485
- }
1486
- };
1487
- }
1488
- function compileAgentProject(definition, options = {}) {
1489
- return definition.kind === "agent-definition" ? compileAgent(definition, options) : compileSnapshot(definition, options);
1490
- }
1491
- function collectActionVersionUuids(content) {
1492
- const versionUuids = /* @__PURE__ */ new Set();
1493
- for (const useSite of content.config.toolUseSites ?? []) {
1494
- versionUuids.add(useSite.actionVersionUuid);
1495
- }
1496
- const beforeCallAction = content.config.automaticActions.beforeCallStart;
1497
- if (beforeCallAction !== null) {
1498
- versionUuids.add(beforeCallAction.actionVersionUuid);
1499
- }
1500
- for (const node2 of content.nodes) {
1501
- if (node2.type === "action_node") {
1502
- versionUuids.add(node2.actionVersionUuid);
1503
- }
1504
- if (node2.type === "standard" && node2.perTurnAction != null) {
1505
- versionUuids.add(node2.perTurnAction.actionVersionUuid);
1506
- }
1507
- }
1508
- return [...versionUuids];
1509
- }
1510
- export {
1511
- DataClient,
1512
- MAX_BATCH_ROWS,
1513
- MAX_QUERY_SIZE,
1514
- SIMPLE_ACTION_BRAND,
1515
- SimpleAI,
1516
- SimpleAIError,
1517
- action,
1518
- actionsIoSchemaFromZod,
1519
- batchUpsertRowsSchema,
1520
- canonicalAuthoringKey,
1521
- canonicalAuthoringKeys,
1522
- collectActionVersionUuids,
1523
- compileAction,
1524
- compileAgent,
1525
- compileAgentProject,
1526
- dataColumnPathSchema,
1527
- dataFilterSchema,
1528
- defineAction,
1529
- defineAgent,
1530
- defineAgentSnapshot,
1531
- listOptionsSchema,
1532
- node,
1533
- prompt,
1534
- queryInputSchema,
1535
- recordPayloadSchema,
1536
- reference,
1537
- sourceFile,
1538
- tableNameSchema
1539
- };
1540
- //# sourceMappingURL=index.js.map
1
+ export { resolveActionHttpHeaders, resolveActionIoSchema, action, actionsIoSchemaFromZod, canonicalActionSource, compileAction, sourceFile, } from "./actions.js";
2
+ export { canonicalAuthoringKey, canonicalAuthoringKeys, compileAgent, DEFAULT_CHECK_IN_AFTER_SILENCE_DELAY_SECONDS, DEFAULT_PER_TURN_RETRIEVAL_RECENT_TURNS, DEFAULT_PER_TURN_RETRIEVAL_TOP_K, DEFAULT_TRANSITION_MESSAGE, defaultBackgroundNoise, defineAgent, FIVE9_SIP_BYE_HEADER_NAMES, MAX_CONTAINMENT_RULE_DEPTH, node, prompt, reference, resolveExtractionFields, TRANSITION_FILTER_MAX_CONDITIONS, TRANSITION_FILTER_MAX_DEPTH, } from "./agents.js";
3
+ export { BUILT_IN_ACTION_CONTRACTS, SEND_EMAIL_INPUT_SCHEMA, SEND_EMAIL_OUTPUT_MAPPINGS, SEND_EMAIL_OUTPUT_SCHEMA, SEND_TEXT_MESSAGE_INPUT_SCHEMA, SEND_TEXT_MESSAGE_OUTPUT_MAPPINGS, SEND_TEXT_MESSAGE_OUTPUT_SCHEMA, VALIDATE_ADDRESS_INPUT_SCHEMA, VALIDATE_ADDRESS_OUTPUT_MAPPINGS, VALIDATE_ADDRESS_OUTPUT_SCHEMA, } from "./built-in-actions.js";
4
+ export { SimpleAI } from "./client.js";
5
+ export { defineAction, defineCustomDataTransform, SIMPLE_ACTION_BRAND, } from "./code-action/define-action.js";
6
+ export { ActionCapability } from "./code-action/types.js";
7
+ export { DataClient } from "./data.js";
8
+ export { collectActionVersionUuids, compileAgentProject, defineAgentSnapshot, normalizeAgentV2CommitContent, } from "./projects.js";
9
+ export { batchUpsertRowsSchema, dataColumnPathSchema, dataFilterSchema, listOptionsSchema, MAX_BATCH_ROWS, MAX_QUERY_SIZE, queryInputSchema, recordPayloadSchema, tableNameSchema, } from "./schemas.js";
10
+ export { MissingCapabilityError, SimpleAIError } from "./shared/errors.js";