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
@@ -13,11 +13,24 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
13
13
  step((generator = generator.apply(thisArg, _arguments || [])).next());
14
14
  });
15
15
  };
16
+ var __rest = (this && this.__rest) || function (s, e) {
17
+ var t = {};
18
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
19
+ t[p] = s[p];
20
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
21
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
22
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
23
+ t[p[i]] = s[p[i]];
24
+ }
25
+ return t;
26
+ };
16
27
  import { AgoraError } from "../errors/index.mjs";
28
+ import { V3Error } from "../v3/transport.mjs";
17
29
  import { isAkoolAvatar, isAnamAvatar, isAvatarTokenManaged, isGenericAvatar, isHeyGenAvatar, isLiveAvatarAvatar, isSensetimeAvatar, isSpatiusAvatar, validateAvatarConfig, validateTtsSampleRate, } from "./avatar-types.mjs";
18
30
  import { redactHeadersForDebug, redactSecrets } from "./debug.mjs";
19
31
  import { getPresetCategory, inferAsrPreset, inferLlmPreset, inferTtsPreset, normalizePresetInput, resolveSessionPresets, } from "./presets.mjs";
20
32
  import { applyPreviewShape, createPreviewRoute, previewRequestHeaders, requiredPreviewFeatures, } from "./preview/client.mjs";
33
+ import { UnsupportedSessionOperationError } from "./session-backend.mjs";
21
34
  import { ExpiresIn as ExpiresInHelper, generateConvoAIToken } from "./token.mjs";
22
35
  /**
23
36
  * AgentSession class for managing agent lifecycle and interactions.
@@ -53,14 +66,28 @@ import { ExpiresIn as ExpiresInHelper, generateConvoAIToken } from "./token.mjs"
53
66
  * ```
54
67
  */
55
68
  export class AgentSession {
69
+ _beginLifecycle() {
70
+ const revision = ++this._lifecycleRevision;
71
+ this._pendingLifecycle = revision;
72
+ return revision;
73
+ }
74
+ _finishLifecycle(revision) {
75
+ if (revision !== undefined && this._pendingLifecycle === revision) {
76
+ this._pendingLifecycle = undefined;
77
+ ++this._lifecycleRevision;
78
+ }
79
+ }
56
80
  constructor(options) {
57
81
  var _a, _b;
58
82
  this._previewFeatures = [];
59
83
  this._agentId = null;
60
84
  this._status = "idle";
85
+ this._lifecycleRevision = 0;
86
+ this._infoReadRevision = 0;
61
87
  this._eventHandlers = new Map();
62
88
  this._client = options.client;
63
89
  this._agent = options.agent;
90
+ this._backend = options.backend;
64
91
  this._appId = options.appId;
65
92
  this._appCertificate = options.appCertificate;
66
93
  this._name = options.name;
@@ -75,8 +102,8 @@ export class AgentSession {
75
102
  this._expiresIn = options.expiresIn;
76
103
  this._debug = options.debug;
77
104
  this._warn = (_a = options.warn) !== null && _a !== void 0 ? _a : ((msg) => console.warn(msg));
78
- // Read authMode from pool client if available, else fall back to basic
79
- this._authMode = (_b = options.client.authMode) !== null && _b !== void 0 ? _b : "basic";
105
+ // Read authMode from pool client if available, else leave authorization to the supplied client
106
+ this._authMode = (_b = options.client.authMode) !== null && _b !== void 0 ? _b : "token";
80
107
  this._agentsClient = options.client.agents;
81
108
  this._agentManagementClient = options.client.agentManagement;
82
109
  this._sessionBaseUrl = this._clientCurrentUrl();
@@ -154,6 +181,8 @@ export class AgentSession {
154
181
  * The agent configuration.
155
182
  */
156
183
  get agent() {
184
+ if (!this._agent)
185
+ throw new Error("This session uses a saved agent; no local configuration is available");
157
186
  return this._agent;
158
187
  }
159
188
  /**
@@ -182,19 +211,23 @@ export class AgentSession {
182
211
  * ```
183
212
  */
184
213
  get raw() {
214
+ if (this._backend)
215
+ throw new UnsupportedSessionOperationError("raw running-agent client");
185
216
  return this._agentsClient;
186
217
  }
187
218
  /**
188
219
  * Direct access to the underlying Fern-generated AgentManagement client.
189
220
  */
190
221
  get rawAgentManagement() {
222
+ if (this._backend)
223
+ throw new UnsupportedSessionOperationError("rawAgentManagement");
191
224
  return this._agentManagementClient;
192
225
  }
193
226
  /**
194
227
  * Returns true when the agent is configured for MLLM (multimodal end-to-end audio).
195
228
  */
196
229
  _isMllmMode() {
197
- const mllm = this._agent.mllm;
230
+ const mllm = this.agent.mllm;
198
231
  if ((mllm === null || mllm === void 0 ? void 0 : mllm.enable) === true) {
199
232
  return true;
200
233
  }
@@ -210,10 +243,10 @@ export class AgentSession {
210
243
  */
211
244
  _warnOnDroppedMllmInstructions() {
212
245
  var _a;
213
- if (!this._isMllmMode() || this._agent.instructions === undefined) {
246
+ if (!this._isMllmMode() || this.agent.instructions === undefined) {
214
247
  return;
215
248
  }
216
- const params = (_a = this._agent.mllm) === null || _a === void 0 ? void 0 : _a.params;
249
+ const params = (_a = this.agent.mllm) === null || _a === void 0 ? void 0 : _a.params;
217
250
  if (typeof (params === null || params === void 0 ? void 0 : params.instructions) === "string" && params.instructions.length > 0) {
218
251
  return;
219
252
  }
@@ -230,9 +263,9 @@ export class AgentSession {
230
263
  * @throws {Error} If configuration is invalid
231
264
  */
232
265
  _validateAvatarConfig() {
233
- const agentConfig = this._agent.config;
266
+ const agentConfig = this.agent.config;
234
267
  const avatar = agentConfig.avatar;
235
- const tts = this._agent.tts;
268
+ const tts = this.agent.tts;
236
269
  // Skip validation if no avatar is configured
237
270
  if (!avatar || avatar.enable === false) {
238
271
  return;
@@ -376,13 +409,13 @@ export class AgentSession {
376
409
  }
377
410
  }
378
411
  }
379
- if (inferAsrPreset(this._agent.stt)) {
412
+ if (inferAsrPreset(this.agent.stt)) {
380
413
  skipVendorValidationCategories.add("asr");
381
414
  }
382
- if (inferLlmPreset(this._agent.llm)) {
415
+ if (inferLlmPreset(this.agent.llm)) {
383
416
  skipVendorValidationCategories.add("llm");
384
417
  }
385
- if (inferTtsPreset(this._agent.tts)) {
418
+ if (inferTtsPreset(this.agent.tts)) {
386
419
  skipVendorValidationCategories.add("tts");
387
420
  }
388
421
  return { skipVendorValidationCategories, allowMissingVendorCategories };
@@ -401,6 +434,25 @@ export class AgentSession {
401
434
  if (this._status !== "idle" && this._status !== "stopped" && this._status !== "error") {
402
435
  throw new Error(`Cannot start session in ${this._status} state`);
403
436
  }
437
+ if (this._backend) {
438
+ const lifecycle = this._beginLifecycle();
439
+ this._agentId = null;
440
+ this._status = "starting";
441
+ try {
442
+ const started = yield this._backend.start();
443
+ this._agentId = started.id;
444
+ this._status = started.status;
445
+ this._finishLifecycle(lifecycle);
446
+ this._emit("started", { agentId: this._agentId, sessionId: this._agentId });
447
+ return this._agentId;
448
+ }
449
+ catch (error) {
450
+ this._status = "error";
451
+ this._finishLifecycle(lifecycle);
452
+ this._emit("error", error);
453
+ throw error;
454
+ }
455
+ }
404
456
  // Validate avatar configuration before starting
405
457
  this._validateAvatarConfig();
406
458
  this._warnOnDroppedMllmInstructions();
@@ -411,7 +463,7 @@ export class AgentSession {
411
463
  }
412
464
  this._status = "starting";
413
465
  try {
414
- const pipelineId = (_a = this._pipelineId) !== null && _a !== void 0 ? _a : this._agent.pipelineId;
466
+ const pipelineId = (_a = this._pipelineId) !== null && _a !== void 0 ? _a : this.agent.pipelineId;
415
467
  // appCertificate presence is guaranteed by the guard above when no token is provided.
416
468
  let expiresIn = this._expiresIn;
417
469
  if (expiresIn !== undefined) {
@@ -425,7 +477,7 @@ export class AgentSession {
425
477
  expiresIn,
426
478
  };
427
479
  const { skipVendorValidationCategories, allowMissingVendorCategories } = this._vendorValidationCategories(pipelineId);
428
- const properties = this._agent.toProperties(Object.assign({ channel: this._channel, agentUid: this._agentUid, remoteUids: this._remoteUids, idleTimeout: this._idleTimeout, enableStringUid: this._enableStringUid, skipVendorValidationCategories,
480
+ const properties = this.agent.toProperties(Object.assign({ channel: this._channel, agentUid: this._agentUid, remoteUids: this._remoteUids, idleTimeout: this._idleTimeout, enableStringUid: this._enableStringUid, skipVendorValidationCategories,
429
481
  allowMissingVendorCategories }, tokenOpts));
430
482
  const resolved = resolveSessionPresets({
431
483
  preset: this._preset,
@@ -481,29 +533,47 @@ export class AgentSession {
481
533
  */
482
534
  stop() {
483
535
  return __awaiter(this, void 0, void 0, function* () {
484
- if (this._status !== "running") {
536
+ if (this._status !== "running" && !(this._backend && this._status === "starting")) {
485
537
  throw new Error(`Cannot stop session in ${this._status} state`);
486
538
  }
487
539
  if (!this._agentId) {
488
540
  throw new Error("No agent ID available");
489
541
  }
542
+ const lifecycle = this._backend ? this._beginLifecycle() : undefined;
490
543
  this._status = "stopping";
491
544
  try {
492
- yield this._agentsClient.stop({
493
- appid: this._appId,
494
- agentId: this._agentId,
495
- }, { headers: this._requestHeaders() });
545
+ if (this._backend)
546
+ yield this._backend.stop(this._agentId);
547
+ else
548
+ yield this._agentsClient.stop({
549
+ appid: this._appId,
550
+ agentId: this._agentId,
551
+ }, { headers: this._requestHeaders() });
496
552
  this._status = "stopped";
497
- this._emit("stopped", { agentId: this._agentId });
553
+ this._finishLifecycle(lifecycle);
554
+ this._emit("stopped", Object.assign({ agentId: this._agentId }, (this._backend ? { sessionId: this._agentId } : {})));
498
555
  }
499
556
  catch (error) {
500
557
  // Handle 404 "task not found" gracefully - agent is already stopped
501
- if (error instanceof AgoraError && error.statusCode === 404) {
558
+ if (!this._backend && error instanceof AgoraError && error.statusCode === 404) {
502
559
  this._status = "stopped";
503
- this._emit("stopped", { agentId: this._agentId });
560
+ this._emit("stopped", Object.assign({ agentId: this._agentId }, (this._backend ? { sessionId: this._agentId } : {})));
504
561
  return; // Don't throw - agent is already stopped
505
562
  }
506
- this._status = "error";
563
+ const reason = error instanceof V3Error &&
564
+ error.statusCode === 409 &&
565
+ error.body !== null &&
566
+ typeof error.body === "object" &&
567
+ "reason" in error.body
568
+ ? error.body.reason
569
+ : undefined;
570
+ this._status =
571
+ this._backend && reason === "TaskNotRunning"
572
+ ? "stopped"
573
+ : this._backend && reason === "TaskConflict"
574
+ ? "stopping"
575
+ : "error";
576
+ this._finishLifecycle(lifecycle);
507
577
  this._emit("error", error);
508
578
  throw error;
509
579
  }
@@ -517,6 +587,8 @@ export class AgentSession {
517
587
  */
518
588
  say(text, options) {
519
589
  return __awaiter(this, void 0, void 0, function* () {
590
+ if (this._backend)
591
+ throw new UnsupportedSessionOperationError("say");
520
592
  if (this._status !== "running") {
521
593
  throw new Error(`Cannot say in ${this._status} state`);
522
594
  }
@@ -537,6 +609,8 @@ export class AgentSession {
537
609
  */
538
610
  interrupt() {
539
611
  return __awaiter(this, void 0, void 0, function* () {
612
+ if (this._backend)
613
+ throw new UnsupportedSessionOperationError("interrupt");
540
614
  if (this._status !== "running") {
541
615
  throw new Error(`Cannot interrupt in ${this._status} state`);
542
616
  }
@@ -554,6 +628,8 @@ export class AgentSession {
554
628
  */
555
629
  think(text, options) {
556
630
  return __awaiter(this, void 0, void 0, function* () {
631
+ if (this._backend)
632
+ throw new UnsupportedSessionOperationError("think");
557
633
  if (this._status !== "running") {
558
634
  throw new Error(`Cannot think in ${this._status} state`);
559
635
  }
@@ -579,16 +655,28 @@ export class AgentSession {
579
655
  */
580
656
  update(config) {
581
657
  return __awaiter(this, void 0, void 0, function* () {
658
+ var _a;
582
659
  if (this._status !== "running") {
583
660
  throw new Error(`Cannot update in ${this._status} state`);
584
661
  }
585
662
  if (!this._agentId) {
586
663
  throw new Error("No agent ID available");
587
664
  }
665
+ if (this._backend) {
666
+ yield this._backend.update(this._agentId, config);
667
+ return;
668
+ }
669
+ let properties = config;
670
+ if ((config === null || config === void 0 ? void 0 : config.messages) !== undefined) {
671
+ if (((_a = config.llm) === null || _a === void 0 ? void 0 : _a.system_messages) !== undefined)
672
+ throw new Error("Provide messages or llm.system_messages, not both");
673
+ const { messages } = config, remaining = __rest(config, ["messages"]);
674
+ properties = Object.assign(Object.assign({}, remaining), { llm: Object.assign(Object.assign({}, remaining.llm), { system_messages: messages }) });
675
+ }
588
676
  yield this._agentsClient.update({
589
677
  appid: this._appId,
590
678
  agentId: this._agentId,
591
- properties: config,
679
+ properties,
592
680
  }, { headers: this._requestHeaders() });
593
681
  });
594
682
  }
@@ -599,6 +687,8 @@ export class AgentSession {
599
687
  */
600
688
  getHistory() {
601
689
  return __awaiter(this, void 0, void 0, function* () {
690
+ if (this._backend)
691
+ throw new UnsupportedSessionOperationError("getHistory");
602
692
  if (!this._agentId) {
603
693
  throw new Error("No agent ID available");
604
694
  }
@@ -615,6 +705,8 @@ export class AgentSession {
615
705
  */
616
706
  getTurns(options) {
617
707
  return __awaiter(this, void 0, void 0, function* () {
708
+ if (this._backend)
709
+ throw new UnsupportedSessionOperationError("getTurns");
618
710
  if (!this._agentId) {
619
711
  throw new Error("No agent ID available");
620
712
  }
@@ -635,6 +727,8 @@ export class AgentSession {
635
727
  getAllTurns(options) {
636
728
  return __awaiter(this, void 0, void 0, function* () {
637
729
  var _a, _b, _c, _d, _e, _f, _g, _h;
730
+ if (this._backend)
731
+ throw new UnsupportedSessionOperationError("getAllTurns");
638
732
  let page = yield this.getTurns({ page_index: 1, page_size: options === null || options === void 0 ? void 0 : options.page_size });
639
733
  const allTurns = [...((_a = page.turns) !== null && _a !== void 0 ? _a : [])];
640
734
  let currentPage = (_c = (_b = page.pagination) === null || _b === void 0 ? void 0 : _b.page_index) !== null && _c !== void 0 ? _c : 1;
@@ -675,9 +769,27 @@ export class AgentSession {
675
769
  */
676
770
  getInfo() {
677
771
  return __awaiter(this, void 0, void 0, function* () {
772
+ var _a;
678
773
  if (!this._agentId) {
679
774
  throw new Error("No agent ID available");
680
775
  }
776
+ if (this._backend) {
777
+ const id = this._agentId;
778
+ const lifecycle = this._lifecycleRevision;
779
+ const read = ++this._infoReadRevision;
780
+ const info = yield this._backend.getInfo(id);
781
+ if (this._pendingLifecycle !== undefined ||
782
+ lifecycle !== this._lifecycleRevision ||
783
+ read !== this._infoReadRevision ||
784
+ id !== this._agentId)
785
+ return info;
786
+ const status = (_a = info.status) === null || _a === void 0 ? void 0 : _a.toLowerCase();
787
+ if (status === "failed")
788
+ this._status = "error";
789
+ else if (status && ["idle", "starting", "running", "stopping", "stopped"].includes(status))
790
+ this._status = status;
791
+ return info;
792
+ }
681
793
  return this._agentsClient.get({
682
794
  appid: this._appId,
683
795
  agentId: this._agentId,
@@ -34,9 +34,12 @@ export { createPreviewRoute, PREVIEW_API_BASE_URL, PREVIEW_FEATURE_HEADER, Previ
34
34
  export type { GeminiTTSConfig, GeminiTTSModel, GeminiTTSOptions } from "./preview/gemini-tts.mjs";
35
35
  export { GeminiTTS, GeminiTTSModels } from "./preview/gemini-tts.mjs";
36
36
  export type { AvatarVendor, CNAvatarVendor, CNLlmVendor, CNMllmVendor, CNSttVendor, CNTtsVendor, GlobalAvatarVendor, GlobalLlmVendor, GlobalMllmVendor, GlobalSttVendor, GlobalTtsVendor, LlmVendor, SttVendor, TtsVendor, } from "./region-vendors.mjs";
37
+ export { UnsupportedSessionOperationError } from "./session-backend.mjs";
37
38
  export type { GenerateConvoAITokenOptions, GenerateTokenOptions, } from "./token.mjs";
38
39
  export { ExpiresIn, generateConvoAIToken, generateRtcToken, MAX_EXPIRY_SECONDS, } from "./token.mjs";
39
- export type { AdvancedFeatures, AgentConfig, AgentConfigUpdate, AmazonTts, AmazonTtsParams, AsrConfig, AsrVendorName, AvatarConfig, AvatarWireVendor, CartesiaTts, CartesiaTtsParams, ConversationHistory, ConversationRole, ConversationSessionTurn, ConversationTurn, ConversationTurns, Eagerness, ElevenLabsTts, ElevenLabsTtsParams, EndOfSpeechConfig, EndOfSpeechMode, EndOfSpeechSemanticConfig, EndOfSpeechVadConfig, FarewellConfig, FillerWordsConfig, FillerWordsContent, FillerWordsContentGeneratedConfig, FillerWordsContentSelectionRule, FillerWordsContentStaticConfig, FillerWordsGeneratedLlmProvider, FillerWordsTrigger, FillerWordsTriggerFixedTimeConfig, FishAudioTts, FishAudioTtsParams, GeminiAsrParams, GenericTts, GenericTtsParams, GeofenceArea, GeofenceConfig, GeofenceExcludeArea, GetTurnsOptions, GoogleTts, GoogleTtsParams, GradiumTts, GradiumTtsParams, HumeAiTts, HumeAiTtsParams, InterruptionConfig, InterruptionMode, InterruptMode, Labels, LlmConfig, LlmGreetingConfigs, LlmGreetingConfigsMode, LlmStyle, LlmTool, LlmToolExecution, LlmToolFunction, LlmToolServer, McpServer, McpServersItem, MicrosoftTts, MicrosoftTtsParams, MinimaxTts, MinimaxTtsParams, MistralTts, MistralTtsParams, MllmConfig, MllmTurnDetectionConfig, MllmTurnDetectionMode, MllmVendor, MurfTts, MurfTtsParams, OpenAiTts, OpenAiTtsParams, ParametersAudioScenario, ParametersDataChannel, RimeTts, RimeTtsParams, RtcConfig, SalConfig, SalMode, SarvamTts, SarvamTtsParams, SayOptions, SessionInfo, SessionListResponse, SessionOptions, SessionParams, SessionParamsInput, SessionStatus, SessionSummary, SilenceAction, SilenceConfig, SmallestAiAsr, SmallestAiAsrParams, SmallestAiTts, SmallestAiTtsParams, SpatiusAvatarParams, SpeakPriority, StartOfSpeechConfig, StartOfSpeechDisabledConfig, StartOfSpeechDisabledConfigStrategy, StartOfSpeechKeywordsConfig, StartOfSpeechMode, StartOfSpeechVadConfig, SttConfig, ThinkOnListeningAction, ThinkOnSpeakingAction, ThinkOnThinkingAction, ThinkOptions, ThinkResponse, TtsConfig, TurnDetectionConfig, TurnDetectionLanguage, TurnDetectionNestedConfig, TurnDetectionType, TypecastTts, TypecastTtsParams, XAiAsr, XAiAsrParams, XAiTts, XAiTtsParams, } from "./types.mjs";
40
+ export type { AdvancedFeatures, AgentConfig, AgentConfigUpdate, AmazonTts, AmazonTtsParams, AsrConfig, AsrVendorName, AvatarConfig, AvatarWireVendor, CallOptions, CartesiaTts, CartesiaTtsParams, ConversationHistory, ConversationRole, ConversationSessionTurn, ConversationTurn, ConversationTurns, Eagerness, ElevenLabsTts, ElevenLabsTtsParams, EndOfSpeechConfig, EndOfSpeechMode, EndOfSpeechSemanticConfig, EndOfSpeechVadConfig, FarewellConfig, FillerWordsConfig, FillerWordsContent, FillerWordsContentGeneratedConfig, FillerWordsContentSelectionRule, FillerWordsContentStaticConfig, FillerWordsGeneratedLlmProvider, FillerWordsTrigger, FillerWordsTriggerFixedTimeConfig, FishAudioTts, FishAudioTtsParams, GeminiAsrParams, GenericTts, GenericTtsParams, GeofenceArea, GeofenceConfig, GeofenceExcludeArea, GetTurnsOptions, GoogleTts, GoogleTtsParams, GradiumTts, GradiumTtsParams, HumeAiTts, HumeAiTtsParams, InterruptionConfig, InterruptionMode, InterruptMode, Labels, LlmConfig, LlmGreetingConfigs, LlmGreetingConfigsMode, LlmStyle, LlmTool, LlmToolExecution, LlmToolFunction, LlmToolServer, McpServer, McpServersItem, MicrosoftTts, MicrosoftTtsParams, MinimaxTts, MinimaxTtsParams, MistralTts, MistralTtsParams, MllmConfig, MllmTurnDetectionConfig, MllmTurnDetectionMode, MllmVendor, MurfTts, MurfTtsParams, OpenAiTts, OpenAiTtsParams, ParametersAudioScenario, ParametersDataChannel, RimeTts, RimeTtsParams, RtcConfig, SalConfig, SalMode, SarvamTts, SarvamTtsParams, SayOptions, SessionInfo, SessionListResponse, SessionOptions, SessionParams, SessionParamsInput, SessionStatus, SessionSummary, SilenceAction, SilenceConfig, SmallestAiAsr, SmallestAiAsrParams, SmallestAiTts, SmallestAiTtsParams, SpatiusAvatarParams, SpeakPriority, StartOfSpeechConfig, StartOfSpeechDisabledConfig, StartOfSpeechDisabledConfigStrategy, StartOfSpeechKeywordsConfig, StartOfSpeechMode, StartOfSpeechVadConfig, SttConfig, ThinkOnListeningAction, ThinkOnSpeakingAction, ThinkOnThinkingAction, ThinkOptions, ThinkResponse, TtsConfig, TurnDetectionConfig, TurnDetectionLanguage, TurnDetectionNestedConfig, TurnDetectionType, TypecastTts, TypecastTtsParams, XAiAsr, XAiAsrParams, XAiTts, XAiTtsParams, } from "./types.mjs";
41
+ export type { AssignNumberOptions, DeployOptions, SaveOptions, SecretRef, VariableDefinition } from "./v3.mjs";
42
+ export { DeployedAgent, NumberNotFoundError, SavedAgent, SecretRefNotSupportedError, secretRef, UnsupportedFieldError, } from "./v3.mjs";
40
43
  export type { AkoolAvatarOptions, AnamAvatarOptions, GenericAvatarOptions, HeyGenAvatarOptions, LemonSliceOptions, LiveAvatarAvatarOptions, ProtofaceOptions, TavusOptions, } from "./vendors/avatar.mjs";
41
44
  export { AkoolAvatar, AnamAvatar, GenericAvatar, HeyGenAvatar, LemonSlice, LiveAvatarAvatar, Protoface, Tavus, } from "./vendors/avatar.mjs";
42
45
  export type { AkoolSampleRate, CartesiaSampleRate, ElevenLabsSampleRate, HeyGenSampleRate, LiveAvatarSampleRate, MicrosoftSampleRate, SampleRate, } from "./vendors/base.mjs";
@@ -28,8 +28,10 @@ export { REDACTED, redactHeadersForDebug, redactSecrets } from "./debug.mjs";
28
28
  export { AgentPresets, normalizePresetInput } from "./presets.mjs";
29
29
  export { createPreviewRoute, PREVIEW_API_BASE_URL, PREVIEW_FEATURE_HEADER, PreviewFeatures, previewRequestHeaders, requiredPreviewFeatures, } from "./preview/client.mjs";
30
30
  export { GeminiTTS, GeminiTTSModels } from "./preview/gemini-tts.mjs";
31
+ export { UnsupportedSessionOperationError } from "./session-backend.mjs";
31
32
  // Token generation
32
33
  export { ExpiresIn, generateConvoAIToken, generateRtcToken, MAX_EXPIRY_SECONDS, } from "./token.mjs";
34
+ export { DeployedAgent, NumberNotFoundError, SavedAgent, SecretRefNotSupportedError, secretRef, UnsupportedFieldError, } from "./v3.mjs";
33
35
  // Avatar vendor classes
34
36
  export { AkoolAvatar, AnamAvatar, GenericAvatar, HeyGenAvatar, LemonSlice, LiveAvatarAvatar, Protoface, Tavus, } from "./vendors/avatar.mjs";
35
37
  // Base vendor classes
@@ -0,0 +1,25 @@
1
+ /** Internal adapter for session identities, without mixing them with running-agent IDs. */
2
+ import type { AgoraClient } from "../AgoraPoolClient.mjs";
3
+ import type { AgentCreateRequest, TelephonyTransport } from "../v3/types.mjs";
4
+ import type { Agent } from "./Agent.mjs";
5
+ import { AgentSession } from "./AgentSession.mjs";
6
+ import type { AgentConfigUpdate, CallOptions, SessionInfo, SessionOptions } from "./types.mjs";
7
+ export interface SessionBackend {
8
+ start(): Promise<{
9
+ id: string;
10
+ status: "starting" | "running";
11
+ }>;
12
+ stop(id: string): Promise<void>;
13
+ update(id: string, config: AgentConfigUpdate): Promise<void>;
14
+ getInfo(id: string): Promise<SessionInfo>;
15
+ }
16
+ export declare class UnsupportedSessionOperationError extends Error {
17
+ constructor(operation: string);
18
+ }
19
+ /** Validate mixed transports before replacing internal RTC placeholders. */
20
+ export declare function callSessionOptions(options: CallOptions): SessionOptions;
21
+ export declare function createStoredSession(client: AgoraClient, options: SessionOptions, source: {
22
+ agent_id: string;
23
+ } | {
24
+ agent: Omit<AgentCreateRequest, "agent_name">;
25
+ }, config?: Agent, telephony?: TelephonyTransport): AgentSession;
@@ -0,0 +1,191 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { validateSessionStart } from "../v3/session-lifecycle.mjs";
11
+ import { AgentSession } from "./AgentSession.mjs";
12
+ import { ExpiresIn, generateConvoAIToken, generateRtcTokenWithAccount } from "./token.mjs";
13
+ export class UnsupportedSessionOperationError extends Error {
14
+ constructor(operation) {
15
+ super(`${operation} is not supported by this session backend; start, stop, getInfo and update are available`);
16
+ this.name = "UnsupportedSessionOperationError";
17
+ }
18
+ }
19
+ /** Validate mixed transports before replacing internal RTC placeholders. */
20
+ export function callSessionOptions(options) {
21
+ for (const key of [
22
+ "channel",
23
+ "remoteUids",
24
+ "agentUid",
25
+ "token",
26
+ "encryption",
27
+ "audioScenario",
28
+ "geofence",
29
+ "enableStringUid",
30
+ "expiresIn",
31
+ ]) {
32
+ if (options[key] !== undefined)
33
+ throw new Error(`Phone calls do not accept RTC option ${key}`);
34
+ }
35
+ return Object.assign(Object.assign({}, options), { channel: "", remoteUids: [] });
36
+ }
37
+ export function createStoredSession(client, options, source, config, telephony) {
38
+ var _a, _b;
39
+ for (const key of ["clientReference", "client_reference", "enableStringUid", "preset", "pipelineId"]) {
40
+ if (key in options && options[key] !== undefined)
41
+ throw new Error(`${key} is not supported by this session backend`);
42
+ }
43
+ const lifecycle = {};
44
+ for (const [key, wire] of [
45
+ ["idleTimeout", "idle_timeout_ms"],
46
+ ["maxDuration", "max_duration_ms"],
47
+ ]) {
48
+ if (options[key] !== undefined)
49
+ lifecycle[wire] = options[key] * 1000;
50
+ }
51
+ if (options.gracefulStop !== undefined)
52
+ lifecycle.graceful_stop = options.gracefulStop;
53
+ const payload = JSON.parse(JSON.stringify(Object.assign(Object.assign(Object.assign({}, source), { values: options.values, idempotencyKey: options.idempotencyKey, data_policy: options.dataPolicy, labels: options.labels, transport: telephony !== null && telephony !== void 0 ? telephony : {
54
+ type: "rtc",
55
+ channel: options.channel,
56
+ uid: options.agentUid,
57
+ subscribe_uids: options.remoteUids,
58
+ token: options.token,
59
+ encryption: options.encryption,
60
+ audio_scenario: options.audioScenario,
61
+ geofence: options.geofence,
62
+ } }), (Object.keys(lifecycle).length ? { lifecycle } : {}))));
63
+ validateSessionStart(payload);
64
+ if (options.expiresIn !== undefined &&
65
+ (!Number.isInteger(options.expiresIn) || !Number.isFinite(options.expiresIn)))
66
+ throw new Error("expiresIn must be a whole number of seconds");
67
+ if (telephony &&
68
+ [options.agentUid, options.token, options.encryption, options.audioScenario, options.geofence].some((value) => value !== undefined))
69
+ throw new Error("RTC options are not supported for phone calls");
70
+ const expiry = options.expiresIn === undefined ? undefined : ExpiresIn.seconds(options.expiresIn);
71
+ const signing = !telephony &&
72
+ options.token === undefined &&
73
+ client.appCertificate &&
74
+ options.agentUid !== undefined &&
75
+ !/^0+$/.test(options.agentUid)
76
+ ? {
77
+ appId: client.appId,
78
+ appCertificate: client.appCertificate,
79
+ channel: options.channel,
80
+ uid: options.agentUid,
81
+ }
82
+ : undefined;
83
+ let successfullyStarted = false;
84
+ const backend = {
85
+ start() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ if (payload.idempotencyKey && successfullyStarted)
88
+ throw new Error("This idempotency key already started a session; create a new handle with a new key for another session");
89
+ if (successfullyStarted && !payload.idempotencyKey) {
90
+ // A new unkeyed session needs a fresh token. Failed starts retain
91
+ // their request snapshot, and keyed starts cannot be reused.
92
+ if (signing)
93
+ delete payload.transport.token;
94
+ successfullyStarted = false;
95
+ }
96
+ if (signing &&
97
+ payload.transport.token === undefined &&
98
+ (!/^\d+$/.test(signing.uid) ||
99
+ (Number.isSafeInteger(Number(signing.uid)) && Number(signing.uid) <= 4294967295))) {
100
+ // Larger numeric identities remain opaque; the service provisions
101
+ // their token instead of coercing them through the local signer.
102
+ payload.transport.token = /^\d+$/.test(signing.uid)
103
+ ? generateConvoAIToken({
104
+ appId: signing.appId,
105
+ appCertificate: signing.appCertificate,
106
+ channelName: signing.channel,
107
+ uid: Number(signing.uid),
108
+ tokenExpire: expiry,
109
+ })
110
+ : generateRtcTokenWithAccount({
111
+ appId: signing.appId,
112
+ appCertificate: signing.appCertificate,
113
+ channel: signing.channel,
114
+ account: signing.uid,
115
+ expirySeconds: expiry,
116
+ });
117
+ }
118
+ const result = "agent_id" in payload
119
+ ? yield client.v3.sessions.start(payload)
120
+ : yield client.v3.sessions.startEphemeral(payload);
121
+ if (typeof result.agent_session_id !== "string" || !result.agent_session_id.trim()) {
122
+ throw new Error("Session start response is missing agent_session_id");
123
+ }
124
+ successfullyStarted = true;
125
+ return { id: result.agent_session_id, status: result.status === "STARTING" ? "starting" : "running" };
126
+ });
127
+ },
128
+ stop(id) {
129
+ return __awaiter(this, void 0, void 0, function* () {
130
+ yield client.v3.sessions.stop({ agentSessionId: id });
131
+ });
132
+ },
133
+ update(id, config) {
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ var _a, _b, _c;
136
+ const input = config;
137
+ if (!input || typeof input !== "object" || Array.isArray(input))
138
+ throw new Error("Invalid session update");
139
+ for (const key of Object.keys(input))
140
+ if (!["token", "messages", "llm"].includes(key))
141
+ throw new Error(`Unsupported session update field: ${key}`);
142
+ if (input.messages !== undefined && ((_a = input.llm) === null || _a === void 0 ? void 0 : _a.system_messages) !== undefined)
143
+ throw new Error("Provide messages or llm.system_messages, not both");
144
+ const patch = {};
145
+ if (input.token !== undefined) {
146
+ if (typeof input.token !== "string" || !input.token)
147
+ throw new Error("token must be a string");
148
+ patch.transport = { token: input.token };
149
+ }
150
+ const overrides = {};
151
+ const messages = (_b = input.messages) !== null && _b !== void 0 ? _b : (_c = input.llm) === null || _c === void 0 ? void 0 : _c.system_messages;
152
+ if (messages !== undefined) {
153
+ if (!Array.isArray(messages) ||
154
+ messages.some((message) => !message ||
155
+ !["system", "user", "assistant"].includes(message.role) ||
156
+ typeof message.content !== "string" ||
157
+ Object.keys(message).some((key) => !["role", "content"].includes(key))))
158
+ throw new Error("Invalid session messages");
159
+ overrides.messages = messages;
160
+ }
161
+ for (const kind of ["llm"])
162
+ if (input[kind] !== undefined) {
163
+ const module = input[kind];
164
+ if (!module ||
165
+ typeof module !== "object" ||
166
+ Array.isArray(module) ||
167
+ Object.keys(module).some((key) => !["params", ...(kind === "llm" ? ["system_messages"] : [])].includes(key)))
168
+ throw new Error(`Invalid ${kind} update`);
169
+ if (module.params !== undefined) {
170
+ if (!module.params || typeof module.params !== "object" || Array.isArray(module.params))
171
+ throw new Error("params must be an object");
172
+ if (Object.keys(module.params).some((key) => ["url", "base_url", "api_base_url", "endpoint"].includes(key.toLowerCase())))
173
+ throw new Error("Runtime endpoint aliases are not mutable");
174
+ overrides.pipeline = { [kind]: { params: module.params } };
175
+ }
176
+ }
177
+ if (Object.keys(overrides).length)
178
+ patch.agent = { overrides };
179
+ yield client.v3.sessions.update(Object.assign({ agentSessionId: id }, patch));
180
+ });
181
+ },
182
+ getInfo(id) {
183
+ return __awaiter(this, void 0, void 0, function* () {
184
+ var _a, _b;
185
+ const info = yield client.v3.sessions.get({ agentSessionId: id });
186
+ return Object.assign(Object.assign({}, info), { message: (_a = info.message) !== null && _a !== void 0 ? _a : undefined, stop_ts: (_b = info.stop_ts) !== null && _b !== void 0 ? _b : undefined });
187
+ });
188
+ },
189
+ };
190
+ return new AgentSession(Object.assign(Object.assign({ client, agent: config, backend, appId: client.appId, name: (_a = options.name) !== null && _a !== void 0 ? _a : "session" }, options), { agentUid: (_b = options.agentUid) !== null && _b !== void 0 ? _b : "0" }));
191
+ }
@@ -235,17 +235,29 @@ export type McpServersItem = McpServer & Record<string, unknown>;
235
235
  /** Full agent configuration (alias for StartAgentsRequest.Properties) */
236
236
  export type AgentConfig = StartAgentsRequest.Properties;
237
237
  /** Agent configuration update (for runtime updates) */
238
- export type AgentConfigUpdate = UpdateAgentsRequest.Properties;
238
+ export type AgentConfigUpdate = UpdateAgentsRequest.Properties & {
239
+ messages?: import("../v3/types.mjs").Message[];
240
+ };
239
241
  /** Options for creating a session via {@link Agent.createSession} */
240
242
  export interface SessionOptions {
243
+ /** Runtime values for declared template variables; selects ephemeral startup for inline builders. */
244
+ values?: Record<string, string | number | boolean>;
245
+ idempotencyKey?: string;
246
+ labels?: Record<string, string>;
247
+ maxDuration?: number;
248
+ encryption?: import("../v3/session-schema.mjs").RtcEncryption;
249
+ audioScenario?: "aiserver" | "chorus";
250
+ geofence?: import("../v3/session-lifecycle.mjs").SessionGeofence;
251
+ gracefulStop?: import("../v3/session-schema.mjs").GracefulStop;
252
+ dataPolicy?: import("../v3/session-schema.mjs").DataPolicy;
241
253
  /** Unique agent instance name sent to the Agora API. Omit to auto-generate `agent-{timestamp}`. */
242
254
  name?: string;
243
255
  /** The channel to join */
244
256
  channel: string;
245
257
  /** Authentication token for the channel. Omit to auto-generate (requires appCertificate on the session). */
246
258
  token?: string;
247
- /** The agent's RTC UID */
248
- agentUid: string;
259
+ /** The agent's RTC UID. Omit for server auto-assignment (legacy inline sessions use 0). */
260
+ agentUid?: string;
249
261
  /** Remote user UIDs to subscribe to */
250
262
  remoteUids: string[];
251
263
  /** Idle timeout in seconds (0 = no auto-exit) */
@@ -267,10 +279,21 @@ export interface SessionOptions {
267
279
  /** Optional warning logger. Defaults to console.warn. Set to a no-op to silence warnings. */
268
280
  warn?: (message: string) => void;
269
281
  }
282
+ /** Outbound telephony options; from is a registered number ID, to is an E.164 number. */
283
+ export type CallOptions = Pick<SessionOptions, "name" | "values" | "idempotencyKey" | "labels" | "maxDuration" | "idleTimeout" | "gracefulStop" | "dataPolicy" | "debug" | "warn"> & {
284
+ from: string;
285
+ to: string;
286
+ callPolicy?: import("../v3/types.mjs").CallPolicy;
287
+ };
270
288
  /** Session status */
271
289
  export type SessionStatus = ListAgentsResponse.Data.List.Item.Status;
272
290
  /** Session info (from get endpoint) */
273
- export type SessionInfo = GetAgentsResponse;
291
+ export type SessionInfo = GetAgentsResponse & {
292
+ agent_session_id?: string;
293
+ agent_name?: string;
294
+ /** Extraction analysis, when returned by the service. */
295
+ analysis?: import("../v3/types.mjs").SessionAnalysis | null;
296
+ };
274
297
  /** Session list response */
275
298
  export type SessionListResponse = ListAgentsResponse;
276
299
  /** Session summary (list item) */