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