@simple-ai-lab/sdk 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,33 +1,1169 @@
1
- // src/schemas.ts
1
+ // src/actions.ts
2
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";
3
1139
  var MAX_QUERY_SIZE = 50;
4
1140
  var MAX_BATCH_ROWS = 1e3;
5
- var tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
6
- var filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);
7
- var dataColumnPathSchema = z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
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), {
8
1144
  message: "Must be a dot-separated column path with no empty segments"
9
1145
  });
10
- var dataFilterSchema = z.object({
1146
+ var dataFilterSchema = z3.object({
11
1147
  column: dataColumnPathSchema,
12
- values: z.array(filterValueSchema)
1148
+ values: z3.array(filterValueSchema)
13
1149
  });
14
- var queryInputSchema = z.object({
1150
+ var queryInputSchema = z3.object({
15
1151
  tableName: tableNameSchema,
16
- filters: z.array(dataFilterSchema).optional(),
17
- text: z.string().max(5e3).optional(),
18
- size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
19
- from: z.number().int().min(0).optional()
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()
20
1156
  });
21
- var listOptionsSchema = z.object({
22
- page: z.number().int().min(1).optional(),
23
- perPage: z.number().int().min(1).max(200).optional(),
24
- orderBy: z.string().optional(),
25
- orderDirection: z.enum(["asc", "desc"]).optional(),
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(),
26
1162
  /** Column-name → value equality filters applied server-side. */
27
- filters: z.record(z.string(), z.string()).optional()
1163
+ filters: z3.record(z3.string(), z3.string()).optional()
28
1164
  });
29
- var recordPayloadSchema = z.record(z.string(), z.unknown());
30
- var batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
1165
+ var recordPayloadSchema = z3.record(z3.string(), z3.unknown());
1166
+ var batchUpsertRowsSchema = z3.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
31
1167
 
32
1168
  // src/data.ts
33
1169
  function encodeTable(tableName) {
@@ -243,6 +1379,134 @@ function defineAction(handler) {
243
1379
  };
244
1380
  return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
245
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
+ }
246
1510
  export {
247
1511
  DataClient,
248
1512
  MAX_BATCH_ROWS,
@@ -250,13 +1514,27 @@ export {
250
1514
  SIMPLE_ACTION_BRAND,
251
1515
  SimpleAI,
252
1516
  SimpleAIError,
1517
+ action,
1518
+ actionsIoSchemaFromZod,
253
1519
  batchUpsertRowsSchema,
1520
+ canonicalAuthoringKey,
1521
+ canonicalAuthoringKeys,
1522
+ collectActionVersionUuids,
1523
+ compileAction,
1524
+ compileAgent,
1525
+ compileAgentProject,
254
1526
  dataColumnPathSchema,
255
1527
  dataFilterSchema,
256
1528
  defineAction,
1529
+ defineAgent,
1530
+ defineAgentSnapshot,
257
1531
  listOptionsSchema,
1532
+ node,
1533
+ prompt,
258
1534
  queryInputSchema,
259
1535
  recordPayloadSchema,
1536
+ reference,
1537
+ sourceFile,
260
1538
  tableNameSchema
261
1539
  };
262
1540
  //# sourceMappingURL=index.js.map