@simple-ai-lab/sdk 0.1.0 → 0.4.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.cjs CHANGED
@@ -26,47 +26,1197 @@ __export(index_exports, {
26
26
  SIMPLE_ACTION_BRAND: () => SIMPLE_ACTION_BRAND,
27
27
  SimpleAI: () => SimpleAI,
28
28
  SimpleAIError: () => SimpleAIError,
29
+ action: () => action,
30
+ actionsIoSchemaFromZod: () => actionsIoSchemaFromZod,
29
31
  batchUpsertRowsSchema: () => batchUpsertRowsSchema,
32
+ canonicalAuthoringKey: () => canonicalAuthoringKey,
33
+ canonicalAuthoringKeys: () => canonicalAuthoringKeys,
34
+ collectActionVersionUuids: () => collectActionVersionUuids,
35
+ compileAction: () => compileAction,
36
+ compileAgent: () => compileAgent,
37
+ compileAgentProject: () => compileAgentProject,
30
38
  dataColumnPathSchema: () => dataColumnPathSchema,
31
39
  dataFilterSchema: () => dataFilterSchema,
32
40
  defineAction: () => defineAction,
41
+ defineAgent: () => defineAgent,
42
+ defineAgentSnapshot: () => defineAgentSnapshot,
33
43
  listOptionsSchema: () => listOptionsSchema,
44
+ node: () => node,
45
+ prompt: () => prompt,
34
46
  queryInputSchema: () => queryInputSchema,
35
47
  recordPayloadSchema: () => recordPayloadSchema,
48
+ reference: () => reference,
49
+ sourceFile: () => sourceFile,
36
50
  tableNameSchema: () => tableNameSchema
37
51
  });
38
52
  module.exports = __toCommonJS(index_exports);
39
53
 
40
- // src/schemas.ts
54
+ // src/actions.ts
41
55
  var import_zod = require("zod");
56
+ function isRecord(value) {
57
+ return value !== null && typeof value === "object" && !Array.isArray(value);
58
+ }
59
+ function nullableJsonSchema(value) {
60
+ const type = value.type;
61
+ if (Array.isArray(type)) {
62
+ const nonNullTypes = type.filter((item) => item !== "null");
63
+ if (nonNullTypes.length === 1 && typeof nonNullTypes[0] === "string") {
64
+ return { schema: { ...value, type: nonNullTypes[0] }, nullable: type.includes("null") };
65
+ }
66
+ }
67
+ const anyOf = value.anyOf;
68
+ if (Array.isArray(anyOf)) {
69
+ const schemas = anyOf.filter(isRecord);
70
+ const nonNullSchemas = schemas.filter((schema) => schema.type !== "null");
71
+ const containsNull = schemas.some((schema) => schema.type === "null");
72
+ if (containsNull && nonNullSchemas.length === 1) {
73
+ const nonNullSchema = nonNullSchemas[0] ?? {};
74
+ return {
75
+ schema: {
76
+ ...nonNullSchema,
77
+ ...typeof value.description === "string" ? { description: value.description } : {}
78
+ },
79
+ nullable: true
80
+ };
81
+ }
82
+ }
83
+ return { schema: value, nullable: false };
84
+ }
85
+ function schemaDescription(schema) {
86
+ return typeof schema.description === "string" ? schema.description : "";
87
+ }
88
+ function convertJsonSchemaNode(value, path) {
89
+ if (!isRecord(value)) {
90
+ throw new Error(`${path} is not a representable Zod schema`);
91
+ }
92
+ const { schema, nullable } = nullableJsonSchema(value);
93
+ if (schema.enum !== void 0 || schema.const !== void 0) {
94
+ throw new Error(`${path} uses enum/const, which Actions I/O schemas do not support`);
95
+ }
96
+ switch (schema.type) {
97
+ case "string":
98
+ case "number":
99
+ case "boolean":
100
+ return {
101
+ type: schema.type,
102
+ description: schemaDescription(schema),
103
+ nullable
104
+ };
105
+ case "object": {
106
+ const rawProperties = isRecord(schema.properties) ? schema.properties : {};
107
+ const properties = {};
108
+ for (const [name, child] of Object.entries(rawProperties)) {
109
+ if (!/^[A-Za-z_]\w*$/.test(name) || ["__proto__", "constructor", "prototype"].includes(name)) {
110
+ throw new Error(`${path}.${name} is not a valid Actions I/O property name`);
111
+ }
112
+ properties[name] = convertJsonSchemaNode(child, `${path}.${name}`);
113
+ }
114
+ const required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name === "string") : [];
115
+ const additionalProperties = schema.additionalProperties === true;
116
+ return {
117
+ type: "object",
118
+ description: schemaDescription(schema),
119
+ nullable,
120
+ properties,
121
+ required,
122
+ additionalProperties
123
+ };
124
+ }
125
+ case "array":
126
+ return {
127
+ type: "array",
128
+ description: schemaDescription(schema),
129
+ nullable,
130
+ ...schema.items === void 0 ? {} : { items: convertJsonSchemaNode(schema.items, `${path}[]`) }
131
+ };
132
+ case "integer":
133
+ return {
134
+ type: "number",
135
+ description: schemaDescription(schema),
136
+ nullable
137
+ };
138
+ default:
139
+ throw new Error(`${path} uses unsupported Zod/JSON Schema type "${String(schema.type)}"`);
140
+ }
141
+ }
142
+ function actionsIoSchemaFromZod(schema) {
143
+ const converted = convertJsonSchemaNode(import_zod.z.toJSONSchema(schema), "schema");
144
+ if (converted.type !== "object") {
145
+ throw new Error("Action input and output schemas must be Zod objects");
146
+ }
147
+ return {
148
+ type: "object",
149
+ description: converted.description,
150
+ properties: converted.properties,
151
+ required: converted.required,
152
+ additionalProperties: converted.additionalProperties
153
+ };
154
+ }
155
+ function pointerForName(name) {
156
+ const escaped = name.replace(/~/g, "~0").replace(/\//g, "~1");
157
+ return `/${escaped}`;
158
+ }
159
+ function normalizeOutputMappings({
160
+ mappings,
161
+ outputSchema
162
+ }) {
163
+ const normalized = Object.fromEntries(
164
+ Object.entries(mappings).map(([name, template]) => [name.startsWith("/") ? name : pointerForName(name), template])
165
+ );
166
+ for (const name of Object.keys(outputSchema.properties)) {
167
+ const pointer = pointerForName(name);
168
+ if (normalized[pointer] === void 0) {
169
+ throw new Error(`Action output "${name}" needs an output mapping`);
170
+ }
171
+ }
172
+ for (const pointer of Object.keys(normalized)) {
173
+ const firstToken = pointer.slice(1).split("/")[0]?.replace(/~1/g, "/").replace(/~0/g, "~");
174
+ if (firstToken === void 0 || outputSchema.properties[firstToken] === void 0) {
175
+ throw new Error(`Action output mapping "${pointer}" does not reference a declared output`);
176
+ }
177
+ }
178
+ return normalized;
179
+ }
180
+ function compileContracts({
181
+ input,
182
+ output
183
+ }) {
184
+ return {
185
+ inputSchema: actionsIoSchemaFromZod(input),
186
+ outputSchema: actionsIoSchemaFromZod(output)
187
+ };
188
+ }
189
+ function requireSourceFile({
190
+ reference: reference2,
191
+ options
192
+ }) {
193
+ if (options.readSourceFile === void 0) {
194
+ throw new Error(`Action source file "${reference2.path}" requires a readSourceFile compiler option`);
195
+ }
196
+ return options.readSourceFile(reference2.path);
197
+ }
198
+ function compileHttpAction(config) {
199
+ const contract = compileContracts(config);
200
+ return {
201
+ kind: "inline",
202
+ key: config.key,
203
+ contract,
204
+ compile: () => ({
205
+ actionType: "http",
206
+ name: config.name,
207
+ description: config.description,
208
+ ...contract,
209
+ outputMappings: normalizeOutputMappings({
210
+ mappings: config.outputMappings,
211
+ outputSchema: contract.outputSchema
212
+ }),
213
+ operation: {
214
+ type: "request",
215
+ method: config.request.method,
216
+ urlTemplate: config.request.url,
217
+ headers: Object.entries(config.request.headers ?? {}).map(([name, valueTemplate]) => ({
218
+ name,
219
+ valueTemplate
220
+ })),
221
+ bodyTemplate: config.request.body ?? null
222
+ }
223
+ })
224
+ };
225
+ }
226
+ function compileCodeAction(config) {
227
+ const contract = compileContracts(config);
228
+ return {
229
+ kind: "inline",
230
+ key: config.key,
231
+ contract,
232
+ compile: (options) => ({
233
+ actionType: "code",
234
+ name: config.name,
235
+ description: config.description,
236
+ ...contract,
237
+ outputMappings: normalizeOutputMappings({
238
+ mappings: config.outputMappings,
239
+ outputSchema: contract.outputSchema
240
+ }),
241
+ operation: {
242
+ type: "execute",
243
+ language: "typescript",
244
+ source: typeof config.source === "string" ? config.source : requireSourceFile({ reference: config.source, options }),
245
+ compiledJs: null,
246
+ runtime: "cloudflare-worker",
247
+ timeoutMs: config.timeoutMs ?? 3e4
248
+ }
249
+ })
250
+ };
251
+ }
252
+ function compileCustomDataQueryAction(config) {
253
+ const contract = compileContracts(config);
254
+ return {
255
+ kind: "inline",
256
+ key: config.key,
257
+ contract,
258
+ compile: () => ({
259
+ actionType: "custom_data",
260
+ name: config.name,
261
+ description: config.description,
262
+ ...contract,
263
+ outputMappings: normalizeOutputMappings({
264
+ mappings: config.outputMappings,
265
+ outputSchema: contract.outputSchema
266
+ }),
267
+ operation: { type: "query", sql: config.sql }
268
+ })
269
+ };
270
+ }
271
+ function compileCustomDataSearchAction(config) {
272
+ const contract = compileContracts(config);
273
+ return {
274
+ kind: "inline",
275
+ key: config.key,
276
+ contract,
277
+ compile: () => ({
278
+ actionType: "custom_data",
279
+ name: config.name,
280
+ description: config.description,
281
+ ...contract,
282
+ outputMappings: normalizeOutputMappings({
283
+ mappings: config.outputMappings,
284
+ outputSchema: contract.outputSchema
285
+ }),
286
+ operation: { type: "search", table: config.table, bodyTemplate: config.body }
287
+ })
288
+ };
289
+ }
290
+ function compileKnowledgeBaseSearchAction(config) {
291
+ const contract = compileContracts(config);
292
+ return {
293
+ kind: "inline",
294
+ key: config.key,
295
+ contract,
296
+ compile: () => ({
297
+ actionType: "knowledge_base",
298
+ name: config.name,
299
+ description: config.description,
300
+ ...contract,
301
+ outputMappings: normalizeOutputMappings({
302
+ mappings: config.outputMappings,
303
+ outputSchema: contract.outputSchema
304
+ }),
305
+ operation: {
306
+ type: "search",
307
+ knowledgeBaseIds: config.knowledgeBaseIds,
308
+ bodyTemplate: config.body
309
+ }
310
+ })
311
+ };
312
+ }
313
+ var action = {
314
+ http(config) {
315
+ return compileHttpAction(config);
316
+ },
317
+ code(config) {
318
+ return compileCodeAction(config);
319
+ },
320
+ customDataQuery(config) {
321
+ return compileCustomDataQueryAction(config);
322
+ },
323
+ customDataSearch(config) {
324
+ return compileCustomDataSearchAction(config);
325
+ },
326
+ knowledgeBaseSearch(config) {
327
+ return compileKnowledgeBaseSearchAction(config);
328
+ },
329
+ ref(config) {
330
+ return {
331
+ kind: "reference",
332
+ key: config.key,
333
+ versionUuid: config.versionUuid,
334
+ contract: config.contract ?? null
335
+ };
336
+ },
337
+ callable(config) {
338
+ return { kind: "callable", ...config };
339
+ },
340
+ run(config) {
341
+ return { kind: "run", ...config };
342
+ },
343
+ fromAgent(description) {
344
+ return { source: "agent", description };
345
+ },
346
+ from(value) {
347
+ return { source: "template", value };
348
+ }
349
+ };
350
+ function compileAction(definition, options = {}) {
351
+ return definition.compile(options);
352
+ }
353
+ function sourceFile(path) {
354
+ return { kind: "source-file", path };
355
+ }
356
+
357
+ // src/agents.ts
358
+ var import_node_crypto = require("crypto");
359
+ var import_zod2 = require("zod");
360
+ function defaultTransferCapability() {
361
+ return {
362
+ enabled: false,
363
+ phoneNumber: null,
364
+ timeout: 120,
365
+ mode: "cold",
366
+ description: null,
367
+ voicemailMessage: null
368
+ };
369
+ }
370
+ function defineAgent(input) {
371
+ const transferDefaults = defaultTransferCapability();
372
+ return {
373
+ kind: "agent-definition",
374
+ key: input.key,
375
+ name: input.name,
376
+ description: input.description ?? null,
377
+ branch: input.branch,
378
+ modality: input.modality ?? "voice",
379
+ folderUuid: input.folderUuid ?? null,
380
+ analyzerUuids: input.analyzerUuids ?? [],
381
+ tagUuids: input.tagUuids ?? [],
382
+ containmentConfig: input.containmentConfig ?? null,
383
+ voice: {
384
+ voiceUuid: input.voice?.voiceUuid ?? null,
385
+ backgroundNoise: input.voice?.backgroundNoise ?? "off"
386
+ },
387
+ llm: {
388
+ model: input.llm?.model ?? "gpt-4.1",
389
+ modelUuid: input.llm?.modelUuid ?? null,
390
+ temperature: input.llm?.temperature ?? 0.65
391
+ },
392
+ speech: {
393
+ language: input.speech?.language ?? "en",
394
+ keyterms: input.speech?.keyterms ?? []
395
+ },
396
+ call: {
397
+ agentSpeaksFirst: input.call?.agentSpeaksFirst ?? false,
398
+ firstSentence: input.call?.firstSentence ?? null,
399
+ maxCallLengthSeconds: input.call?.maxCallLengthSeconds ?? 1800,
400
+ record: input.call?.record ?? true,
401
+ checkInAfterSilence: input.call?.checkInAfterSilence ?? { enabled: false, prompt: null },
402
+ endCallAfterExtendedSilence: input.call?.endCallAfterExtendedSilence ?? false,
403
+ pciEnabled: input.call?.pciEnabled ?? false,
404
+ backgroundNoiseTrack: input.call?.backgroundNoiseTrack ?? null,
405
+ backgroundNoiseGain: input.call?.backgroundNoiseGain === void 0 ? 1 : input.call.backgroundNoiseGain,
406
+ interruptionMode: input.call?.interruptionMode === void 0 ? "medium" : input.call.interruptionMode
407
+ },
408
+ preCallWebhook: {
409
+ enabled: input.preCallWebhook?.enabled ?? false,
410
+ url: input.preCallWebhook?.url ?? null,
411
+ authToken: input.preCallWebhook?.authToken ?? null,
412
+ timeout: input.preCallWebhook?.timeout ?? 5,
413
+ parameters: input.preCallWebhook?.parameters ?? []
414
+ },
415
+ capabilities: {
416
+ dtmf: {
417
+ enabled: input.capabilities?.dtmf?.enabled ?? false,
418
+ description: input.capabilities?.dtmf?.description ?? null
419
+ },
420
+ hangup: {
421
+ enabled: input.capabilities?.hangup?.enabled ?? true,
422
+ description: input.capabilities?.hangup?.description ?? null,
423
+ message: input.capabilities?.hangup?.message ?? null
424
+ },
425
+ transfer: {
426
+ enabled: input.capabilities?.transfer?.enabled ?? transferDefaults.enabled,
427
+ phoneNumber: input.capabilities?.transfer?.phoneNumber ?? transferDefaults.phoneNumber,
428
+ timeout: input.capabilities?.transfer?.timeout ?? transferDefaults.timeout,
429
+ mode: input.capabilities?.transfer?.mode ?? transferDefaults.mode,
430
+ description: input.capabilities?.transfer?.description ?? transferDefaults.description,
431
+ voicemailMessage: input.capabilities?.transfer?.voicemailMessage ?? transferDefaults.voicemailMessage
432
+ }
433
+ },
434
+ knowledgeBases: input.knowledgeBases ?? [],
435
+ beforeCallAction: input.beforeCallAction ?? null,
436
+ summaryPrompt: input.summaryPrompt ?? null,
437
+ abTestGroupIds: input.abTestGroupIds ?? null,
438
+ nodes: input.nodes
439
+ };
440
+ }
441
+ var node = {
442
+ global(config) {
443
+ return { type: "global", ...config };
444
+ },
445
+ prompt(config) {
446
+ return { type: "prompt", ...config };
447
+ },
448
+ action(config) {
449
+ return { type: "action", ...config };
450
+ },
451
+ http(config) {
452
+ return { type: "http", ...config };
453
+ },
454
+ extract(config) {
455
+ return { type: "extract", ...config };
456
+ },
457
+ say(config) {
458
+ return { type: "say", ...config };
459
+ },
460
+ endCall(config) {
461
+ return { type: "end-call", ...config };
462
+ },
463
+ route(config) {
464
+ return { type: "route", ...config };
465
+ },
466
+ abTest(config) {
467
+ return { type: "ab-test", ...config };
468
+ },
469
+ transfer(config) {
470
+ return { type: "transfer", ...config };
471
+ },
472
+ transferChat(config) {
473
+ return { type: "transfer-chat", ...config };
474
+ }
475
+ };
476
+ var prompt = {
477
+ inline(text, example = null, generatedExamples) {
478
+ return { kind: "inline", text, example, ...generatedExamples === void 0 ? {} : { generatedExamples } };
479
+ },
480
+ file(path, example = null) {
481
+ return { kind: "file", path, example };
482
+ },
483
+ version(versionId) {
484
+ return { kind: "version", versionId };
485
+ }
486
+ };
487
+ function reference(uuid) {
488
+ return { uuid };
489
+ }
490
+ function isRecord2(value) {
491
+ return value !== null && typeof value === "object" && !Array.isArray(value);
492
+ }
493
+ function deterministicUuid(input) {
494
+ const bytes = Buffer.from((0, import_node_crypto.createHash)("sha256").update(`${input.kind}:${input.key}`).digest().subarray(0, 16));
495
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
496
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
497
+ const hex = bytes.toString("hex");
498
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
499
+ }
500
+ function resolveIdentity({
501
+ options,
502
+ kind,
503
+ key,
504
+ fallbackKeys = []
505
+ }) {
506
+ for (const candidateKey of [key, ...fallbackKeys]) {
507
+ const identity = options.identity?.({ kind, key: candidateKey });
508
+ if (identity !== void 0) {
509
+ return identity;
510
+ }
511
+ }
512
+ return deterministicUuid({ kind, key });
513
+ }
514
+ function canonicalAuthoringKey(value, fallback) {
515
+ const normalizedCharacters = [];
516
+ let needsSeparator = false;
517
+ for (const character of value.toLowerCase()) {
518
+ const characterCode = character.charCodeAt(0);
519
+ const isLowercaseLetter = characterCode >= 97 && characterCode <= 122;
520
+ const isDigit = characterCode >= 48 && characterCode <= 57;
521
+ if (isLowercaseLetter || isDigit) {
522
+ if (needsSeparator && normalizedCharacters.length > 0) {
523
+ normalizedCharacters.push("-");
524
+ }
525
+ normalizedCharacters.push(character);
526
+ needsSeparator = false;
527
+ } else if (normalizedCharacters.length > 0) {
528
+ needsSeparator = true;
529
+ }
530
+ }
531
+ const normalized = normalizedCharacters.join("");
532
+ return normalized === "" ? fallback : normalized;
533
+ }
534
+ function canonicalAuthoringKeys(values) {
535
+ const used = /* @__PURE__ */ new Set();
536
+ return values.map(({ value, fallback }) => {
537
+ const base = canonicalAuthoringKey(value, fallback);
538
+ let candidate = base;
539
+ let sequence = 2;
540
+ while (used.has(candidate)) {
541
+ candidate = `${base}-${sequence}`;
542
+ sequence += 1;
543
+ }
544
+ used.add(candidate);
545
+ return candidate;
546
+ });
547
+ }
548
+ function jsonSchemaDescription(value) {
549
+ return typeof value.description === "string" ? value.description : "";
550
+ }
551
+ function extractionFieldFromJsonSchema({
552
+ name,
553
+ value,
554
+ required,
555
+ path
556
+ }) {
557
+ if (!isRecord2(value)) {
558
+ throw new Error(`${path} is not a representable extraction field`);
559
+ }
560
+ const enumValues = Array.isArray(value.enum) ? value.enum.filter(
561
+ (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean"
562
+ ) : void 0;
563
+ if (value.type === "object") {
564
+ const rawProperties = isRecord2(value.properties) ? value.properties : {};
565
+ const requiredNames = new Set(
566
+ Array.isArray(value.required) ? value.required.filter((item) => typeof item === "string") : []
567
+ );
568
+ return {
569
+ name,
570
+ type: "object",
571
+ description: jsonSchemaDescription(value),
572
+ required,
573
+ properties: Object.entries(rawProperties).map(
574
+ ([childName, child]) => extractionFieldFromJsonSchema({
575
+ name: childName,
576
+ value: child,
577
+ required: requiredNames.has(childName),
578
+ path: `${path}.${childName}`
579
+ })
580
+ )
581
+ };
582
+ }
583
+ if (value.type === "array") {
584
+ if (value.items === void 0) {
585
+ throw new Error(`${path} must declare an array item schema`);
586
+ }
587
+ return {
588
+ name,
589
+ type: "array",
590
+ description: jsonSchemaDescription(value),
591
+ required,
592
+ items: extractionFieldFromJsonSchema({
593
+ name: "item",
594
+ value: value.items,
595
+ required: true,
596
+ path: `${path}[]`
597
+ })
598
+ };
599
+ }
600
+ if (!["string", "number", "integer", "boolean"].includes(String(value.type))) {
601
+ throw new Error(`${path} uses unsupported extraction type "${String(value.type)}"`);
602
+ }
603
+ return {
604
+ name,
605
+ type: value.type === "integer" ? "number" : String(value.type),
606
+ description: jsonSchemaDescription(value),
607
+ required,
608
+ ...enumValues === void 0 ? {} : { enum: enumValues }
609
+ };
610
+ }
611
+ function extractionFieldsFromZod(schema) {
612
+ const jsonSchema = import_zod2.z.toJSONSchema(schema);
613
+ if (!isRecord2(jsonSchema) || jsonSchema.type !== "object") {
614
+ throw new Error("Extraction schemas must be Zod objects");
615
+ }
616
+ const rawProperties = isRecord2(jsonSchema.properties) ? jsonSchema.properties : {};
617
+ const requiredNames = new Set(
618
+ Array.isArray(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
619
+ );
620
+ return Object.entries(rawProperties).map(
621
+ ([name, value]) => extractionFieldFromJsonSchema({
622
+ name,
623
+ value,
624
+ required: requiredNames.has(name),
625
+ path: `schema.${name}`
626
+ })
627
+ );
628
+ }
629
+ function compilePrompt(referenceValue, options) {
630
+ switch (referenceValue.kind) {
631
+ case "inline":
632
+ return {
633
+ type: "inline",
634
+ prompt: referenceValue.text,
635
+ example: referenceValue.example,
636
+ // Product-generated; preserved verbatim so pulled prompts round-trip.
637
+ ...referenceValue.generatedExamples === void 0 ? {} : { generatedExamples: referenceValue.generatedExamples }
638
+ };
639
+ case "file": {
640
+ if (options.readPromptFile === void 0) {
641
+ throw new Error(`Prompt file "${referenceValue.path}" requires a readPromptFile compiler option`);
642
+ }
643
+ return {
644
+ type: "inline",
645
+ prompt: options.readPromptFile(referenceValue.path),
646
+ example: referenceValue.example
647
+ };
648
+ }
649
+ case "version":
650
+ return { type: "reference", promptVersionId: referenceValue.versionId };
651
+ }
652
+ }
653
+ function resolveActionVersion({
654
+ definition,
655
+ options
656
+ }) {
657
+ if (definition.kind === "reference") {
658
+ return definition.versionUuid;
659
+ }
660
+ const resolved = options.actionVersionUuids?.[definition.key];
661
+ if (resolved !== void 0) {
662
+ return resolved;
663
+ }
664
+ if (options.allowUnresolvedActionVersions === true) {
665
+ return resolveIdentity({
666
+ options,
667
+ kind: "action-version-placeholder",
668
+ key: definition.key
669
+ });
670
+ }
671
+ throw new Error(`Action "${definition.key}" does not have a resolved version UUID`);
672
+ }
673
+ function pointerForInputName(name) {
674
+ return `/${name.replace(/~/g, "~0").replace(/\//g, "~1")}`;
675
+ }
676
+ function compileOutputParameterMappings(outputParameters) {
677
+ const mappedParameters = /* @__PURE__ */ new Set();
678
+ const mappings = [];
679
+ for (const [outputName, parameterName] of Object.entries(outputParameters)) {
680
+ if (mappedParameters.has(parameterName)) {
681
+ throw new Error(`Agent parameter "${parameterName}" is mapped from more than one Action output`);
682
+ }
683
+ mappedParameters.add(parameterName);
684
+ mappings.push([parameterName, `{{ outputs.${outputName} }}`]);
685
+ }
686
+ return Object.fromEntries(mappings);
687
+ }
688
+ function compileCallableUseSite({
689
+ callable,
690
+ canonicalKey,
691
+ options
692
+ }) {
693
+ const inputMappings = {};
694
+ const inputDescriptions = {};
695
+ for (const [name, input] of Object.entries(callable.inputs)) {
696
+ const pointer = pointerForInputName(name);
697
+ if (input.source === "agent") {
698
+ inputDescriptions[pointer] = input.description;
699
+ } else {
700
+ inputMappings[pointer] = input.value;
701
+ }
702
+ }
703
+ const contractProperties = callable.action.contract?.inputSchema.properties ?? {};
704
+ for (const [name, schema] of Object.entries(contractProperties)) {
705
+ const pointer = pointerForInputName(name);
706
+ if (inputMappings[pointer] !== void 0 || inputDescriptions[pointer] !== void 0) {
707
+ continue;
708
+ }
709
+ if (schema.description.trim() === "") {
710
+ throw new Error(`Callable Action "${callable.key}" input "${name}" needs an agent-facing description`);
711
+ }
712
+ inputDescriptions[pointer] = schema.description;
713
+ }
714
+ return {
715
+ actionUseSiteUuid: resolveIdentity({
716
+ options,
717
+ kind: "action-use-site",
718
+ key: callable.key,
719
+ fallbackKeys: [canonicalKey]
720
+ }),
721
+ actionVersionUuid: resolveActionVersion({ definition: callable.action, options }),
722
+ name: callable.name,
723
+ description: callable.description,
724
+ inputDescriptions,
725
+ inputMappings,
726
+ outputParameterMappings: compileOutputParameterMappings(callable.outputParameters)
727
+ };
728
+ }
729
+ function compileActionRun({
730
+ run,
731
+ trigger,
732
+ canonicalKey,
733
+ options
734
+ }) {
735
+ return {
736
+ actionUseSiteUuid: resolveIdentity({
737
+ options,
738
+ kind: "action-use-site",
739
+ key: run.key,
740
+ fallbackKeys: [canonicalKey]
741
+ }),
742
+ actionVersionUuid: resolveActionVersion({ definition: run.action, options }),
743
+ inputMappings: Object.fromEntries(
744
+ Object.entries(run.inputs).map(([name, value]) => [
745
+ name.startsWith("/") ? name : pointerForInputName(name),
746
+ value
747
+ ])
748
+ ),
749
+ outputParameterMappings: compileOutputParameterMappings(run.outputParameters),
750
+ trigger
751
+ };
752
+ }
753
+ function collectCallableActions(nodes) {
754
+ const byKey = /* @__PURE__ */ new Map();
755
+ for (const definition of nodes) {
756
+ if (definition.type !== "prompt") {
757
+ continue;
758
+ }
759
+ for (const callable of definition.actions ?? []) {
760
+ const existing = byKey.get(callable.key);
761
+ if (existing !== void 0 && existing !== callable) {
762
+ throw new Error(`Callable Action key "${callable.key}" is defined more than once`);
763
+ }
764
+ byKey.set(callable.key, callable);
765
+ }
766
+ }
767
+ return [...byKey.values()];
768
+ }
769
+ function collectInlineActions(definition) {
770
+ const byKey = /* @__PURE__ */ new Map();
771
+ const visit = (actionDefinition) => {
772
+ if (actionDefinition.kind !== "inline") {
773
+ return;
774
+ }
775
+ const existing = byKey.get(actionDefinition.key);
776
+ if (existing !== void 0 && existing !== actionDefinition) {
777
+ throw new Error(`Inline Action key "${actionDefinition.key}" is defined more than once`);
778
+ }
779
+ byKey.set(actionDefinition.key, actionDefinition);
780
+ };
781
+ for (const callable of collectCallableActions(definition.nodes)) {
782
+ visit(callable.action);
783
+ }
784
+ if (definition.beforeCallAction !== null) {
785
+ visit(definition.beforeCallAction.action);
786
+ }
787
+ for (const definitionNode of definition.nodes) {
788
+ if (definitionNode.type === "action") {
789
+ visit(definitionNode.action);
790
+ }
791
+ if (definitionNode.type === "prompt" && definitionNode.perTurnAction !== null && definitionNode.perTurnAction !== void 0) {
792
+ visit(definitionNode.perTurnAction.action);
793
+ }
794
+ }
795
+ return [...byKey.values()];
796
+ }
797
+ function compileEdges({
798
+ definition,
799
+ canonicalNodeKey,
800
+ nodeUuids,
801
+ options
802
+ }) {
803
+ return (definition.edges ?? []).map((edgeDefinition, index) => {
804
+ const targetUuid = nodeUuids.get(edgeDefinition.to);
805
+ if (targetUuid === void 0) {
806
+ throw new Error(`Node "${definition.key}" points to unknown node "${edgeDefinition.to}"`);
807
+ }
808
+ const edgeKey = edgeDefinition.key ?? `${definition.key}:${index}`;
809
+ return {
810
+ uuid: resolveIdentity({
811
+ options,
812
+ kind: "edge",
813
+ key: edgeKey,
814
+ fallbackKeys: [`${canonicalNodeKey}:${index}`]
815
+ }),
816
+ toNodeUuid: targetUuid,
817
+ description: edgeDefinition.when,
818
+ priority: edgeDefinition.priority ?? index,
819
+ condition: edgeDefinition.condition ?? null
820
+ };
821
+ });
822
+ }
823
+ function baseNodeWire({
824
+ definition,
825
+ canonicalNodeKey,
826
+ index,
827
+ nodeUuids,
828
+ options
829
+ }) {
830
+ const uuid = nodeUuids.get(definition.key);
831
+ if (uuid === void 0) {
832
+ throw new Error(`Node "${definition.key}" has no compiled identity`);
833
+ }
834
+ return {
835
+ uuid,
836
+ name: definition.name,
837
+ isRoot: definition.root ?? false,
838
+ position: definition.position ?? { x: index % 4 * 320, y: Math.floor(index / 4) * 220 },
839
+ behavior: { waitAfterExecuting: definition.waitAfterExecuting ?? 0 },
840
+ edges: compileEdges({ definition, canonicalNodeKey, nodeUuids, options })
841
+ };
842
+ }
843
+ function nodeCapabilities(definition) {
844
+ return definition.alwaysAvailable === void 0 ? {} : { alwaysAvailable: definition.alwaysAvailable };
845
+ }
846
+ function promptNodeCapabilities(definition) {
847
+ const base = nodeCapabilities(definition);
848
+ if (definition.transfer === void 0) {
849
+ return base;
850
+ }
851
+ return {
852
+ ...base,
853
+ transfer: {
854
+ enabled: definition.transfer.enabled,
855
+ phoneNumber: definition.transfer.phoneNumber ?? null,
856
+ timeout: definition.transfer.timeout ?? 120,
857
+ mode: definition.transfer.mode ?? "cold",
858
+ description: definition.transfer.description ?? null,
859
+ voicemailMessage: definition.transfer.voicemailMessage ?? null
860
+ }
861
+ };
862
+ }
863
+ function compileNode({
864
+ definition,
865
+ canonicalNodeKey,
866
+ canonicalCallableKeys,
867
+ index,
868
+ nodeUuids,
869
+ options
870
+ }) {
871
+ const base = baseNodeWire({ definition, canonicalNodeKey, index, nodeUuids, options });
872
+ const builtInTools = nodeCapabilities(definition);
873
+ switch (definition.type) {
874
+ case "global":
875
+ return {
876
+ ...base,
877
+ type: "global",
878
+ prompt: compilePrompt(definition.prompt, options)
879
+ };
880
+ case "prompt": {
881
+ const perTurnAction = definition.perTurnAction === null || definition.perTurnAction === void 0 ? null : compileActionRun({
882
+ run: definition.perTurnAction,
883
+ trigger: "every_turn",
884
+ canonicalKey: `${canonicalNodeKey}:every-turn`,
885
+ options
886
+ });
887
+ return {
888
+ ...base,
889
+ type: "standard",
890
+ prompt: compilePrompt(definition.prompt, options),
891
+ toolUuids: [],
892
+ // Present whenever `actions` is declared, even when empty, so an
893
+ // explicit empty list survives the round trip.
894
+ ...definition.actions === void 0 ? {} : {
895
+ toolUseSiteUuids: definition.actions.map(
896
+ (callable) => resolveIdentity({
897
+ options,
898
+ kind: "action-use-site",
899
+ key: callable.key,
900
+ fallbackKeys: [canonicalCallableKeys.get(callable.key) ?? callable.key]
901
+ })
902
+ )
903
+ },
904
+ knowledgeBaseUuids: (definition.knowledgeBases ?? []).map((item) => item.uuid),
905
+ customDataTableNames: definition.customDataTables ?? [],
906
+ builtInTools: promptNodeCapabilities(definition),
907
+ sopSpec: definition.sopSpec ?? null,
908
+ overrides: {
909
+ ...definition.voiceOverride === void 0 ? {} : { voice: definition.voiceOverride },
910
+ ...definition.llmOverride === void 0 ? {} : {
911
+ llm: {
912
+ model: definition.llmOverride.model,
913
+ llmModelUuid: definition.llmOverride.modelUuid,
914
+ temperature: definition.llmOverride.temperature
915
+ }
916
+ }
917
+ },
918
+ behavior: {
919
+ ...base.behavior,
920
+ ...definition.vadMinSilenceDuration === void 0 ? {} : { vadMinSilenceDuration: definition.vadMinSilenceDuration },
921
+ ...definition.waitAfterTransfer === void 0 ? {} : { waitAfterTransfer: definition.waitAfterTransfer }
922
+ },
923
+ // These three round-trip three states each: absent, explicit null, or a
924
+ // value. The product emits all three across different nodes, so
925
+ // `undefined` means "omit the key" and `null` means "write null".
926
+ ...definition.perTurnWebhook === void 0 ? {} : { perTurnWebhook: definition.perTurnWebhook },
927
+ ...definition.perTurnExtraction === void 0 ? {} : {
928
+ perTurnExtractionFields: definition.perTurnExtraction === null ? null : extractionFieldsFromZod(definition.perTurnExtraction)
929
+ },
930
+ ...definition.perTurnAction === void 0 ? {} : { perTurnAction }
931
+ };
932
+ }
933
+ case "action":
934
+ return {
935
+ ...base,
936
+ type: "action_node",
937
+ actionVersionUuid: resolveActionVersion({ definition: definition.action, options }),
938
+ inputMappings: Object.fromEntries(
939
+ Object.entries(definition.inputs).map(([name, value]) => [
940
+ name.startsWith("/") ? name : pointerForInputName(name),
941
+ value
942
+ ])
943
+ ),
944
+ outputParameterMappings: compileOutputParameterMappings(definition.outputParameters ?? {}),
945
+ runInBackground: definition.runInBackground ?? false,
946
+ backgroundMessage: definition.backgroundMessage ?? null,
947
+ executionMessage: definition.executionMessage ?? null,
948
+ mockResponseData: definition.mockResponseData ?? null,
949
+ builtInTools
950
+ };
951
+ case "http":
952
+ return {
953
+ ...base,
954
+ type: "http",
955
+ url: definition.url,
956
+ method: definition.method,
957
+ headers: definition.headers ?? {},
958
+ body: definition.body ?? null,
959
+ responseSelectors: definition.responseSelectors ?? [],
960
+ runInBackground: definition.runInBackground ?? false,
961
+ backgroundMessage: definition.backgroundMessage ?? null,
962
+ executionMessage: definition.executionMessage ?? null,
963
+ mockResponseData: definition.mockResponseData ?? null,
964
+ builtInTools
965
+ };
966
+ case "extract":
967
+ return {
968
+ ...base,
969
+ type: "extract",
970
+ fields: extractionFieldsFromZod(definition.schema),
971
+ executionMessage: definition.message ?? null,
972
+ builtInTools
973
+ };
974
+ case "say":
975
+ return {
976
+ ...base,
977
+ type: "say",
978
+ executionMessage: definition.text,
979
+ overrides: definition.voiceUuid === void 0 ? {} : { voice: { voiceUuid: definition.voiceUuid } },
980
+ behavior: {
981
+ ...base.behavior,
982
+ ...definition.waitAfterSay === void 0 ? {} : { waitAfterSay: definition.waitAfterSay }
983
+ },
984
+ builtInTools
985
+ };
986
+ case "end-call":
987
+ return {
988
+ ...base,
989
+ type: "end_call",
990
+ executionMessage: definition.message ?? null,
991
+ builtInTools
992
+ };
993
+ case "route":
994
+ return {
995
+ ...base,
996
+ type: "routing",
997
+ description: definition.description,
998
+ builtInTools
999
+ };
1000
+ case "ab-test":
1001
+ return {
1002
+ ...base,
1003
+ type: "ab_test",
1004
+ abTestGroupUuid: definition.abTestGroupUuid,
1005
+ builtInTools
1006
+ };
1007
+ case "transfer": {
1008
+ const transfer = {
1009
+ enabled: true,
1010
+ phoneNumber: definition.phoneNumber,
1011
+ timeout: definition.timeout ?? 120,
1012
+ mode: definition.mode ?? "cold",
1013
+ description: definition.description ?? null,
1014
+ voicemailMessage: definition.voicemailMessage ?? null
1015
+ };
1016
+ return {
1017
+ ...base,
1018
+ type: "transfer",
1019
+ executionMessage: definition.message ?? null,
1020
+ behavior: {
1021
+ ...base.behavior,
1022
+ ...definition.waitAfterTransfer === void 0 ? {} : { waitAfterTransfer: definition.waitAfterTransfer }
1023
+ },
1024
+ builtInTools: { ...builtInTools, transfer }
1025
+ };
1026
+ }
1027
+ case "transfer-chat":
1028
+ return {
1029
+ ...base,
1030
+ type: "transfer_chat",
1031
+ executionMessage: definition.message ?? null,
1032
+ mode: definition.mode,
1033
+ five9TenantName: definition.five9TenantName ?? "",
1034
+ five9CampaignName: definition.five9CampaignName ?? "",
1035
+ five9ContactMapping: definition.five9ContactMapping ?? {},
1036
+ five9AttributesMapping: definition.five9AttributesMapping ?? [],
1037
+ builtInTools
1038
+ };
1039
+ }
1040
+ }
1041
+ function validateDefinition(definition) {
1042
+ const keys = definition.nodes.map((definitionNode) => definitionNode.key);
1043
+ if (new Set(keys).size !== keys.length) {
1044
+ throw new Error("Every node key must be unique");
1045
+ }
1046
+ if (definition.nodes.length === 0) {
1047
+ return;
1048
+ }
1049
+ const roots = definition.nodes.filter((definitionNode) => definitionNode.root === true);
1050
+ if (roots.length !== 1) {
1051
+ throw new Error(`An agent with nodes must contain exactly one root node; received ${roots.length}`);
1052
+ }
1053
+ if (definition.nodes.some((definitionNode) => definitionNode.type === "global" && definitionNode.root === true)) {
1054
+ throw new Error("The global node cannot be the root node");
1055
+ }
1056
+ }
1057
+ function compileAgent(definition, options = {}) {
1058
+ validateDefinition(definition);
1059
+ const canonicalNodeKeys = canonicalAuthoringKeys(
1060
+ definition.nodes.map((definitionNode, index) => ({
1061
+ value: definitionNode.name,
1062
+ fallback: `node-${index + 1}`
1063
+ }))
1064
+ );
1065
+ const canonicalNodeKeysByDefinitionKey = new Map(
1066
+ definition.nodes.map((definitionNode, index) => [
1067
+ definitionNode.key,
1068
+ canonicalNodeKeys[index] ?? definitionNode.key
1069
+ ])
1070
+ );
1071
+ const nodeUuids = new Map(
1072
+ definition.nodes.map((definitionNode, index) => [
1073
+ definitionNode.key,
1074
+ resolveIdentity({
1075
+ options,
1076
+ kind: "node",
1077
+ key: definitionNode.key,
1078
+ fallbackKeys: [canonicalNodeKeys[index] ?? definitionNode.key]
1079
+ })
1080
+ ])
1081
+ );
1082
+ const callables = collectCallableActions(definition.nodes);
1083
+ const canonicalCallableKeys = canonicalAuthoringKeys(
1084
+ callables.map((callable, index) => ({
1085
+ value: callable.name,
1086
+ fallback: `action-${index + 1}`
1087
+ }))
1088
+ );
1089
+ const canonicalCallableKeysByDefinitionKey = new Map(
1090
+ callables.map((callable, index) => [callable.key, canonicalCallableKeys[index] ?? callable.key])
1091
+ );
1092
+ const toolUseSites = callables.map(
1093
+ (callable) => compileCallableUseSite({
1094
+ callable,
1095
+ canonicalKey: canonicalCallableKeysByDefinitionKey.get(callable.key) ?? callable.key,
1096
+ options
1097
+ })
1098
+ );
1099
+ const inlineActions = collectInlineActions(definition);
1100
+ const abTestGroupIds = [
1101
+ ...new Set(
1102
+ definition.nodes.flatMap(
1103
+ (definitionNode) => definitionNode.type === "ab-test" ? [definitionNode.abTestGroupUuid] : []
1104
+ )
1105
+ )
1106
+ ];
1107
+ return {
1108
+ agent: {
1109
+ key: definition.key,
1110
+ name: definition.name,
1111
+ description: definition.description,
1112
+ modality: definition.modality,
1113
+ folderUuid: definition.folderUuid,
1114
+ analyzerUuids: definition.analyzerUuids,
1115
+ tagUuids: definition.tagUuids,
1116
+ containmentConfig: definition.containmentConfig
1117
+ },
1118
+ branch: { name: definition.branch },
1119
+ actions: inlineActions.map((definitionAction) => ({
1120
+ key: definitionAction.key,
1121
+ versionUuid: resolveActionVersion({
1122
+ definition: definitionAction,
1123
+ options
1124
+ }),
1125
+ values: compileAction(definitionAction, {
1126
+ ...options.readActionSourceFile === void 0 ? {} : { readSourceFile: options.readActionSourceFile }
1127
+ })
1128
+ })),
1129
+ content: {
1130
+ config: {
1131
+ voice: {
1132
+ voiceUuid: definition.voice.voiceUuid,
1133
+ backgroundNoise: definition.voice.backgroundNoise
1134
+ },
1135
+ llm: {
1136
+ model: definition.llm.model,
1137
+ llmModelUuid: definition.llm.modelUuid,
1138
+ temperature: definition.llm.temperature
1139
+ },
1140
+ speech: definition.speech,
1141
+ call: {
1142
+ agentSpeaksFirst: definition.call.agentSpeaksFirst,
1143
+ firstSentence: definition.call.firstSentence,
1144
+ maxCallLengthSeconds: definition.call.maxCallLengthSeconds,
1145
+ record: definition.call.record,
1146
+ checkInAfterSilence: definition.call.checkInAfterSilence,
1147
+ endCallAfterExtendedSilence: definition.call.endCallAfterExtendedSilence,
1148
+ pciEnabled: definition.call.pciEnabled,
1149
+ backgroundNoise: {
1150
+ trackName: definition.call.backgroundNoiseTrack ?? definition.voice.backgroundNoise,
1151
+ ...definition.call.backgroundNoiseGain === null ? {} : { gainMultiplier: definition.call.backgroundNoiseGain }
1152
+ },
1153
+ ...definition.call.interruptionMode === null ? {} : { interruptionConfig: { mode: definition.call.interruptionMode } }
1154
+ },
1155
+ preCallWebhook: definition.preCallWebhook,
1156
+ builtInTools: definition.capabilities,
1157
+ assignedToolIds: [],
1158
+ // Emitted whenever any node declares an `actions` array, so an Agent
1159
+ // that once had callable Actions keeps its explicit empty list rather
1160
+ // than dropping the key.
1161
+ ...definition.nodes.some(
1162
+ (definitionNode) => definitionNode.type === "prompt" && definitionNode.actions !== void 0
1163
+ ) ? { toolUseSites } : {},
1164
+ automaticActions: {
1165
+ beforeCallStart: definition.beforeCallAction === null ? null : compileActionRun({
1166
+ run: definition.beforeCallAction,
1167
+ trigger: "before_call_start",
1168
+ canonicalKey: "before-call-start",
1169
+ options
1170
+ })
1171
+ },
1172
+ knowledgeBaseIds: definition.knowledgeBases.map((item) => item.uuid),
1173
+ abTestGroupIds: definition.abTestGroupIds ?? abTestGroupIds
1174
+ },
1175
+ nodes: definition.nodes.map(
1176
+ (definitionNode, index) => compileNode({
1177
+ definition: definitionNode,
1178
+ canonicalNodeKey: canonicalNodeKeysByDefinitionKey.get(definitionNode.key) ?? definitionNode.key,
1179
+ canonicalCallableKeys: canonicalCallableKeysByDefinitionKey,
1180
+ index,
1181
+ nodeUuids,
1182
+ options
1183
+ })
1184
+ ),
1185
+ summaryPrompt: definition.summaryPrompt
1186
+ }
1187
+ };
1188
+ }
1189
+
1190
+ // src/schemas.ts
1191
+ var import_zod3 = require("zod");
42
1192
  var MAX_QUERY_SIZE = 50;
43
1193
  var MAX_BATCH_ROWS = 1e3;
44
- var tableNameSchema = import_zod.z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
45
- var filterValueSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean()]);
46
- var dataColumnPathSchema = import_zod.z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
1194
+ var tableNameSchema = import_zod3.z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
1195
+ var filterValueSchema = import_zod3.z.union([import_zod3.z.string(), import_zod3.z.number(), import_zod3.z.boolean()]);
1196
+ var dataColumnPathSchema = import_zod3.z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
47
1197
  message: "Must be a dot-separated column path with no empty segments"
48
1198
  });
49
- var dataFilterSchema = import_zod.z.object({
1199
+ var dataFilterSchema = import_zod3.z.object({
50
1200
  column: dataColumnPathSchema,
51
- values: import_zod.z.array(filterValueSchema)
1201
+ values: import_zod3.z.array(filterValueSchema)
52
1202
  });
53
- var queryInputSchema = import_zod.z.object({
1203
+ var queryInputSchema = import_zod3.z.object({
54
1204
  tableName: tableNameSchema,
55
- filters: import_zod.z.array(dataFilterSchema).optional(),
56
- text: import_zod.z.string().max(5e3).optional(),
57
- size: import_zod.z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
58
- from: import_zod.z.number().int().min(0).optional()
1205
+ filters: import_zod3.z.array(dataFilterSchema).optional(),
1206
+ text: import_zod3.z.string().max(5e3).optional(),
1207
+ size: import_zod3.z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
1208
+ from: import_zod3.z.number().int().min(0).optional()
59
1209
  });
60
- var listOptionsSchema = import_zod.z.object({
61
- page: import_zod.z.number().int().min(1).optional(),
62
- perPage: import_zod.z.number().int().min(1).max(200).optional(),
63
- orderBy: import_zod.z.string().optional(),
64
- orderDirection: import_zod.z.enum(["asc", "desc"]).optional(),
1210
+ var listOptionsSchema = import_zod3.z.object({
1211
+ page: import_zod3.z.number().int().min(1).optional(),
1212
+ perPage: import_zod3.z.number().int().min(1).max(200).optional(),
1213
+ orderBy: import_zod3.z.string().optional(),
1214
+ orderDirection: import_zod3.z.enum(["asc", "desc"]).optional(),
65
1215
  /** Column-name → value equality filters applied server-side. */
66
- filters: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional()
1216
+ filters: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).optional()
67
1217
  });
68
- var recordPayloadSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
69
- var batchUpsertRowsSchema = import_zod.z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
1218
+ var recordPayloadSchema = import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown());
1219
+ var batchUpsertRowsSchema = import_zod3.z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
70
1220
 
71
1221
  // src/data.ts
72
1222
  function encodeTable(tableName) {
@@ -275,12 +1425,144 @@ var SimpleAI = class {
275
1425
 
276
1426
  // src/define-action.ts
277
1427
  var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
1428
+ var SIMPLE_ACTION_RUNTIME = /* @__PURE__ */ Symbol.for("simple-ai.action-runtime");
278
1429
  function defineAction(handler) {
279
- const wrapped = async ({ inputs, config }) => {
280
- const client = new SimpleAI();
1430
+ const wrapped = async (invocation) => {
1431
+ const { inputs, config } = invocation;
1432
+ const runtime = invocation[SIMPLE_ACTION_RUNTIME];
1433
+ const client = runtime === void 0 ? new SimpleAI() : new SimpleAI(runtime);
281
1434
  return handler({ inputs, config, client });
282
1435
  };
283
- return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
1436
+ const brand = { [SIMPLE_ACTION_BRAND]: true };
1437
+ return Object.assign(wrapped, brand);
1438
+ }
1439
+
1440
+ // src/projects.ts
1441
+ function defineAgentSnapshot(definition) {
1442
+ return { kind: "agent-snapshot", ...definition };
1443
+ }
1444
+ function replaceActionVersionUuid({
1445
+ versionUuid,
1446
+ actions,
1447
+ options
1448
+ }) {
1449
+ const actionDefinition = actions.find((item) => item.sourceVersionUuid === versionUuid);
1450
+ if (actionDefinition === void 0) {
1451
+ return versionUuid;
1452
+ }
1453
+ return options.actionVersionUuids?.[actionDefinition.key] ?? versionUuid;
1454
+ }
1455
+ function compileSnapshotNode({
1456
+ node: node2,
1457
+ actions,
1458
+ options
1459
+ }) {
1460
+ if (node2.type === "action_node") {
1461
+ return {
1462
+ ...node2,
1463
+ actionVersionUuid: replaceActionVersionUuid({
1464
+ versionUuid: node2.actionVersionUuid,
1465
+ actions,
1466
+ options
1467
+ })
1468
+ };
1469
+ }
1470
+ if (node2.type === "standard" && node2.perTurnAction != null) {
1471
+ return {
1472
+ ...node2,
1473
+ perTurnAction: {
1474
+ ...node2.perTurnAction,
1475
+ actionVersionUuid: replaceActionVersionUuid({
1476
+ versionUuid: node2.perTurnAction.actionVersionUuid,
1477
+ actions,
1478
+ options
1479
+ })
1480
+ }
1481
+ };
1482
+ }
1483
+ return node2;
1484
+ }
1485
+ function compileSnapshot(definition, options) {
1486
+ const snapshotActionValues = (values) => {
1487
+ switch (values.actionType) {
1488
+ case "code":
1489
+ return {
1490
+ ...values,
1491
+ operation: {
1492
+ ...values.operation,
1493
+ compiledJs: null
1494
+ }
1495
+ };
1496
+ case "http":
1497
+ case "custom_data":
1498
+ case "knowledge_base":
1499
+ return values;
1500
+ }
1501
+ };
1502
+ return {
1503
+ agent: definition.agent,
1504
+ branch: definition.branch,
1505
+ actions: definition.actions.map((item) => ({
1506
+ key: item.key,
1507
+ versionUuid: replaceActionVersionUuid({
1508
+ versionUuid: item.sourceVersionUuid,
1509
+ actions: definition.actions,
1510
+ options
1511
+ }),
1512
+ values: snapshotActionValues(item.values)
1513
+ })),
1514
+ content: {
1515
+ ...definition.content,
1516
+ config: {
1517
+ ...definition.content.config,
1518
+ ...definition.content.config.toolUseSites === void 0 ? {} : {
1519
+ toolUseSites: definition.content.config.toolUseSites.map((useSite) => ({
1520
+ ...useSite,
1521
+ actionVersionUuid: replaceActionVersionUuid({
1522
+ versionUuid: useSite.actionVersionUuid,
1523
+ actions: definition.actions,
1524
+ options
1525
+ })
1526
+ }))
1527
+ },
1528
+ automaticActions: {
1529
+ beforeCallStart: definition.content.config.automaticActions.beforeCallStart === null ? null : {
1530
+ ...definition.content.config.automaticActions.beforeCallStart,
1531
+ actionVersionUuid: replaceActionVersionUuid({
1532
+ versionUuid: definition.content.config.automaticActions.beforeCallStart.actionVersionUuid,
1533
+ actions: definition.actions,
1534
+ options
1535
+ })
1536
+ }
1537
+ }
1538
+ },
1539
+ nodes: definition.content.nodes.map(
1540
+ (node2) => compileSnapshotNode({ node: node2, actions: definition.actions, options })
1541
+ )
1542
+ }
1543
+ };
1544
+ }
1545
+ function compileAgentProject(definition, options = {}) {
1546
+ return definition.kind === "agent-definition" ? compileAgent(definition, options) : compileSnapshot(definition, options);
1547
+ }
1548
+ function collectActionVersionUuids(content) {
1549
+ const versionUuids = /* @__PURE__ */ new Set();
1550
+ for (const useSite of content.config.toolUseSites ?? []) {
1551
+ versionUuids.add(useSite.actionVersionUuid);
1552
+ }
1553
+ const beforeCallAction = content.config.automaticActions.beforeCallStart;
1554
+ if (beforeCallAction !== null) {
1555
+ versionUuids.add(beforeCallAction.actionVersionUuid);
1556
+ }
1557
+ for (const node2 of content.nodes) {
1558
+ if (node2.type === "action_node") {
1559
+ versionUuids.add(node2.actionVersionUuid);
1560
+ }
1561
+ if (node2.type === "standard" && node2.perTurnAction != null) {
1562
+ versionUuids.add(node2.perTurnAction.actionVersionUuid);
1563
+ }
1564
+ }
1565
+ return [...versionUuids];
284
1566
  }
285
1567
  // Annotate the CommonJS export names for ESM import in node:
286
1568
  0 && (module.exports = {
@@ -290,13 +1572,27 @@ function defineAction(handler) {
290
1572
  SIMPLE_ACTION_BRAND,
291
1573
  SimpleAI,
292
1574
  SimpleAIError,
1575
+ action,
1576
+ actionsIoSchemaFromZod,
293
1577
  batchUpsertRowsSchema,
1578
+ canonicalAuthoringKey,
1579
+ canonicalAuthoringKeys,
1580
+ collectActionVersionUuids,
1581
+ compileAction,
1582
+ compileAgent,
1583
+ compileAgentProject,
294
1584
  dataColumnPathSchema,
295
1585
  dataFilterSchema,
296
1586
  defineAction,
1587
+ defineAgent,
1588
+ defineAgentSnapshot,
297
1589
  listOptionsSchema,
1590
+ node,
1591
+ prompt,
298
1592
  queryInputSchema,
299
1593
  recordPayloadSchema,
1594
+ reference,
1595
+ sourceFile,
300
1596
  tableNameSchema
301
1597
  });
302
1598
  //# sourceMappingURL=index.cjs.map