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
package/README.md CHANGED
@@ -7,10 +7,18 @@
7
7
 
8
8
  The Agora Agents SDK for TypeScript lets you build real-time voice agents on Agora Conversational AI with a high-level `Agent` / `AgentSession` API and a generated REST client.
9
9
 
10
+ ## Configure once, then run or save
11
+
12
+ `Agent` is the configuration builder. Choose `config.createSession(...).start()` for a running conversation, or `await config.save({name})` for a `SavedAgent`. Continue with the returned session or saved handle: `saved.update(revisedConfig)`, `assignNumber()`, `unassignNumber()`, `listNumbers()`, and `delete()`.
13
+
14
+ **Saving agents and project provisioning are part of SDK preview `3.0.0-alpha.2`.** Existing session behavior is unchanged. Use `client.secrets` and `secretRef()` for stored credentials, `withVariable()` for template/extraction definitions, and `client.numbers` to register numbers. Number listing scans project pages and filters assignments locally. `client.campaigns` provides typed campaign creation, reads, updates, pause/resume/cancel, and deletion.
15
+
16
+ Start with [Saving agents](docs/guides/saved-agents.md). Use `saved.createSession(...).start()` to run a saved configuration. Builders with secret references or variable definitions automatically start an ephemeral session without saving first. These sessions support values, labels, optional RTC token/encryption, retention, graceful stop, start, stop, and get-info. Runtime updates support RTC token, messages, and complete model params replacement; conversation actions remain unavailable. The public client uses token authentication and the public preview origin; no internal gateway headers are needed. Advanced users can access 32 operations, ETags, raw headers, pagination, and project session reads and start/stop/update through the [transport reference](docs/reference/v3.md). [Staging setup and mapping limits](docs/guides/v3-preview.md) remain documented separately.
17
+
10
18
  ## Installation
11
19
 
12
20
  ```sh
13
- npm install agora-agents
21
+ npm install agora-agents@3.0.0-alpha.2
14
22
  ```
15
23
 
16
24
  ## Quick Start
@@ -208,6 +216,9 @@ If you want to bring your own vendor credentials instead of using Agora-managed
208
216
 
209
217
  ## MLLM (Realtime / Multimodal)
210
218
 
219
+ MLLM is supported for existing inline sessions. Saved agents and ephemeral preview sessions support cascaded pipelines only; saving an MLLM configuration or using preview-only session options with it fails before HTTP.
220
+
221
+
211
222
  Use `withMllm()` for OpenAI Realtime, Gemini Live, Vertex AI, or xAI Grok — no STT, LLM, or TTS vendor needed. MLLM mode is enabled automatically.
212
223
 
213
224
  ```typescript
@@ -228,15 +239,30 @@ const agent = new Agent({ client }).withMllm(
228
239
  );
229
240
  ```
230
241
 
242
+ For Gemini 3.8 Live Extended Thinking, use the same single `GeminiLive` class as the regular Live model:
243
+
244
+ ```typescript
245
+ import { GeminiLive } from 'agora-agents';
246
+
247
+ const geminiAgent = new Agent({ client }).withMllm(new GeminiLive({
248
+ apiKey: process.env.GOOGLE_API_KEY!,
249
+ model: 'models/gemini-3.8-live-extended-thinking',
250
+ thinkingLevel: 'medium',
251
+ greetingMessage: 'Hello! Ready to chat.',
252
+ }));
253
+ ```
254
+
255
+ Use `models/gemini-3.8-live` without `thinkingLevel` for the lower-latency model. Gemini sessions use the preview gateway and `agora-feature: gemini-live`; the Google key is sent as `mllm.api_key`. See the [Preview Endpoint guide](./docs/guides/preview-endpoint.md).
256
+
231
257
  See the [MLLM Flow guide](./docs/guides/mllm-flow.md) for full examples with Gemini Live, Vertex AI, and xAI Grok.
232
258
 
233
259
  > Avatars are not supported with MLLM. The avatar publisher requires the cascading ASR + LLM + TTS pipeline; combining `withMllm()` with `withAvatar()` throws at `Agent.toProperties()` and `AgentSession.start()`.
234
260
 
235
261
  ## Avatars
236
262
 
237
- AgentKit supports LiveAvatar, Generic Avatar, Anam, Akool, SenseTime (CN), and deprecated HeyGen. Avatar `agoraToken` is optional: when omitted, `session.start()` generates a token using the same ConvoAI token format as the agent token, scoped to the avatar `agoraUid`. Avatars require the cascading ASR + LLM + TTS pipeline (not MLLM).
263
+ AgentKit supports LiveAvatar, Generic Avatar (including Tavus, Protoface, and LemonSlice), Anam, Akool, SenseTime (CN), and deprecated HeyGen. Avatar `agoraToken` is optional: when omitted, `session.start()` generates a token using the same ConvoAI token format as the agent token, scoped to the avatar `agoraUid`. Avatars require the cascading ASR + LLM + TTS pipeline (not MLLM).
238
264
 
239
- See the [Avatar Integration guide](./docs/guides/avatars.md) for sample-rate requirements and Generic Avatar setup.
265
+ See the [Avatar Integration guide](./docs/guides/avatars.md) for sample-rate requirements, provider URL defaults, LemonSlice image/agent selectors and aspect ratios, and Generic Avatar setup.
240
266
 
241
267
  ## Documentation
242
268
 
@@ -246,8 +272,17 @@ See the [Avatar Integration guide](./docs/guides/avatars.md) for sample-rate req
246
272
  - [BYOK Guide](./docs/guides/byok.md)
247
273
  - [MLLM Flow](./docs/guides/mllm-flow.md)
248
274
  - [Low-Level API](./docs/guides/low-level-api.md)
275
+ - [Saving agents](./docs/guides/saved-agents.md)
276
+ - [v3 Preview Guide](./docs/guides/v3-preview.md)
277
+ - [v3 Preview Reference](./docs/reference/v3.md)
249
278
 
250
279
  ## Reference
251
280
 
252
281
  - [SDK Reference](./reference.md)
253
282
  - [Agora Conversational AI Docs](https://docs.agora.io/en/conversational-ai/overview)
283
+
284
+ ### Installing a preview checkout
285
+
286
+ The v3 alpha preview is distributed separately from stable 2.x packages. This checkout targets `3.0.0-alpha.2`. Git installs run `prepare` to build importable CommonJS/ESM output; lifecycle scripts and development dependencies must be enabled. To build a checkout on Windows, PowerShell, Command Prompt, macOS, or Linux, run `npm install` then `npm run build` (the clean step uses Node).
287
+
288
+ Use `agent.createEphemeralSession(options)` to explicitly start an unsaved Platform configuration. Use `agent.call(options)` or `saved.call(options)` for an outbound phone session, then call `start()` on the returned handle.
@@ -1,47 +1,39 @@
1
+ import { V3Client, type V3Options } from "./v3/index.js";
1
2
  import type { AgoraArea } from "./agentkit/area.js";
2
3
  import type { BaseClientOptions, BaseRequestOptions } from "./BaseClient.js";
3
4
  import { AgoraClient as BaseAgoraClient } from "./Client.js";
4
5
  import { Pool } from "./core/domain/index.js";
5
6
  /**
6
7
  * Auth mode for the client:
7
- * - `basic`: Customer ID + Secret for REST API (HTTP Basic Auth)
8
8
  * - `token`: Pre-built `agora token=<value>` auth header
9
9
  * - `app-credentials`: appId + appCertificate only; AgentSession generates
10
10
  * a fresh ConvoAI token per API call
11
11
  */
12
- export type AgoraAuthMode = "basic" | "token" | "app-credentials";
12
+ export type AgoraAuthMode = "token" | "app-credentials";
13
13
  export declare namespace AgoraClient {
14
14
  type Options<TArea extends AgoraArea = AgoraArea> = BaseOptions<TArea> & AuthOptions;
15
15
  interface BaseOptions<TArea extends AgoraArea = AgoraArea> extends Omit<BaseClientOptions, "baseUrl" | "environment" | "username" | "password" | "authorization"> {
16
16
  /** The area to use for regional URL selection */
17
17
  area: TArea;
18
+ /** Optional public origin override; baseUrl is a host, without the API prefix. */
19
+ v3?: V3Options;
18
20
  /** Agora App ID — used as the `appid` path parameter and for RTC token generation */
19
21
  appId: string;
20
- /** Agora App Certificate — used to sign RTC tokens. Keep this secret. */
21
- appCertificate: string;
22
- }
23
- /** Use Customer ID + Secret for REST API authentication (HTTP Basic Auth) */
24
- interface BasicAuthOptions {
25
- customerId: string;
26
- customerSecret: string;
27
- authToken?: never;
28
22
  }
29
23
  /** Use a pre-built Agora token for REST API authentication. Pass the raw token; the SDK sets `Authorization: agora token=<authToken>` automatically. */
30
24
  interface TokenAuthOptions {
25
+ appCertificate?: string;
31
26
  authToken: string;
32
- customerId?: never;
33
- customerSecret?: never;
34
27
  }
35
28
  /**
36
29
  * Use only appId + appCertificate. AgentSession generates a fresh
37
30
  * ConvoAI token per API call — no Customer Secret required.
38
31
  */
39
32
  interface AppCredentialsOptions {
40
- customerId?: never;
41
- customerSecret?: never;
33
+ appCertificate: string;
42
34
  authToken?: never;
43
35
  }
44
- type AuthOptions = BasicAuthOptions | TokenAuthOptions | AppCredentialsOptions;
36
+ type AuthOptions = TokenAuthOptions | AppCredentialsOptions;
45
37
  interface RequestOptions extends BaseRequestOptions {
46
38
  }
47
39
  }
@@ -49,7 +41,7 @@ export declare namespace AgoraClient {
49
41
  * AgoraClient extends the base client with domain pool support for
50
42
  * regional URL cycling and automatic domain selection.
51
43
  *
52
- * Three authentication modes are supported:
44
+ * Two authentication modes are supported:
53
45
  *
54
46
  * **App credentials (recommended)** — no Customer Secret needed; AgentSession
55
47
  * generates a short-lived ConvoAI token per API call:
@@ -71,23 +63,19 @@ export declare namespace AgoraClient {
71
63
  * });
72
64
  * ```
73
65
  *
74
- * **Basic auth** — Customer ID + Secret from Agora Console:
75
- * ```typescript
76
- * const client = new AgoraClient({
77
- * area: Area.US,
78
- * appId: "your-app-id",
79
- * appCertificate: "your-app-certificate",
80
- * customerId: "your-customer-id",
81
- * customerSecret: "your-customer-secret",
82
- * });
83
- * ```
84
66
  */
85
67
  export declare class AgoraClient<TArea extends AgoraArea = AgoraArea> extends BaseAgoraClient {
86
68
  protected readonly _pool: Pool;
69
+ readonly v3: V3Client;
70
+ get campaigns(): V3Client["campaigns"];
71
+ /** Project secrets shared with the advanced resource client. */
72
+ get secrets(): V3Client["secrets"];
73
+ /** Registered project numbers shared with the advanced resource client. */
74
+ get numbers(): V3Client["numbers"];
87
75
  /** Agora App ID */
88
76
  readonly appId: string;
89
77
  /** Agora App Certificate (used for RTC token signing) */
90
- readonly appCertificate: string;
78
+ readonly appCertificate: string | undefined;
91
79
  /** The active authentication mode */
92
80
  readonly authMode: AgoraAuthMode;
93
81
  /** The configured routing area */
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- // This file was auto-generated by Fern from our API Definition.
3
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -22,10 +21,12 @@ var __rest = (this && this.__rest) || function (s, e) {
22
21
  };
23
22
  Object.defineProperty(exports, "__esModule", { value: true });
24
23
  exports.AgoraClient = void 0;
24
+ const index_js_1 = require("./v3/index.js");
25
25
  const token_js_1 = require("./agentkit/token.js");
26
26
  const Client_js_1 = require("./Client.js");
27
- const index_js_1 = require("./core/domain/index.js");
28
- const index_js_2 = require("./errors/index.js");
27
+ const index_js_2 = require("./core/domain/index.js");
28
+ const publicHeaders_js_1 = require("./core/publicHeaders.js");
29
+ const index_js_3 = require("./errors/index.js");
29
30
  const API_BASE_URL_ENV = "AGORA_AGENTS_API_BASE_URL";
30
31
  function getConfiguredApiBaseUrl() {
31
32
  var _a;
@@ -41,11 +42,11 @@ function buildApiUrl(baseUrl, area) {
41
42
  const message = error instanceof Error ? error.message : String(error);
42
43
  throw new Error(`invalid ${API_BASE_URL_ENV}: ${message}`);
43
44
  }
44
- const apiPath = area === index_js_1.Area.CN ? index_js_1.CNAPIPath : index_js_1.GlobalAPIPath;
45
+ const apiPath = area === index_js_2.Area.CN ? index_js_2.CNAPIPath : index_js_2.GlobalAPIPath;
45
46
  parsedUrl.pathname = `${parsedUrl.pathname.replace(/\/+$/, "")}${apiPath}`;
46
47
  return parsedUrl.toString();
47
48
  }
48
- class ConfiguredBaseUrlPool extends index_js_1.Pool {
49
+ class ConfiguredBaseUrlPool extends index_js_2.Pool {
49
50
  constructor(area, configuredBaseUrl) {
50
51
  super(area);
51
52
  this.configuredBaseUrl = configuredBaseUrl;
@@ -62,13 +63,13 @@ class ConfiguredBaseUrlPool extends index_js_1.Pool {
62
63
  }
63
64
  function createClientPool(area) {
64
65
  const configuredBaseUrl = getConfiguredApiBaseUrl();
65
- return configuredBaseUrl ? new ConfiguredBaseUrlPool(area, buildApiUrl(configuredBaseUrl, area)) : new index_js_1.Pool(area);
66
+ return configuredBaseUrl ? new ConfiguredBaseUrlPool(area, buildApiUrl(configuredBaseUrl, area)) : new index_js_2.Pool(area);
66
67
  }
67
68
  /**
68
69
  * AgoraClient extends the base client with domain pool support for
69
70
  * regional URL cycling and automatic domain selection.
70
71
  *
71
- * Three authentication modes are supported:
72
+ * Two authentication modes are supported:
72
73
  *
73
74
  * **App credentials (recommended)** — no Customer Secret needed; AgentSession
74
75
  * generates a short-lived ConvoAI token per API call:
@@ -90,60 +91,80 @@ function createClientPool(area) {
90
91
  * });
91
92
  * ```
92
93
  *
93
- * **Basic auth** — Customer ID + Secret from Agora Console:
94
- * ```typescript
95
- * const client = new AgoraClient({
96
- * area: Area.US,
97
- * appId: "your-app-id",
98
- * appCertificate: "your-app-certificate",
99
- * customerId: "your-customer-id",
100
- * customerSecret: "your-customer-secret",
101
- * });
102
- * ```
103
94
  */
104
95
  class AgoraClient extends Client_js_1.AgoraClient {
96
+ get campaigns() {
97
+ return this.v3.campaigns;
98
+ }
99
+ /** Project secrets shared with the advanced resource client. */
100
+ get secrets() {
101
+ return this.v3.secrets;
102
+ }
103
+ /** Registered project numbers shared with the advanced resource client. */
104
+ get numbers() {
105
+ return this.v3.numbers;
106
+ }
105
107
  constructor(options) {
108
+ var _a, _b, _c, _d;
106
109
  const pool = createClientPool(options.area);
107
- let authMode;
108
- let username;
109
- let password;
110
- let authToken = "";
111
- const opts = options;
112
- if (opts.customerId != null && opts.customerSecret != null) {
113
- authMode = "basic";
114
- username = opts.customerId;
115
- password = opts.customerSecret;
116
- }
117
- else if (opts.customerId != null) {
118
- throw new Error("customerSecret is required when customerId is provided");
119
- }
120
- else if (opts.authToken != null) {
121
- authMode = "token";
122
- authToken = opts.authToken;
123
- username = "";
124
- password = "";
125
- }
126
- else {
127
- authMode = "app-credentials";
128
- username = "";
129
- password = "";
110
+ for (const key of Object.keys(options)) {
111
+ if ([
112
+ "customerid",
113
+ "customersecret",
114
+ "clientid",
115
+ "clientsecret",
116
+ "username",
117
+ "password",
118
+ "authorization",
119
+ ].includes(key.replace(/_/g, "").toLowerCase())) {
120
+ throw new Error(`${key} is not supported; use appId/appCertificate or authToken`);
121
+ }
130
122
  }
131
- const { customerId: _cid, customerSecret: _cs, authToken: _at } = opts, rest = __rest(opts, ["customerId", "customerSecret", "authToken"]);
132
- // _getCustomAuthorizationHeaders() in the generated client spreads { Authorization }
133
- // after _getAuthorizationHeader(), so it overrides the Basic header on every request.
134
- const authorization = authMode === "basic"
135
- ? `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`
136
- : authMode === "token"
137
- ? `agora token=${authToken}`
138
- : "";
139
- super(Object.assign(Object.assign({}, rest), { username,
140
- password,
141
- authorization, baseUrl: () => pool.getCurrentURL() }));
123
+ const authMode = options.authToken !== undefined ? "token" : "app-credentials";
124
+ const { authToken, appId, appCertificate } = options, rest = __rest(options, ["authToken", "appId", "appCertificate"]);
125
+ if (authMode === "app-credentials" && !appCertificate)
126
+ throw new Error("appCertificate or authToken is required");
127
+ const authorization = () => authMode === "token"
128
+ ? `agora token=${authToken}`
129
+ : `agora token=${(0, token_js_1.generateConvoAIToken)({ appId, appCertificate: appCertificate, channelName: "", uid: 0 })}`;
130
+ const originalFetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;
131
+ const tokenOnlyFetch = (input, init) => __awaiter(this, void 0, void 0, function* () {
132
+ const finalHeaders = new Headers(input instanceof Request ? input.headers : undefined);
133
+ new Headers(init === null || init === void 0 ? void 0 : init.headers).forEach((value, key) => finalHeaders.set(key, value));
134
+ const auth = finalHeaders.get("authorization");
135
+ if (auth !== null && !/^agora token=\S+$/i.test(auth))
136
+ throw new Error("Only Agora token authorization is supported");
137
+ for (const name of finalHeaders.keys())
138
+ if ((0, publicHeaders_js_1.isInternalHeader)(name))
139
+ throw new Error(`${name} is an internal header and is not supported`);
140
+ return originalFetch(input, init);
141
+ });
142
+ super(Object.assign(Object.assign({}, rest), { fetch: tokenOnlyFetch, username: "", password: "", authorization, baseUrl: () => pool.getCurrentURL() }));
142
143
  this._pool = pool;
143
- this.appId = options.appId;
144
- this.appCertificate = options.appCertificate;
144
+ this.appId = appId;
145
+ this.appCertificate = appCertificate;
145
146
  this.authMode = authMode;
146
147
  this.area = options.area;
148
+ const v3Base = (_c = (_b = options.v3) === null || _b === void 0 ? void 0 : _b.baseUrl) !== null && _c !== void 0 ? _c : process.env.AGORA_AGENTS_V3_BASE_URL;
149
+ if (v3Base !== undefined) {
150
+ let origin;
151
+ try {
152
+ origin = new URL(v3Base);
153
+ }
154
+ catch (_e) {
155
+ throw new Error("v3.baseUrl must be an HTTP(S) origin");
156
+ }
157
+ if (!["http:", "https:"].includes(origin.protocol) ||
158
+ origin.username ||
159
+ origin.password ||
160
+ origin.pathname !== "/" ||
161
+ origin.search ||
162
+ origin.hash ||
163
+ v3Base.includes("?") ||
164
+ v3Base.includes("#"))
165
+ throw new Error("v3.baseUrl must be an HTTP(S) origin without credentials, path, query or fragment");
166
+ }
167
+ this.v3 = new index_js_1.V3Client(new index_js_1.V3Transport(this._options, this.appId, () => v3Base !== null && v3Base !== void 0 ? v3Base : "https://preview.ai.agora.io", authorization, (_d = options.v3) === null || _d === void 0 ? void 0 : _d.headers));
147
168
  }
148
169
  /**
149
170
  * Get the underlying domain pool for advanced usage.
@@ -207,7 +228,7 @@ class AgoraClient extends Client_js_1.AgoraClient {
207
228
  yield this.agents.stop({ appid: this.appId, agentId }, { headers });
208
229
  }
209
230
  catch (error) {
210
- if (error instanceof index_js_2.AgoraError && error.statusCode === 404) {
231
+ if (error instanceof index_js_3.AgoraError && error.statusCode === 404) {
211
232
  return; // Agent already stopped — treat as success
212
233
  }
213
234
  throw error;
@@ -37,12 +37,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
37
37
  exports.normalizeClientOptions = normalizeClientOptions;
38
38
  const headers_js_1 = require("./core/headers.js");
39
39
  const core = __importStar(require("./core/index.js"));
40
+ const version_js_1 = require("./version.js");
40
41
  function normalizeClientOptions(options) {
41
42
  const headers = (0, headers_js_1.mergeHeaders)({
42
43
  "X-Fern-Language": "JavaScript",
43
44
  "X-Fern-SDK-Name": "agora-agents",
44
- "X-Fern-SDK-Version": "v2.12.0",
45
- "User-Agent": "agora-agents/v2.12.0",
45
+ "X-Fern-SDK-Version": version_js_1.SDK_VERSION,
46
+ "User-Agent": `agora-agents/${version_js_1.SDK_VERSION}`,
46
47
  "X-Fern-Runtime": core.RUNTIME.type,
47
48
  "X-Fern-Runtime-Version": core.RUNTIME.version,
48
49
  }, options === null || options === void 0 ? void 0 : options.headers);
@@ -1,3 +1,4 @@
1
+ import { type DeployedAgent, type DeployOptions, type SavedAgent, type SaveOptions, type VariableDefinition } from "./v3.js";
1
2
  /**
2
3
  * Agent class - A reusable agent definition.
3
4
  *
@@ -10,7 +11,7 @@ import type * as Agora from "../api/index.js";
10
11
  import { AgentSession } from "./AgentSession.js";
11
12
  import type { AgoraArea } from "./area.js";
12
13
  import type { AvatarVendor, CNMllmVendor, GlobalMllmVendor, LlmVendor, SttVendor, TtsVendor } from "./region-vendors.js";
13
- import type { AdvancedFeatures, AvatarConfig, FillerWordsConfig, GeofenceConfig, InterruptionConfig, Labels, LlmConfig, LlmGreetingConfigs, MllmConfig, ParametersAudioScenario, RtcConfig, SalConfig, SessionOptions, SessionParamsInput, SttConfig, TtsConfig, TurnDetectionConfig } from "./types.js";
14
+ import type { AdvancedFeatures, AvatarConfig, CallOptions, FillerWordsConfig, GeofenceConfig, InterruptionConfig, Labels, LlmConfig, LlmGreetingConfigs, MllmConfig, ParametersAudioScenario, RtcConfig, SalConfig, SessionOptions, SessionParamsInput, SttConfig, TtsConfig, TurnDetectionConfig } from "./types.js";
14
15
  /**
15
16
  * Configuration options for creating an Agent.
16
17
  *
@@ -97,6 +98,7 @@ export interface AgentOptions<TArea extends AgoraArea = AgoraArea> {
97
98
  * ```
98
99
  */
99
100
  export declare class Agent<TTSSampleRate extends number = number, TArea extends AgoraArea = AgoraArea> {
101
+ private _variables;
100
102
  private _client;
101
103
  private _pipelineId?;
102
104
  private _llm?;
@@ -412,7 +414,17 @@ export declare class Agent<TTSSampleRate extends number = number, TArea extends
412
414
  * const agentId = await session.start();
413
415
  * ```
414
416
  */
417
+ withVariable(name: string, definition: VariableDefinition): Agent<TTSSampleRate, TArea>;
418
+ /** Persist this configuration and return a stored-agent handle. Does not start a session. */
419
+ save(options?: SaveOptions): Promise<SavedAgent>;
420
+ /** Compatibility alias for save(). */
421
+ deploy(options?: DeployOptions): Promise<DeployedAgent>;
415
422
  createSession(options: SessionOptions): AgentSession;
423
+ /** Start an unsaved configuration explicitly through the Platform API. */
424
+ createEphemeralSession(options: SessionOptions): AgentSession;
425
+ /** Create an outbound phone-call session from this unsaved configuration. */
426
+ call(options: CallOptions): AgentSession;
427
+ private _createPlatformSession;
416
428
  /**
417
429
  * Converts the Agent configuration to the Fern request properties format.
418
430
  *
@@ -456,6 +468,7 @@ export declare class Agent<TTSSampleRate extends number = number, TArea extends
456
468
  * If a new private field is added to Agent, it MUST also be added here.
457
469
  */
458
470
  private _clone;
471
+ private _resolvePlatformAsrConfig;
459
472
  private _resolveAsrConfig;
460
473
  private _resolveTurnDetectionConfig;
461
474
  }
@@ -1,13 +1,19 @@
1
1
  "use strict";
2
- /**
3
- * Agent class - A reusable agent definition.
4
- *
5
- * This class represents an agent configuration that can be used to create
6
- * multiple sessions. Set the unique agent instance `name` in
7
- * {@link Agent.createSession}, not on the Agent itself.
8
- */
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
9
13
  Object.defineProperty(exports, "__esModule", { value: true });
10
14
  exports.Agent = void 0;
15
+ const session_backend_js_1 = require("./session-backend.js");
16
+ const v3_js_1 = require("./v3.js");
11
17
  const index_js_1 = require("../core/domain/index.js");
12
18
  const AgentSession_js_1 = require("./AgentSession.js");
13
19
  const constants_js_1 = require("./constants.js");
@@ -86,6 +92,7 @@ function assertTurnDetectionLanguage(value) {
86
92
  */
87
93
  class Agent {
88
94
  constructor(options) {
95
+ this._variables = {};
89
96
  this._client = options.client;
90
97
  this._pipelineId = options.pipelineId;
91
98
  this._instructions = options.instructions;
@@ -573,10 +580,110 @@ class Agent {
573
580
  * const agentId = await session.start();
574
581
  * ```
575
582
  */
583
+ withVariable(name, definition) {
584
+ (0, v3_js_1.validateVariable)(name, definition);
585
+ const next = this._clone();
586
+ next._variables = Object.assign(Object.assign({}, this._variables), { [name]: Object.assign(Object.assign({}, definition), (definition.options ? { options: [...definition.options] } : {})) });
587
+ return next;
588
+ }
589
+ /** Persist this configuration and return a stored-agent handle. Does not start a session. */
590
+ save(options = {}) {
591
+ var _a, _b;
592
+ const config = this.config;
593
+ if (config.mllm === undefined && (config.stt !== undefined || ((_a = config.turnDetection) === null || _a === void 0 ? void 0 : _a.language) !== undefined)) {
594
+ // Keep Platform language precedence separate from legacy interaction defaults.
595
+ config.stt = this._resolvePlatformAsrConfig();
596
+ }
597
+ return (0, v3_js_1.deployAgent)(this._client, (0, v3_js_1.buildV3Agent)(config, this._variables, (_b = options.name) !== null && _b !== void 0 ? _b : `agent-${Date.now()}`), options);
598
+ }
599
+ /** Compatibility alias for save(). */
600
+ deploy(options = {}) {
601
+ return this.save(options);
602
+ }
576
603
  createSession(options) {
577
- var _a;
604
+ var _a, _b;
605
+ if ("clientReference" in options || "client_reference" in options)
606
+ throw new Error("client_reference is being removed; use the returned session ID for correlation");
607
+ const _c = this.config, { client: _client } = _c, config = __rest(_c, ["client"]);
608
+ let requiresStoredSession = Object.keys(this._variables).length > 0 ||
609
+ options.values !== undefined ||
610
+ options.idempotencyKey !== undefined ||
611
+ options.encryption !== undefined ||
612
+ options.audioScenario !== undefined ||
613
+ options.geofence !== undefined ||
614
+ options.gracefulStop !== undefined ||
615
+ options.dataPolicy !== undefined ||
616
+ options.labels !== undefined ||
617
+ options.maxDuration !== undefined;
618
+ try {
619
+ (0, v3_js_1.assertNoSecretRefs)(config);
620
+ }
621
+ catch (error) {
622
+ if (error instanceof v3_js_1.SecretRefNotSupportedError)
623
+ requiresStoredSession = true;
624
+ else
625
+ throw error;
626
+ }
627
+ if (requiresStoredSession)
628
+ return this.createEphemeralSession(options);
578
629
  const name = (_a = options.name) !== null && _a !== void 0 ? _a : `agent-${Date.now()}`;
579
- return new AgentSession_js_1.AgentSession(Object.assign(Object.assign({ client: this._client, agent: this, appId: this._client.appId, appCertificate: this._client.appCertificate }, options), { name }));
630
+ return new AgentSession_js_1.AgentSession(Object.assign(Object.assign({ client: this._client, agent: this, appId: this._client.appId, appCertificate: this._client.appCertificate }, options), { agentUid: (_b = options.agentUid) !== null && _b !== void 0 ? _b : "0", name }));
631
+ }
632
+ /** Start an unsaved configuration explicitly through the Platform API. */
633
+ createEphemeralSession(options) {
634
+ return this._createPlatformSession(options);
635
+ }
636
+ /** Create an outbound phone-call session from this unsaved configuration. */
637
+ call(options) {
638
+ return this._createPlatformSession((0, session_backend_js_1.callSessionOptions)(options), {
639
+ type: "telephony",
640
+ from: options.from,
641
+ to: options.to,
642
+ call_policy: options.callPolicy,
643
+ });
644
+ }
645
+ _createPlatformSession(options, transport) {
646
+ var _a, _b, _c, _d, _e, _f, _g;
647
+ const normalized = this.config;
648
+ const sessionOptions = Object.assign({}, options);
649
+ if (normalized.geofence !== undefined) {
650
+ (_a = sessionOptions.geofence) !== null && _a !== void 0 ? _a : (sessionOptions.geofence = Object.assign({ area: normalized.geofence.area.toLowerCase() }, (normalized.geofence.exclude_area === undefined
651
+ ? {}
652
+ : {
653
+ exclude_area: normalized.geofence.exclude_area.toLowerCase(),
654
+ })));
655
+ normalized.geofence = undefined;
656
+ }
657
+ const params = Object.assign({}, normalized.parameters);
658
+ if (params.opt_out !== undefined) {
659
+ (_b = sessionOptions.dataPolicy) !== null && _b !== void 0 ? _b : (sessionOptions.dataPolicy = { retention: params.opt_out ? "none" : "30_days" });
660
+ delete params.opt_out;
661
+ }
662
+ if (params.farewell_config !== undefined) {
663
+ const farewell = params.farewell_config;
664
+ (_c = sessionOptions.gracefulStop) !== null && _c !== void 0 ? _c : (sessionOptions.gracefulStop = {
665
+ enabled: farewell.graceful_enabled,
666
+ timeout_ms: farewell.graceful_timeout_seconds === undefined
667
+ ? undefined
668
+ : farewell.graceful_timeout_seconds * 1000,
669
+ });
670
+ delete params.farewell_config;
671
+ }
672
+ if (params.audio_scenario !== undefined) {
673
+ (_d = sessionOptions.audioScenario) !== null && _d !== void 0 ? _d : (sessionOptions.audioScenario = params.audio_scenario === "default" ? "aiserver" : params.audio_scenario);
674
+ delete params.audio_scenario;
675
+ }
676
+ normalized.parameters = Object.keys(params).length ? params : undefined;
677
+ if (normalized.labels !== undefined) {
678
+ (_e = sessionOptions.labels) !== null && _e !== void 0 ? _e : (sessionOptions.labels = normalized.labels);
679
+ normalized.labels = undefined;
680
+ }
681
+ if (normalized.mllm === undefined &&
682
+ (normalized.stt !== undefined || ((_f = normalized.turnDetection) === null || _f === void 0 ? void 0 : _f.language) !== undefined)) {
683
+ normalized.stt = this._resolvePlatformAsrConfig();
684
+ }
685
+ const _h = (0, v3_js_1.buildV3Agent)(normalized, this._variables, (_g = options.name) !== null && _g !== void 0 ? _g : "ephemeral"), { agent_name: _name } = _h, agent = __rest(_h, ["agent_name"]);
686
+ return (0, session_backend_js_1.createStoredSession)(this._client, sessionOptions, { agent }, this, transport);
580
687
  }
581
688
  /**
582
689
  * Converts the Agent configuration to the Fern request properties format.
@@ -587,6 +694,8 @@ class Agent {
587
694
  */
588
695
  toProperties(opts) {
589
696
  var _a, _b, _c, _d, _e, _f, _g, _h;
697
+ const _j = this.config, { client: _client } = _j, config = __rest(_j, ["client"]);
698
+ (0, v3_js_1.assertNoSecretRefs)(config);
590
699
  // In MLLM mode the backend handles audio end-to-end; LLM, TTS, and ASR
591
700
  // are not required.
592
701
  const isMllmMode = ((_a = this._mllm) === null || _a === void 0 ? void 0 : _a.enable) === true || this._mllm !== undefined;
@@ -711,6 +820,7 @@ class Agent {
711
820
  */
712
821
  _clone() {
713
822
  const newAgent = new Agent({ client: this._client });
823
+ newAgent._variables = Object.assign({}, this._variables);
714
824
  newAgent._pipelineId = this._pipelineId;
715
825
  newAgent._llm = this._llm;
716
826
  newAgent._tts = this._tts;
@@ -733,6 +843,13 @@ class Agent {
733
843
  newAgent._greetingConfigs = this._greetingConfigs;
734
844
  return newAgent;
735
845
  }
846
+ _resolvePlatformAsrConfig() {
847
+ var _a, _b, _c, _d;
848
+ const config = this._stt ? Object.assign({}, this._stt) : { vendor: this._client.area === index_js_1.Area.CN ? "fengming" : "ares" };
849
+ const params = config.params;
850
+ const language = (_d = (_c = (_b = (_a = this._turnDetection) === null || _a === void 0 ? void 0 : _a.language) !== null && _b !== void 0 ? _b : config.language) !== null && _c !== void 0 ? _c : params === null || params === void 0 ? void 0 : params.language) !== null && _d !== void 0 ? _d : (["ares", "fengming"].includes(config.vendor) ? DEFAULT_TURN_DETECTION_LANGUAGE : undefined);
851
+ return Object.assign(Object.assign({}, config), (typeof language === "string" ? { language } : {}));
852
+ }
736
853
  _resolveAsrConfig(turnDetectionConfig) {
737
854
  const asrConfig = this._stt !== undefined
738
855
  ? Object.assign({}, this._stt)
@@ -10,6 +10,7 @@ import type { AgentsClient } from "../api/resources/agents/client/Client.js";
10
10
  import type { Agent } from "./Agent.js";
11
11
  import type { AgoraArea } from "./area.js";
12
12
  import { type PresetInput } from "./presets.js";
13
+ import { type SessionBackend } from "./session-backend.js";
13
14
  import type { AgentConfigUpdate, ConversationHistory, ConversationTurns, GetTurnsOptions, SayOptions, SessionInfo, ThinkOptions, ThinkResponse } from "./types.js";
14
15
  /**
15
16
  * Event types that can be emitted by AgentSession.
@@ -26,7 +27,9 @@ export interface AgentSessionOptions {
26
27
  /** The Agora client instance */
27
28
  client: AgoraClient<AgoraArea>;
28
29
  /** The agent configuration */
29
- agent: Agent<number, AgoraArea>;
30
+ agent?: Agent<number, AgoraArea>;
31
+ /** @internal Transport adapter for stored/ephemeral session identities. */
32
+ backend?: SessionBackend;
30
33
  /** The App ID */
31
34
  appId: string;
32
35
  /** The App Certificate — enables automatic RTC token generation when starting sessions */
@@ -98,7 +101,8 @@ export interface AgentSessionOptions {
98
101
  */
99
102
  export declare class AgentSession {
100
103
  private readonly _client;
101
- private readonly _agent;
104
+ private readonly _agent?;
105
+ private readonly _backend?;
102
106
  private readonly _appId;
103
107
  private readonly _appCertificate?;
104
108
  private readonly _name;
@@ -119,6 +123,11 @@ export declare class AgentSession {
119
123
  private _sessionBaseUrl?;
120
124
  private _agentId;
121
125
  private _status;
126
+ private _lifecycleRevision;
127
+ private _infoReadRevision;
128
+ private _pendingLifecycle;
129
+ private _beginLifecycle;
130
+ private _finishLifecycle;
122
131
  private _eventHandlers;
123
132
  private readonly _warn;
124
133
  constructor(options: AgentSessionOptions);