agora-agents 3.0.0-alpha.3 → 3.0.0-alpha.4

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 (50) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/AgoraPoolClient.js +25 -8
  3. package/dist/cjs/agentkit/AgentSession.js +2 -8
  4. package/dist/cjs/agentkit/index.d.ts +2 -2
  5. package/dist/cjs/agentkit/index.js +4 -3
  6. package/dist/cjs/agentkit/session-backend.d.ts +3 -1
  7. package/dist/cjs/agentkit/session-backend.js +32 -33
  8. package/dist/cjs/agentkit/token.d.ts +38 -3
  9. package/dist/cjs/agentkit/token.js +28 -1
  10. package/dist/cjs/agentkit/v3.d.ts +7 -3
  11. package/dist/cjs/agentkit/v3.js +22 -14
  12. package/dist/cjs/index.d.ts +4 -4
  13. package/dist/cjs/index.js +9 -3
  14. package/dist/cjs/v3/campaigns.js +5 -2
  15. package/dist/cjs/v3/errors.d.ts +103 -0
  16. package/dist/cjs/v3/errors.js +179 -0
  17. package/dist/cjs/v3/index.d.ts +2 -0
  18. package/dist/cjs/v3/index.js +9 -1
  19. package/dist/cjs/v3/resources.js +17 -8
  20. package/dist/cjs/v3/session-lifecycle.d.ts +2 -1
  21. package/dist/cjs/v3/session-lifecycle.js +22 -18
  22. package/dist/cjs/v3/transport.d.ts +1 -13
  23. package/dist/cjs/v3/transport.js +86 -41
  24. package/dist/cjs/version.d.ts +1 -1
  25. package/dist/cjs/version.js +1 -1
  26. package/dist/esm/AgoraPoolClient.mjs +26 -9
  27. package/dist/esm/agentkit/AgentSession.mjs +2 -8
  28. package/dist/esm/agentkit/index.d.mts +2 -2
  29. package/dist/esm/agentkit/index.mjs +1 -1
  30. package/dist/esm/agentkit/session-backend.d.mts +3 -1
  31. package/dist/esm/agentkit/session-backend.mjs +33 -34
  32. package/dist/esm/agentkit/token.d.mts +38 -3
  33. package/dist/esm/agentkit/token.mjs +27 -1
  34. package/dist/esm/agentkit/v3.d.mts +7 -3
  35. package/dist/esm/agentkit/v3.mjs +21 -13
  36. package/dist/esm/index.d.mts +4 -4
  37. package/dist/esm/index.mjs +2 -2
  38. package/dist/esm/v3/campaigns.mjs +5 -2
  39. package/dist/esm/v3/errors.d.mts +103 -0
  40. package/dist/esm/v3/errors.mjs +167 -0
  41. package/dist/esm/v3/index.d.mts +2 -0
  42. package/dist/esm/v3/index.mjs +1 -0
  43. package/dist/esm/v3/resources.mjs +17 -8
  44. package/dist/esm/v3/session-lifecycle.d.mts +2 -1
  45. package/dist/esm/v3/session-lifecycle.mjs +22 -18
  46. package/dist/esm/v3/transport.d.mts +1 -13
  47. package/dist/esm/v3/transport.mjs +83 -38
  48. package/dist/esm/version.d.mts +1 -1
  49. package/dist/esm/version.mjs +1 -1
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -11,14 +11,14 @@ The Agora Agents SDK for TypeScript lets you build real-time voice agents on Ago
11
11
 
12
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
13
 
14
- **Saving agents and project provisioning are part of SDK preview `3.0.0-alpha.3`.** 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.
14
+ **Saving agents and project provisioning are part of SDK preview `3.0.0-alpha.4`.** 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
15
 
16
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 supports Agora token007 and Customer ID/Secret HTTP Basic authentication at 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
17
 
18
18
  ## Installation
19
19
 
20
20
  ```sh
21
- npm install agora-agents@3.0.0-alpha.3
21
+ npm install agora-agents@3.0.0-alpha.4
22
22
  ```
23
23
 
24
24
  ## Quick Start
@@ -283,6 +283,6 @@ See the [Avatar Integration guide](./docs/guides/avatars.md) for sample-rate req
283
283
 
284
284
  ### Installing a preview checkout
285
285
 
286
- The v3 alpha preview is distributed separately from stable 2.x packages. This checkout targets `3.0.0-alpha.3`. 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).
286
+ The v3 alpha preview is distributed separately from stable 2.x packages. This checkout targets `3.0.0-alpha.4`. 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
287
 
288
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.
@@ -122,18 +122,18 @@ class AgoraClient extends Client_js_1.AgoraClient {
122
122
  "password",
123
123
  "authorization",
124
124
  ].includes(key.replace(/_/g, "").toLowerCase())) {
125
- throw new Error(`${key} is not supported; use appId/appCertificate, authToken, or customerId/customerSecret`);
125
+ throw new index_js_1.V3ConfigurationError(`${key} is not supported; use appId/appCertificate, authToken, or customerId/customerSecret`);
126
126
  }
127
127
  }
128
128
  const { authToken, appId, appCertificate, customerId, customerSecret } = options, rest = __rest(options, ["authToken", "appId", "appCertificate", "customerId", "customerSecret"]);
129
129
  const basic = customerId !== undefined || customerSecret !== undefined;
130
130
  if (basic && authToken !== undefined)
131
- throw new Error("customerId/customerSecret cannot be combined with authToken");
131
+ throw new index_js_1.V3ConfigurationError("customerId/customerSecret cannot be combined with authToken");
132
132
  if (basic)
133
- (0, publicAuthorization_js_1.validateBasicCredentials)(customerId, customerSecret);
133
+ asConfiguration(() => (0, publicAuthorization_js_1.validateBasicCredentials)(customerId, customerSecret));
134
134
  const authMode = basic ? "basic" : authToken !== undefined ? "token" : "app-credentials";
135
135
  if (authMode === "app-credentials" && !appCertificate)
136
- throw new Error("appCertificate, authToken, or customerId/customerSecret is required");
136
+ throw new index_js_1.V3ConfigurationError("appCertificate, authToken, or customerId/customerSecret is required");
137
137
  const authorization = () => {
138
138
  if (authMode === "basic")
139
139
  return BasicAuth_js_1.BasicAuth.toAuthorizationHeader({ username: customerId, password: customerSecret });
@@ -159,14 +159,17 @@ class AgoraClient extends Client_js_1.AgoraClient {
159
159
  this.appCertificate = appCertificate;
160
160
  this.authMode = authMode;
161
161
  this.area = options.area;
162
- 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;
162
+ // A blank option or environment value (e.g. `AGORA_AGENTS_V3_BASE_URL=` in
163
+ // a .env file) means "unset" and surrounding whitespace is ignored,
164
+ // matching the Go and Python SDKs.
165
+ const v3Base = (_c = nonBlank((_b = options.v3) === null || _b === void 0 ? void 0 : _b.baseUrl)) !== null && _c !== void 0 ? _c : nonBlank(process.env.AGORA_AGENTS_V3_BASE_URL);
163
166
  if (v3Base !== undefined) {
164
167
  let origin;
165
168
  try {
166
169
  origin = new URL(v3Base);
167
170
  }
168
- catch (_e) {
169
- throw new Error("v3.baseUrl must be an HTTP(S) origin");
171
+ catch (error) {
172
+ throw new index_js_1.V3ConfigurationError("v3.baseUrl must be an HTTP(S) origin", { cause: error });
170
173
  }
171
174
  if (!["http:", "https:"].includes(origin.protocol) ||
172
175
  origin.username ||
@@ -176,7 +179,7 @@ class AgoraClient extends Client_js_1.AgoraClient {
176
179
  origin.hash ||
177
180
  v3Base.includes("?") ||
178
181
  v3Base.includes("#"))
179
- throw new Error("v3.baseUrl must be an HTTP(S) origin without credentials, path, query or fragment");
182
+ throw new index_js_1.V3ConfigurationError("v3.baseUrl must be an HTTP(S) origin without credentials, path, query or fragment");
180
183
  }
181
184
  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));
182
185
  }
@@ -251,3 +254,17 @@ class AgoraClient extends Client_js_1.AgoraClient {
251
254
  }
252
255
  }
253
256
  exports.AgoraClient = AgoraClient;
257
+ function asConfiguration(run) {
258
+ try {
259
+ run();
260
+ }
261
+ catch (error) {
262
+ if (error instanceof Error)
263
+ throw new index_js_1.V3ConfigurationError(error.message, { cause: error });
264
+ throw error;
265
+ }
266
+ }
267
+ function nonBlank(value) {
268
+ const trimmed = value === null || value === void 0 ? void 0 : value.trim();
269
+ return trimmed ? trimmed : undefined;
270
+ }
@@ -28,7 +28,7 @@ var __rest = (this && this.__rest) || function (s, e) {
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.AgentSession = void 0;
30
30
  const index_js_1 = require("../errors/index.js");
31
- const transport_js_1 = require("../v3/transport.js");
31
+ const errors_js_1 = require("../v3/errors.js");
32
32
  const avatar_types_js_1 = require("./avatar-types.js");
33
33
  const debug_js_1 = require("./debug.js");
34
34
  const presets_js_1 = require("./presets.js");
@@ -567,13 +567,7 @@ class AgentSession {
567
567
  this._emit("stopped", Object.assign({ agentId: this._agentId }, (this._backend ? { sessionId: this._agentId } : {})));
568
568
  return; // Don't throw - agent is already stopped
569
569
  }
570
- const reason = error instanceof transport_js_1.V3Error &&
571
- error.statusCode === 409 &&
572
- error.body !== null &&
573
- typeof error.body === "object" &&
574
- "reason" in error.body
575
- ? error.body.reason
576
- : undefined;
570
+ const reason = error instanceof errors_js_1.V3Error && error.statusCode === 409 ? error.reason : undefined;
577
571
  this._status =
578
572
  this._backend && reason === "TaskNotRunning"
579
573
  ? "stopped"
@@ -33,8 +33,8 @@ export type { PreviewFeature, PreviewRoute } from "./preview/client.js";
33
33
  export { createPreviewRoute, PREVIEW_API_BASE_URL, PREVIEW_FEATURE_HEADER, PreviewFeatures, previewRequestHeaders, requiredPreviewFeatures, } from "./preview/client.js";
34
34
  export type { AvatarVendor, CNAvatarVendor, CNLlmVendor, CNMllmVendor, CNSttVendor, CNTtsVendor, GlobalAvatarVendor, GlobalLlmVendor, GlobalMllmVendor, GlobalSttVendor, GlobalTtsVendor, LlmVendor, SttVendor, TtsVendor, } from "./region-vendors.js";
35
35
  export { UnsupportedSessionOperationError } from "./session-backend.js";
36
- export type { GenerateConvoAITokenOptions, GenerateTokenOptions, } from "./token.js";
37
- export { ExpiresIn, generateConvoAIToken, generateRtcToken, MAX_EXPIRY_SECONDS, } from "./token.js";
36
+ export type { GenerateClientTokenOptions, GenerateConvoAITokenOptions, GenerateTokenOptions, } from "./token.js";
37
+ export { ExpiresIn, generateClientToken, generateConvoAIToken, generateRtcToken, MAX_EXPIRY_SECONDS, } from "./token.js";
38
38
  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, RtzrAsr, RtzrAsrParams, SalConfig, SalMode, SarvamTts, SarvamTtsParams, SayOptions, SessionInfo, SessionListResponse, SessionOptions, SessionParams, SessionParamsInput, SessionStatus, SessionSummary, SilenceAction, SilenceConfig, SmallestAiAsr, SmallestAiAsrParams, SmallestAiTts, SmallestAiTtsParams, SpatiusAvatarParams, SpeakConfig, 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.js";
39
39
  export type { AssignNumberOptions, DeployOptions, SaveOptions, SecretRef, VariableDefinition } from "./v3.js";
40
40
  export { DeployedAgent, NumberNotFoundError, SavedAgent, SecretRefNotSupportedError, secretRef, UnsupportedFieldError, } from "./v3.js";
@@ -21,9 +21,9 @@
21
21
  */
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.PREVIEW_FEATURE_HEADER = exports.PREVIEW_API_BASE_URL = exports.createPreviewRoute = exports.normalizePresetInput = exports.AgentPresets = exports.redactSecrets = exports.redactHeadersForDebug = exports.REDACTED = exports.TurnDetectionTypeValues = exports.ThinkOnThinkingActionInterrupt = exports.ThinkOnThinkingActionIgnore = exports.ThinkOnSpeakingActionInterrupt = exports.ThinkOnSpeakingActionIgnore = exports.ThinkOnListeningActionInterrupt = exports.ThinkOnListeningActionInject = exports.ThinkOnListeningActionIgnore = exports.SpeakPriorityValues = exports.SpeakPriorityInterrupt = exports.SpeakPriorityIgnore = exports.SpeakPriorityAppend = exports.SilenceActionValues = exports.SalModeValues = exports.MllmTurnDetectionModeValues = exports.MllmTurnDetectionModeServerVad = exports.MllmTurnDetectionModeSemanticVad = exports.MllmTurnDetectionModeAgoraVad = exports.InterruptionModeValues = exports.InterruptionModeStartOfSpeech = exports.InterruptionModeKeywords = exports.InterruptionDisabledStrategyIgnore = exports.InterruptionDisabledStrategyAppend = exports.InterruptionDisabledStrategy = exports.Geofence = exports.FillerWordsSelectionRule = exports.DataChannel = exports.CredentialMode = exports.AudioScenario = exports.validateTtsSampleRate = exports.validateAvatarConfig = exports.toBaseAvatarConfig = exports.isSpatiusAvatar = exports.isSensetimeAvatar = exports.isLiveAvatarAvatar = exports.isHeyGenAvatar = exports.isGenericAvatar = exports.isAvatarTokenManaged = exports.isAnamAvatar = exports.isAkoolAvatar = exports.AgentSession = exports.Agent = void 0;
24
- exports.XfyunDialectSTT = exports.XfyunBigModelSTT = exports.TencentTTS = exports.TencentSTT = exports.TencentLLM = exports.StepFunTTS = exports.SpatiusAvatar = exports.SensetimeAvatar = exports.MiniMaxCNTTS = exports.MicrosoftCNTTS = exports.MicrosoftCNSTT = exports.FengmingSTT = exports.DeepSeekLLM = exports.CosyVoiceTTS = exports.BytedanceTTS = exports.BytedanceLLM = exports.BytedanceDuplexTTS = exports.AliyunLLM = exports.BaseTTS = exports.BaseSTT = exports.BaseMLLM = exports.BaseLLM = exports.BaseCNTTS = exports.BaseCNSTT = exports.BaseCNMLLM = exports.BaseCNLLM = exports.BaseCNAvatar = exports.BaseAvatar = exports.Tavus = exports.Protoface = exports.LiveAvatarAvatar = exports.LemonSlice = exports.HeyGenAvatar = exports.GenericAvatar = exports.AnamAvatar = exports.AkoolAvatar = exports.UnsupportedFieldError = exports.secretRef = exports.SecretRefNotSupportedError = exports.SavedAgent = exports.NumberNotFoundError = exports.DeployedAgent = exports.MAX_EXPIRY_SECONDS = exports.generateRtcToken = exports.generateConvoAIToken = exports.ExpiresIn = exports.UnsupportedSessionOperationError = exports.requiredPreviewFeatures = exports.previewRequestHeaders = exports.PreviewFeatures = void 0;
25
- exports.MiniMaxTTS = exports.MicrosoftTTS = exports.HumeAITTS = exports.GradiumTTS = exports.GoogleTTS = exports.GenericTTS = exports.GeminiTTSModels = exports.GeminiTTS = exports.FishAudioTTS = exports.ElevenLabsTTS = exports.DeepgramTTS = exports.CartesiaTTS = exports.AmazonTTS = exports.XAiSTT = exports.SpeechmaticsSTT = exports.SmallestAISTT = exports.SarvamSTT = exports.RTZRSTT = exports.OpenAISTT = exports.MicrosoftSTT = exports.GoogleSTT = exports.GeminiTranscriptionMode = exports.GeminiSTTModels = exports.GeminiSTT = exports.DeepgramSTT = exports.AssemblyAISTT = exports.AresSTT = exports.AmazonSTT = exports.XaiGrok = exports.VertexAI = exports.QwenOmni = exports.OpenAIRealtime = exports.OpenAIGPTLive = exports.GeminiThinkingLevels = exports.GeminiLiveModels = exports.GeminiLive = exports.GEMINI_PREVIEW_MLLM_URL = exports.GEMINI_MLLM_URL = exports.GEMINI_MLLM_DEFAULT_MODEL = exports.AzureOpenAIRealtime = exports.VertexAILLM = exports.OpenAI = exports.Groq = exports.Gemini = exports.Dify = exports.CustomLLM = exports.AzureOpenAI = exports.Anthropic = exports.AmazonBedrock = exports.XfyunSTT = void 0;
26
- exports.XAiTTS = exports.TypecastTTS = exports.SmallestAITTS = exports.SarvamTTSLanguage = exports.SarvamTTS = exports.RimeTTS = exports.OpenAITTS = exports.MurfTTS = exports.MistralTTS = void 0;
24
+ exports.XfyunBigModelSTT = exports.TencentTTS = exports.TencentSTT = exports.TencentLLM = exports.StepFunTTS = exports.SpatiusAvatar = exports.SensetimeAvatar = exports.MiniMaxCNTTS = exports.MicrosoftCNTTS = exports.MicrosoftCNSTT = exports.FengmingSTT = exports.DeepSeekLLM = exports.CosyVoiceTTS = exports.BytedanceTTS = exports.BytedanceLLM = exports.BytedanceDuplexTTS = exports.AliyunLLM = exports.BaseTTS = exports.BaseSTT = exports.BaseMLLM = exports.BaseLLM = exports.BaseCNTTS = exports.BaseCNSTT = exports.BaseCNMLLM = exports.BaseCNLLM = exports.BaseCNAvatar = exports.BaseAvatar = exports.Tavus = exports.Protoface = exports.LiveAvatarAvatar = exports.LemonSlice = exports.HeyGenAvatar = exports.GenericAvatar = exports.AnamAvatar = exports.AkoolAvatar = exports.UnsupportedFieldError = exports.secretRef = exports.SecretRefNotSupportedError = exports.SavedAgent = exports.NumberNotFoundError = exports.DeployedAgent = exports.MAX_EXPIRY_SECONDS = exports.generateRtcToken = exports.generateConvoAIToken = exports.generateClientToken = exports.ExpiresIn = exports.UnsupportedSessionOperationError = exports.requiredPreviewFeatures = exports.previewRequestHeaders = exports.PreviewFeatures = void 0;
25
+ exports.MicrosoftTTS = exports.HumeAITTS = exports.GradiumTTS = exports.GoogleTTS = exports.GenericTTS = exports.GeminiTTSModels = exports.GeminiTTS = exports.FishAudioTTS = exports.ElevenLabsTTS = exports.DeepgramTTS = exports.CartesiaTTS = exports.AmazonTTS = exports.XAiSTT = exports.SpeechmaticsSTT = exports.SmallestAISTT = exports.SarvamSTT = exports.RTZRSTT = exports.OpenAISTT = exports.MicrosoftSTT = exports.GoogleSTT = exports.GeminiTranscriptionMode = exports.GeminiSTTModels = exports.GeminiSTT = exports.DeepgramSTT = exports.AssemblyAISTT = exports.AresSTT = exports.AmazonSTT = exports.XaiGrok = exports.VertexAI = exports.QwenOmni = exports.OpenAIRealtime = exports.OpenAIGPTLive = exports.GeminiThinkingLevels = exports.GeminiLiveModels = exports.GeminiLive = exports.GEMINI_PREVIEW_MLLM_URL = exports.GEMINI_MLLM_URL = exports.GEMINI_MLLM_DEFAULT_MODEL = exports.AzureOpenAIRealtime = exports.VertexAILLM = exports.OpenAI = exports.Groq = exports.Gemini = exports.Dify = exports.CustomLLM = exports.AzureOpenAI = exports.Anthropic = exports.AmazonBedrock = exports.XfyunSTT = exports.XfyunDialectSTT = void 0;
26
+ exports.XAiTTS = exports.TypecastTTS = exports.SmallestAITTS = exports.SarvamTTSLanguage = exports.SarvamTTS = exports.RimeTTS = exports.OpenAITTS = exports.MurfTTS = exports.MistralTTS = exports.MiniMaxTTS = void 0;
27
27
  // Core classes
28
28
  var Agent_js_1 = require("./Agent.js");
29
29
  Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return Agent_js_1.Agent; } });
@@ -91,6 +91,7 @@ Object.defineProperty(exports, "UnsupportedSessionOperationError", { enumerable:
91
91
  // Token generation
92
92
  var token_js_1 = require("./token.js");
93
93
  Object.defineProperty(exports, "ExpiresIn", { enumerable: true, get: function () { return token_js_1.ExpiresIn; } });
94
+ Object.defineProperty(exports, "generateClientToken", { enumerable: true, get: function () { return token_js_1.generateClientToken; } });
94
95
  Object.defineProperty(exports, "generateConvoAIToken", { enumerable: true, get: function () { return token_js_1.generateConvoAIToken; } });
95
96
  Object.defineProperty(exports, "generateRtcToken", { enumerable: true, get: function () { return token_js_1.generateRtcToken; } });
96
97
  Object.defineProperty(exports, "MAX_EXPIRY_SECONDS", { enumerable: true, get: function () { return token_js_1.MAX_EXPIRY_SECONDS; } });
@@ -1,5 +1,6 @@
1
1
  /** Internal adapter for session identities, without mixing them with running-agent IDs. */
2
2
  import type { AgoraClient } from "../AgoraPoolClient.js";
3
+ import { V3ValidationError } from "../v3/errors.js";
3
4
  import type { AgentCreateRequest, TelephonyTransport } from "../v3/types.js";
4
5
  import type { Agent } from "./Agent.js";
5
6
  import { AgentSession } from "./AgentSession.js";
@@ -13,7 +14,8 @@ export interface SessionBackend {
13
14
  update(id: string, config: AgentConfigUpdate): Promise<void>;
14
15
  getInfo(id: string): Promise<SessionInfo>;
15
16
  }
16
- export declare class UnsupportedSessionOperationError extends Error {
17
+ /** The operation is not available on a v3 Platform session. A {@link V3ValidationError}. */
18
+ export declare class UnsupportedSessionOperationError extends V3ValidationError {
17
19
  constructor(operation: string);
18
20
  }
19
21
  /** Validate mixed transports before replacing internal RTC placeholders. */
@@ -12,16 +12,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.UnsupportedSessionOperationError = void 0;
13
13
  exports.callSessionOptions = callSessionOptions;
14
14
  exports.createStoredSession = createStoredSession;
15
+ const errors_js_1 = require("../v3/errors.js");
15
16
  const session_lifecycle_js_1 = require("../v3/session-lifecycle.js");
16
17
  const AgentSession_js_1 = require("./AgentSession.js");
17
18
  const token_js_1 = require("./token.js");
18
- class UnsupportedSessionOperationError extends Error {
19
+ /** The operation is not available on a v3 Platform session. A {@link V3ValidationError}. */
20
+ class UnsupportedSessionOperationError extends errors_js_1.V3ValidationError {
19
21
  constructor(operation) {
20
22
  super(`${operation} is not supported by this session backend; start, stop, getInfo and update are available`);
21
23
  this.name = "UnsupportedSessionOperationError";
22
24
  }
23
25
  }
24
26
  exports.UnsupportedSessionOperationError = UnsupportedSessionOperationError;
27
+ (0, errors_js_1.registerV3ErrorClass)(UnsupportedSessionOperationError, "UnsupportedSessionOperationError");
25
28
  /** Validate mixed transports before replacing internal RTC placeholders. */
26
29
  function callSessionOptions(options) {
27
30
  for (const key of [
@@ -36,7 +39,7 @@ function callSessionOptions(options) {
36
39
  "expiresIn",
37
40
  ]) {
38
41
  if (options[key] !== undefined)
39
- throw new Error(`Phone calls do not accept RTC option ${key}`);
42
+ throw new errors_js_1.V3ValidationError(`Phone calls do not accept RTC option ${key}`);
40
43
  }
41
44
  return Object.assign(Object.assign({}, options), { channel: "", remoteUids: [] });
42
45
  }
@@ -44,7 +47,7 @@ function createStoredSession(client, options, source, config, telephony) {
44
47
  var _a, _b;
45
48
  for (const key of ["clientReference", "client_reference", "enableStringUid", "preset", "pipelineId"]) {
46
49
  if (key in options && options[key] !== undefined)
47
- throw new Error(`${key} is not supported by this session backend`);
50
+ throw new errors_js_1.V3ValidationError(`${key} is not supported by this session backend`);
48
51
  }
49
52
  const lifecycle = {};
50
53
  for (const [key, wire] of [
@@ -69,10 +72,10 @@ function createStoredSession(client, options, source, config, telephony) {
69
72
  (0, session_lifecycle_js_1.validateSessionStart)(payload);
70
73
  if (options.expiresIn !== undefined &&
71
74
  (!Number.isInteger(options.expiresIn) || !Number.isFinite(options.expiresIn)))
72
- throw new Error("expiresIn must be a whole number of seconds");
75
+ throw new errors_js_1.V3ValidationError("expiresIn must be a whole number of seconds");
73
76
  if (telephony &&
74
77
  [options.agentUid, options.token, options.encryption, options.audioScenario, options.geofence].some((value) => value !== undefined))
75
- throw new Error("RTC options are not supported for phone calls");
78
+ throw new errors_js_1.V3ValidationError("RTC options are not supported for phone calls");
76
79
  const expiry = options.expiresIn === undefined ? undefined : token_js_1.ExpiresIn.seconds(options.expiresIn);
77
80
  const signing = !telephony &&
78
81
  options.token === undefined &&
@@ -91,7 +94,7 @@ function createStoredSession(client, options, source, config, telephony) {
91
94
  start() {
92
95
  return __awaiter(this, void 0, void 0, function* () {
93
96
  if (payload.idempotencyKey && successfullyStarted)
94
- throw new Error("This idempotency key already started a session; create a new handle with a new key for another session");
97
+ throw new errors_js_1.V3ValidationError("This idempotency key already started a session; create a new handle with a new key for another session");
95
98
  if (successfullyStarted && !payload.idempotencyKey) {
96
99
  // A new unkeyed session needs a fresh token. Failed starts retain
97
100
  // their request snapshot, and keyed starts cannot be reused.
@@ -105,27 +108,23 @@ function createStoredSession(client, options, source, config, telephony) {
105
108
  (Number.isSafeInteger(Number(signing.uid)) && Number(signing.uid) <= 4294967295))) {
106
109
  // Larger numeric identities remain opaque; the service provisions
107
110
  // their token instead of coercing them through the local signer.
108
- payload.transport.token = /^\d+$/.test(signing.uid)
109
- ? (0, token_js_1.generateConvoAIToken)({
110
- appId: signing.appId,
111
- appCertificate: signing.appCertificate,
112
- channelName: signing.channel,
113
- uid: Number(signing.uid),
114
- tokenExpire: expiry,
115
- })
116
- : (0, token_js_1.generateRtcTokenWithAccount)({
117
- appId: signing.appId,
118
- appCertificate: signing.appCertificate,
119
- channel: signing.channel,
120
- account: signing.uid,
121
- expirySeconds: expiry,
122
- });
111
+ // String accounts get the same RTC + RTM + ConvoAI token as numeric
112
+ // UIDs: RTM is the session's only data channel.
113
+ payload.transport.token = (0, token_js_1.generateConvoAIToken)({
114
+ appId: signing.appId,
115
+ appCertificate: signing.appCertificate,
116
+ channelName: signing.channel,
117
+ uid: /^\d+$/.test(signing.uid) ? Number(signing.uid) : signing.uid,
118
+ tokenExpire: expiry,
119
+ });
123
120
  }
124
- const result = "agent_id" in payload
125
- ? yield client.v3.sessions.start(payload)
126
- : yield client.v3.sessions.startEphemeral(payload);
121
+ const { data: result, rawResponse } = yield ("agent_id" in payload
122
+ ? client.v3.sessions.start(payload)
123
+ : client.v3.sessions.startEphemeral(payload)).withRawResponse();
127
124
  if (typeof result.agent_session_id !== "string" || !result.agent_session_id.trim()) {
128
- throw new Error("Session start response is missing agent_session_id");
125
+ throw new errors_js_1.V3Error(rawResponse.status, result, rawResponse, {
126
+ message: "Session start response is missing agent_session_id",
127
+ });
129
128
  }
130
129
  successfullyStarted = true;
131
130
  return { id: result.agent_session_id, status: result.status === "STARTING" ? "starting" : "running" };
@@ -141,16 +140,16 @@ function createStoredSession(client, options, source, config, telephony) {
141
140
  var _a, _b, _c;
142
141
  const input = config;
143
142
  if (!input || typeof input !== "object" || Array.isArray(input))
144
- throw new Error("Invalid session update");
143
+ throw new errors_js_1.V3ValidationError("Invalid session update");
145
144
  for (const key of Object.keys(input))
146
145
  if (!["token", "messages", "llm"].includes(key))
147
- throw new Error(`Unsupported session update field: ${key}`);
146
+ throw new errors_js_1.V3ValidationError(`Unsupported session update field: ${key}`);
148
147
  if (input.messages !== undefined && ((_a = input.llm) === null || _a === void 0 ? void 0 : _a.system_messages) !== undefined)
149
- throw new Error("Provide messages or llm.system_messages, not both");
148
+ throw new errors_js_1.V3ValidationError("Provide messages or llm.system_messages, not both");
150
149
  const patch = {};
151
150
  if (input.token !== undefined) {
152
151
  if (typeof input.token !== "string" || !input.token)
153
- throw new Error("token must be a string");
152
+ throw new errors_js_1.V3ValidationError("token must be a string");
154
153
  patch.transport = { token: input.token };
155
154
  }
156
155
  const overrides = {};
@@ -161,7 +160,7 @@ function createStoredSession(client, options, source, config, telephony) {
161
160
  !["system", "user", "assistant"].includes(message.role) ||
162
161
  typeof message.content !== "string" ||
163
162
  Object.keys(message).some((key) => !["role", "content"].includes(key))))
164
- throw new Error("Invalid session messages");
163
+ throw new errors_js_1.V3ValidationError("Invalid session messages");
165
164
  overrides.messages = messages;
166
165
  }
167
166
  for (const kind of ["llm"])
@@ -171,12 +170,12 @@ function createStoredSession(client, options, source, config, telephony) {
171
170
  typeof module !== "object" ||
172
171
  Array.isArray(module) ||
173
172
  Object.keys(module).some((key) => !["params", ...(kind === "llm" ? ["system_messages"] : [])].includes(key)))
174
- throw new Error(`Invalid ${kind} update`);
173
+ throw new errors_js_1.V3ValidationError(`Invalid ${kind} update`);
175
174
  if (module.params !== undefined) {
176
175
  if (!module.params || typeof module.params !== "object" || Array.isArray(module.params))
177
- throw new Error("params must be an object");
176
+ throw new errors_js_1.V3ValidationError("params must be an object");
178
177
  if (Object.keys(module.params).some((key) => ["url", "base_url", "api_base_url", "endpoint"].includes(key.toLowerCase())))
179
- throw new Error("Runtime endpoint aliases are not mutable");
178
+ throw new errors_js_1.V3ValidationError("Runtime endpoint aliases are not mutable");
180
179
  overrides.pipeline = { [kind]: { params: module.params } };
181
180
  }
182
181
  }
@@ -4,7 +4,10 @@
4
4
  * - RTC tokens authenticate a specific (appId, channel, uid) combination with
5
5
  * the Agora RTC network.
6
6
  * - ConvoAI tokens are RTC + RTM + ConvoAI tokens used to authenticate
7
- * ConvoAI REST API calls via `Authorization: agora token=<token>`.
7
+ * ConvoAI REST API calls via `Authorization: agora token=<token>`. Keep them
8
+ * on the server.
9
+ * - Client tokens are RTC + RTM only, for front-end token routes. They join a
10
+ * channel and log in to RTM but cannot call the ConvoAI REST API.
8
11
  *
9
12
  * The `agora-token` library handles the AccessToken2 signing.
10
13
  */
@@ -74,8 +77,12 @@ export interface GenerateConvoAITokenOptions {
74
77
  appCertificate: string;
75
78
  /** The channel the agent will join — must match the channel used in the start request */
76
79
  channelName: string;
77
- /** Numeric ConvoAI participant UID. Use the RTC UID for a user, agent, or avatar. */
78
- uid: number;
80
+ /**
81
+ * ConvoAI participant UID: a numeric RTC UID or a string user account. Use the
82
+ * RTC UID for a user, agent, or avatar. Both forms are signed as the UID's
83
+ * string form, which is also the RTM user ID.
84
+ */
85
+ uid: number | string;
79
86
  /** Seconds until the token expires (default: 86400) */
80
87
  tokenExpire?: number;
81
88
  /**
@@ -96,3 +103,31 @@ export interface GenerateConvoAITokenOptions {
96
103
  * privileges in a single AccessToken2 token.
97
104
  */
98
105
  export declare function generateConvoAIToken(opts: GenerateConvoAITokenOptions): string;
106
+ export interface GenerateClientTokenOptions {
107
+ appId: string;
108
+ appCertificate: string;
109
+ /** The channel the client will join. */
110
+ channelName: string;
111
+ /**
112
+ * The client's RTC UID or string user account. It is also the RTM user ID, so
113
+ * it must be nonzero and nonempty.
114
+ */
115
+ uid: number | string;
116
+ /** Seconds until the token expires (default: 86400) */
117
+ tokenExpire?: number;
118
+ /**
119
+ * Seconds until RTC privileges expire. Defaults to `tokenExpire`. RTM login
120
+ * keeps the token lifetime.
121
+ */
122
+ privilegeExpire?: number;
123
+ }
124
+ /**
125
+ * Builds an RTC + RTM token for a front-end client. Use it in token routes that
126
+ * hand tokens to browsers or apps.
127
+ *
128
+ * The token joins the RTC channel as a publisher and logs in to RTM, the data
129
+ * channel for agent transcripts and state. It carries no ConvoAI service, so it
130
+ * cannot authenticate ConvoAI REST calls. Use {@link generateConvoAIToken} for
131
+ * server-side REST authentication and agent tokens instead.
132
+ */
133
+ export declare function generateClientToken(opts: GenerateClientTokenOptions): string;
@@ -5,7 +5,10 @@
5
5
  * - RTC tokens authenticate a specific (appId, channel, uid) combination with
6
6
  * the Agora RTC network.
7
7
  * - ConvoAI tokens are RTC + RTM + ConvoAI tokens used to authenticate
8
- * ConvoAI REST API calls via `Authorization: agora token=<token>`.
8
+ * ConvoAI REST API calls via `Authorization: agora token=<token>`. Keep them
9
+ * on the server.
10
+ * - Client tokens are RTC + RTM only, for front-end token routes. They join a
11
+ * channel and log in to RTM but cannot call the ConvoAI REST API.
9
12
  *
10
13
  * The `agora-token` library handles the AccessToken2 signing.
11
14
  */
@@ -17,6 +20,7 @@ exports.ExpiresIn = exports.MAX_EXPIRY_SECONDS = void 0;
17
20
  exports.generateRtcToken = generateRtcToken;
18
21
  exports.generateRtcTokenWithAccount = generateRtcTokenWithAccount;
19
22
  exports.generateConvoAIToken = generateConvoAIToken;
23
+ exports.generateClientToken = generateClientToken;
20
24
  const agora_token_1 = __importDefault(require("agora-token"));
21
25
  const DEFAULT_EXPIRY_SECONDS = 86400;
22
26
  exports.MAX_EXPIRY_SECONDS = 86400;
@@ -156,8 +160,31 @@ function generateConvoAIToken(opts) {
156
160
  return _requireBuiltToken(agora_token_1.default.ConvoAITokenBuilder.buildTokenWithPrivilege(opts.appId, opts.appCertificate, opts.channelName, account, agora_token_1.default.RtcRole.PUBLISHER, tokenExpire, privilegeExpire, privilegeExpire, privilegeExpire, privilegeExpire, account, tokenExpire), opts.appId, opts.appCertificate);
157
161
  }
158
162
  function _uidToAccount(uid) {
163
+ if (typeof uid === "string") {
164
+ return uid;
165
+ }
159
166
  if (!Number.isInteger(uid)) {
160
167
  throw new Error("uid must be an integer when provided as a number");
161
168
  }
162
169
  return String(uid);
163
170
  }
171
+ /**
172
+ * Builds an RTC + RTM token for a front-end client. Use it in token routes that
173
+ * hand tokens to browsers or apps.
174
+ *
175
+ * The token joins the RTC channel as a publisher and logs in to RTM, the data
176
+ * channel for agent transcripts and state. It carries no ConvoAI service, so it
177
+ * cannot authenticate ConvoAI REST calls. Use {@link generateConvoAIToken} for
178
+ * server-side REST authentication and agent tokens instead.
179
+ */
180
+ function generateClientToken(opts) {
181
+ var _a;
182
+ const account = _uidToAccount(opts.uid);
183
+ if (account === "" || /^0+$/.test(account)) {
184
+ throw new Error("uid must be nonzero and nonempty: it is also the RTM user ID");
185
+ }
186
+ const tokenExpire = (_a = opts.tokenExpire) !== null && _a !== void 0 ? _a : DEFAULT_EXPIRY_SECONDS;
187
+ // Per Agora docs, privilegeExpire=0 means "expires immediately", which is invalid.
188
+ const privilegeExpire = opts.privilegeExpire || tokenExpire;
189
+ return _requireBuiltToken(agora_token_1.default.RtcTokenBuilder.buildTokenWithRtm(opts.appId, opts.appCertificate, opts.channelName, account, agora_token_1.default.RtcRole.PUBLISHER, tokenExpire, privilegeExpire), opts.appId, opts.appCertificate);
190
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AgoraClient } from "../AgoraPoolClient.js";
2
+ import { V3ValidationError } from "../v3/errors.js";
2
3
  import type * as V3 from "../v3/types.js";
3
4
  import type { Agent, AgentOptions } from "./Agent.js";
4
5
  import type { AgentSession } from "./AgentSession.js";
@@ -7,14 +8,17 @@ export type SecretRef = string & {
7
8
  readonly __secretRef: unique symbol;
8
9
  };
9
10
  export declare function secretRef(set: string, key: string): SecretRef;
10
- export declare class SecretRefNotSupportedError extends Error {
11
+ /** A `secretRef()` value was used where only saved agents can resolve it. A {@link V3ValidationError}. */
12
+ export declare class SecretRefNotSupportedError extends V3ValidationError {
11
13
  constructor();
12
14
  }
13
- export declare class UnsupportedFieldError extends Error {
15
+ /** The configuration uses fields the v3 API does not accept. A {@link V3ValidationError}. */
16
+ export declare class UnsupportedFieldError extends V3ValidationError {
14
17
  readonly fields: string[];
15
18
  constructor(fields: string[]);
16
19
  }
17
- export declare class NumberNotFoundError extends Error {
20
+ /** A phone number given by E.164 value is not registered in the project. A {@link V3ValidationError}. */
21
+ export declare class NumberNotFoundError extends V3ValidationError {
18
22
  constructor(number: string, appid: string);
19
23
  }
20
24
  export declare function assertNoSecretRefs(value: unknown): void;
@@ -37,21 +37,23 @@ exports.redeployPatch = redeployPatch;
37
37
  exports.deployAgent = deployAgent;
38
38
  const index_js_1 = require("../core/domain/index.js");
39
39
  const contract_js_1 = require("../v3/contract.js");
40
- const transport_js_1 = require("../v3/transport.js");
40
+ const errors_js_1 = require("../v3/errors.js");
41
41
  const session_backend_js_1 = require("./session-backend.js");
42
42
  function secretRef(set, key) {
43
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");
44
+ throw new errors_js_1.V3ValidationError("Secret names and keys must be 1–64 letters, digits or underscores");
45
45
  return `$secrets.${set}.${key}`;
46
46
  }
47
- class SecretRefNotSupportedError extends Error {
47
+ /** A `secretRef()` value was used where only saved agents can resolve it. A {@link V3ValidationError}. */
48
+ class SecretRefNotSupportedError extends errors_js_1.V3ValidationError {
48
49
  constructor() {
49
50
  super("secretRef requires save()");
50
51
  this.name = "SecretRefNotSupportedError";
51
52
  }
52
53
  }
53
54
  exports.SecretRefNotSupportedError = SecretRefNotSupportedError;
54
- class UnsupportedFieldError extends Error {
55
+ /** The configuration uses fields the v3 API does not accept. A {@link V3ValidationError}. */
56
+ class UnsupportedFieldError extends errors_js_1.V3ValidationError {
55
57
  constructor(fields) {
56
58
  super(`Unsupported v3 fields: ${fields.join(", ")}`);
57
59
  this.fields = fields;
@@ -59,13 +61,17 @@ class UnsupportedFieldError extends Error {
59
61
  }
60
62
  }
61
63
  exports.UnsupportedFieldError = UnsupportedFieldError;
62
- class NumberNotFoundError extends Error {
64
+ /** A phone number given by E.164 value is not registered in the project. A {@link V3ValidationError}. */
65
+ class NumberNotFoundError extends errors_js_1.V3ValidationError {
63
66
  constructor(number, appid) {
64
67
  super(`Number ${number} not found in project ${appid}; create it first with client.v3.numbers.create()`);
65
68
  this.name = "NumberNotFoundError";
66
69
  }
67
70
  }
68
71
  exports.NumberNotFoundError = NumberNotFoundError;
72
+ (0, errors_js_1.registerV3ErrorClass)(SecretRefNotSupportedError, "SecretRefNotSupportedError");
73
+ (0, errors_js_1.registerV3ErrorClass)(UnsupportedFieldError, "UnsupportedFieldError");
74
+ (0, errors_js_1.registerV3ErrorClass)(NumberNotFoundError, "NumberNotFoundError");
69
75
  function assertNoSecretRefs(value) {
70
76
  if (typeof value === "string" && value.startsWith("$secrets."))
71
77
  throw new SecretRefNotSupportedError();
@@ -76,15 +82,15 @@ function assertNoSecretRefs(value) {
76
82
  function validateVariable(name, def) {
77
83
  var _a;
78
84
  if (!/^[a-z][a-z0-9_]{0,63}$/.test(name))
79
- throw new Error("Invalid v3 variable name");
85
+ throw new errors_js_1.V3ValidationError("Invalid v3 variable name");
80
86
  if (!["str", "int", "float", "bool", "date", "datetime"].includes(def.type))
81
- throw new Error("Invalid v3 variable type");
87
+ throw new errors_js_1.V3ValidationError("Invalid v3 variable type");
82
88
  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");
89
+ throw new errors_js_1.V3ValidationError("Variable options must be unique");
84
90
  if (def.extract && !((_a = def.description) === null || _a === void 0 ? void 0 : _a.trim()))
85
- throw new Error("Extracted variables require a description");
91
+ throw new errors_js_1.V3ValidationError("Extracted variables require a description");
86
92
  if (validateContract(def, contract_js_1.contract.AgentRequest_VariableDefinition, `variables.${name}`).length)
87
- throw new Error("Invalid v3 variable definition");
93
+ throw new errors_js_1.V3ValidationError("Invalid v3 variable definition");
88
94
  }
89
95
  const clean = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined));
90
96
  function leftovers(value, allowed, path, errors) {
@@ -549,7 +555,9 @@ function redeployPatch(previous, desired) {
549
555
  function etag(response) {
550
556
  const tag = response.rawResponse.headers.get("ETag");
551
557
  if (!tag)
552
- throw new Error("v3 response is missing ETag");
558
+ throw new errors_js_1.V3Error(response.rawResponse.status, response.data, response.rawResponse, {
559
+ message: "v3 response is missing ETag",
560
+ });
553
561
  return tag;
554
562
  }
555
563
  function deployAgent(client, body, options) {
@@ -562,7 +570,7 @@ function deployAgent(client, body, options) {
562
570
  if (object(module) && "credential" in module && ((_b = module.credential) === null || _b === void 0 ? void 0 : _b.mode) === "byok") {
563
571
  for (const value of Object.values((_c = module.credential.fields) !== null && _c !== void 0 ? _c : {}))
564
572
  if (typeof value !== "string" || !/^\$secrets\.[A-Za-z0-9_]{1,64}\.[A-Za-z0-9_]{1,64}$/.test(value))
565
- throw new Error(`Saved ${kind} credentials require secretRef(); use an ephemeral session for inline credentials`);
573
+ throw new errors_js_1.V3ValidationError(`Saved ${kind} credentials require secretRef(); use an ephemeral session for inline credentials`);
566
574
  }
567
575
  }
568
576
  const agentId = options.agentId;
@@ -608,7 +616,7 @@ class SavedAgent {
608
616
  update(config, options = {}) {
609
617
  var _a;
610
618
  if (config.config.client !== this.client) {
611
- throw new Error("SavedAgent.update requires a configuration bound to the same client");
619
+ throw new errors_js_1.V3ValidationError("SavedAgent.update requires a configuration bound to the same client");
612
620
  }
613
621
  return config.save({ agentId: this.id, name: (_a = options.name) !== null && _a !== void 0 ? _a : this.name });
614
622
  }
@@ -695,7 +703,7 @@ class SavedAgent {
695
703
  });
696
704
  }
697
705
  catch (error) {
698
- if (!(error instanceof transport_js_1.PreconditionFailedError) || attempt >= 1)
706
+ if (!(error instanceof errors_js_1.PreconditionFailedError) || attempt >= 1)
699
707
  throw error;
700
708
  }
701
709
  }