@microsoft/agents-hosting 1.6.1 → 1.7.0-beta.5.g67b2005119

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 (163) hide show
  1. package/README.md +16 -0
  2. package/dist/package.json +3 -3
  3. package/dist/src/agent-client/agentClient.js +4 -3
  4. package/dist/src/agent-client/agentClient.js.map +1 -1
  5. package/dist/src/agent-client/agentResponseHandler.d.ts +25 -6
  6. package/dist/src/agent-client/agentResponseHandler.js +16 -55
  7. package/dist/src/agent-client/agentResponseHandler.js.map +1 -1
  8. package/dist/src/agent-client/createAgentResponseHandler.d.ts +48 -0
  9. package/dist/src/agent-client/createAgentResponseHandler.js +92 -0
  10. package/dist/src/agent-client/createAgentResponseHandler.js.map +1 -0
  11. package/dist/src/agent-client/index.d.ts +1 -0
  12. package/dist/src/agent-client/index.js +1 -0
  13. package/dist/src/agent-client/index.js.map +1 -1
  14. package/dist/src/app/adaptiveCards/activityValueParsers.js +2 -1
  15. package/dist/src/app/adaptiveCards/activityValueParsers.js.map +1 -1
  16. package/dist/src/app/adaptiveCards/adaptiveCardsActions.js +13 -12
  17. package/dist/src/app/adaptiveCards/adaptiveCardsActions.js.map +1 -1
  18. package/dist/src/app/agentApplication.js +8 -8
  19. package/dist/src/app/agentApplication.js.map +1 -1
  20. package/dist/src/app/streaming/streamingResponse.d.ts +11 -0
  21. package/dist/src/app/streaming/streamingResponse.js +23 -2
  22. package/dist/src/app/streaming/streamingResponse.js.map +1 -1
  23. package/dist/src/app/turnState.d.ts +0 -1
  24. package/dist/src/app/turnState.js +15 -14
  25. package/dist/src/app/turnState.js.map +1 -1
  26. package/dist/src/app/turnStateProperty.js +4 -2
  27. package/dist/src/app/turnStateProperty.js.map +1 -1
  28. package/dist/src/auth/MemoryCache.d.ts +2 -1
  29. package/dist/src/auth/MemoryCache.js +7 -1
  30. package/dist/src/auth/MemoryCache.js.map +1 -1
  31. package/dist/src/auth/authConfiguration.d.ts +1 -1
  32. package/dist/src/auth/authConfiguration.js +41 -4
  33. package/dist/src/auth/authConfiguration.js.map +1 -1
  34. package/dist/src/auth/authConstants.d.ts +7 -7
  35. package/dist/src/auth/authConstants.js.map +1 -1
  36. package/dist/src/auth/connectionManager.d.ts +92 -0
  37. package/dist/src/auth/{msalConnectionManager.js → connectionManager.js} +50 -48
  38. package/dist/src/auth/connectionManager.js.map +1 -0
  39. package/dist/src/auth/index.d.ts +5 -3
  40. package/dist/src/auth/index.js +5 -3
  41. package/dist/src/auth/index.js.map +1 -1
  42. package/dist/src/auth/jwt-middleware.d.ts +8 -2
  43. package/dist/src/auth/jwt-middleware.js +116 -7
  44. package/dist/src/auth/jwt-middleware.js.map +1 -1
  45. package/dist/src/auth/msal/msalConnectionManager.d.ts +17 -0
  46. package/dist/src/auth/msal/msalConnectionManager.js +50 -0
  47. package/dist/src/auth/msal/msalConnectionManager.js.map +1 -0
  48. package/dist/src/auth/msal/msalConnectionSettings.d.ts +68 -0
  49. package/dist/src/auth/msal/msalConnectionSettings.js +7 -0
  50. package/dist/src/auth/msal/msalConnectionSettings.js.map +1 -0
  51. package/dist/src/auth/{msalTokenCredential.d.ts → msal/msalTokenCredential.d.ts} +1 -1
  52. package/dist/src/auth/{msalTokenCredential.js → msal/msalTokenCredential.js} +2 -2
  53. package/dist/src/auth/msal/msalTokenCredential.js.map +1 -0
  54. package/dist/src/auth/{msalTokenProvider.d.ts → msal/msalTokenProvider.d.ts} +23 -3
  55. package/dist/src/auth/{msalTokenProvider.js → msal/msalTokenProvider.js} +280 -176
  56. package/dist/src/auth/msal/msalTokenProvider.js.map +1 -0
  57. package/dist/src/auth/settings.d.ts +142 -133
  58. package/dist/src/auth/settings.js +49 -5
  59. package/dist/src/auth/settings.js.map +1 -1
  60. package/dist/src/auth/sidecar/sidecarAuthProvider.d.ts +74 -0
  61. package/dist/src/auth/sidecar/sidecarAuthProvider.js +181 -0
  62. package/dist/src/auth/sidecar/sidecarAuthProvider.js.map +1 -0
  63. package/dist/src/auth/sidecar/sidecarConnectionSettings.d.ts +65 -0
  64. package/dist/src/auth/sidecar/sidecarConnectionSettings.js +7 -0
  65. package/dist/src/auth/sidecar/sidecarConnectionSettings.js.map +1 -0
  66. package/dist/src/auth/sidecar/sidecarHttpClient.d.ts +95 -0
  67. package/dist/src/auth/sidecar/sidecarHttpClient.js +406 -0
  68. package/dist/src/auth/sidecar/sidecarHttpClient.js.map +1 -0
  69. package/dist/src/auth/sidecar/sidecarModels.d.ts +110 -0
  70. package/dist/src/auth/sidecar/sidecarModels.js +48 -0
  71. package/dist/src/auth/sidecar/sidecarModels.js.map +1 -0
  72. package/dist/src/auth/sidecar/sidecarTokenExpiry.d.ts +13 -0
  73. package/dist/src/auth/sidecar/sidecarTokenExpiry.js +39 -0
  74. package/dist/src/auth/sidecar/sidecarTokenExpiry.js.map +1 -0
  75. package/dist/src/baseAdapter.js +3 -1
  76. package/dist/src/baseAdapter.js.map +1 -1
  77. package/dist/src/cloudAdapter.d.ts +2 -2
  78. package/dist/src/cloudAdapter.js +11 -11
  79. package/dist/src/cloudAdapter.js.map +1 -1
  80. package/dist/src/createCloudAdapter.d.ts +40 -0
  81. package/dist/src/createCloudAdapter.js +44 -0
  82. package/dist/src/createCloudAdapter.js.map +1 -0
  83. package/dist/src/errorHelper.js +302 -79
  84. package/dist/src/errorHelper.js.map +1 -1
  85. package/dist/src/headerPropagation.js +3 -1
  86. package/dist/src/headerPropagation.js.map +1 -1
  87. package/dist/src/index.d.ts +3 -1
  88. package/dist/src/index.js +4 -1
  89. package/dist/src/index.js.map +1 -1
  90. package/dist/src/interfaces/index.d.ts +5 -0
  91. package/dist/src/interfaces/index.js +22 -0
  92. package/dist/src/interfaces/index.js.map +1 -0
  93. package/dist/src/interfaces/webResponse.d.ts +41 -0
  94. package/dist/src/interfaces/webResponse.js +7 -0
  95. package/dist/src/interfaces/webResponse.js.map +1 -0
  96. package/dist/src/middlewareSet.d.ts +0 -1
  97. package/dist/src/middlewareSet.js +4 -1
  98. package/dist/src/middlewareSet.js.map +1 -1
  99. package/dist/src/oauth/userTokenClient.d.ts +12 -0
  100. package/dist/src/oauth/userTokenClient.js +30 -9
  101. package/dist/src/oauth/userTokenClient.js.map +1 -1
  102. package/dist/src/state/conversationState.js +4 -2
  103. package/dist/src/state/conversationState.js.map +1 -1
  104. package/dist/src/state/userState.js +4 -2
  105. package/dist/src/state/userState.js.map +1 -1
  106. package/dist/src/storage/memoryStorage.js +5 -3
  107. package/dist/src/storage/memoryStorage.js.map +1 -1
  108. package/dist/src/transcript/consoleTranscriptLogger.js +3 -1
  109. package/dist/src/transcript/consoleTranscriptLogger.js.map +1 -1
  110. package/dist/src/transcript/fileTranscriptLogger.js +5 -4
  111. package/dist/src/transcript/fileTranscriptLogger.js.map +1 -1
  112. package/dist/src/transcript/transcriptLoggerMiddleware.js +2 -1
  113. package/dist/src/transcript/transcriptLoggerMiddleware.js.map +1 -1
  114. package/dist/src/turnContext.js +2 -1
  115. package/dist/src/turnContext.js.map +1 -1
  116. package/package.json +3 -3
  117. package/src/agent-client/agentClient.ts +5 -4
  118. package/src/agent-client/agentResponseHandler.ts +43 -67
  119. package/src/agent-client/createAgentResponseHandler.ts +133 -0
  120. package/src/agent-client/index.ts +1 -0
  121. package/src/app/adaptiveCards/activityValueParsers.ts +3 -2
  122. package/src/app/adaptiveCards/adaptiveCardsActions.ts +5 -5
  123. package/src/app/agentApplication.ts +8 -16
  124. package/src/app/streaming/streamingResponse.ts +26 -3
  125. package/src/app/turnState.ts +15 -14
  126. package/src/app/turnStateProperty.ts +4 -2
  127. package/src/auth/MemoryCache.ts +7 -1
  128. package/src/auth/authConfiguration.ts +41 -6
  129. package/src/auth/authConstants.ts +7 -7
  130. package/src/auth/{msalConnectionManager.ts → connectionManager.ts} +65 -61
  131. package/src/auth/index.ts +5 -3
  132. package/src/auth/jwt-middleware.ts +118 -9
  133. package/src/auth/msal/msalConnectionManager.ts +55 -0
  134. package/src/auth/msal/msalConnectionSettings.ts +79 -0
  135. package/src/auth/{msalTokenCredential.ts → msal/msalTokenCredential.ts} +2 -1
  136. package/src/auth/{msalTokenProvider.ts → msal/msalTokenProvider.ts} +353 -172
  137. package/src/auth/settings.ts +131 -76
  138. package/src/auth/sidecar/sidecarAuthProvider.ts +234 -0
  139. package/src/auth/sidecar/sidecarConnectionSettings.ts +72 -0
  140. package/src/auth/sidecar/sidecarHttpClient.ts +443 -0
  141. package/src/auth/sidecar/sidecarModels.ts +153 -0
  142. package/src/auth/sidecar/sidecarTokenExpiry.ts +35 -0
  143. package/src/baseAdapter.ts +3 -2
  144. package/src/cloudAdapter.ts +13 -13
  145. package/src/createCloudAdapter.ts +56 -0
  146. package/src/errorHelper.ts +354 -89
  147. package/src/headerPropagation.ts +4 -1
  148. package/src/index.ts +3 -1
  149. package/src/interfaces/index.ts +6 -0
  150. package/src/interfaces/webResponse.ts +44 -0
  151. package/src/middlewareSet.ts +3 -1
  152. package/src/oauth/userTokenClient.ts +46 -11
  153. package/src/state/conversationState.ts +4 -3
  154. package/src/state/userState.ts +4 -3
  155. package/src/storage/memoryStorage.ts +5 -3
  156. package/src/transcript/consoleTranscriptLogger.ts +3 -2
  157. package/src/transcript/fileTranscriptLogger.ts +6 -5
  158. package/src/transcript/transcriptLoggerMiddleware.ts +3 -2
  159. package/src/turnContext.ts +3 -2
  160. package/dist/src/auth/msalConnectionManager.d.ts +0 -64
  161. package/dist/src/auth/msalConnectionManager.js.map +0 -1
  162. package/dist/src/auth/msalTokenCredential.js.map +0 -1
  163. package/dist/src/auth/msalTokenProvider.js.map +0 -1
@@ -9,16 +9,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.MsalTokenProvider = void 0;
11
11
  const msal_node_1 = require("@azure/msal-node");
12
- const authConfiguration_1 = require("./authConfiguration");
12
+ const authConfiguration_1 = require("../authConfiguration");
13
13
  const agents_telemetry_1 = require("@microsoft/agents-telemetry");
14
14
  const crypto_1 = require("crypto");
15
- const MemoryCache_1 = require("./MemoryCache");
15
+ const MemoryCache_1 = require("../MemoryCache");
16
16
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
17
17
  const fs_1 = __importDefault(require("fs"));
18
18
  const crypto_2 = __importDefault(require("crypto"));
19
- const observability_1 = require("../observability");
19
+ const observability_1 = require("../../observability");
20
20
  const agents_activity_1 = require("@microsoft/agents-activity");
21
- const errorHelper_1 = require("../errorHelper");
21
+ const errorHelper_1 = require("../../errorHelper");
22
22
  const audience = 'api://AzureADTokenExchange';
23
23
  const logger = (0, agents_telemetry_1.debug)('agents:msal');
24
24
  const agenticTokenRequestTimeoutMs = 30000;
@@ -59,9 +59,171 @@ class MsalTokenProvider {
59
59
  piiLoggingEnabled: false
60
60
  }
61
61
  };
62
- this._agenticTokenCache = new MemoryCache_1.MemoryCache();
63
62
  this.connectionSettings = connectionSettings;
64
63
  }
64
+ /**
65
+ * Clears process-wide auth caches.
66
+ */
67
+ static clearSharedCaches() {
68
+ MsalTokenProvider._accessTokenCache.clear();
69
+ MsalTokenProvider._agenticTokenCache.clear();
70
+ MsalTokenProvider._confidentialClients.clear();
71
+ }
72
+ static cacheKey(...parts) {
73
+ return JSON.stringify(parts.map(part => part !== null && part !== void 0 ? part : ''));
74
+ }
75
+ static digest(value) {
76
+ return value ? crypto_2.default.createHash('sha256').update(value).digest('base64url') : '';
77
+ }
78
+ getOrCreateConfidentialClient(cacheKey, createClient) {
79
+ const existing = MsalTokenProvider._confidentialClients.get(cacheKey);
80
+ if (existing) {
81
+ MsalTokenProvider._confidentialClients.delete(cacheKey);
82
+ MsalTokenProvider._confidentialClients.set(cacheKey, existing);
83
+ return existing;
84
+ }
85
+ const created = createClient();
86
+ MsalTokenProvider._confidentialClients.set(cacheKey, created);
87
+ while (MsalTokenProvider._confidentialClients.size > MsalTokenProvider._maxConfidentialClients) {
88
+ const oldestKey = MsalTokenProvider._confidentialClients.keys().next().value;
89
+ if (oldestKey === undefined) {
90
+ break;
91
+ }
92
+ MsalTokenProvider._confidentialClients.delete(oldestKey);
93
+ }
94
+ return created;
95
+ }
96
+ getFileCacheIdentity(path) {
97
+ if (!path) {
98
+ return '';
99
+ }
100
+ try {
101
+ const stat = fs_1.default.statSync(path);
102
+ return `${path}:${stat.size}:${stat.mtimeMs}`;
103
+ }
104
+ catch {
105
+ return path;
106
+ }
107
+ }
108
+ getAccessTokenCacheKey(authConfig, scope) {
109
+ var _a, _b, _c, _d, _e;
110
+ const authType = (0, authConfiguration_1.resolveAuthType)(authConfig);
111
+ let authority = (0, authConfiguration_1.resolveAuthority)((_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority, authConfig.tenantId);
112
+ let credentialIdentity = '';
113
+ switch (authType) {
114
+ case authConfiguration_1.AuthType.ClientSecret:
115
+ credentialIdentity = MsalTokenProvider.digest(authConfig.clientSecret);
116
+ break;
117
+ case authConfiguration_1.AuthType.Certificate:
118
+ case authConfiguration_1.AuthType.CertificateSubjectName:
119
+ credentialIdentity = MsalTokenProvider.cacheKey(this.getFileCacheIdentity(authConfig.certPemFile), this.getFileCacheIdentity(authConfig.certKeyFile), authConfig.sendX5C);
120
+ break;
121
+ case authConfiguration_1.AuthType.WorkloadIdentity:
122
+ authority = `https://login.microsoftonline.com/${authConfig.tenantId}`;
123
+ credentialIdentity = this.getFileCacheIdentity((_b = authConfig.federatedTokenFile) !== null && _b !== void 0 ? _b : authConfig.WIDAssertionFile);
124
+ break;
125
+ case authConfiguration_1.AuthType.FederatedCredentials:
126
+ credentialIdentity = (_d = (_c = authConfig.federatedClientId) !== null && _c !== void 0 ? _c : authConfig.FICClientId) !== null && _d !== void 0 ? _d : '';
127
+ break;
128
+ case authConfiguration_1.AuthType.UserManagedIdentity:
129
+ authority = 'managed-identity';
130
+ credentialIdentity = (_e = authConfig.clientId) !== null && _e !== void 0 ? _e : '';
131
+ break;
132
+ case authConfiguration_1.AuthType.SystemManagedIdentity:
133
+ authority = 'managed-identity';
134
+ credentialIdentity = 'system';
135
+ break;
136
+ default:
137
+ credentialIdentity = 'unknown';
138
+ }
139
+ return MsalTokenProvider.cacheKey('access-token', authType, authority, authConfig.clientId, scope, authConfig.azureRegion, credentialIdentity);
140
+ }
141
+ cacheAccessToken(cacheKey, token, expiresOn) {
142
+ const ttlSeconds = this.getTokenCacheTtlSeconds(token, expiresOn);
143
+ if (ttlSeconds > 0) {
144
+ MsalTokenProvider._accessTokenCache.set(cacheKey, token, ttlSeconds);
145
+ }
146
+ }
147
+ cacheAgenticToken(cacheKey, token, ttlSeconds) {
148
+ const safeTtlSeconds = Math.floor(ttlSeconds) - 300;
149
+ if (safeTtlSeconds > 0) {
150
+ MsalTokenProvider._agenticTokenCache.set(cacheKey, token, safeTtlSeconds);
151
+ }
152
+ }
153
+ cacheAgenticAuthenticationResult(cacheKey, token) {
154
+ const ttlSeconds = this.getTokenCacheTtlSeconds(token.accessToken, token.expiresOn);
155
+ if (ttlSeconds > 0) {
156
+ MsalTokenProvider._agenticTokenCache.set(cacheKey, token.accessToken, ttlSeconds);
157
+ }
158
+ }
159
+ getAgenticTokenCacheKey(tenantId, clientId, scopes, tokenBodyParameters) {
160
+ const bodyKey = Object.keys(tokenBodyParameters)
161
+ .sort()
162
+ .filter(key => key !== 'user_federated_identity_credential')
163
+ .map(key => `${key}=${MsalTokenProvider.digest(String(tokenBodyParameters[key]))}`)
164
+ .join('&');
165
+ return MsalTokenProvider.cacheKey('agentic-token', this.resolveAuthority(tenantId), clientId, scopes.join(' '), bodyKey);
166
+ }
167
+ getTokenCacheTtlSeconds(token, expiresOn) {
168
+ var _a;
169
+ const expiresAtMs = (_a = expiresOn === null || expiresOn === void 0 ? void 0 : expiresOn.getTime()) !== null && _a !== void 0 ? _a : this.getJwtExpiresAtMs(token);
170
+ if (!expiresAtMs) {
171
+ return 0;
172
+ }
173
+ return Math.floor((expiresAtMs - Date.now()) / 1000) - 300;
174
+ }
175
+ getJwtExpiresAtMs(token) {
176
+ const payload = jsonwebtoken_1.default.decode(token);
177
+ if (!payload || typeof payload === 'string' || typeof payload.exp !== 'number') {
178
+ return undefined;
179
+ }
180
+ return payload.exp * 1000;
181
+ }
182
+ getClientSecretClient(authConfig) {
183
+ var _a;
184
+ const cacheKey = MsalTokenProvider.cacheKey('confidential-client', authConfiguration_1.AuthType.ClientSecret, authConfig.clientId, (0, authConfiguration_1.resolveAuthority)((_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority, authConfig.tenantId), MsalTokenProvider.digest(authConfig.clientSecret));
185
+ return this.getOrCreateConfidentialClient(cacheKey, () => {
186
+ var _a;
187
+ return new msal_node_1.ConfidentialClientApplication({
188
+ auth: {
189
+ clientId: authConfig.clientId,
190
+ authority: (0, authConfiguration_1.resolveAuthority)((_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority, authConfig.tenantId),
191
+ clientSecret: authConfig.clientSecret
192
+ },
193
+ system: this.sysOptions
194
+ });
195
+ });
196
+ }
197
+ getCertificateClient(authConfig) {
198
+ var _a, _b;
199
+ const cacheKey = MsalTokenProvider.cacheKey('confidential-client', (_a = authConfig.authType) !== null && _a !== void 0 ? _a : authConfiguration_1.AuthType.Certificate, authConfig.clientId, (0, authConfiguration_1.resolveAuthority)((_b = authConfig.authorityEndpoint) !== null && _b !== void 0 ? _b : authConfig.authority, authConfig.tenantId), this.getFileCacheIdentity(authConfig.certPemFile), this.getFileCacheIdentity(authConfig.certKeyFile), authConfig.sendX5C);
200
+ return this.getOrCreateConfidentialClient(cacheKey, () => {
201
+ var _a;
202
+ const privateKeySource = fs_1.default.readFileSync(authConfig.certKeyFile);
203
+ const privateKeyObject = crypto_2.default.createPrivateKey({
204
+ key: privateKeySource,
205
+ format: 'pem'
206
+ });
207
+ const privateKey = privateKeyObject.export({
208
+ format: 'pem',
209
+ type: 'pkcs8'
210
+ });
211
+ const pemFile = fs_1.default.readFileSync(authConfig.certPemFile);
212
+ const pubKeyObject = new crypto_2.default.X509Certificate(pemFile);
213
+ return new msal_node_1.ConfidentialClientApplication({
214
+ auth: {
215
+ clientId: authConfig.clientId || '',
216
+ authority: (0, authConfiguration_1.resolveAuthority)((_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority, authConfig.tenantId),
217
+ clientCertificate: {
218
+ privateKey: privateKey,
219
+ thumbprint: pubKeyObject.fingerprint.replaceAll(':', ''),
220
+ x5c: pemFile.toString()
221
+ }
222
+ },
223
+ system: this.sysOptions
224
+ });
225
+ });
226
+ }
65
227
  async getAccessToken(authConfigOrScope, scope) {
66
228
  return (0, agents_telemetry_1.trace)(observability_1.AuthenticationTraceDefinitions.getAccessToken, async ({ record }) => {
67
229
  var _a;
@@ -70,7 +232,7 @@ class MsalTokenProvider {
70
232
  if (typeof authConfigOrScope === 'string') {
71
233
  // Called as getAccessToken(scope)
72
234
  if (!this.connectionSettings) {
73
- throw new Error('Connection settings must be provided to constructor when calling getAccessToken(scope)');
235
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConnectionSettingsRequiredForGetAccessTokenScope);
74
236
  }
75
237
  authConfig = this.connectionSettings;
76
238
  actualScope = authConfigOrScope;
@@ -85,98 +247,72 @@ class MsalTokenProvider {
85
247
  record({ method: 'unknown' });
86
248
  return '';
87
249
  }
250
+ const accessTokenCacheKey = this.getAccessTokenCacheKey(authConfig, actualScope);
251
+ const cachedAccessToken = MsalTokenProvider._accessTokenCache.get(accessTokenCacheKey);
252
+ if (cachedAccessToken) {
253
+ logger.debug('getAccessToken cache hit clientId=%s scope=%s', authConfig.clientId, actualScope);
254
+ return cachedAccessToken;
255
+ }
88
256
  let token;
89
- if (authConfig.authType) {
90
- record({ method: authConfig.authType });
91
- logger.debug(`getAccessToken via ${authConfig.authType} clientId=${authConfig.clientId} scope=${actualScope}`);
92
- switch (authConfig.authType) {
93
- case authConfiguration_1.AuthType.WorkloadIdentity: {
94
- const tokenFilePath = (_a = authConfig.federatedTokenFile) !== null && _a !== void 0 ? _a : authConfig.WIDAssertionFile;
95
- if (!tokenFilePath) {
96
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.WorkloadIdentityTokenFileRequired);
97
- }
98
- token = await this.acquireAccessTokenViaWID(authConfig, actualScope);
99
- break;
257
+ const authType = (0, authConfiguration_1.resolveAuthType)(authConfig);
258
+ record({ method: authType });
259
+ logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authType, authConfig.clientId, actualScope);
260
+ switch (authType) {
261
+ case authConfiguration_1.AuthType.WorkloadIdentity: {
262
+ const tokenFilePath = (_a = authConfig.federatedTokenFile) !== null && _a !== void 0 ? _a : authConfig.WIDAssertionFile;
263
+ if (!tokenFilePath) {
264
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.WorkloadIdentityTokenFileRequired);
100
265
  }
101
- case authConfiguration_1.AuthType.FederatedCredentials:
102
- if (!authConfig.federatedClientId && !authConfig.FICClientId) {
103
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FICClientIdRequired);
104
- }
105
- token = await this.acquireAccessTokenViaFIC(authConfig, actualScope);
106
- break;
107
- case authConfiguration_1.AuthType.ClientSecret:
108
- if (!authConfig.clientSecret) {
109
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ClientSecretRequired);
110
- }
111
- token = await this.acquireAccessTokenViaSecret(authConfig, actualScope);
112
- break;
113
- case authConfiguration_1.AuthType.Certificate:
114
- case authConfiguration_1.AuthType.CertificateSubjectName:
115
- if (!authConfig.certPemFile || !authConfig.certKeyFile) {
116
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.CertificateFilesRequired);
117
- }
118
- token = await this.acquireTokenWithCertificate(authConfig, actualScope);
119
- break;
120
- case authConfiguration_1.AuthType.UserManagedIdentity:
121
- if (!authConfig.clientId) {
122
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ClientIdRequiredForUserManagedIdentity);
123
- }
124
- token = await this.acquireTokenWithUserAssignedIdentity(authConfig, actualScope);
125
- break;
126
- case authConfiguration_1.AuthType.SystemManagedIdentity:
127
- token = await this.acquireTokenWithSystemAssignedIdentity(authConfig, actualScope);
128
- break;
129
- default:
130
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.UnsupportedAuthType, undefined, { authType: authConfig.authType });
266
+ token = await this.acquireAccessTokenViaWID(authConfig, actualScope);
267
+ break;
131
268
  }
132
- }
133
- else if (authConfig.WIDAssertionFile !== undefined) {
134
- record({ method: authConfiguration_1.AuthType.WorkloadIdentity });
135
- logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authConfiguration_1.AuthType.WorkloadIdentity, authConfig.clientId, actualScope);
136
- token = await this.acquireAccessTokenViaWID(authConfig, actualScope);
137
- }
138
- else if (authConfig.federatedClientId !== undefined || authConfig.FICClientId !== undefined) {
139
- record({ method: authConfiguration_1.AuthType.FederatedCredentials });
140
- logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authConfiguration_1.AuthType.FederatedCredentials, authConfig.clientId, actualScope);
141
- token = await this.acquireAccessTokenViaFIC(authConfig, actualScope);
142
- }
143
- else if (authConfig.clientSecret !== undefined) {
144
- record({ method: authConfiguration_1.AuthType.ClientSecret });
145
- logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authConfiguration_1.AuthType.ClientSecret, authConfig.clientId, actualScope);
146
- token = await this.acquireAccessTokenViaSecret(authConfig, actualScope);
147
- }
148
- else if (authConfig.certPemFile !== undefined &&
149
- authConfig.certKeyFile !== undefined) {
150
- record({ method: authConfiguration_1.AuthType.Certificate });
151
- logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authConfiguration_1.AuthType.Certificate, authConfig.clientId, actualScope);
152
- token = await this.acquireTokenWithCertificate(authConfig, actualScope);
153
- }
154
- else if (authConfig.clientSecret === undefined &&
155
- authConfig.certPemFile === undefined &&
156
- authConfig.certKeyFile === undefined) {
157
- record({ method: authConfiguration_1.AuthType.UserManagedIdentity });
158
- logger.debug('getAccessToken via method=%s clientId=%s scope=%s', authConfiguration_1.AuthType.UserManagedIdentity, authConfig.clientId, actualScope);
159
- token = await this.acquireTokenWithUserAssignedIdentity(authConfig, actualScope);
160
- }
161
- else {
162
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidAuthConfig);
269
+ case authConfiguration_1.AuthType.FederatedCredentials:
270
+ if (!authConfig.federatedClientId && !authConfig.FICClientId) {
271
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FICClientIdRequired);
272
+ }
273
+ token = await this.acquireAccessTokenViaFIC(authConfig, actualScope);
274
+ break;
275
+ case authConfiguration_1.AuthType.ClientSecret:
276
+ if (!authConfig.clientSecret) {
277
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ClientSecretRequired);
278
+ }
279
+ token = await this.acquireAccessTokenViaSecret(authConfig, actualScope);
280
+ break;
281
+ case authConfiguration_1.AuthType.Certificate:
282
+ case authConfiguration_1.AuthType.CertificateSubjectName:
283
+ if (!authConfig.certPemFile || !authConfig.certKeyFile) {
284
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.CertificateFilesRequired);
285
+ }
286
+ token = await this.acquireTokenWithCertificate(authConfig, actualScope);
287
+ break;
288
+ case authConfiguration_1.AuthType.UserManagedIdentity:
289
+ if (!authConfig.clientId) {
290
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ClientIdRequiredForUserManagedIdentity);
291
+ }
292
+ token = await this.acquireTokenWithUserAssignedIdentity(authConfig, actualScope);
293
+ break;
294
+ case authConfiguration_1.AuthType.SystemManagedIdentity:
295
+ token = await this.acquireTokenWithSystemAssignedIdentity(authConfig, actualScope);
296
+ break;
297
+ default:
298
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.UnsupportedAuthType, undefined, { authType });
163
299
  }
164
300
  if (token === undefined) {
165
301
  throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireToken);
166
302
  }
303
+ this.cacheAccessToken(accessTokenCacheKey, token);
167
304
  return token;
168
305
  });
169
306
  }
170
307
  async acquireTokenOnBehalfOf(authConfigOrScopes, scopesOrOboAssertion, oboAssertion) {
171
308
  return (0, agents_telemetry_1.trace)(observability_1.AuthenticationTraceDefinitions.acquireTokenOnBehalfOf, async ({ record }) => {
172
- var _a;
173
309
  let authConfig;
174
310
  let actualScopes;
175
311
  let actualOboAssertion;
176
312
  if (Array.isArray(authConfigOrScopes)) {
177
313
  // Called as acquireTokenOnBehalfOf(scopes, oboAssertion)
178
314
  if (!this.connectionSettings) {
179
- throw new Error('Connection settings must be provided to constructor when calling acquireTokenOnBehalfOf(scopes, oboAssertion)');
315
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConnectionSettingsRequiredForAcquireTokenOnBehalfOf);
180
316
  }
181
317
  authConfig = this.connectionSettings;
182
318
  actualScopes = authConfigOrScopes;
@@ -190,20 +326,13 @@ class MsalTokenProvider {
190
326
  }
191
327
  record({ scopes: actualScopes });
192
328
  logger.debug('acquireTokenOnBehalfOf clientId=%s scopes=%o', authConfig.clientId, actualScopes);
193
- const cca = new msal_node_1.ConfidentialClientApplication({
194
- auth: {
195
- clientId: authConfig.clientId,
196
- authority: `${(_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority}/${authConfig.tenantId || 'botframework.com'}`,
197
- clientSecret: authConfig.clientSecret
198
- },
199
- system: this.sysOptions
200
- });
329
+ const cca = this.getClientSecretClient(authConfig);
201
330
  const token = await cca.acquireTokenOnBehalfOf({
202
331
  oboAssertion: actualOboAssertion,
203
332
  scopes: actualScopes
204
333
  });
205
334
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
206
- throw new Error('Failed to acquire token on behalf of user');
335
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenOnBehalfOf);
207
336
  }
208
337
  return token.accessToken;
209
338
  });
@@ -214,7 +343,12 @@ class MsalTokenProvider {
214
343
  logger.debug('getAgenticInstanceToken tenantId=%s agentAppInstanceId=%s', tenantId, agentAppInstanceId);
215
344
  record({ agenticInstanceId: agentAppInstanceId });
216
345
  if (!this.connectionSettings) {
217
- throw new Error('Connection settings must be provided when calling getAgenticInstanceToken');
346
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConnectionSettingsRequiredForGetAgenticInstanceToken);
347
+ }
348
+ const instanceTokenCacheKey = MsalTokenProvider.cacheKey('agentic-instance-token', this.resolveAuthority(tenantId), agentAppInstanceId, this.connectionSettings.clientId, this.connectionSettings.azureRegion);
349
+ const cachedInstanceToken = MsalTokenProvider._agenticTokenCache.get(instanceTokenCacheKey);
350
+ if (cachedInstanceToken) {
351
+ return cachedInstanceToken;
218
352
  }
219
353
  const appToken = await this.getAgenticApplicationToken(tenantId, agentAppInstanceId);
220
354
  const cca = new msal_node_1.ConfidentialClientApplication({
@@ -231,8 +365,9 @@ class MsalTokenProvider {
231
365
  azureRegion: (_a = this.connectionSettings) === null || _a === void 0 ? void 0 : _a.azureRegion
232
366
  });
233
367
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
234
- throw new Error(`Failed to acquire instance token for agent instance: ${agentAppInstanceId}`);
368
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireInstanceTokenForAgentInstance, undefined, { agentAppInstanceId });
235
369
  }
370
+ this.cacheAgenticAuthenticationResult(instanceTokenCacheKey, token);
236
371
  return token.accessToken;
237
372
  });
238
373
  }
@@ -271,13 +406,13 @@ class MsalTokenProvider {
271
406
  */
272
407
  async acquireTokenForAgenticScenarios(tenantId, clientId, clientAssertion, scopes, tokenBodyParameters) {
273
408
  if (!this.connectionSettings) {
274
- throw new Error('Connection settings must be provided when calling getAgenticInstanceToken');
409
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConnectionSettingsRequiredForGetAgenticInstanceToken);
275
410
  }
276
411
  logger.debug('acquireTokenForAgenticScenarios clientId=%s tenantId=%s scopes=%o grant_type=%s', clientId, tenantId, scopes, tokenBodyParameters.grant_type);
277
412
  // Check cache first
278
- const cacheKey = `${clientId}/${Object.keys(tokenBodyParameters).map(key => key !== 'user_federated_identity_credential' ? `${key}=${tokenBodyParameters[key]}` : '').join('&')}/${scopes.join(';')}`;
279
- if (this._agenticTokenCache.get(cacheKey)) {
280
- return this._agenticTokenCache.get(cacheKey);
413
+ const cacheKey = this.getAgenticTokenCacheKey(tenantId, clientId, scopes, tokenBodyParameters);
414
+ if (MsalTokenProvider._agenticTokenCache.get(cacheKey)) {
415
+ return MsalTokenProvider._agenticTokenCache.get(cacheKey);
281
416
  }
282
417
  const url = `${this.resolveAuthority(tenantId)}/oauth2/v2.0/token`;
283
418
  const data = {
@@ -324,39 +459,48 @@ class MsalTokenProvider {
324
459
  clearTimeout(timeoutId);
325
460
  });
326
461
  // capture token, expire local cache 5 minutes early
327
- this._agenticTokenCache.set(cacheKey, token.access_token, token.expires_in - 300);
462
+ this.cacheAgenticToken(cacheKey, token.access_token, token.expires_in);
328
463
  return token.access_token;
329
464
  }
330
465
  async getAgenticUserToken(tenantId, agentAppInstanceId, agenticUserId, scopes) {
331
466
  return (0, agents_telemetry_1.trace)(observability_1.AuthenticationTraceDefinitions.getAgenticUserToken, async ({ record }) => {
332
467
  logger.debug('getAgenticUserToken tenantId=%s agentAppInstanceId=%s scopes=%o', tenantId, agentAppInstanceId, scopes);
333
468
  record({ agenticInstanceId: agentAppInstanceId, agenticUserId, scopes });
469
+ const userTokenParameters = {
470
+ user_id: agenticUserId,
471
+ grant_type: 'user_fic',
472
+ };
473
+ const userTokenCacheKey = this.getAgenticTokenCacheKey(tenantId, agentAppInstanceId, scopes, userTokenParameters);
474
+ const cachedUserToken = MsalTokenProvider._agenticTokenCache.get(userTokenCacheKey);
475
+ if (cachedUserToken) {
476
+ return cachedUserToken;
477
+ }
334
478
  const agentToken = await this.getAgenticApplicationToken(tenantId, agentAppInstanceId);
335
479
  const instanceToken = await this.getAgenticInstanceToken(tenantId, agentAppInstanceId);
336
480
  const token = await this.acquireTokenForAgenticScenarios(tenantId, agentAppInstanceId, agentToken, scopes, {
337
- user_id: agenticUserId,
481
+ ...userTokenParameters,
338
482
  user_federated_identity_credential: instanceToken,
339
- grant_type: 'user_fic',
340
483
  });
341
484
  if (!token) {
342
- throw new Error(`Failed to acquire instance token for user token: ${agentAppInstanceId}`);
485
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireInstanceTokenForUserToken, undefined, { agentAppInstanceId });
343
486
  }
344
487
  return token;
345
488
  });
346
489
  }
347
490
  async getAgenticApplicationToken(tenantId, agentAppInstanceId) {
348
- var _a, _b, _c;
491
+ var _a, _b;
349
492
  if (!((_a = this.connectionSettings) === null || _a === void 0 ? void 0 : _a.clientId)) {
350
- throw new Error('Connection settings must be provided when calling getAgenticApplicationToken');
493
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConnectionSettingsRequiredForGetAgenticApplicationToken);
351
494
  }
352
495
  logger.debug('getAgenticApplicationToken clientId=%s tenantId=%s agentAppInstanceId=%s', this.connectionSettings.clientId, tenantId, agentAppInstanceId);
353
- if (this.connectionSettings.authType === authConfiguration_1.AuthType.IdentityProxyManager) {
496
+ const authType = (0, authConfiguration_1.resolveAuthType)(this.connectionSettings);
497
+ if (authType === authConfiguration_1.AuthType.IdentityProxyManager) {
354
498
  let resource;
355
499
  if (!this.connectionSettings.idpmResource) {
356
500
  resource = 'api://AzureAdTokenExchange/.default';
357
501
  }
358
502
  else if (!URL.canParse(this.connectionSettings.idpmResource)) {
359
- throw new Error('idpmResource must be a valid absolute URI');
503
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.IdpmResourceAbsoluteUriRequired);
360
504
  }
361
505
  else {
362
506
  resource = this.connectionSettings.idpmResource;
@@ -369,54 +513,41 @@ class MsalTokenProvider {
369
513
  });
370
514
  const tokenResult = await msiApp.acquireToken({ resource });
371
515
  if (!(tokenResult === null || tokenResult === void 0 ? void 0 : tokenResult.accessToken)) {
372
- throw new Error(`Failed to acquire token via IdentityProxyManager for agent instance: ${agentAppInstanceId}`);
516
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenViaIdentityProxyManagerForAgentInstance, undefined, { agentAppInstanceId });
373
517
  }
374
518
  logger.debug('getAgenticApplicationToken via IdentityProxyManager clientId=%s resource=%s', this.connectionSettings.clientId, resource);
375
519
  return tokenResult.accessToken;
376
520
  }
377
521
  let clientAssertion;
378
- if (this.connectionSettings.authType) {
379
- switch (this.connectionSettings.authType) {
380
- case authConfiguration_1.AuthType.WorkloadIdentity: {
381
- const tokenFilePath = (_b = this.connectionSettings.federatedTokenFile) !== null && _b !== void 0 ? _b : this.connectionSettings.WIDAssertionFile;
382
- if (tokenFilePath === undefined) {
383
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.WorkloadIdentityTokenFileRequired);
384
- }
385
- clientAssertion = fs_1.default.readFileSync(tokenFilePath, 'utf8');
386
- break;
522
+ switch (authType) {
523
+ case authConfiguration_1.AuthType.WorkloadIdentity: {
524
+ const tokenFilePath = (_b = this.connectionSettings.federatedTokenFile) !== null && _b !== void 0 ? _b : this.connectionSettings.WIDAssertionFile;
525
+ if (tokenFilePath === undefined) {
526
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.WorkloadIdentityTokenFileRequired);
387
527
  }
388
- case authConfiguration_1.AuthType.FederatedCredentials:
389
- if (!this.connectionSettings.federatedClientId && !this.connectionSettings.FICClientId) {
390
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FICClientIdRequired);
391
- }
392
- clientAssertion = await this.fetchExternalToken(this.connectionSettings.federatedClientId || this.connectionSettings.FICClientId);
393
- break;
394
- case authConfiguration_1.AuthType.Certificate:
395
- case authConfiguration_1.AuthType.CertificateSubjectName:
396
- if (!this.connectionSettings.certPemFile || !this.connectionSettings.certKeyFile) {
397
- throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.CertificateFilesRequired);
398
- }
399
- clientAssertion = this.getAssertionFromCert(this.connectionSettings);
400
- break;
528
+ clientAssertion = fs_1.default.readFileSync(tokenFilePath, 'utf8');
529
+ break;
401
530
  }
402
- }
403
- else if (this.connectionSettings.WIDAssertionFile !== undefined) {
404
- const tokenFilePath = (_c = this.connectionSettings.federatedTokenFile) !== null && _c !== void 0 ? _c : this.connectionSettings.WIDAssertionFile;
405
- clientAssertion = fs_1.default.readFileSync(tokenFilePath, 'utf8');
406
- }
407
- else if (this.connectionSettings.federatedClientId !== undefined || this.connectionSettings.FICClientId !== undefined) {
408
- clientAssertion = await this.fetchExternalToken(this.connectionSettings.federatedClientId || this.connectionSettings.FICClientId);
409
- }
410
- else if (this.connectionSettings.certPemFile !== undefined &&
411
- this.connectionSettings.certKeyFile !== undefined) {
412
- clientAssertion = this.getAssertionFromCert(this.connectionSettings);
531
+ case authConfiguration_1.AuthType.FederatedCredentials:
532
+ if (!this.connectionSettings.federatedClientId && !this.connectionSettings.FICClientId) {
533
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FICClientIdRequired);
534
+ }
535
+ clientAssertion = await this.fetchExternalToken(this.connectionSettings.federatedClientId || this.connectionSettings.FICClientId);
536
+ break;
537
+ case authConfiguration_1.AuthType.Certificate:
538
+ case authConfiguration_1.AuthType.CertificateSubjectName:
539
+ if (!this.connectionSettings.certPemFile || !this.connectionSettings.certKeyFile) {
540
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.CertificateFilesRequired);
541
+ }
542
+ clientAssertion = this.getAssertionFromCert(this.connectionSettings);
543
+ break;
413
544
  }
414
545
  const token = await this.acquireTokenForAgenticScenarios(tenantId, this.connectionSettings.clientId, clientAssertion, ['api://AzureAdTokenExchange/.default'], {
415
546
  grant_type: 'client_credentials',
416
547
  fmi_path: agentAppInstanceId,
417
548
  });
418
549
  if (!token) {
419
- throw new Error(`Failed to acquire token for agent instance: ${agentAppInstanceId}`);
550
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireInstanceTokenForAgentInstance, undefined, { agentAppInstanceId });
420
551
  }
421
552
  return token;
422
553
  }
@@ -491,37 +622,14 @@ class MsalTokenProvider {
491
622
  * @returns A promise that resolves to the access token.
492
623
  */
493
624
  async acquireTokenWithCertificate(authConfig, scope) {
494
- var _a;
495
- const privateKeySource = fs_1.default.readFileSync(authConfig.certKeyFile);
496
- const privateKeyObject = crypto_2.default.createPrivateKey({
497
- key: privateKeySource,
498
- format: 'pem'
499
- });
500
- const privateKey = privateKeyObject.export({
501
- format: 'pem',
502
- type: 'pkcs8'
503
- });
504
- const pemFile = fs_1.default.readFileSync(authConfig.certPemFile);
505
- const pubKeyObject = new crypto_2.default.X509Certificate(pemFile);
506
- const cca = new msal_node_1.ConfidentialClientApplication({
507
- auth: {
508
- clientId: authConfig.clientId || '',
509
- authority: `${(_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority}/${authConfig.tenantId || 'botframework.com'}`,
510
- clientCertificate: {
511
- privateKey: privateKey,
512
- thumbprint: pubKeyObject.fingerprint.replaceAll(':', ''),
513
- x5c: pemFile.toString()
514
- }
515
- },
516
- system: this.sysOptions
517
- });
625
+ const cca = this.getCertificateClient(authConfig);
518
626
  const token = await cca.acquireTokenByClientCredential({
519
627
  scopes: [`${scope}/.default`],
520
628
  correlationId: (0, crypto_1.randomUUID)(),
521
629
  azureRegion: authConfig.azureRegion
522
630
  });
523
631
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
524
- throw new Error('Failed to acquire token using certificate');
632
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenUsingCertificate);
525
633
  }
526
634
  return token.accessToken;
527
635
  }
@@ -532,22 +640,14 @@ class MsalTokenProvider {
532
640
  * @returns A promise that resolves to the access token.
533
641
  */
534
642
  async acquireAccessTokenViaSecret(authConfig, scope) {
535
- var _a;
536
- const cca = new msal_node_1.ConfidentialClientApplication({
537
- auth: {
538
- clientId: authConfig.clientId,
539
- authority: `${(_a = authConfig.authorityEndpoint) !== null && _a !== void 0 ? _a : authConfig.authority}/${authConfig.tenantId || 'botframework.com'}`,
540
- clientSecret: authConfig.clientSecret
541
- },
542
- system: this.sysOptions
543
- });
643
+ const cca = this.getClientSecretClient(authConfig);
544
644
  const token = await cca.acquireTokenByClientCredential({
545
645
  scopes: [`${scope}/.default`],
546
646
  correlationId: (0, crypto_1.randomUUID)(),
547
647
  azureRegion: authConfig.azureRegion
548
648
  });
549
649
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
550
- throw new Error('Failed to acquire token using client secret');
650
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenUsingClientSecret);
551
651
  }
552
652
  return token.accessToken;
553
653
  }
@@ -572,7 +672,7 @@ class MsalTokenProvider {
572
672
  const token = await cca.acquireTokenByClientCredential({ scopes, azureRegion: authConfig.azureRegion });
573
673
  logger.debug('got token using FIC client assertion');
574
674
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
575
- throw new Error('Failed to acquire token using FIC client assertion');
675
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenUsingFICClientAssertion);
576
676
  }
577
677
  return token.accessToken;
578
678
  }
@@ -598,7 +698,7 @@ class MsalTokenProvider {
598
698
  const token = await cca.acquireTokenByClientCredential({ scopes, azureRegion: authConfig.azureRegion });
599
699
  logger.debug('got token using WID client assertion');
600
700
  if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
601
- throw new Error('Failed to acquire token using WID client assertion');
701
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireTokenUsingWIDClientAssertion);
602
702
  }
603
703
  return token.accessToken;
604
704
  }
@@ -620,10 +720,14 @@ class MsalTokenProvider {
620
720
  });
621
721
  logger.debug('got token for FIC');
622
722
  if (!(response === null || response === void 0 ? void 0 : response.accessToken)) {
623
- throw new Error('Failed to acquire external token for FIC client assertion');
723
+ throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.FailedToAcquireExternalTokenForFICClientAssertion);
624
724
  }
625
725
  return response.accessToken;
626
726
  }
627
727
  }
628
728
  exports.MsalTokenProvider = MsalTokenProvider;
729
+ MsalTokenProvider._accessTokenCache = new MemoryCache_1.MemoryCache();
730
+ MsalTokenProvider._agenticTokenCache = new MemoryCache_1.MemoryCache();
731
+ MsalTokenProvider._confidentialClients = new Map();
732
+ MsalTokenProvider._maxConfidentialClients = 100;
629
733
  //# sourceMappingURL=msalTokenProvider.js.map