@wabot-dev/framework 0.1.0-beta.24 → 0.1.0-beta.26

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.
@@ -92,7 +92,7 @@ let DeepSeekChatBotAdapter = class DeepSeekChatBotAdapter extends ChatBotAdapter
92
92
  deepSeekInput.push({
93
93
  role: 'tool',
94
94
  tool_call_id: itemData.content.id,
95
- content: itemData.content.result,
95
+ content: itemData.content.result ?? 'No result',
96
96
  });
97
97
  }
98
98
  }
@@ -0,0 +1,101 @@
1
+ import { Logger } from '../../logger/Logger.js';
2
+ import { OpenAI } from 'openai';
3
+
4
+ class OpenaiChatAdapter {
5
+ openai = new OpenAI();
6
+ logger = new Logger('wabot:openai-chat-adapter');
7
+ async nextItem(req) {
8
+ const openIaInput = [];
9
+ openIaInput.push({ role: 'system', content: req.systemPrompt });
10
+ openIaInput.push(...this.mapChatItems(req.prevItems));
11
+ const tools = req.tools.map((x) => this.mapTool(x));
12
+ const response = await this.openai.responses.create({
13
+ model: req.model,
14
+ input: openIaInput,
15
+ tools,
16
+ });
17
+ return this.mapResponse(response);
18
+ }
19
+ mapChatItems(chatItems) {
20
+ const openIaInput = [];
21
+ for (const { type, content } of chatItems) {
22
+ switch (type) {
23
+ case 'CONNECTION_MESSAGE':
24
+ openIaInput.push(this.mapConectionMessage(content));
25
+ break;
26
+ case 'BOT_MESSAGE':
27
+ openIaInput.push(this.mapBotMessage(content));
28
+ break;
29
+ case 'FUNCTION_CALL':
30
+ openIaInput.push(...this.mapFunctionCall(content));
31
+ break;
32
+ }
33
+ }
34
+ return openIaInput;
35
+ }
36
+ mapConectionMessage(item) {
37
+ if (!item.text) {
38
+ throw new Error('System message content is empty');
39
+ }
40
+ return { role: 'user', content: item.text };
41
+ }
42
+ mapBotMessage(item) {
43
+ if (!item.text) {
44
+ throw new Error('System message content is empty');
45
+ }
46
+ return { role: 'assistant', content: item.text };
47
+ }
48
+ mapFunctionCall(item) {
49
+ return [
50
+ {
51
+ type: 'function_call',
52
+ call_id: item.id,
53
+ name: item.name,
54
+ arguments: JSON.stringify(item.arguments),
55
+ },
56
+ {
57
+ type: 'function_call_output',
58
+ call_id: item.id,
59
+ output: item.result ?? 'Not result',
60
+ },
61
+ ];
62
+ }
63
+ mapTool(tool) {
64
+ return {
65
+ type: 'function',
66
+ name: tool.name,
67
+ description: tool.description,
68
+ parameters: {
69
+ type: 'object',
70
+ properties: tool.parameters.reduce((prev, param) => ({
71
+ ...prev,
72
+ [param.name]: { type: param.type, description: param.description },
73
+ }), {}),
74
+ required: tool.parameters.map((param) => param.name),
75
+ },
76
+ strict: true,
77
+ };
78
+ }
79
+ mapResponse(response) {
80
+ let newItem;
81
+ if (response.output_text) {
82
+ newItem = { type: 'BOT_MESSAGE', content: { text: response.output_text } };
83
+ }
84
+ else if (response.output && response.output[0]?.type == 'function_call') {
85
+ newItem = {
86
+ type: 'FUNCTION_CALL',
87
+ content: {
88
+ id: response.output[0].call_id,
89
+ name: response.output[0].name,
90
+ arguments: response.output[0].arguments,
91
+ },
92
+ };
93
+ }
94
+ else {
95
+ throw new Error('Not supported OpenIA Response');
96
+ }
97
+ return newItem;
98
+ }
99
+ }
100
+
101
+ export { OpenaiChatAdapter };
@@ -73,7 +73,7 @@ let OpenaiChatBotAdapter = class OpenaiChatBotAdapter extends ChatBotAdapter {
73
73
  openIaInput.push({
74
74
  type: 'function_call_output',
75
75
  call_id: itemData.content.id,
76
- output: itemData.content.result,
76
+ output: itemData.content.result ?? 'Not result',
77
77
  });
78
78
  }
79
79
  }
@@ -9,6 +9,7 @@ import { Socket } from 'socket.io-client';
9
9
  import * as tsyringe from 'tsyringe';
10
10
  import { DependencyContainer as DependencyContainer$1 } from 'tsyringe';
11
11
  export { DependencyContainer } from 'tsyringe';
12
+ import { Algorithm } from 'jsonwebtoken';
12
13
 
13
14
  interface IMindsetFunctionConfig {
14
15
  description: string;
@@ -116,7 +117,7 @@ interface IChatMessage extends IStorableData {
116
117
  text?: string;
117
118
  documents?: IChatDocument[];
118
119
  images?: IChatImage[];
119
- senderName: string;
120
+ senderName?: string;
120
121
  }
121
122
  interface IConnectionChatMessage extends IChatMessage {
122
123
  chatConnection: IChatConnection;
@@ -128,7 +129,7 @@ interface IChatFunctionCall {
128
129
  id: string;
129
130
  name: string;
130
131
  arguments?: string;
131
- result: string;
132
+ result?: string;
132
133
  }
133
134
 
134
135
  type ISystemMessageItem = {
@@ -143,7 +144,8 @@ type ISystemFunctionCallItem = {
143
144
  type: 'FUNCTION_CALL';
144
145
  content: IChatFunctionCall;
145
146
  };
146
- type IChatItemData = IEntityData & (ISystemMessageItem | IReceivedMessageItem | ISystemFunctionCallItem);
147
+ type IChatItemRawData = ISystemMessageItem | IReceivedMessageItem | ISystemFunctionCallItem;
148
+ type IChatItemData = IEntityData & IChatItemRawData;
147
149
  type IChatItemType = IChatItemData['type'];
148
150
  declare class ChatItem extends Entity<IChatItemData> {
149
151
  getType(): "BOT_MESSAGE" | "CONNECTION_MESSAGE" | "FUNCTION_CALL";
@@ -331,7 +333,17 @@ declare class MindsetOperator implements IMindset {
331
333
  identity(): Promise<IMindsetIdentity>;
332
334
  skills(): Promise<string>;
333
335
  limits(): Promise<string>;
336
+ systemPrompt(): Promise<string>;
337
+ tools(): IChatTool[];
338
+ tool(fn: IMindsetFunctionMetadata, module: IMindsetModuleMetadata): IChatTool;
339
+ private toolParameter;
340
+ /**
341
+ * @deprecated use id
342
+ */
334
343
  callFunction(name: string, params: string): Promise<string>;
344
+ /**
345
+ * @deprecated use id
346
+ */
335
347
  allFunctionsDescriptors(): Promise<{
336
348
  readonly type: "function";
337
349
  readonly name: string;
@@ -342,7 +354,13 @@ declare class MindsetOperator implements IMindset {
342
354
  readonly required: string[];
343
355
  };
344
356
  }[]>;
357
+ /**
358
+ * @deprecated use id
359
+ */
345
360
  private functionDescriptor;
361
+ /**
362
+ * @deprecated use id
363
+ */
346
364
  private toolParam;
347
365
  }
348
366
 
@@ -384,6 +402,27 @@ declare class ChatBot implements IChatBot {
384
402
  protected processLoop(callback: (message: IChatMessage) => void): Promise<void>;
385
403
  }
386
404
 
405
+ interface IChatToolParameter {
406
+ type: string;
407
+ name: string;
408
+ description: string;
409
+ }
410
+ interface IChatTool {
411
+ language: string;
412
+ name: string;
413
+ description: string;
414
+ parameters: IChatToolParameter[];
415
+ }
416
+ interface IChatAdapterNextItemReq {
417
+ model: string;
418
+ systemPrompt: string;
419
+ tools: IChatTool[];
420
+ prevItems: IChatItemRawData[];
421
+ }
422
+ interface IChatAdapter {
423
+ nextItem(req: IChatAdapterNextItemReq): Promise<IChatItemRawData>;
424
+ }
425
+
387
426
  declare class DeepSeekChatBotAdapter extends ChatBotAdapter {
388
427
  private deepSeek;
389
428
  private model;
@@ -402,6 +441,18 @@ declare class OpenaiChatBotAdapter extends ChatBotAdapter {
402
441
  private mapChatItems;
403
442
  }
404
443
 
444
+ declare class OpenaiChatAdapter implements IChatAdapter {
445
+ private openai;
446
+ private logger;
447
+ nextItem(req: IChatAdapterNextItemReq): Promise<IChatItemRawData>;
448
+ private mapChatItems;
449
+ private mapConectionMessage;
450
+ private mapBotMessage;
451
+ private mapFunctionCall;
452
+ private mapTool;
453
+ private mapResponse;
454
+ }
455
+
405
456
  declare class ClaudeChatBotAdapter extends ChatBotAdapter {
406
457
  private anthropic;
407
458
  private model;
@@ -464,6 +515,7 @@ declare class Job extends Entity<IJobData> {
464
515
  interface ICrudRepository<T> {
465
516
  find(id: string): Promise<T | null>;
466
517
  findOrThrow(id: string): Promise<T>;
518
+ findByIds(ids: string[]): Promise<T[]>;
467
519
  findAll(id: string): Promise<T[]>;
468
520
  create(item: T): Promise<void>;
469
521
  update(item: T): Promise<void>;
@@ -514,6 +566,7 @@ declare class PgCrudRepository<P extends Entity<IEntityData>> extends PgReposito
514
566
  protected readonly config: IPgRepositoryConfig<P>;
515
567
  constructor(pool: Pool, config: IPgRepositoryConfig<P>);
516
568
  find(id: string): Promise<P | null>;
569
+ findByIds(ids: string[]): Promise<P[]>;
517
570
  findOrThrow(id: string): Promise<P>;
518
571
  findAll(): Promise<P[]>;
519
572
  create(item: P): Promise<void>;
@@ -1005,10 +1058,129 @@ declare class CustomError extends Error {
1005
1058
  constructor(data: ICustomErrorData);
1006
1059
  }
1007
1060
 
1061
+ declare function jwtGuard(): (target: object, propertyKey: string | symbol) => void;
1062
+
1063
+ declare class JwtTokenDto {
1064
+ token?: string;
1065
+ expiration?: Date;
1066
+ }
1067
+
1068
+ declare class JwtAccessAndRefreshTokenDto {
1069
+ access?: JwtTokenDto;
1070
+ refresh?: JwtTokenDto;
1071
+ }
1072
+
1073
+ declare class JwtConfig {
1074
+ secretOrPublicKey: string;
1075
+ secretOrPrivateKey: string;
1076
+ algorithm: Algorithm;
1077
+ accessExpirationSeconds: number;
1078
+ refreshExpirationSeconds: number;
1079
+ constructor(env: Env);
1080
+ }
1081
+
1082
+ interface IJwtRefreshTokenData<A extends IStorableData> extends IEntityData {
1083
+ authInfo: A;
1084
+ }
1085
+ declare class JwtRefreshToken<A extends IStorableData> extends Entity<IJwtRefreshTokenData<A>> {
1086
+ get authInfo(): A;
1087
+ }
1088
+
1008
1089
  declare class Mapper {
1009
1090
  map<T>(data: any, ctor: IConstructor<T>): T;
1010
1091
  }
1011
1092
 
1093
+ declare class JwtSigner {
1094
+ private config;
1095
+ private mapper;
1096
+ constructor(config: JwtConfig, mapper: Mapper);
1097
+ signAccessToken<D extends IStorableData>(info: D | JwtRefreshToken<any>): Promise<JwtTokenDto>;
1098
+ signRefreshToken(refreshToken: JwtRefreshToken<any>): Promise<JwtTokenDto>;
1099
+ signAccessAndRefreshToken(refreshToken: JwtRefreshToken<any>): Promise<JwtAccessAndRefreshTokenDto>;
1100
+ }
1101
+
1102
+ declare class JwtRefreshTokenRepository<D extends IStorableData> extends PgCrudRepository<JwtRefreshToken<D>> {
1103
+ constructor(pool: Pool);
1104
+ }
1105
+
1106
+ declare class Jwt {
1107
+ private auth;
1108
+ private jwtSigner;
1109
+ private jwtRefreshTokenRepository;
1110
+ constructor(auth: Auth<any>, jwtSigner: JwtSigner, jwtRefreshTokenRepository: JwtRefreshTokenRepository<any>);
1111
+ createToken(): Promise<JwtAccessAndRefreshTokenDto>;
1112
+ }
1113
+
1114
+ interface IGetConfig {
1115
+ path?: string;
1116
+ }
1117
+
1118
+ declare function get(config?: string | IGetConfig): (target: object, propertyKey: string | symbol) => void;
1119
+
1120
+ interface IMiddleware {
1121
+ handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1122
+ }
1123
+
1124
+ declare function middleware(middlewareConstructor: IConstructor<IMiddleware>): (target: object, propertyKey: string | symbol) => void;
1125
+
1126
+ interface IPostConfig {
1127
+ path?: string;
1128
+ }
1129
+
1130
+ declare function post(config?: string | IPostConfig): (target: object, propertyKey: string | symbol) => void;
1131
+
1132
+ interface IRestControllerConfig {
1133
+ path: string;
1134
+ }
1135
+
1136
+ declare function restController(config: string | IRestControllerConfig): (target: IConstructor<any>) => void;
1137
+
1138
+ interface IEndPointMetadata {
1139
+ method: 'get' | 'post';
1140
+ path?: string;
1141
+ controllerConstructor: IConstructor<any>;
1142
+ functionName: string;
1143
+ paramsTypes: any[];
1144
+ }
1145
+
1146
+ interface IMiddlewareMetadata {
1147
+ controllerConstructor: IConstructor<any>;
1148
+ functionName: string;
1149
+ middlewareConstructor: IConstructor<IMiddleware>;
1150
+ }
1151
+
1152
+ interface IRestControllerMetadata {
1153
+ controllerConstructor: IConstructor<any>;
1154
+ path: string;
1155
+ }
1156
+
1157
+ declare class RestControllerMetadataStore {
1158
+ private endPoints;
1159
+ private middlewares;
1160
+ private restControllers;
1161
+ saveControllerMetadata(controllerMetadata: IRestControllerMetadata): void;
1162
+ saveEndPointMetadata(endPointMetadata: IEndPointMetadata): void;
1163
+ saveMiddlewareMetadata(middlewareMetadata: IMiddlewareMetadata): void;
1164
+ getControllerEndPointsInfo(controllerConstructor: IConstructor<any>): {
1165
+ middlewares: IMiddlewareMetadata[];
1166
+ controller: IRestControllerMetadata;
1167
+ method: "get" | "post";
1168
+ path?: string;
1169
+ controllerConstructor: IConstructor<any>;
1170
+ functionName: string;
1171
+ paramsTypes: any[];
1172
+ }[];
1173
+ }
1174
+
1175
+ declare function runRestControllers(controllers: IConstructor<any>[]): void;
1176
+
1177
+ declare class JwtGuardMiddleware implements IMiddleware {
1178
+ private config;
1179
+ private auth;
1180
+ constructor(config: JwtConfig, auth: Auth<any>);
1181
+ handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1182
+ }
1183
+
1012
1184
  declare class SendOneTimePasswordRequest {
1013
1185
  fromEmail: string;
1014
1186
  toEmail: string;
@@ -1119,69 +1291,6 @@ declare class Random {
1119
1291
  static numberCode(length: number): string;
1120
1292
  }
1121
1293
 
1122
- interface IGetConfig {
1123
- path?: string;
1124
- }
1125
-
1126
- declare function get(config?: string | IGetConfig): (target: object, propertyKey: string | symbol) => void;
1127
-
1128
- interface IMiddleware {
1129
- handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1130
- }
1131
-
1132
- declare function middleware(middlewareConstructor: IConstructor<IMiddleware>): (target: object, propertyKey: string | symbol) => void;
1133
-
1134
- interface IPostConfig {
1135
- path?: string;
1136
- }
1137
-
1138
- declare function post(config?: string | IPostConfig): (target: object, propertyKey: string | symbol) => void;
1139
-
1140
- interface IRestControllerConfig {
1141
- path: string;
1142
- }
1143
-
1144
- declare function restController(config: string | IRestControllerConfig): (target: IConstructor<any>) => void;
1145
-
1146
- interface IEndPointMetadata {
1147
- method: 'get' | 'post';
1148
- path?: string;
1149
- controllerConstructor: IConstructor<any>;
1150
- functionName: string;
1151
- paramsTypes: any[];
1152
- }
1153
-
1154
- interface IMiddlewareMetadata {
1155
- controllerConstructor: IConstructor<any>;
1156
- functionName: string;
1157
- middlewareConstructor: IConstructor<IMiddleware>;
1158
- }
1159
-
1160
- interface IRestControllerMetadata {
1161
- controllerConstructor: IConstructor<any>;
1162
- path: string;
1163
- }
1164
-
1165
- declare class RestControllerMetadataStore {
1166
- private endPoints;
1167
- private middlewares;
1168
- private restControllers;
1169
- saveControllerMetadata(controllerMetadata: IRestControllerMetadata): void;
1170
- saveEndPointMetadata(endPointMetadata: IEndPointMetadata): void;
1171
- saveMiddlewareMetadata(middlewareMetadata: IMiddlewareMetadata): void;
1172
- getControllerEndPointsInfo(controllerConstructor: IConstructor<any>): {
1173
- middlewares: IMiddlewareMetadata[];
1174
- controller: IRestControllerMetadata;
1175
- method: "get" | "post";
1176
- path?: string;
1177
- controllerConstructor: IConstructor<any>;
1178
- functionName: string;
1179
- paramsTypes: any[];
1180
- }[];
1181
- }
1182
-
1183
- declare function runRestControllers(controllers: IConstructor<any>[]): void;
1184
-
1185
1294
  declare function prepareChatContainer(container: DependencyContainer$1, context: IMessageContext, mindsetCtor?: IConstructor<IMindset>): Promise<DependencyContainer$1>;
1186
1295
 
1187
1296
  interface IrunChannelProps {
@@ -1302,4 +1411,4 @@ declare function validateModel<V>(value: any, info: IModelValidatorsInfo<V>): IM
1302
1411
 
1303
1412
  declare function validate<V>(value: any, modelConstructor: IConstructor<V>): IModelValidationResult<V>;
1304
1413
 
1305
- export { Async, Auth, AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatBotAdapter, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatBotAdapter, EmailService, Entity, Env, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEmailService, type IEndPointMetadata, type IEntityData, type IEnvType, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IJobData, type IJobEvent, type IJobEventListener, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Job, JobRepository, JobRunner, JobsEventsHub, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, Random, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, command, commandHandler, container, get, inject, injectable, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, max, middleware, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runAsyncCommandHandlers, runChannel, runRestControllers, runServer, scoped, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
1414
+ export { Async, Auth, AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatBotAdapter, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatBotAdapter, EmailService, Entity, Env, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemReq, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemRawData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatTool, type IChatToolParameter, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEmailService, type IEndPointMetadata, type IEntityData, type IEnvType, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IJobData, type IJobEvent, type IJobEventListener, type IJwtRefreshTokenData, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatAdapter, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, Random, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, command, commandHandler, container, get, inject, injectable, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runAsyncCommandHandlers, runChannel, runRestControllers, runServer, scoped, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
package/dist/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { DeepSeekChatBotAdapter } from './ai/deepseek/DeepSeekChatBotAdapter.js';
2
2
  export { OpenaiChatBotAdapter } from './ai/openia/OpenaiChatBotAdapter.js';
3
+ export { OpenaiChatAdapter } from './ai/openia/OpenaiChatAdapter.js';
3
4
  export { ClaudeChatBotAdapter } from './ai/claude/ClaudeChatBotAdapter.js';
4
5
  export { command } from './async/@command.js';
5
6
  export { commandHandler } from './async/@commandHandler.js';
@@ -56,6 +57,15 @@ export { Storable } from './core/Storable.js';
56
57
  export { Env } from './env/Env.js';
57
58
  export { CustomError } from './error/CustomError.js';
58
59
  export { Lifecycle, container, inject, injectable, scoped, singleton } from './injection/index.js';
60
+ export { jwtGuard } from './jwt/@jwtGuard.js';
61
+ export { JwtAccessAndRefreshTokenDto } from './jwt/JwtAccessAndRefreshTokenDto.js';
62
+ export { JwtConfig } from './jwt/JwtConfig.js';
63
+ export { Jwt } from './jwt/Jwt.js';
64
+ export { JwtGuardMiddleware } from './jwt/JwtGuardMiddleware.js';
65
+ export { JwtRefreshToken } from './jwt/JwtRefreshToken.js';
66
+ export { JwtSigner } from './jwt/JwtSigner.js';
67
+ export { JwtTokenDto } from './jwt/JwtTokenDto.js';
68
+ export { JwtRefreshTokenRepository } from './jwt/JwtRefreshTokenRepository.js';
59
69
  export { Logger } from './logger/Logger.js';
60
70
  export { Mapper } from './mapper/Mapper.js';
61
71
  export { mindsetFunction } from './mindset/metadata/functions/@mindsetFunction.js';
@@ -0,0 +1,34 @@
1
+ import '../injection/index.js';
2
+ import '../rest-controller/metadata/RestControllerMetadataStore.js';
3
+ import { middleware } from '../rest-controller/metadata/@middleware.js';
4
+ import '../controller/channel/ChatResolver.js';
5
+ import '../controller/channel/UserResolver.js';
6
+ import '../controller/metadata/ControllerMetadataStore.js';
7
+ import '../channels/cmd/CmdChannel.js';
8
+ import '../channels/express/ExpressProvider.js';
9
+ import '../channels/http/HttpServerProvider.js';
10
+ import '../channels/socket/SocketChannel.js';
11
+ import '../channels/socket/SocketChannelConfig.js';
12
+ import '../channels/socket/SocketServerProvider.js';
13
+ import '../channels/telegram/TelegramChannel.js';
14
+ import '../channels/whatsapp/WhatsAppChannel.js';
15
+ import '../channels/whatsapp/EnvWhatsAppRepository.js';
16
+ import '../channels/whatsapp/PgWhatsAppRepository.js';
17
+ import '../core/chat/repository/IChatRepository.js';
18
+ import '../core/user/IUserRepository.js';
19
+ import '../channels/whatsapp/WhatsAppReceiverByDevConnection.js';
20
+ import '../channels/whatsapp/WhatsAppReceiverByWebHook.js';
21
+ import '../channels/whatsapp/WhatsAppSenderByCloudApi.js';
22
+ import '../channels/whatsapp/WhatsAppSenderByDevConnection.js';
23
+ import 'debug';
24
+ import '../validation/metadata/ValidationMetadataStore.js';
25
+ import 'path';
26
+ import { JwtGuardMiddleware } from './JwtGuardMiddleware.js';
27
+
28
+ function jwtGuard() {
29
+ return function (target, propertyKey) {
30
+ middleware(JwtGuardMiddleware)(target, propertyKey);
31
+ };
32
+ }
33
+
34
+ export { jwtGuard };
@@ -0,0 +1,31 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Auth } from '../auth/Auth.js';
3
+ import { JwtSigner } from './JwtSigner.js';
4
+ import { JwtRefreshTokenRepository } from './JwtRefreshTokenRepository.js';
5
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
6
+ import { injectable } from '../injection/index.js';
7
+
8
+ let Jwt = class Jwt {
9
+ auth;
10
+ jwtSigner;
11
+ jwtRefreshTokenRepository;
12
+ constructor(auth, jwtSigner, jwtRefreshTokenRepository) {
13
+ this.auth = auth;
14
+ this.jwtSigner = jwtSigner;
15
+ this.jwtRefreshTokenRepository = jwtRefreshTokenRepository;
16
+ }
17
+ async createToken() {
18
+ const authInfo = this.auth.require();
19
+ const refreshToken = new JwtRefreshToken({ authInfo });
20
+ await this.jwtRefreshTokenRepository.create(refreshToken);
21
+ return await this.jwtSigner.signAccessAndRefreshToken(refreshToken);
22
+ }
23
+ };
24
+ Jwt = __decorate([
25
+ injectable(),
26
+ __metadata("design:paramtypes", [Auth,
27
+ JwtSigner,
28
+ JwtRefreshTokenRepository])
29
+ ], Jwt);
30
+
31
+ export { Jwt };
@@ -0,0 +1,20 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import '../injection/index.js';
3
+ import '../validation/metadata/ValidationMetadataStore.js';
4
+ import { isModel } from '../validation/metadata/@isModel.js';
5
+ import { JwtTokenDto } from './JwtTokenDto.js';
6
+
7
+ class JwtAccessAndRefreshTokenDto {
8
+ access;
9
+ refresh;
10
+ }
11
+ __decorate([
12
+ isModel(JwtTokenDto),
13
+ __metadata("design:type", JwtTokenDto)
14
+ ], JwtAccessAndRefreshTokenDto.prototype, "access", void 0);
15
+ __decorate([
16
+ isModel(JwtTokenDto),
17
+ __metadata("design:type", JwtTokenDto)
18
+ ], JwtAccessAndRefreshTokenDto.prototype, "refresh", void 0);
19
+
20
+ export { JwtAccessAndRefreshTokenDto };
@@ -0,0 +1,28 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Env } from '../env/Env.js';
3
+ import { singleton } from '../injection/index.js';
4
+
5
+ let JwtConfig = class JwtConfig {
6
+ secretOrPublicKey;
7
+ secretOrPrivateKey;
8
+ algorithm;
9
+ accessExpirationSeconds;
10
+ refreshExpirationSeconds;
11
+ constructor(env) {
12
+ this.algorithm = env.requireString('JWT_ALGORITHM', { default: 'HS256' });
13
+ this.secretOrPublicKey = env.requireString('JWT_SECRET');
14
+ this.secretOrPrivateKey = env.requireString('JWT_SECRET');
15
+ this.accessExpirationSeconds = env.requireNumber('JWT_ACCESS_EXPIRATION_SECONDS', {
16
+ default: 10 * 60,
17
+ });
18
+ this.refreshExpirationSeconds = env.requireNumber('JWT_REFRESH_EXPIRATION_SECONDS', {
19
+ default: 365 * 24 * 3600,
20
+ });
21
+ }
22
+ };
23
+ JwtConfig = __decorate([
24
+ singleton(),
25
+ __metadata("design:paramtypes", [Env])
26
+ ], JwtConfig);
27
+
28
+ export { JwtConfig };
@@ -0,0 +1,45 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Auth } from '../auth/Auth.js';
3
+ import jwt from 'jsonwebtoken';
4
+ import { JwtConfig } from './JwtConfig.js';
5
+ import { injectable } from '../injection/index.js';
6
+ import { CustomError } from '../error/CustomError.js';
7
+
8
+ let JwtGuardMiddleware = class JwtGuardMiddleware {
9
+ config;
10
+ auth;
11
+ constructor(config, auth) {
12
+ this.config = config;
13
+ this.auth = auth;
14
+ }
15
+ async handle(req, res, container) {
16
+ const authorization = req.header('Authorization');
17
+ if (!authorization) {
18
+ throw new CustomError({ httpCode: 401, message: 'Authorization header not available' });
19
+ }
20
+ const [bearer, token] = authorization.split(' ');
21
+ if (bearer.toLowerCase() !== 'bearer' || !token) {
22
+ throw new CustomError({ httpCode: 401, message: 'Authorization should be a bearer token' });
23
+ }
24
+ try {
25
+ const jwtPayload = jwt.verify(token, this.config.secretOrPublicKey, {
26
+ algorithms: [this.config.algorithm],
27
+ });
28
+ this.auth.assign(jwtPayload);
29
+ }
30
+ catch (err) {
31
+ throw new CustomError({
32
+ httpCode: 401,
33
+ message: err instanceof Error ? `Invalid token: ${err.message}` : 'Invalid token',
34
+ cause: err instanceof Error ? err : undefined,
35
+ });
36
+ }
37
+ }
38
+ };
39
+ JwtGuardMiddleware = __decorate([
40
+ injectable(),
41
+ __metadata("design:paramtypes", [JwtConfig,
42
+ Auth])
43
+ ], JwtGuardMiddleware);
44
+
45
+ export { JwtGuardMiddleware };
@@ -0,0 +1,11 @@
1
+ import '../core/chat/repository/IChatRepository.js';
2
+ import { Entity } from '../core/Entity.js';
3
+ import '../core/user/IUserRepository.js';
4
+
5
+ class JwtRefreshToken extends Entity {
6
+ get authInfo() {
7
+ return this.data.authInfo;
8
+ }
9
+ }
10
+
11
+ export { JwtRefreshToken };
@@ -0,0 +1,21 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
4
+ import { Pool } from 'pg';
5
+ import { PgCrudRepository } from '../repository/pg/PgCrudRepository.js';
6
+
7
+ let JwtRefreshTokenRepository = class JwtRefreshTokenRepository extends PgCrudRepository {
8
+ constructor(pool) {
9
+ super(pool, {
10
+ schema: 'wabot',
11
+ table: 'jwt_refresh_token',
12
+ constructor: JwtRefreshToken,
13
+ });
14
+ }
15
+ };
16
+ JwtRefreshTokenRepository = __decorate([
17
+ singleton(),
18
+ __metadata("design:paramtypes", [Pool])
19
+ ], JwtRefreshTokenRepository);
20
+
21
+ export { JwtRefreshTokenRepository };
@@ -0,0 +1,48 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { JwtConfig } from './JwtConfig.js';
3
+ import jwt from 'jsonwebtoken';
4
+ import { JwtTokenDto } from './JwtTokenDto.js';
5
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
6
+ import { JwtAccessAndRefreshTokenDto } from './JwtAccessAndRefreshTokenDto.js';
7
+ import { injectable } from '../injection/index.js';
8
+ import { Mapper } from '../mapper/Mapper.js';
9
+
10
+ let JwtSigner = class JwtSigner {
11
+ config;
12
+ mapper;
13
+ constructor(config, mapper) {
14
+ this.config = config;
15
+ this.mapper = mapper;
16
+ }
17
+ async signAccessToken(info) {
18
+ const _authInfo = info instanceof JwtRefreshToken
19
+ ? {
20
+ ...info.authInfo,
21
+ refreshTokenId: info.id,
22
+ }
23
+ : info;
24
+ const token = jwt.sign(_authInfo, this.config.secretOrPrivateKey, {
25
+ expiresIn: this.config.accessExpirationSeconds,
26
+ });
27
+ const expiration = new Date().getTime() + this.config.accessExpirationSeconds * 1000;
28
+ return this.mapper.map({ token, expiration }, JwtTokenDto);
29
+ }
30
+ async signRefreshToken(refreshToken) {
31
+ const token = jwt.sign({ refreshTokenId: refreshToken.id }, this.config.secretOrPrivateKey, {
32
+ expiresIn: this.config.refreshExpirationSeconds,
33
+ });
34
+ const expiration = new Date().getTime() + this.config.refreshExpirationSeconds * 1000;
35
+ return this.mapper.map({ token, expiration }, JwtTokenDto);
36
+ }
37
+ async signAccessAndRefreshToken(refreshToken) {
38
+ const access = await this.signAccessToken(refreshToken);
39
+ const refresh = await this.signRefreshToken(refreshToken);
40
+ return this.mapper.map({ access, refresh }, JwtAccessAndRefreshTokenDto);
41
+ }
42
+ };
43
+ JwtSigner = __decorate([
44
+ injectable(),
45
+ __metadata("design:paramtypes", [JwtConfig, Mapper])
46
+ ], JwtSigner);
47
+
48
+ export { JwtSigner };
@@ -0,0 +1,22 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import '../injection/index.js';
3
+ import '../validation/metadata/ValidationMetadataStore.js';
4
+ import { isDate } from '../validation/metadata/@isDate.js';
5
+ import { isNotEmpty } from '../validation/metadata/@isNotEmpty.js';
6
+ import { isString } from '../validation/metadata/@isString.js';
7
+
8
+ class JwtTokenDto {
9
+ token;
10
+ expiration;
11
+ }
12
+ __decorate([
13
+ isString(),
14
+ isNotEmpty(),
15
+ __metadata("design:type", String)
16
+ ], JwtTokenDto.prototype, "token", void 0);
17
+ __decorate([
18
+ isDate(),
19
+ __metadata("design:type", Date)
20
+ ], JwtTokenDto.prototype, "expiration", void 0);
21
+
22
+ export { JwtTokenDto };
@@ -22,6 +22,80 @@ let MindsetOperator = class MindsetOperator {
22
22
  limits() {
23
23
  return this.mindset.limits();
24
24
  }
25
+ async systemPrompt() {
26
+ let [identity, skills, limits] = await Promise.all([
27
+ this.identity(),
28
+ this.skills(),
29
+ this.limits(),
30
+ ]);
31
+ const language = identity.language.replaceAll('#', ' ');
32
+ const name = identity.name.replaceAll('#', ' ');
33
+ const age = identity.age ? identity.age.toString().replaceAll('#', ' ') : null;
34
+ const personality = identity.personality ? identity.personality.replaceAll('#', ' ') : null;
35
+ skills = skills.replaceAll('#', ' ');
36
+ limits = limits.replaceAll('#', ' ');
37
+ const systemPrompt = `
38
+ # System Instructions
39
+ you should act as a assistant.
40
+ your main language is ${language}.
41
+ your name is ${name}.
42
+ ${age ? 'you are ' + age + ' years old.' : ''}
43
+
44
+ ${personality ? '## Personality (in your main language) \n' + personality : ''}
45
+
46
+ ## Skills (in your main language)
47
+ ${skills}
48
+
49
+ ## System limitations (in your main language)
50
+ ${limits}
51
+
52
+ ## Chat memory
53
+ Next you will receive a chat history,
54
+ you should use this information to answer the user.
55
+ `;
56
+ return systemPrompt;
57
+ }
58
+ tools() {
59
+ return this.metadata.modules
60
+ .map((module) => module.functions.map((fn) => this.tool(fn, module)))
61
+ .flat();
62
+ }
63
+ tool(fn, module) {
64
+ const description = fn.config.description.replaceAll('#', ' ');
65
+ return {
66
+ language: module.config.language ?? 'english',
67
+ name: fn.name,
68
+ description,
69
+ parameters: fn.params.map((param) => this.toolParameter(param)),
70
+ };
71
+ }
72
+ toolParameter(param) {
73
+ let description = `
74
+ ### description (in your main language)
75
+ ${param.config.description.replaceAll('#', ' ')}
76
+ `;
77
+ const type = (() => {
78
+ if (param.type === Number)
79
+ return 'number';
80
+ if (param.type === String)
81
+ return 'string';
82
+ if (param.type === Date) {
83
+ description = `${description}
84
+ ### format: ISO 8681 - YYYY-MM-DDTHH:mm:ssZ
85
+ `;
86
+ return 'string';
87
+ }
88
+ throw new Error(`Unsupported type`);
89
+ })();
90
+ return {
91
+ type,
92
+ name: param.name,
93
+ description,
94
+ };
95
+ }
96
+ /**
97
+ * @deprecated use id
98
+ */
25
99
  async callFunction(name, params) {
26
100
  const fnMetadata = this.metadata.modules
27
101
  .map((module) => module.functions)
@@ -43,11 +117,17 @@ let MindsetOperator = class MindsetOperator {
43
117
  return `Error: ${error}`;
44
118
  }
45
119
  }
120
+ /**
121
+ * @deprecated use id
122
+ */
46
123
  async allFunctionsDescriptors() {
47
124
  return this.metadata.modules
48
125
  .map((module) => module.functions.map((fn) => this.functionDescriptor(fn)))
49
126
  .flat();
50
127
  }
128
+ /**
129
+ * @deprecated use id
130
+ */
51
131
  functionDescriptor(fn) {
52
132
  const description = fn.config.description.replaceAll('#', ' ');
53
133
  return {
@@ -64,6 +144,9 @@ let MindsetOperator = class MindsetOperator {
64
144
  },
65
145
  };
66
146
  }
147
+ /**
148
+ * @deprecated use id
149
+ */
67
150
  toolParam(param) {
68
151
  const addons = {
69
152
  description: `
@@ -18,6 +18,16 @@ class PgCrudRepository extends PgRepositoryBase {
18
18
  const items = await this.query(sql, [id]);
19
19
  return items.at(0) ?? null;
20
20
  }
21
+ async findByIds(ids) {
22
+ const sql = `
23
+ SELECT ${this.columns}
24
+ FROM ${this.table}
25
+ WHERE id IN (${ids.map((_, i) => '$' + (i + 1)).join(',')})
26
+ LIMIT 1
27
+ `;
28
+ const items = await this.query(sql, ids);
29
+ return items;
30
+ }
21
31
  async findOrThrow(id) {
22
32
  const item = await this.find(id);
23
33
  if (!item) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.1.0-beta.24",
3
+ "version": "0.1.0-beta.26",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",