agentlang 0.10.9 → 0.11.0

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 (108) hide show
  1. package/README.md +60 -0
  2. package/out/api/http.d.ts.map +1 -1
  3. package/out/api/http.js +64 -39
  4. package/out/api/http.js.map +1 -1
  5. package/out/cli/main.d.ts +1 -1
  6. package/out/cli/main.d.ts.map +1 -1
  7. package/out/cli/main.js +7 -3
  8. package/out/cli/main.js.map +1 -1
  9. package/out/extension/main.cjs +250 -250
  10. package/out/extension/main.cjs.map +2 -2
  11. package/out/language/main.cjs +504 -504
  12. package/out/language/main.cjs.map +3 -3
  13. package/out/runtime/auth/cognito.d.ts.map +1 -1
  14. package/out/runtime/auth/cognito.js +129 -64
  15. package/out/runtime/auth/cognito.js.map +1 -1
  16. package/out/runtime/defs.d.ts +22 -9
  17. package/out/runtime/defs.d.ts.map +1 -1
  18. package/out/runtime/defs.js +44 -9
  19. package/out/runtime/defs.js.map +1 -1
  20. package/out/runtime/document-retriever.d.ts +24 -0
  21. package/out/runtime/document-retriever.d.ts.map +1 -0
  22. package/out/runtime/document-retriever.js +258 -0
  23. package/out/runtime/document-retriever.js.map +1 -0
  24. package/out/runtime/errors/coded-error.d.ts +8 -0
  25. package/out/runtime/errors/coded-error.d.ts.map +1 -0
  26. package/out/runtime/errors/coded-error.js +13 -0
  27. package/out/runtime/errors/coded-error.js.map +1 -0
  28. package/out/runtime/errors/http-error.d.ts +25 -0
  29. package/out/runtime/errors/http-error.d.ts.map +1 -0
  30. package/out/runtime/errors/http-error.js +169 -0
  31. package/out/runtime/errors/http-error.js.map +1 -0
  32. package/out/runtime/excel-resolver.d.ts +4 -0
  33. package/out/runtime/excel-resolver.d.ts.map +1 -0
  34. package/out/runtime/excel-resolver.js +96 -0
  35. package/out/runtime/excel-resolver.js.map +1 -0
  36. package/out/runtime/excel.d.ts +25 -0
  37. package/out/runtime/excel.d.ts.map +1 -0
  38. package/out/runtime/excel.js +127 -0
  39. package/out/runtime/excel.js.map +1 -0
  40. package/out/runtime/interpreter.d.ts.map +1 -1
  41. package/out/runtime/interpreter.js +26 -25
  42. package/out/runtime/interpreter.js.map +1 -1
  43. package/out/runtime/logger.d.ts +6 -0
  44. package/out/runtime/logger.d.ts.map +1 -1
  45. package/out/runtime/logger.js +21 -0
  46. package/out/runtime/logger.js.map +1 -1
  47. package/out/runtime/module.d.ts.map +1 -1
  48. package/out/runtime/module.js +14 -13
  49. package/out/runtime/module.js.map +1 -1
  50. package/out/runtime/modules/ai.d.ts +1 -0
  51. package/out/runtime/modules/ai.d.ts.map +1 -1
  52. package/out/runtime/modules/ai.js +1 -0
  53. package/out/runtime/modules/ai.js.map +1 -1
  54. package/out/runtime/modules/auth.d.ts.map +1 -1
  55. package/out/runtime/modules/auth.js +35 -12
  56. package/out/runtime/modules/auth.js.map +1 -1
  57. package/out/runtime/modules/core.d.ts +6 -0
  58. package/out/runtime/modules/core.d.ts.map +1 -1
  59. package/out/runtime/modules/core.js +20 -0
  60. package/out/runtime/modules/core.js.map +1 -1
  61. package/out/runtime/resolvers/sqldb/database.d.ts.map +1 -1
  62. package/out/runtime/resolvers/sqldb/database.js +76 -39
  63. package/out/runtime/resolvers/sqldb/database.js.map +1 -1
  64. package/out/runtime/resolvers/sqldb/db-errors.d.ts +6 -0
  65. package/out/runtime/resolvers/sqldb/db-errors.d.ts.map +1 -0
  66. package/out/runtime/resolvers/sqldb/db-errors.js +100 -0
  67. package/out/runtime/resolvers/sqldb/db-errors.js.map +1 -0
  68. package/out/runtime/resolvers/vector/lancedb-store.d.ts +16 -0
  69. package/out/runtime/resolvers/vector/lancedb-store.d.ts.map +1 -0
  70. package/out/runtime/resolvers/vector/lancedb-store.js +159 -0
  71. package/out/runtime/resolvers/vector/lancedb-store.js.map +1 -0
  72. package/out/runtime/resolvers/vector/types.d.ts +32 -0
  73. package/out/runtime/resolvers/vector/types.d.ts.map +1 -0
  74. package/out/runtime/resolvers/vector/types.js +2 -0
  75. package/out/runtime/resolvers/vector/types.js.map +1 -0
  76. package/out/runtime/state.d.ts +3 -0
  77. package/out/runtime/state.d.ts.map +1 -1
  78. package/out/runtime/state.js +7 -0
  79. package/out/runtime/state.js.map +1 -1
  80. package/out/setupClassic.d.ts +98 -0
  81. package/out/setupClassic.d.ts.map +1 -0
  82. package/out/setupClassic.js +38 -0
  83. package/out/setupClassic.js.map +1 -0
  84. package/out/setupCommon.d.ts +2 -0
  85. package/out/setupCommon.d.ts.map +1 -0
  86. package/out/setupCommon.js +33 -0
  87. package/out/setupCommon.js.map +1 -0
  88. package/out/setupExtended.d.ts +40 -0
  89. package/out/setupExtended.d.ts.map +1 -0
  90. package/out/setupExtended.js +67 -0
  91. package/out/setupExtended.js.map +1 -0
  92. package/package.json +19 -18
  93. package/src/api/http.ts +71 -37
  94. package/src/cli/main.ts +12 -4
  95. package/src/runtime/auth/cognito.ts +187 -65
  96. package/src/runtime/defs.ts +51 -18
  97. package/src/runtime/errors/coded-error.ts +18 -0
  98. package/src/runtime/errors/http-error.ts +197 -0
  99. package/src/runtime/interpreter.ts +70 -27
  100. package/src/runtime/logger.ts +27 -0
  101. package/src/runtime/module.ts +45 -13
  102. package/src/runtime/modules/ai.ts +1 -0
  103. package/src/runtime/modules/auth.ts +35 -12
  104. package/src/runtime/modules/core.ts +26 -0
  105. package/src/runtime/resolvers/sqldb/database.ts +88 -37
  106. package/src/runtime/resolvers/sqldb/db-errors.ts +113 -0
  107. package/src/runtime/state.ts +7 -0
  108. package/src/xlsx.d.ts +17 -0
@@ -32,6 +32,7 @@ import {
32
32
  CodeMismatchError,
33
33
  BadRequestError,
34
34
  } from '../defs.js';
35
+ import { createCodedError } from '../errors/coded-error.js';
35
36
 
36
37
  let fromEnv: any = undefined;
37
38
  let CognitoIdentityProviderClient: any = undefined;
@@ -105,154 +106,227 @@ function handleCognitoError(err: any, context: string): never {
105
106
  switch (err.name) {
106
107
  case 'UserNotFoundException':
107
108
  logger.debug(`User not found in context: ${context}`);
108
- throw new UserNotFoundError('User account not found. Please check your email or sign up.');
109
+ throw new UserNotFoundError('User account not found. Please check your email or sign up.', {
110
+ agentlangCode: 'AL_COGNITO_USER_NOT_FOUND_EXCEPTION',
111
+ });
109
112
 
110
113
  case 'NotAuthorizedException':
111
114
  // Check if this is a password-related error vs other auth issues
112
115
  if (err.message && err.message.includes('password')) {
113
116
  logger.debug(`Invalid password attempt in context: ${context}`);
114
- throw new UnauthorisedError('Invalid password. Please try again.');
117
+ throw new UnauthorisedError('Invalid password. Please try again.', {
118
+ agentlangCode: 'AL_COGNITO_INVALID_PASSWORD',
119
+ });
115
120
  } else if (err.message && err.message.includes('not confirmed')) {
116
121
  logger.debug(`User not confirmed in context: ${context}`);
117
- throw new UserNotConfirmedError();
122
+ throw new UserNotConfirmedError(undefined, {
123
+ agentlangCode: 'AL_COGNITO_NOT_CONFIRMED_MSG',
124
+ });
118
125
  } else {
119
126
  logger.debug(`Authentication failed in context: ${context}`);
120
- throw new UnauthorisedError('Authentication failed. Please check your credentials.');
127
+ throw new UnauthorisedError('Authentication failed. Please check your credentials.', {
128
+ agentlangCode: 'AL_COGNITO_AUTH_FAILED',
129
+ });
121
130
  }
122
131
 
123
132
  case 'UserNotConfirmedException':
124
133
  logger.debug(`User not confirmed in context: ${context}`);
125
- throw new UserNotConfirmedError();
134
+ throw new UserNotConfirmedError(undefined, {
135
+ agentlangCode: 'AL_COGNITO_USER_NOT_CONFIRMED_EX',
136
+ });
126
137
 
127
138
  case 'PasswordResetRequiredException':
128
139
  logger.debug(`Password reset required in context: ${context}`);
129
- throw new PasswordResetRequiredError();
140
+ throw new PasswordResetRequiredError(undefined, {
141
+ agentlangCode: 'AL_COGNITO_PASSWORD_RESET_REQUIRED_EX',
142
+ });
130
143
 
131
144
  case 'TooManyRequestsException':
132
145
  logger.warn(`Rate limit exceeded in context: ${context}`);
133
- throw new TooManyRequestsError();
146
+ throw new TooManyRequestsError(undefined, { agentlangCode: 'AL_COGNITO_TOO_MANY_REQUESTS' });
134
147
 
135
148
  case 'TooManyFailedAttemptsException':
136
149
  logger.warn(`Too many failed attempts in context: ${context}`);
137
- throw new TooManyRequestsError('Too many failed login attempts. Please try again later.');
150
+ throw new TooManyRequestsError('Too many failed login attempts. Please try again later.', {
151
+ agentlangCode: 'AL_COGNITO_TOO_MANY_FAILED_ATTEMPTS',
152
+ });
138
153
 
139
154
  case 'InvalidParameterException':
140
155
  logger.debug(`Invalid parameters in context: ${context}`);
141
156
  throw new InvalidParameterError(
142
- sanitizeErrorMessage(err.message) || 'Invalid parameters provided'
157
+ sanitizeErrorMessage(err.message) || 'Invalid parameters provided',
158
+ { agentlangCode: 'AL_COGNITO_INVALID_PARAMETER_EX' }
143
159
  );
144
160
 
145
161
  case 'ExpiredCodeException':
146
162
  logger.debug(`Expired code in context: ${context}`);
147
- throw new ExpiredCodeError();
163
+ throw new ExpiredCodeError(undefined, { agentlangCode: 'AL_COGNITO_EXPIRED_CODE_EX' });
148
164
 
149
165
  case 'CodeMismatchException':
150
166
  logger.debug(`Code mismatch in context: ${context}`);
151
- throw new CodeMismatchError();
167
+ throw new CodeMismatchError(undefined, { agentlangCode: 'AL_COGNITO_CODE_MISMATCH_EX' });
152
168
 
153
169
  case 'UsernameExistsException':
154
170
  logger.debug(`Username exists in context: ${context}`);
155
- throw new BadRequestError('An account with this email already exists.');
171
+ throw new BadRequestError('An account with this email already exists.', {
172
+ agentlangCode: 'AL_COGNITO_USERNAME_EXISTS',
173
+ });
156
174
 
157
175
  case 'InvalidPasswordException':
158
176
  logger.debug(`Invalid password format in context: ${context}`);
159
177
  throw new BadRequestError(
160
- 'Password does not meet requirements. It must be at least 8 characters long and contain uppercase, lowercase, numbers, and special characters.'
178
+ 'Password does not meet requirements. It must be at least 8 characters long and contain uppercase, lowercase, numbers, and special characters.',
179
+ { agentlangCode: 'AL_COGNITO_INVALID_PASSWORD_FORMAT' }
161
180
  );
162
181
 
163
182
  case 'LimitExceededException':
164
183
  logger.warn(`Service limit exceeded in context: ${context}`);
165
- throw new TooManyRequestsError('Service limit exceeded. Please try again later.');
184
+ throw new TooManyRequestsError('Service limit exceeded. Please try again later.', {
185
+ agentlangCode: 'AL_COGNITO_LIMIT_EXCEEDED',
186
+ });
166
187
 
167
188
  case 'InternalErrorException':
168
189
  logger.error(`Internal Cognito error in context: ${context}`);
169
- throw new Error('Authentication service is temporarily unavailable. Please try again later.');
190
+ throw createCodedError(
191
+ 'Authentication service is temporarily unavailable. Please try again later.',
192
+ 'AL_COGNITO_INTERNAL_ERROR_EX'
193
+ );
170
194
 
171
195
  case 'ResourceNotFoundException':
172
196
  logger.error(`Resource not found in context: ${context}`);
173
- throw new Error('Authentication service configuration error. Please contact support.');
197
+ throw createCodedError(
198
+ 'Authentication service configuration error. Please contact support.',
199
+ 'AL_COGNITO_RESOURCE_NOT_FOUND_EX'
200
+ );
174
201
 
175
202
  case 'AliasExistsException':
176
203
  logger.debug(`Alias exists in context: ${context}`);
177
- throw new BadRequestError('An account with this email already exists.');
204
+ throw new BadRequestError('An account with this email already exists.', {
205
+ agentlangCode: 'AL_COGNITO_ALIAS_EXISTS',
206
+ });
178
207
 
179
208
  case 'InvalidEmailRoleAccessPolicyException':
180
209
  logger.error(`Invalid email role access policy in context: ${context}`);
181
- throw new Error('Email service configuration error. Please contact support.');
210
+ throw createCodedError(
211
+ 'Email service configuration error. Please contact support.',
212
+ 'AL_COGNITO_INVALID_EMAIL_ROLE_POLICY'
213
+ );
182
214
 
183
215
  case 'UserLambdaValidationException':
184
216
  logger.error(`User lambda validation error in context: ${context}`);
185
- throw new BadRequestError('User validation failed. Please check your input and try again.');
217
+ throw new BadRequestError('User validation failed. Please check your input and try again.', {
218
+ agentlangCode: 'AL_COGNITO_USER_LAMBDA_VALIDATION',
219
+ });
186
220
 
187
221
  case 'UnsupportedUserStateException':
188
222
  logger.debug(`Unsupported user state in context: ${context}`);
189
223
  throw new UserNotConfirmedError(
190
- 'User account is in an unsupported state. Please contact support.'
224
+ 'User account is in an unsupported state. Please contact support.',
225
+ { agentlangCode: 'AL_COGNITO_UNSUPPORTED_USER_STATE' }
191
226
  );
192
227
 
193
228
  case 'MFAMethodNotFoundException':
194
229
  logger.debug(`MFA method not found in context: ${context}`);
195
- throw new BadRequestError('MFA method not found. Please set up MFA and try again.');
230
+ throw new BadRequestError('MFA method not found. Please set up MFA and try again.', {
231
+ agentlangCode: 'AL_COGNITO_MFA_NOT_FOUND',
232
+ });
196
233
 
197
234
  case 'CodeDeliveryFailureException':
198
235
  logger.error(`Code delivery failure in context: ${context}`);
199
- throw new Error('Unable to deliver verification code. Please try again later.');
236
+ throw createCodedError(
237
+ 'Unable to deliver verification code. Please try again later.',
238
+ 'AL_COGNITO_CODE_DELIVERY_FAILURE'
239
+ );
200
240
 
201
241
  case 'DuplicateProviderException':
202
242
  logger.error(`Duplicate provider in context: ${context}`);
203
- throw new BadRequestError('Authentication provider already exists.');
243
+ throw new BadRequestError('Authentication provider already exists.', {
244
+ agentlangCode: 'AL_COGNITO_DUPLICATE_PROVIDER',
245
+ });
204
246
 
205
247
  case 'EnableSoftwareTokenMFAException':
206
248
  logger.debug(`Software token MFA required in context: ${context}`);
207
- throw new BadRequestError('Software token MFA setup required.');
249
+ throw new BadRequestError('Software token MFA setup required.', {
250
+ agentlangCode: 'AL_COGNITO_ENABLE_SOFTWARE_TOKEN_MFA',
251
+ });
208
252
 
209
253
  case 'ForbiddenException':
210
254
  logger.warn(`Forbidden access in context: ${context}`);
211
- throw new UnauthorisedError('Access forbidden. Please check your permissions.');
255
+ throw new UnauthorisedError('Access forbidden. Please check your permissions.', {
256
+ agentlangCode: 'AL_COGNITO_FORBIDDEN',
257
+ });
212
258
 
213
259
  case 'GroupExistsException':
214
260
  logger.debug(`Group exists in context: ${context}`);
215
- throw new BadRequestError('Group already exists.');
261
+ throw new BadRequestError('Group already exists.', {
262
+ agentlangCode: 'AL_COGNITO_GROUP_EXISTS',
263
+ });
216
264
 
217
265
  case 'InvalidLambdaResponseException':
218
266
  logger.error(`Invalid lambda response in context: ${context}`);
219
- throw new Error('Authentication service error. Please try again later.');
267
+ throw createCodedError(
268
+ 'Authentication service error. Please try again later.',
269
+ 'AL_COGNITO_INVALID_LAMBDA_RESPONSE'
270
+ );
220
271
 
221
272
  case 'InvalidOAuthFlowException':
222
273
  logger.error(`Invalid OAuth flow in context: ${context}`);
223
- throw new BadRequestError('Invalid OAuth flow. Please try again.');
274
+ throw new BadRequestError('Invalid OAuth flow. Please try again.', {
275
+ agentlangCode: 'AL_COGNITO_INVALID_OAUTH_FLOW',
276
+ });
224
277
 
225
278
  case 'InvalidSmsRoleAccessPolicyException':
226
279
  logger.error(`Invalid SMS role access policy in context: ${context}`);
227
- throw new Error('SMS service configuration error. Please contact support.');
280
+ throw createCodedError(
281
+ 'SMS service configuration error. Please contact support.',
282
+ 'AL_COGNITO_INVALID_SMS_ROLE_POLICY'
283
+ );
228
284
 
229
285
  case 'InvalidSmsRoleTrustRelationshipException':
230
286
  logger.error(`Invalid SMS role trust relationship in context: ${context}`);
231
- throw new Error('SMS service configuration error. Please contact support.');
287
+ throw createCodedError(
288
+ 'SMS service configuration error. Please contact support.',
289
+ 'AL_COGNITO_INVALID_SMS_TRUST'
290
+ );
232
291
 
233
292
  case 'InvalidUserPoolConfigurationException':
234
293
  logger.error(`Invalid user pool configuration in context: ${context}`);
235
- throw new Error('Authentication service configuration error. Please contact support.');
294
+ throw createCodedError(
295
+ 'Authentication service configuration error. Please contact support.',
296
+ 'AL_COGNITO_INVALID_USER_POOL_CONFIG'
297
+ );
236
298
 
237
299
  case 'PreconditionNotMetException':
238
300
  logger.debug(`Precondition not met in context: ${context}`);
239
- throw new BadRequestError('Precondition not met. Please check your request and try again.');
301
+ throw new BadRequestError('Precondition not met. Please check your request and try again.', {
302
+ agentlangCode: 'AL_COGNITO_PRECONDITION_NOT_MET',
303
+ });
240
304
 
241
305
  case 'ScopeDoesNotExistException':
242
306
  logger.error(`Scope does not exist in context: ${context}`);
243
- throw new BadRequestError('Invalid scope. Please check your request.');
307
+ throw new BadRequestError('Invalid scope. Please check your request.', {
308
+ agentlangCode: 'AL_COGNITO_SCOPE_MISSING',
309
+ });
244
310
 
245
311
  case 'UnexpectedLambdaException':
246
312
  logger.error(`Unexpected lambda exception in context: ${context}`);
247
- throw new Error('Authentication service error. Please try again later.');
313
+ throw createCodedError(
314
+ 'Authentication service error. Please try again later.',
315
+ 'AL_COGNITO_UNEXPECTED_LAMBDA'
316
+ );
248
317
 
249
318
  case 'UserImportInProgressException':
250
319
  logger.warn(`User import in progress in context: ${context}`);
251
- throw new TooManyRequestsError('User import in progress. Please try again later.');
320
+ throw new TooManyRequestsError('User import in progress. Please try again later.', {
321
+ agentlangCode: 'AL_COGNITO_USER_IMPORT_IN_PROGRESS',
322
+ });
252
323
 
253
324
  case 'UserPoolTaggingException':
254
325
  logger.error(`User pool tagging exception in context: ${context}`);
255
- throw new Error('Authentication service configuration error. Please contact support.');
326
+ throw createCodedError(
327
+ 'Authentication service configuration error. Please contact support.',
328
+ 'AL_COGNITO_USER_POOL_TAGGING'
329
+ );
256
330
 
257
331
  default:
258
332
  // For any other errors, throw a generic error with sanitized message
@@ -261,8 +335,9 @@ function handleCognitoError(err: any, context: string): never {
261
335
  errorCode: err.code,
262
336
  context: context,
263
337
  });
264
- throw new Error(
265
- `Authentication error: ${sanitizeErrorMessage(err.message) || 'An unexpected error occurred'}`
338
+ throw createCodedError(
339
+ `Authentication error: ${sanitizeErrorMessage(err.message) || 'An unexpected error occurred'}`,
340
+ 'AL_COGNITO_UNHANDLED'
266
341
  );
267
342
  }
268
343
  }
@@ -337,7 +412,7 @@ export class CognitoAuth implements AgentlangAuth {
337
412
  if (id) {
338
413
  return id;
339
414
  }
340
- throw new Error(`${k} is not set`);
415
+ throw createCodedError(`${k} is not set`, 'AL_COGNITO_CONFIG_KEY_MISSING');
341
416
  }
342
417
 
343
418
  async signUp(
@@ -404,7 +479,12 @@ export class CognitoAuth implements AgentlangAuth {
404
479
  username: username,
405
480
  statusCode: response.$metadata.httpStatusCode,
406
481
  });
407
- throw new BadRequestError(`Signup failed with status ${response.$metadata.httpStatusCode}`);
482
+ throw new BadRequestError(
483
+ `Signup failed with status ${response.$metadata.httpStatusCode}`,
484
+ {
485
+ agentlangCode: 'AL_COGNITO_SIGNUP_HTTP_STATUS',
486
+ }
487
+ );
408
488
  }
409
489
  } catch (err: any) {
410
490
  if (err instanceof BadRequestError) throw err;
@@ -565,12 +645,13 @@ export class CognitoAuth implements AgentlangAuth {
565
645
  },
566
646
  mfaRequired: (challengeName: any, _challengeParameters: any) => {
567
647
  logger.info(`MFA required for user ${username}: ${challengeName}`);
568
- authError = new Error('MFA authentication required');
648
+ authError = createCodedError('MFA authentication required', 'AL_COGNITO_MFA_REQUIRED');
569
649
  },
570
650
  newPasswordRequired: (_userAttributes: any, _requiredAttributes: any) => {
571
651
  logger.info(`New password required for user ${username}`);
572
652
  authError = new PasswordResetRequiredError(
573
- 'New password required. Please reset your password.'
653
+ 'New password required. Please reset your password.',
654
+ { agentlangCode: 'AL_COGNITO_NEW_PASSWORD_REQUIRED_CHALLENGE' }
574
655
  );
575
656
  },
576
657
  });
@@ -627,7 +708,9 @@ export class CognitoAuth implements AgentlangAuth {
627
708
  cb(sessInfo);
628
709
  } else {
629
710
  logger.error(`Login failed for ${username} - no result received`);
630
- throw new UnauthorisedError('Login failed. Please try again.');
711
+ throw new UnauthorisedError('Login failed. Please try again.', {
712
+ agentlangCode: 'AL_COGNITO_LOGIN_NO_RESULT_SDK',
713
+ });
631
714
  }
632
715
  } else {
633
716
  // Cognito not configured, fall back to local authentication
@@ -659,12 +742,16 @@ export class CognitoAuth implements AgentlangAuth {
659
742
  },
660
743
  mfaRequired: (challengeName: any, _challengeParameters: any) => {
661
744
  logger.info(`MFA required for user ${username}: ${challengeName}`);
662
- authError = new Error('MFA authentication required');
745
+ authError = createCodedError(
746
+ 'MFA authentication required',
747
+ 'AL_COGNITO_MFA_REQUIRED_LOCAL'
748
+ );
663
749
  },
664
750
  newPasswordRequired: (_userAttributes: any, _requiredAttributes: any) => {
665
751
  logger.info(`New password required for user ${username}`);
666
752
  authError = new PasswordResetRequiredError(
667
- 'New password required. Please reset your password.'
753
+ 'New password required. Please reset your password.',
754
+ { agentlangCode: 'AL_COGNITO_NEW_PASSWORD_REQUIRED_CHALLENGE_LOCAL' }
668
755
  );
669
756
  },
670
757
  });
@@ -706,7 +793,9 @@ export class CognitoAuth implements AgentlangAuth {
706
793
  cb(sessInfo);
707
794
  } else {
708
795
  logger.error(`Login failed for ${username} - no result received`);
709
- throw new UnauthorisedError('Login failed. Please try again.');
796
+ throw new UnauthorisedError('Login failed. Please try again.', {
797
+ agentlangCode: 'AL_COGNITO_LOGIN_NO_RESULT_LOCAL',
798
+ });
710
799
  }
711
800
  }
712
801
  }
@@ -813,7 +902,7 @@ export class CognitoAuth implements AgentlangAuth {
813
902
  if (this.userPool) {
814
903
  return this.userPool;
815
904
  }
816
- throw new Error('UserPool not initialized');
905
+ throw createCodedError('UserPool not initialized', 'AL_COGNITO_USER_POOL_NOT_INIT');
817
906
  }
818
907
 
819
908
  async verifyToken(token: string): Promise<void> {
@@ -834,20 +923,29 @@ export class CognitoAuth implements AgentlangAuth {
834
923
 
835
924
  // Handle specific token verification errors
836
925
  if (err.message && err.message.includes('expired')) {
837
- throw new UnauthorisedError('Token has expired. Please login again.');
926
+ throw new UnauthorisedError('Token has expired. Please login again.', {
927
+ agentlangCode: 'AL_COGNITO_TOKEN_EXPIRED',
928
+ });
838
929
  }
839
930
  if (err.message && err.message.includes('invalid')) {
840
- throw new UnauthorisedError('Invalid token format.');
931
+ throw new UnauthorisedError('Invalid token format.', {
932
+ agentlangCode: 'AL_COGNITO_TOKEN_INVALID',
933
+ });
841
934
  }
842
935
  if (err.message && err.message.includes('not before')) {
843
- throw new UnauthorisedError('Token is not yet valid.');
936
+ throw new UnauthorisedError('Token is not yet valid.', {
937
+ agentlangCode: 'AL_COGNITO_TOKEN_NOT_YET_VALID',
938
+ });
844
939
  }
845
940
  if (err.message && err.message.includes('audience')) {
846
- throw new UnauthorisedError('Token audience mismatch.');
941
+ throw new UnauthorisedError('Token audience mismatch.', {
942
+ agentlangCode: 'AL_COGNITO_TOKEN_AUDIENCE',
943
+ });
847
944
  }
848
945
 
849
946
  throw new UnauthorisedError(
850
- `Token verification failed: ${sanitizeErrorMessage(err.message) || 'Invalid token'}`
947
+ `Token verification failed: ${sanitizeErrorMessage(err.message) || 'Invalid token'}`,
948
+ { agentlangCode: 'AL_COGNITO_TOKEN_VERIFY_FAILED' }
851
949
  );
852
950
  }
853
951
  }
@@ -855,7 +953,9 @@ export class CognitoAuth implements AgentlangAuth {
855
953
  async getUser(userId: string, env: Environment): Promise<UserInfo> {
856
954
  const localUser = await findUser(userId, env);
857
955
  if (!localUser) {
858
- throw new UserNotFoundError(`User ${userId} not found in local database`);
956
+ throw new UserNotFoundError(`User ${userId} not found in local database`, {
957
+ agentlangCode: 'AL_COGNITO_USER_NOT_FOUND_LOCAL_ID',
958
+ });
859
959
  }
860
960
 
861
961
  const userEmail = localUser.lookup('email');
@@ -928,7 +1028,9 @@ export class CognitoAuth implements AgentlangAuth {
928
1028
  async getUserByEmail(email: string, env: Environment): Promise<UserInfo> {
929
1029
  const localUser = await findUserByEmail(email, env);
930
1030
  if (!localUser) {
931
- throw new UserNotFoundError(`User with email ${email} not found in local database`);
1031
+ throw new UserNotFoundError(`User with email ${email} not found in local database`, {
1032
+ agentlangCode: 'AL_COGNITO_USER_NOT_FOUND_LOCAL_EMAIL',
1033
+ });
932
1034
  }
933
1035
 
934
1036
  const userId = localUser.lookup('id');
@@ -1017,7 +1119,9 @@ export class CognitoAuth implements AgentlangAuth {
1017
1119
  const response = await client.send(command);
1018
1120
 
1019
1121
  if (!response.AuthenticationResult) {
1020
- throw new UnauthorisedError('Token refresh failed');
1122
+ throw new UnauthorisedError('Token refresh failed', {
1123
+ agentlangCode: 'AL_COGNITO_TOKEN_REFRESH_NO_RESULT',
1124
+ });
1021
1125
  }
1022
1126
 
1023
1127
  const newIdToken = response.AuthenticationResult.IdToken!;
@@ -1059,7 +1163,9 @@ export class CognitoAuth implements AgentlangAuth {
1059
1163
  } catch (err: any) {
1060
1164
  logger.error(`Refresh token operation failed: ${err.message}`);
1061
1165
  if (err.name === 'NotAuthorizedException') {
1062
- throw new UnauthorisedError('Invalid or expired refresh token');
1166
+ throw new UnauthorisedError('Invalid or expired refresh token', {
1167
+ agentlangCode: 'AL_COGNITO_REFRESH_NOT_AUTHORIZED',
1168
+ });
1063
1169
  }
1064
1170
  handleCognitoError(err, 'refreshToken');
1065
1171
  throw err; // This line won't be reached due to handleCognitoError throwing
@@ -1158,7 +1264,8 @@ export class CognitoAuth implements AgentlangAuth {
1158
1264
  }
1159
1265
  );
1160
1266
  throw new BadRequestError(
1161
- `User invitation failed with status ${response.$metadata.httpStatusCode}`
1267
+ `User invitation failed with status ${response.$metadata.httpStatusCode}`,
1268
+ { agentlangCode: 'AL_COGNITO_INVITE_HTTP_STATUS' }
1162
1269
  );
1163
1270
  }
1164
1271
  } catch (err: any) {
@@ -1185,7 +1292,9 @@ export class CognitoAuth implements AgentlangAuth {
1185
1292
  await client.send(getUserCommand);
1186
1293
  } catch (err: any) {
1187
1294
  if (err.name === 'UserNotFoundException') {
1188
- throw new UserNotFoundError(`User ${email} not found. Cannot resend invitation.`);
1295
+ throw new UserNotFoundError(`User ${email} not found. Cannot resend invitation.`, {
1296
+ agentlangCode: 'AL_COGNITO_RESEND_USER_NOT_FOUND',
1297
+ });
1189
1298
  }
1190
1299
  throw err;
1191
1300
  }
@@ -1211,7 +1320,8 @@ export class CognitoAuth implements AgentlangAuth {
1211
1320
  }
1212
1321
  );
1213
1322
  throw new BadRequestError(
1214
- `Failed to resend invitation with status ${response.$metadata.httpStatusCode}`
1323
+ `Failed to resend invitation with status ${response.$metadata.httpStatusCode}`,
1324
+ { agentlangCode: 'AL_COGNITO_RESEND_INVITE_HTTP_STATUS' }
1215
1325
  );
1216
1326
  }
1217
1327
  } catch (err: any) {
@@ -1263,7 +1373,10 @@ export class CognitoAuth implements AgentlangAuth {
1263
1373
  await client.send(respond);
1264
1374
  logger.info(`User invitation accepted successfully for: ${email}`);
1265
1375
  } else {
1266
- throw new Error(`Unexpected challenge: ${initResponse.ChallengeName}`);
1376
+ throw createCodedError(
1377
+ `Unexpected challenge: ${initResponse.ChallengeName}`,
1378
+ 'AL_COGNITO_UNEXPECTED_CHALLENGE'
1379
+ );
1267
1380
  }
1268
1381
  } catch (err: any) {
1269
1382
  logger.error(`Accept invitation failed for ${email}: ${sanitizeErrorMessage(err.message)}`);
@@ -1274,7 +1387,10 @@ export class CognitoAuth implements AgentlangAuth {
1274
1387
  async callback(code: string, env: Environment, cb: LoginCallback): Promise<void> {
1275
1388
  try {
1276
1389
  if (!isNodeEnv) {
1277
- throw new Error('Callback authentication is only supported in Node.js environment');
1390
+ throw createCodedError(
1391
+ 'Callback authentication is only supported in Node.js environment',
1392
+ 'AL_COGNITO_CALLBACK_NODE_ONLY'
1393
+ );
1278
1394
  }
1279
1395
 
1280
1396
  const clientId = this.fetchConfig('ClientId');
@@ -1303,13 +1419,16 @@ export class CognitoAuth implements AgentlangAuth {
1303
1419
 
1304
1420
  if (!response.ok) {
1305
1421
  const errorText = await response.text();
1306
- throw new Error(`Token exchange failed: ${response.status} ${errorText}`);
1422
+ throw createCodedError(
1423
+ `Token exchange failed: ${response.status} ${errorText}`,
1424
+ 'AL_COGNITO_TOKEN_EXCHANGE_FAILED'
1425
+ );
1307
1426
  }
1308
1427
 
1309
1428
  const tokenData = await response.json();
1310
1429
 
1311
1430
  if (!tokenData.access_token || !tokenData.id_token || !tokenData.refresh_token) {
1312
- throw new Error('Missing required tokens in response');
1431
+ throw createCodedError('Missing required tokens in response', 'AL_COGNITO_MISSING_TOKENS');
1313
1432
  }
1314
1433
 
1315
1434
  const {
@@ -1325,7 +1444,10 @@ export class CognitoAuth implements AgentlangAuth {
1325
1444
  const userGroups = idTokenPayload['cognito:groups'];
1326
1445
 
1327
1446
  if (!userEmail) {
1328
- throw new Error('Email not found in ID attributes');
1447
+ throw createCodedError(
1448
+ 'Email not found in ID attributes',
1449
+ 'AL_COGNITO_EMAIL_MISSING_IN_ID'
1450
+ );
1329
1451
  }
1330
1452
 
1331
1453
  let localUser = await findUserByEmail(userEmail, env);
@@ -1379,7 +1501,7 @@ export class CognitoAuth implements AgentlangAuth {
1379
1501
  return JSON.parse(jsonPayload);
1380
1502
  } catch (err) {
1381
1503
  logger.error(`Failed to decode JWT payload: ${err}`);
1382
- throw new Error('Invalid JWT token');
1504
+ throw createCodedError('Invalid JWT token', 'AL_COGNITO_INVALID_JWT_PAYLOAD');
1383
1505
  }
1384
1506
  }
1385
1507
 
@@ -23,63 +23,96 @@ function asUnauthMessage(obj: string | UnautInfo): string {
23
23
  }
24
24
  }
25
25
 
26
+ /** Optional `agentlangCode` is stripped before passing to `Error` (not a standard ErrorOptions field). */
27
+ export type AgentlangErrorOptions = ErrorOptions & { agentlangCode?: string };
28
+
29
+ function baseErrorOptions(opts?: AgentlangErrorOptions): ErrorOptions | undefined {
30
+ if (!opts) return undefined;
31
+ const { agentlangCode: _c, ...rest } = opts;
32
+ return Object.keys(rest).length > 0 ? rest : undefined;
33
+ }
34
+
26
35
  export class UnauthorisedError extends Error {
27
- constructor(message?: string | UnautInfo, options?: ErrorOptions) {
36
+ readonly agentlangCode: string;
37
+ constructor(message?: string | UnautInfo, options?: AgentlangErrorOptions) {
28
38
  super(
29
39
  message ? asUnauthMessage(message) : 'User not authorised to perform this operation',
30
- options
40
+ baseErrorOptions(options)
31
41
  );
42
+ this.agentlangCode = options?.agentlangCode ?? 'AL_UNAUTHORIZED';
32
43
  }
33
44
  }
34
45
 
35
46
  export class BadRequestError extends Error {
36
- constructor(message?: string, options?: ErrorOptions) {
37
- super(message ? asUnauthMessage(message) : 'BadRequest', options);
47
+ readonly agentlangCode: string;
48
+ constructor(message?: string, options?: AgentlangErrorOptions) {
49
+ super(message ? asUnauthMessage(message) : 'BadRequest', baseErrorOptions(options));
50
+ this.agentlangCode = options?.agentlangCode ?? 'AL_BAD_REQUEST';
38
51
  }
39
52
  }
40
53
 
41
54
  export class UserNotFoundError extends Error {
42
- constructor(message?: string, options?: ErrorOptions) {
43
- super(message || 'User not found', options);
55
+ readonly agentlangCode: string;
56
+ constructor(message?: string, options?: AgentlangErrorOptions) {
57
+ super(message || 'User not found', baseErrorOptions(options));
58
+ this.agentlangCode = options?.agentlangCode ?? 'AL_USER_NOT_FOUND';
44
59
  }
45
60
  }
46
61
 
47
62
  export class UserNotConfirmedError extends Error {
48
- constructor(message?: string, options?: ErrorOptions) {
63
+ readonly agentlangCode: string;
64
+ constructor(message?: string, options?: AgentlangErrorOptions) {
49
65
  super(
50
66
  message || 'User account is not confirmed. Please check your email for verification code.',
51
- options
67
+ baseErrorOptions(options)
52
68
  );
69
+ this.agentlangCode = options?.agentlangCode ?? 'AL_USER_NOT_CONFIRMED';
53
70
  }
54
71
  }
55
72
 
56
73
  export class PasswordResetRequiredError extends Error {
57
- constructor(message?: string, options?: ErrorOptions) {
58
- super(message || 'Password reset is required for this account', options);
74
+ readonly agentlangCode: string;
75
+ constructor(message?: string, options?: AgentlangErrorOptions) {
76
+ super(message || 'Password reset is required for this account', baseErrorOptions(options));
77
+ this.agentlangCode = options?.agentlangCode ?? 'AL_PASSWORD_RESET_REQUIRED';
59
78
  }
60
79
  }
61
80
 
62
81
  export class TooManyRequestsError extends Error {
63
- constructor(message?: string, options?: ErrorOptions) {
64
- super(message || 'Too many requests. Please try again later.', options);
82
+ readonly agentlangCode: string;
83
+ constructor(message?: string, options?: AgentlangErrorOptions) {
84
+ super(message || 'Too many requests. Please try again later.', baseErrorOptions(options));
85
+ this.agentlangCode = options?.agentlangCode ?? 'AL_TOO_MANY_REQUESTS';
65
86
  }
66
87
  }
67
88
 
68
89
  export class InvalidParameterError extends Error {
69
- constructor(message?: string, options?: ErrorOptions) {
70
- super(message || 'Invalid parameters provided', options);
90
+ readonly agentlangCode: string;
91
+ constructor(message?: string, options?: AgentlangErrorOptions) {
92
+ super(message || 'Invalid parameters provided', baseErrorOptions(options));
93
+ this.agentlangCode = options?.agentlangCode ?? 'AL_INVALID_PARAMETER';
71
94
  }
72
95
  }
73
96
 
74
97
  export class ExpiredCodeError extends Error {
75
- constructor(message?: string, options?: ErrorOptions) {
76
- super(message || 'The verification code has expired. Please request a new one.', options);
98
+ readonly agentlangCode: string;
99
+ constructor(message?: string, options?: AgentlangErrorOptions) {
100
+ super(
101
+ message || 'The verification code has expired. Please request a new one.',
102
+ baseErrorOptions(options)
103
+ );
104
+ this.agentlangCode = options?.agentlangCode ?? 'AL_EXPIRED_CODE';
77
105
  }
78
106
  }
79
107
 
80
108
  export class CodeMismatchError extends Error {
81
- constructor(message?: string, options?: ErrorOptions) {
82
- super(message || 'The verification code is incorrect. Please try again.', options);
109
+ readonly agentlangCode: string;
110
+ constructor(message?: string, options?: AgentlangErrorOptions) {
111
+ super(
112
+ message || 'The verification code is incorrect. Please try again.',
113
+ baseErrorOptions(options)
114
+ );
115
+ this.agentlangCode = options?.agentlangCode ?? 'AL_CODE_MISMATCH';
83
116
  }
84
117
  }
85
118