agora-agents 2.12.0 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +38 -3
  2. package/dist/cjs/AgoraPoolClient.d.ts +15 -27
  3. package/dist/cjs/AgoraPoolClient.js +75 -54
  4. package/dist/cjs/BaseClient.js +3 -2
  5. package/dist/cjs/agentkit/Agent.d.ts +14 -1
  6. package/dist/cjs/agentkit/Agent.js +126 -9
  7. package/dist/cjs/agentkit/AgentSession.d.ts +11 -2
  8. package/dist/cjs/agentkit/AgentSession.js +134 -22
  9. package/dist/cjs/agentkit/index.d.ts +4 -1
  10. package/dist/cjs/agentkit/index.js +12 -2
  11. package/dist/cjs/agentkit/session-backend.d.ts +25 -0
  12. package/dist/cjs/agentkit/session-backend.js +197 -0
  13. package/dist/cjs/agentkit/types.d.ts +27 -4
  14. package/dist/cjs/agentkit/v3.d.ts +70 -0
  15. package/dist/cjs/agentkit/v3.js +700 -0
  16. package/dist/cjs/agentkit/vendors/avatar.d.ts +24 -12
  17. package/dist/cjs/agentkit/vendors/avatar.js +48 -3
  18. package/dist/cjs/agentkit/vendors/base.d.ts +8 -0
  19. package/dist/cjs/agentkit/vendors/base.js +33 -7
  20. package/dist/cjs/agentkit/vendors/llm.d.ts +7 -7
  21. package/dist/cjs/agentkit/vendors/llm.js +26 -22
  22. package/dist/cjs/agentkit/vendors/tts.d.ts +20 -0
  23. package/dist/cjs/agentkit/vendors/tts.js +5 -2
  24. package/dist/cjs/core/publicHeaders.d.ts +2 -0
  25. package/dist/cjs/core/publicHeaders.js +8 -0
  26. package/dist/cjs/index.d.ts +5 -0
  27. package/dist/cjs/index.js +14 -1
  28. package/dist/cjs/v3/campaign-schema.d.ts +1 -0
  29. package/dist/cjs/v3/campaign-schema.js +18 -0
  30. package/dist/cjs/v3/campaigns.d.ts +50 -0
  31. package/dist/cjs/v3/campaigns.js +81 -0
  32. package/dist/cjs/v3/contract.d.ts +1 -0
  33. package/dist/cjs/v3/contract.js +9115 -0
  34. package/dist/cjs/v3/index.d.ts +15 -0
  35. package/dist/cjs/v3/index.js +56 -0
  36. package/dist/cjs/v3/resources.d.ts +121 -0
  37. package/dist/cjs/v3/resources.js +186 -0
  38. package/dist/cjs/v3/session-lifecycle.d.ts +51 -0
  39. package/dist/cjs/v3/session-lifecycle.js +127 -0
  40. package/dist/cjs/v3/session-schema.d.ts +1 -0
  41. package/dist/cjs/v3/session-schema.js +18 -0
  42. package/dist/cjs/v3/transport.d.ts +36 -0
  43. package/dist/cjs/v3/transport.js +161 -0
  44. package/dist/cjs/v3/types.d.ts +1004 -0
  45. package/dist/cjs/v3/types.js +2 -0
  46. package/dist/cjs/version.d.ts +1 -1
  47. package/dist/cjs/version.js +1 -1
  48. package/dist/esm/AgoraPoolClient.d.mts +15 -27
  49. package/dist/esm/AgoraPoolClient.mjs +69 -48
  50. package/dist/esm/BaseClient.mjs +3 -2
  51. package/dist/esm/agentkit/Agent.d.mts +14 -1
  52. package/dist/esm/agentkit/Agent.mjs +126 -9
  53. package/dist/esm/agentkit/AgentSession.d.mts +11 -2
  54. package/dist/esm/agentkit/AgentSession.mjs +134 -22
  55. package/dist/esm/agentkit/index.d.mts +4 -1
  56. package/dist/esm/agentkit/index.mjs +2 -0
  57. package/dist/esm/agentkit/session-backend.d.mts +25 -0
  58. package/dist/esm/agentkit/session-backend.mjs +191 -0
  59. package/dist/esm/agentkit/types.d.mts +27 -4
  60. package/dist/esm/agentkit/v3.d.mts +70 -0
  61. package/dist/esm/agentkit/v3.mjs +687 -0
  62. package/dist/esm/agentkit/vendors/avatar.d.mts +24 -12
  63. package/dist/esm/agentkit/vendors/avatar.mjs +45 -6
  64. package/dist/esm/agentkit/vendors/base.d.mts +8 -0
  65. package/dist/esm/agentkit/vendors/base.mjs +33 -7
  66. package/dist/esm/agentkit/vendors/llm.d.mts +7 -7
  67. package/dist/esm/agentkit/vendors/llm.mjs +26 -22
  68. package/dist/esm/agentkit/vendors/tts.d.mts +20 -0
  69. package/dist/esm/agentkit/vendors/tts.mjs +5 -2
  70. package/dist/esm/core/publicHeaders.d.mts +2 -0
  71. package/dist/esm/core/publicHeaders.mjs +5 -0
  72. package/dist/esm/index.d.mts +5 -0
  73. package/dist/esm/index.mjs +3 -0
  74. package/dist/esm/v3/campaign-schema.d.mts +1 -0
  75. package/dist/esm/v3/campaign-schema.mjs +2 -0
  76. package/dist/esm/v3/campaigns.d.mts +50 -0
  77. package/dist/esm/v3/campaigns.mjs +77 -0
  78. package/dist/esm/v3/contract.d.mts +1 -0
  79. package/dist/esm/v3/contract.mjs +9112 -0
  80. package/dist/esm/v3/index.d.mts +15 -0
  81. package/dist/esm/v3/index.mjs +15 -0
  82. package/dist/esm/v3/resources.d.mts +121 -0
  83. package/dist/esm/v3/resources.mjs +179 -0
  84. package/dist/esm/v3/session-lifecycle.d.mts +51 -0
  85. package/dist/esm/v3/session-lifecycle.mjs +121 -0
  86. package/dist/esm/v3/session-schema.d.mts +1 -0
  87. package/dist/esm/v3/session-schema.mjs +2 -0
  88. package/dist/esm/v3/transport.d.mts +36 -0
  89. package/dist/esm/v3/transport.mjs +151 -0
  90. package/dist/esm/v3/types.d.mts +1004 -0
  91. package/dist/esm/v3/types.mjs +1 -0
  92. package/dist/esm/version.d.mts +1 -1
  93. package/dist/esm/version.mjs +1 -1
  94. package/openapi.yaml +8917 -0
  95. package/package.json +7 -4
  96. package/reference.md +3 -0
@@ -0,0 +1,700 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
23
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
+ var m = o[Symbol.asyncIterator], i;
25
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
26
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.DeployedAgent = exports.SavedAgent = exports.NumberNotFoundError = exports.UnsupportedFieldError = exports.SecretRefNotSupportedError = void 0;
31
+ exports.secretRef = secretRef;
32
+ exports.assertNoSecretRefs = assertNoSecretRefs;
33
+ exports.validateVariable = validateVariable;
34
+ exports.toV3Module = toV3Module;
35
+ exports.buildV3Agent = buildV3Agent;
36
+ exports.redeployPatch = redeployPatch;
37
+ exports.deployAgent = deployAgent;
38
+ const index_js_1 = require("../core/domain/index.js");
39
+ const contract_js_1 = require("../v3/contract.js");
40
+ const transport_js_1 = require("../v3/transport.js");
41
+ const session_backend_js_1 = require("./session-backend.js");
42
+ function secretRef(set, key) {
43
+ if (![set, key].every((v) => /^[A-Za-z0-9_]{1,64}$/.test(v)))
44
+ throw new Error("Secret names and keys must be 1–64 letters, digits or underscores");
45
+ return `$secrets.${set}.${key}`;
46
+ }
47
+ class SecretRefNotSupportedError extends Error {
48
+ constructor() {
49
+ super("secretRef requires save()");
50
+ this.name = "SecretRefNotSupportedError";
51
+ }
52
+ }
53
+ exports.SecretRefNotSupportedError = SecretRefNotSupportedError;
54
+ class UnsupportedFieldError extends Error {
55
+ constructor(fields) {
56
+ super(`Unsupported v3 fields: ${fields.join(", ")}`);
57
+ this.fields = fields;
58
+ this.name = "UnsupportedFieldError";
59
+ }
60
+ }
61
+ exports.UnsupportedFieldError = UnsupportedFieldError;
62
+ class NumberNotFoundError extends Error {
63
+ constructor(number, appid) {
64
+ super(`Number ${number} not found in project ${appid}; create it first with client.v3.numbers.create()`);
65
+ this.name = "NumberNotFoundError";
66
+ }
67
+ }
68
+ exports.NumberNotFoundError = NumberNotFoundError;
69
+ function assertNoSecretRefs(value) {
70
+ if (typeof value === "string" && value.startsWith("$secrets."))
71
+ throw new SecretRefNotSupportedError();
72
+ if (value && typeof value === "object")
73
+ for (const item of Object.values(value))
74
+ assertNoSecretRefs(item);
75
+ }
76
+ function validateVariable(name, def) {
77
+ var _a;
78
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(name))
79
+ throw new Error("Invalid v3 variable name");
80
+ if (!["str", "int", "float", "bool", "date", "datetime"].includes(def.type))
81
+ throw new Error("Invalid v3 variable type");
82
+ if (def.options && new Set(def.options.map((value) => JSON.stringify(value))).size !== def.options.length)
83
+ throw new Error("Variable options must be unique");
84
+ if (def.extract && !((_a = def.description) === null || _a === void 0 ? void 0 : _a.trim()))
85
+ throw new Error("Extracted variables require a description");
86
+ if (validateContract(def, contract_js_1.contract.AgentRequest_VariableDefinition, `variables.${name}`).length)
87
+ throw new Error("Invalid v3 variable definition");
88
+ }
89
+ const clean = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
90
+ function leftovers(value, allowed, path, errors) {
91
+ for (const [key, val] of Object.entries(value))
92
+ if (val !== undefined && !allowed.includes(key))
93
+ errors.push(`${path}.${key}`);
94
+ }
95
+ const moved = [
96
+ "system_messages",
97
+ "messages",
98
+ "greeting_message",
99
+ "greeting_audio_url",
100
+ "greeting_configs",
101
+ "template_variables",
102
+ "turn_detection",
103
+ ];
104
+ function toV3Module(config, kind, errors = []) {
105
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
106
+ const c = Object.assign({}, config), params = Object.assign({}, c.params);
107
+ const path = `pipeline.${kind}`;
108
+ if (kind === "avatar" && c.vendor === "heygen")
109
+ c.vendor = "liveavatar";
110
+ if (kind === "asr" && c.keywords !== undefined) {
111
+ params.keywords = c.keywords;
112
+ delete c.keywords;
113
+ }
114
+ if (kind === "asr") {
115
+ (_a = c.language) !== null && _a !== void 0 ? _a : (c.language = (_b = params.language) !== null && _b !== void 0 ? _b : (c.vendor === "ares" ? "en-US" : undefined));
116
+ delete params.language;
117
+ }
118
+ if (kind === "llm" && (c.vendor === "gemini" || c.style === "gemini") && c.url) {
119
+ // Legacy Gemini uses a query key; Platform credentials must never live in URLs.
120
+ const url = new URL(c.url);
121
+ const key = url.searchParams.get("key");
122
+ if (key !== null) {
123
+ (_c = c.api_key) !== null && _c !== void 0 ? _c : (c.api_key = key);
124
+ url.searchParams.delete("key");
125
+ c.url = url.toString();
126
+ }
127
+ }
128
+ if (kind === "llm" && c.style === "bedrock") {
129
+ (_d = c.vendor) !== null && _d !== void 0 ? _d : (c.vendor = "amazon");
130
+ for (const key of ["access_key", "secret_key", "region"]) {
131
+ if (c[key] !== undefined) {
132
+ if (params[key] !== undefined && params[key] !== c[key])
133
+ errors.push(`${path}.params.${key}`);
134
+ params[key] = c[key];
135
+ delete c[key];
136
+ }
137
+ }
138
+ }
139
+ const allowed = {
140
+ asr: ["vendor", "url", "language", "model"],
141
+ llm: [
142
+ "vendor",
143
+ "url",
144
+ "style",
145
+ "model",
146
+ "input_modalities",
147
+ "output_modalities",
148
+ "max_history",
149
+ "failure_message",
150
+ "mcp_servers",
151
+ "tools",
152
+ "headers",
153
+ ],
154
+ tts: ["vendor", "url", "headers", "skip_patterns"],
155
+ avatar: ["vendor"],
156
+ }[kind];
157
+ leftovers(c, [...allowed, ...moved, "api_key", "params", "enable", "_minimaxPresetModel"], path, errors);
158
+ // Credential aliases are normalized to the selected provider's public fields.
159
+ const fields = {};
160
+ const aliases = c.vendor === "amazon" && kind === "asr"
161
+ ? {
162
+ access_key_id: ["access_key_id", "aws_access_key_id"],
163
+ secret_access_key: ["secret_access_key", "aws_secret_access_key"],
164
+ }
165
+ : c.vendor === "amazon" && kind === "tts"
166
+ ? {
167
+ aws_access_key_id: ["aws_access_key_id", "access_key_id"],
168
+ aws_secret_access_key: ["aws_secret_access_key", "secret_access_key"],
169
+ }
170
+ : c.vendor === "amazon" &&
171
+ kind === "llm" &&
172
+ (params.access_key !== undefined || params.secret_key !== undefined)
173
+ ? { access_key: ["access_key"], secret_key: ["secret_key"] }
174
+ : c.vendor === "google" && kind === "asr"
175
+ ? { adc_credentials_string: ["adc_credentials_string", "api_key"] }
176
+ : c.vendor === "google" && kind === "tts"
177
+ ? { credentials: ["credentials", "adc_credentials_string", "api_key"] }
178
+ : c.vendor === "sarvam" && kind === "tts"
179
+ ? { api_subscription_key: ["api_subscription_key", "api_key"] }
180
+ : (kind === "asr" && ["microsoft", "speechmatics"].includes(c.vendor)) ||
181
+ (kind === "tts" && ["elevenlabs", "humeai", "microsoft", "minimax"].includes(c.vendor))
182
+ ? { key: ["key", "api_key"] }
183
+ : kind === "avatar" && c.vendor === "sensetime"
184
+ ? { app_key: ["app_key", "api_key"] }
185
+ : kind === "avatar" && c.vendor === "spatius"
186
+ ? { spatius_api_key: ["spatius_api_key", "api_key"] }
187
+ : { api_key: ["api_key", "key"] };
188
+ if (Object.keys(aliases).length > 1 && c.api_key !== undefined)
189
+ errors.push(`${path}.credential`);
190
+ for (const [field, keys] of Object.entries(aliases)) {
191
+ const values = keys.map((key) => params[key]).filter((value) => value !== undefined);
192
+ if (Object.keys(aliases).length === 1 && c.api_key !== undefined)
193
+ values.push(c.api_key);
194
+ if (new Set(values).size > 1)
195
+ errors.push(`${path}.credential.fields.${field}`);
196
+ if (values.length)
197
+ fields[field] = values[0];
198
+ for (const key of keys)
199
+ delete params[key];
200
+ }
201
+ for (const key of [
202
+ "api_key",
203
+ "key",
204
+ "api_subscription_key",
205
+ "aws_access_key_id",
206
+ "aws_secret_access_key",
207
+ "access_key",
208
+ "secret_key",
209
+ "access_key_id",
210
+ "secret_access_key",
211
+ "adc_credentials_string",
212
+ "credentials",
213
+ ]) {
214
+ if (params[key] !== undefined)
215
+ errors.push(`${path}.params.${key}`);
216
+ }
217
+ const endpointAlias = kind === "asr"
218
+ ? c.vendor === "assemblyai"
219
+ ? "ws_url"
220
+ : c.vendor === "speechmatics"
221
+ ? "uri"
222
+ : undefined
223
+ : undefined;
224
+ const url = kind === "avatar"
225
+ ? undefined
226
+ : ((_h = (_g = (_f = (_e = c.url) !== null && _e !== void 0 ? _e : (endpointAlias ? params[endpointAlias] : undefined)) !== null && _f !== void 0 ? _f : params.url) !== null && _g !== void 0 ? _g : params.base_url) !== null && _h !== void 0 ? _h : params.api_base_url);
227
+ if (kind !== "avatar") {
228
+ delete params.url;
229
+ delete params.base_url;
230
+ delete params.api_base_url;
231
+ if (endpointAlias)
232
+ delete params[endpointAlias];
233
+ }
234
+ const result = clean(Object.fromEntries(allowed.map((key) => [key, c[key]])));
235
+ if (url !== undefined)
236
+ result.url = url;
237
+ if ((kind === "llm" || kind === "asr") && params.model !== undefined) {
238
+ result.model = (_j = c.model) !== null && _j !== void 0 ? _j : params.model;
239
+ delete params.model;
240
+ }
241
+ if (kind === "tts" && c._minimaxPresetModel !== undefined)
242
+ params.model = c._minimaxPresetModel;
243
+ if (kind === "avatar") {
244
+ if (!["akool", "liveavatar", "anam", "generic", "sensetime", "spatius"].includes(c.vendor))
245
+ errors.push(`${path}.vendor`);
246
+ result.enabled = (_k = c.enable) !== null && _k !== void 0 ? _k : true;
247
+ }
248
+ else if (c.enable === false)
249
+ errors.push(`${path}.enable`);
250
+ if (kind === "tts" && c.skip_patterns) {
251
+ // The v2 numeric enum has no published mapping to the v3 names.
252
+ errors.push(`${path}.skip_patterns`);
253
+ }
254
+ result.credential = Object.keys(fields).length ? { mode: "byok", fields } : { mode: "managed" };
255
+ if (!Object.keys(fields).length)
256
+ delete result.url;
257
+ if (Object.keys(params).length)
258
+ result.params = params;
259
+ return result;
260
+ }
261
+ function interruption(c) {
262
+ var _a, _b, _c, _d, _e;
263
+ if (c.enable === false || c.mode === "disabled")
264
+ return clean({ mode: "off", when_off: (_a = c.disabled_config) === null || _a === void 0 ? void 0 : _a.strategy });
265
+ if (c.mode === "keywords")
266
+ return {
267
+ mode: "keywords",
268
+ keywords: (_e = (_c = (_b = c.keywords_config) === null || _b === void 0 ? void 0 : _b.trigger_keywords) !== null && _c !== void 0 ? _c : (_d = c.keywords_config) === null || _d === void 0 ? void 0 : _d.triggered_keywords) !== null && _e !== void 0 ? _e : [],
269
+ };
270
+ return { mode: "start_of_speech" };
271
+ }
272
+ function turns(c, errors) {
273
+ var _a, _b, _c;
274
+ leftovers(c, ["mode", "config", "language"], "turnDetection", errors);
275
+ const config = (_a = c.config) !== null && _a !== void 0 ? _a : {}, result = clean({ speech_threshold: config.speech_threshold });
276
+ leftovers(config, ["speech_threshold", "start_of_speech", "end_of_speech"], "turnDetection.config", errors);
277
+ for (const key of ["start_of_speech", "end_of_speech"]) {
278
+ const boundary = config[key];
279
+ if (!boundary)
280
+ continue;
281
+ if (["keywords", "disabled"].includes(boundary.mode)) {
282
+ result.interruption = interruption(boundary);
283
+ continue;
284
+ }
285
+ const settings = (_b = boundary[`${boundary.mode}_config`]) !== null && _b !== void 0 ? _b : {};
286
+ if (settings.max_wait_ms !== undefined && settings.max_wait_ms < 500)
287
+ errors.push(`turnDetection.config.${key}.max_wait_ms`);
288
+ result[key] = Object.assign({ type: (_c = boundary.mode) !== null && _c !== void 0 ? _c : "semantic" }, settings);
289
+ }
290
+ return result;
291
+ }
292
+ function validateContract(value, schema, path) {
293
+ var _a, _b, _c, _d, _e, _f;
294
+ if (schema === true)
295
+ return [];
296
+ if (schema === false)
297
+ return [path];
298
+ if (schema.type === "null")
299
+ return value === null ? [] : [path];
300
+ if (schema.allOf) {
301
+ const errors = schema.allOf.flatMap((branch) => validateContract(value, branch, path));
302
+ if (errors.length)
303
+ return errors;
304
+ }
305
+ if (schema.not && validateContract(value, schema.not, path).length === 0)
306
+ return [path];
307
+ if (schema.if) {
308
+ const branch = validateContract(value, schema.if, path).length === 0 ? schema.then : schema.else;
309
+ if (branch) {
310
+ const errors = validateContract(value, branch, path);
311
+ if (errors.length)
312
+ return errors;
313
+ }
314
+ }
315
+ if (object(value) && ((_a = schema.required) === null || _a === void 0 ? void 0 : _a.some((key) => !(key in value))))
316
+ return [path];
317
+ if (schema.$ref)
318
+ return validateContract(value, contract_js_1.contract[schema.$ref.split("/").pop()], path);
319
+ for (const union of ["oneOf", "anyOf"])
320
+ if (schema[union]) {
321
+ const variants = schema[union].map((branch) => validateContract(value, branch, path));
322
+ if (variants.some((errors) => errors.length === 0))
323
+ return [];
324
+ return variants.sort((a, b) => a.length - b.length)[0];
325
+ }
326
+ if (schema.const !== undefined && value !== schema.const)
327
+ return [path];
328
+ if (schema.enum && !schema.enum.includes(value))
329
+ return [path];
330
+ if (Array.isArray(schema.type)) {
331
+ return schema.type.some((type) => validateContract(value, Object.assign(Object.assign({}, schema), { type }), path).length === 0)
332
+ ? []
333
+ : [path];
334
+ }
335
+ if (schema.type === "string") {
336
+ if (typeof value !== "string" ||
337
+ (schema.minLength !== undefined && [...value].length < schema.minLength) ||
338
+ (schema.maxLength !== undefined && [...value].length > schema.maxLength) ||
339
+ (schema.pattern && !new RegExp(schema.pattern).test(value)))
340
+ return [path];
341
+ }
342
+ if (schema.type === "boolean" && typeof value !== "boolean")
343
+ return [path];
344
+ if (["number", "integer"].includes(schema.type) &&
345
+ (typeof value !== "number" ||
346
+ !Number.isFinite(value) ||
347
+ (schema.type === "integer" && !Number.isInteger(value))))
348
+ return [path];
349
+ if ((schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) ||
350
+ (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum))
351
+ return [path];
352
+ if ((schema.minimum !== undefined && value < schema.minimum) ||
353
+ (schema.maximum !== undefined && value > schema.maximum))
354
+ return [path];
355
+ if (schema.type === "array") {
356
+ if (!Array.isArray(value))
357
+ return [path];
358
+ if ((schema.minItems !== undefined && value.length < schema.minItems) ||
359
+ (schema.maxItems !== undefined && value.length > schema.maxItems))
360
+ return [path];
361
+ if (schema.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length)
362
+ return [path];
363
+ return value.flatMap((v, i) => { var _a; return validateContract(v, (_a = schema.items) !== null && _a !== void 0 ? _a : {}, `${path}[${i}]`); });
364
+ }
365
+ if (schema.type === "object" || schema.properties) {
366
+ if (!object(value))
367
+ return [path];
368
+ const errors = ((_b = schema.required) !== null && _b !== void 0 ? _b : [])
369
+ .filter((k) => value[k] === undefined)
370
+ .map((k) => `${path}.${k}`);
371
+ for (const [key, v] of Object.entries(value)) {
372
+ const child = (_d = (_c = schema.properties) === null || _c === void 0 ? void 0 : _c[key]) !== null && _d !== void 0 ? _d : (_f = Object.entries((_e = schema.patternProperties) !== null && _e !== void 0 ? _e : {}).find(([pattern]) => new RegExp(pattern).test(key))) === null || _f === void 0 ? void 0 : _f[1];
373
+ if (child)
374
+ errors.push(...validateContract(v, child, `${path}.${key}`));
375
+ else if (schema.additionalProperties === false)
376
+ errors.push(`${path}.${key}`);
377
+ else if (object(schema.additionalProperties))
378
+ errors.push(...validateContract(v, schema.additionalProperties, `${path}.${key}`));
379
+ }
380
+ return errors;
381
+ }
382
+ return [];
383
+ }
384
+ function buildV3Agent(config, variables, name) {
385
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
386
+ const errors = [];
387
+ for (const key of ["sal", "advancedFeatures", "geofence", "labels", "rtc", "pipelineId"])
388
+ if (config[key] !== undefined)
389
+ errors.push(key);
390
+ if (config.parameters)
391
+ leftovers(config.parameters, ["silence_config"], "parameters", errors);
392
+ if (config.mllm !== undefined)
393
+ throw new UnsupportedFieldError(["mllm (not available for saved or ephemeral preview sessions)"]);
394
+ const pipeline = { mode: "cascaded" };
395
+ for (const [key, kind] of [
396
+ ["stt", "asr"],
397
+ ["llm", "llm"],
398
+ ["tts", "tts"],
399
+ ["avatar", "avatar"],
400
+ ])
401
+ if (config[key])
402
+ pipeline[kind] = toV3Module(config[key], kind, errors);
403
+ if (((_a = config.turnDetection) === null || _a === void 0 ? void 0 : _a.language) !== undefined) {
404
+ // Language controls the interaction ASR, while provider-specific language
405
+ // settings remain in params. Keep direct mapper callers lossless too.
406
+ (_b = pipeline.asr) !== null && _b !== void 0 ? _b : (pipeline.asr = toV3Module({ vendor: config.client.area === index_js_1.Area.CN ? "fengming" : "ares" }, "asr", errors));
407
+ pipeline.asr.language = config.turnDetection.language;
408
+ }
409
+ const vendor = (_c = config.llm) !== null && _c !== void 0 ? _c : {};
410
+ const body = { agent_name: name, pipeline };
411
+ const messages = (_d = vendor.system_messages) !== null && _d !== void 0 ? _d : vendor.messages;
412
+ if (messages !== undefined) {
413
+ const system = [], other = [];
414
+ for (const message of messages) {
415
+ if (message.role === "system" && typeof message.content === "string")
416
+ system.push(message.content);
417
+ else
418
+ other.push(message);
419
+ }
420
+ if (system.length)
421
+ body.instructions = system.join("\n");
422
+ if (other.length)
423
+ body.messages = other;
424
+ }
425
+ if (body.instructions === undefined) {
426
+ if (config.instructions !== undefined)
427
+ body.instructions = config.instructions;
428
+ }
429
+ const vars = {};
430
+ if (vendor.template_variables && Object.keys(vendor.template_variables).length)
431
+ errors.push("llm.template_variables (v3 has no variable defaults)");
432
+ Object.assign(vars, variables);
433
+ for (const [key, value] of Object.entries(vars))
434
+ validateVariable(key, value);
435
+ if (Object.keys(vars).length)
436
+ body.variables = vars;
437
+ const text = (_e = vendor.greeting_message) !== null && _e !== void 0 ? _e : config.greeting;
438
+ const gc = (_g = (_f = vendor.greeting_configs) !== null && _f !== void 0 ? _f : config.greetingConfigs) !== null && _g !== void 0 ? _g : {};
439
+ leftovers(gc, ["on", "mode", "delay_ms", "audio_download_timeout_ms", "audio_pcm_sample_rate"], "greetingConfigs", errors);
440
+ if (text !== undefined || vendor.greeting_audio_url !== undefined)
441
+ body.greeting = clean({
442
+ mode: vendor.greeting_audio_url ? "audio" : "text",
443
+ text,
444
+ url: vendor.greeting_audio_url,
445
+ on: (_h = gc.on) !== null && _h !== void 0 ? _h : (gc.mode === "single_every" ? "each_join" : gc.mode === "single_first" ? "first_join" : gc.mode),
446
+ delay_ms: gc.delay_ms,
447
+ download_timeout_ms: (_j = gc.audio_download_timeout_ms) !== null && _j !== void 0 ? _j : undefined,
448
+ pcm_sample_rate: (_k = gc.audio_pcm_sample_rate) !== null && _k !== void 0 ? _k : undefined,
449
+ });
450
+ if (pipeline.llm) {
451
+ if (pipeline.llm.failure_message === undefined && config.failureMessage !== undefined)
452
+ pipeline.llm.failure_message = config.failureMessage;
453
+ if (pipeline.llm.max_history === undefined && config.maxHistory !== undefined)
454
+ pipeline.llm.max_history = config.maxHistory;
455
+ }
456
+ else {
457
+ if (config.failureMessage !== undefined)
458
+ errors.push("failureMessage");
459
+ if (config.maxHistory !== undefined)
460
+ errors.push("maxHistory");
461
+ }
462
+ const td = (_l = vendor.turn_detection) !== null && _l !== void 0 ? _l : config.turnDetection;
463
+ if (td)
464
+ pipeline.turn_detection = turns(td, errors);
465
+ if (config.interruption) {
466
+ pipeline.turn_detection = Object.assign(Object.assign({}, pipeline.turn_detection), { interruption: interruption(config.interruption) });
467
+ }
468
+ if ((_m = config.parameters) === null || _m === void 0 ? void 0 : _m.silence_config) {
469
+ pipeline.silence_config = Object.assign({ enabled: true }, config.parameters.silence_config);
470
+ }
471
+ if (config.fillerWords) {
472
+ const f = config.fillerWords;
473
+ body.filler_words = clean({
474
+ enable: f.enable,
475
+ trigger: f.trigger && Object.assign({ mode: f.trigger.mode }, f.trigger.fixed_time_config),
476
+ content: f.content &&
477
+ (f.content.mode === "static"
478
+ ? Object.assign({ mode: "static" }, f.content.static_config) : clean({
479
+ mode: "generated",
480
+ instructions: (_o = f.content.generated_config) === null || _o === void 0 ? void 0 : _o.prompt,
481
+ fallback_strategy: (_p = f.content.generated_config) === null || _p === void 0 ? void 0 : _p.fallback_strategy,
482
+ })),
483
+ });
484
+ }
485
+ const { agent_name: _agentName } = body, inline = __rest(body, ["agent_name"]);
486
+ errors.push(...validateContract(inline, { $ref: "#/components/schemas/PublicAgentInput" }, "agent"));
487
+ if (errors.length)
488
+ throw new UnsupportedFieldError([...new Set(errors)]);
489
+ return body;
490
+ }
491
+ const mutable = ["agent_name", "instructions", "messages", "greeting", "variables", "pipeline", "filler_words"];
492
+ function object(v) {
493
+ return !!v && typeof v === "object" && !Array.isArray(v);
494
+ }
495
+ function credentialFieldNames(kind, vendor) {
496
+ if (kind === "asr" && vendor === "amazon")
497
+ return ["access_key_id", "secret_access_key"];
498
+ if (kind === "tts" && vendor === "amazon")
499
+ return ["aws_access_key_id", "aws_secret_access_key"];
500
+ if (kind === "llm" && vendor === "amazon")
501
+ return ["api_key", "access_key", "secret_key"];
502
+ if (kind === "asr" && vendor === "google")
503
+ return ["adc_credentials_string"];
504
+ if (kind === "tts" && vendor === "google")
505
+ return ["credentials"];
506
+ if (kind === "tts" && vendor === "sarvam")
507
+ return ["api_subscription_key"];
508
+ if ((kind === "asr" && ["microsoft", "speechmatics"].includes(vendor !== null && vendor !== void 0 ? vendor : "")) ||
509
+ (kind === "tts" && ["elevenlabs", "humeai", "microsoft", "minimax"].includes(vendor !== null && vendor !== void 0 ? vendor : "")))
510
+ return ["key"];
511
+ if (kind === "avatar" && vendor === "sensetime")
512
+ return ["app_key"];
513
+ if (kind === "avatar" && vendor === "spatius")
514
+ return ["spatius_api_key"];
515
+ return ["api_key"];
516
+ }
517
+ /** Explicitly clear readable stale keys under standard JSON merge-patch semantics. */
518
+ function redeployPatch(previous, desired) {
519
+ const merge = (old, next, path = "") => {
520
+ const module = /^pipeline\.(asr|llm|tts|avatar)$/.test(path);
521
+ const result = Object.assign({}, next);
522
+ for (const [key, value] of Object.entries(old)) {
523
+ // Resolved credentials contain read-only metadata; never echo or diff it.
524
+ if (key === "credential" && module)
525
+ continue;
526
+ if (!(key in next))
527
+ result[key] = null;
528
+ else if (object(value) && object(next[key]))
529
+ result[key] = merge(value, next[key], path ? `${path}.${key}` : key);
530
+ }
531
+ if (module && object(next.credential))
532
+ result.credential = Object.assign(Object.assign({}, next.credential), (next.credential.mode === "managed"
533
+ ? { fields: null }
534
+ : {
535
+ fields: Object.assign(Object.assign({}, Object.fromEntries(credentialFieldNames(path.split(".")[1], old.vendor)
536
+ .filter((key) => !(key in next.credential.fields))
537
+ .map((key) => [key, null]))), next.credential.fields),
538
+ }));
539
+ return result;
540
+ };
541
+ return merge(Object.fromEntries(Object.entries(previous).filter(([key]) => mutable.includes(key))), desired);
542
+ }
543
+ function etag(response) {
544
+ const tag = response.rawResponse.headers.get("ETag");
545
+ if (!tag)
546
+ throw new Error("v3 response is missing ETag");
547
+ return tag;
548
+ }
549
+ function deployAgent(client, body, options) {
550
+ return __awaiter(this, void 0, void 0, function* () {
551
+ var _a, _b, _c;
552
+ const invalid = validateContract(body, contract_js_1.contract.AgentRequest_AgentCreateInput, "agent");
553
+ if (invalid.length)
554
+ throw new UnsupportedFieldError(invalid);
555
+ for (const [kind, module] of Object.entries((_a = body.pipeline) !== null && _a !== void 0 ? _a : {})) {
556
+ if (object(module) && "credential" in module && ((_b = module.credential) === null || _b === void 0 ? void 0 : _b.mode) === "byok") {
557
+ for (const value of Object.values((_c = module.credential.fields) !== null && _c !== void 0 ? _c : {}))
558
+ if (typeof value !== "string" || !/^\$secrets\.[A-Za-z0-9_]{1,64}\.[A-Za-z0-9_]{1,64}$/.test(value))
559
+ throw new Error(`Saved ${kind} credentials require secretRef(); use an ephemeral session for inline credentials`);
560
+ }
561
+ }
562
+ const agentId = options.agentId;
563
+ let response;
564
+ if (agentId !== undefined) {
565
+ const current = yield client.v3.agents.get({ id: agentId }).withRawResponse();
566
+ response = yield client.v3.agents
567
+ .update(Object.assign(Object.assign({}, redeployPatch(current.data, body)), { id: agentId, ifMatch: etag(current) }))
568
+ .withRawResponse();
569
+ }
570
+ else
571
+ response = yield client.v3.agents.create(body).withRawResponse();
572
+ return new SavedAgent(client, response.data, etag(response));
573
+ });
574
+ }
575
+ class SavedAgent {
576
+ constructor(client, data, etag) {
577
+ this.client = client;
578
+ this.etag = etag;
579
+ this.id = data.agent_id;
580
+ this.name = data.agent_name;
581
+ this.raw = client.v3.agents;
582
+ }
583
+ static get(client, agentId) {
584
+ return __awaiter(this, void 0, void 0, function* () {
585
+ const response = yield client.v3.agents.get({ id: agentId }).withRawResponse();
586
+ return new SavedAgent(client, response.data, etag(response));
587
+ });
588
+ }
589
+ createSession(options) {
590
+ return (0, session_backend_js_1.createStoredSession)(this.client, options, { agent_id: this.id });
591
+ }
592
+ /** Create an outbound phone-call session using this saved agent. */
593
+ call(options) {
594
+ return (0, session_backend_js_1.createStoredSession)(this.client, (0, session_backend_js_1.callSessionOptions)(options), { agent_id: this.id }, undefined, {
595
+ type: "telephony",
596
+ from: options.from,
597
+ to: options.to,
598
+ call_policy: options.callPolicy,
599
+ });
600
+ }
601
+ /** Save a revised configuration to this stored identity, preserving its name by default. */
602
+ update(config, options = {}) {
603
+ var _a;
604
+ if (config.config.client !== this.client) {
605
+ throw new Error("SavedAgent.update requires a configuration bound to the same client");
606
+ }
607
+ return config.save({ agentId: this.id, name: (_a = options.name) !== null && _a !== void 0 ? _a : this.name });
608
+ }
609
+ delete() {
610
+ return __awaiter(this, void 0, void 0, function* () {
611
+ yield this.raw.delete({ id: this.id });
612
+ });
613
+ }
614
+ /** Scan project number pages and return numbers assigned to this stored agent. */
615
+ listNumbers() {
616
+ return __awaiter(this, void 0, void 0, function* () {
617
+ var _a, e_1, _b, _c;
618
+ var _d;
619
+ const assigned = [];
620
+ try {
621
+ for (var _e = true, _f = __asyncValues(this.client.v3.numbers.listAll({ limit: 100 })), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
622
+ _c = _g.value;
623
+ _e = false;
624
+ const number = _c;
625
+ if (((_d = number.inbound) === null || _d === void 0 ? void 0 : _d.agent) === this.id)
626
+ assigned.push(number);
627
+ }
628
+ }
629
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
630
+ finally {
631
+ try {
632
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
633
+ }
634
+ finally { if (e_1) throw e_1.error; }
635
+ }
636
+ return assigned;
637
+ });
638
+ }
639
+ assignNumber(number, options = {}) {
640
+ return this.setNumber(number, this.id, options);
641
+ }
642
+ unassignNumber(number) {
643
+ return this.setNumber(number, null);
644
+ }
645
+ setNumber(number_1, agent_1) {
646
+ return __awaiter(this, arguments, void 0, function* (number, agent, options = {}) {
647
+ var _a, e_2, _b, _c;
648
+ var _d, _e, _f, _g;
649
+ const policy = clean(Object.assign(Object.assign({}, options.callPolicy), { max_call_duration_seconds: (_d = options.maxCallDurationSeconds) !== null && _d !== void 0 ? _d : (_e = options.callPolicy) === null || _e === void 0 ? void 0 : _e.max_call_duration_seconds, max_silence_duration_ms: (_f = options.maxSilenceDurationMs) !== null && _f !== void 0 ? _f : (_g = options.callPolicy) === null || _g === void 0 ? void 0 : _g.max_silence_duration_ms }));
650
+ let id;
651
+ if (typeof number === "object")
652
+ id = number.number_id;
653
+ else if (number.startsWith("+")) {
654
+ const normalize = (v) => v.replace(/[\s().-]/g, "");
655
+ let found;
656
+ try {
657
+ for (var _h = true, _j = __asyncValues(this.client.v3.numbers.listAll({ limit: 100 })), _k; _k = yield _j.next(), _a = _k.done, !_a; _h = true) {
658
+ _c = _k.value;
659
+ _h = false;
660
+ const candidate = _c;
661
+ if (normalize(candidate.number) === normalize(number)) {
662
+ found = candidate;
663
+ break;
664
+ }
665
+ }
666
+ }
667
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
668
+ finally {
669
+ try {
670
+ if (!_h && !_a && (_b = _j.return)) yield _b.call(_j);
671
+ }
672
+ finally { if (e_2) throw e_2.error; }
673
+ }
674
+ if (!found)
675
+ throw new NumberNotFoundError(number, this.client.appId);
676
+ id = found.number_id;
677
+ }
678
+ else
679
+ id = number;
680
+ for (let attempt = 0;; attempt++) {
681
+ const current = yield this.client.v3.numbers.get({ id }).withRawResponse();
682
+ try {
683
+ return yield this.client.v3.numbers.update({
684
+ id,
685
+ ifMatch: etag(current),
686
+ inbound: Object.assign({ agent }, (options.callPolicy !== undefined || Object.keys(policy).length
687
+ ? { call_policy: policy }
688
+ : {})),
689
+ });
690
+ }
691
+ catch (error) {
692
+ if (!(error instanceof transport_js_1.PreconditionFailedError) || attempt >= 1)
693
+ throw error;
694
+ }
695
+ }
696
+ });
697
+ }
698
+ }
699
+ exports.SavedAgent = SavedAgent;
700
+ exports.DeployedAgent = SavedAgent;