@wabot-dev/framework 0.2.0-beta.9 → 0.2.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.
@@ -13,7 +13,7 @@ let AnthropicChatAdapter = class AnthropicChatAdapter {
13
13
  const apiKey = this.env.requireString('ANTHROPIC_API_KEY');
14
14
  this.anthropic = new Anthropic({ apiKey });
15
15
  }
16
- async nextItem(req) {
16
+ async nextItems(req) {
17
17
  const tools = req.tools.map((x) => this.mapTool(x));
18
18
  const messages = this.mapChatItems(req.prevItems);
19
19
  const request = {
@@ -96,24 +96,6 @@ let AnthropicChatAdapter = class AnthropicChatAdapter {
96
96
  };
97
97
  }
98
98
  mapResponse(response) {
99
- let chatItem;
100
- const content = response.content[0];
101
- if (content.type === 'text') {
102
- chatItem = { type: 'botMessage', botMessage: { text: content.text } };
103
- }
104
- else if (content.type === 'tool_use') {
105
- chatItem = {
106
- type: 'functionCall',
107
- functionCall: {
108
- id: content.id,
109
- name: content.name,
110
- arguments: JSON.stringify(content.input),
111
- },
112
- };
113
- }
114
- else {
115
- throw new Error('Not supported Claude Response');
116
- }
117
99
  let usage;
118
100
  if (response.usage) {
119
101
  usage = {
@@ -124,7 +106,23 @@ let AnthropicChatAdapter = class AnthropicChatAdapter {
124
106
  else {
125
107
  throw new Error('Unable to found usage info');
126
108
  }
127
- return { chatItem, usage };
109
+ const nextItems = [];
110
+ for (const content of response.content) {
111
+ if (content.type === 'text' && content.text) {
112
+ nextItems.push({ type: 'botMessage', botMessage: { text: content.text } });
113
+ }
114
+ else if (content.type === 'tool_use') {
115
+ nextItems.push({
116
+ type: 'functionCall',
117
+ functionCall: {
118
+ id: content.id,
119
+ name: content.name,
120
+ arguments: JSON.stringify(content.input),
121
+ },
122
+ });
123
+ }
124
+ }
125
+ return { usage, nextItems };
128
126
  }
129
127
  };
130
128
  AnthropicChatAdapter = __decorate([
@@ -18,7 +18,7 @@ class DeepSeekChatAdapter {
18
18
  baseURL,
19
19
  });
20
20
  }
21
- async nextItem(req) {
21
+ async nextItems(req) {
22
22
  const deepSeekInput = [];
23
23
  deepSeekInput.push({ role: 'system', content: req.systemPrompt });
24
24
  deepSeekInput.push(...this.mapChatItems(req.prevItems));
@@ -130,7 +130,7 @@ class DeepSeekChatAdapter {
130
130
  else {
131
131
  throw new Error('Unable to found usage info');
132
132
  }
133
- return { chatItem, usage };
133
+ return { nextItems: [chatItem], usage };
134
134
  }
135
135
  }
136
136
 
@@ -2,122 +2,133 @@ import { __decorate, __metadata } from 'tslib';
2
2
  import { Env } from '../../../core/env/Env.js';
3
3
  import { singleton } from '../../../core/injection/index.js';
4
4
  import { Logger } from '../../../core/logger/Logger.js';
5
- import OpenAI from 'openai';
5
+ import { Random } from '../../../core/random/Random.js';
6
+ import { GoogleGenAI } from '@google/genai';
6
7
 
7
8
  let GoogleChatAdapter = class GoogleChatAdapter {
8
- env;
9
- openai;
10
- logger = new Logger('wabot:google-chat-adapter');
9
+ ai;
10
+ logger = new Logger('wabot:google-chat-adapter-v2');
11
11
  constructor(env) {
12
- this.env = env;
13
- const apiKey = this.env.requireString('GOOGLE_API_KEY');
14
- this.openai = new OpenAI({
15
- apiKey,
16
- baseURL: 'https://generativelanguage.googleapis.com/v1beta/openai/',
17
- });
12
+ this.ai = new GoogleGenAI({ apiKey: env.requireString('GOOGLE_API_KEY') });
18
13
  }
19
- async nextItem(req) {
20
- const messages = [];
21
- messages.push({ role: 'system', content: req.systemPrompt });
22
- messages.push(...this.mapChatItems(req.prevItems));
23
- const tools = req.tools.map((x) => this.mapTool(x));
24
- const request = {
14
+ async nextItems(req) {
15
+ const contents = [];
16
+ contents.push({ role: 'user', parts: [{ text: req.systemPrompt }] });
17
+ contents.push(...this.mapChatItems(req.prevItems));
18
+ const functionDeclarations = req.tools.map((x) => this.mapTool(x));
19
+ const response = await this.ai.models.generateContent({
25
20
  model: req.model,
26
- messages,
27
- tools,
28
- };
29
- const response = await this.openai.chat.completions.create(request);
21
+ contents,
22
+ config: { tools: [{ functionDeclarations }] },
23
+ });
30
24
  return this.mapResponse(response);
31
25
  }
32
26
  mapChatItems(chatItems) {
33
- const messages = [];
27
+ const contents = [];
34
28
  for (const chatItem of chatItems) {
35
29
  switch (chatItem.type) {
36
30
  case 'humanMessage':
37
- messages.push(this.mapHumanMessage(chatItem.humanMessage));
31
+ contents.push(this.mapHumanMessage(chatItem.humanMessage));
38
32
  break;
39
33
  case 'botMessage':
40
- messages.push(this.mapBotMessage(chatItem.botMessage));
34
+ contents.push(this.mapBotMessage(chatItem.botMessage));
41
35
  break;
42
36
  case 'functionCall':
43
- messages.push(...this.mapFunctionCall(chatItem.functionCall));
37
+ contents.push(...this.mapFunctionCall(chatItem.functionCall));
44
38
  break;
45
39
  }
46
40
  }
47
- return messages;
41
+ return contents;
48
42
  }
49
43
  mapHumanMessage(item) {
50
44
  if (!item.text) {
51
45
  throw new Error('User message content is empty');
52
46
  }
53
- return { role: 'user', content: item.text };
47
+ return { role: 'user', parts: [{ text: item.text }] };
54
48
  }
55
49
  mapBotMessage(item) {
56
50
  if (!item.text) {
57
51
  throw new Error('Bot message content is empty');
58
52
  }
59
- return { role: 'assistant', content: item.text };
53
+ return { role: 'model', parts: [{ text: item.text }] };
60
54
  }
61
55
  mapFunctionCall(item) {
62
56
  return [
57
+ {
58
+ role: 'model',
59
+ parts: [
60
+ {
61
+ functionCall: {
62
+ id: item.id,
63
+ name: item.name,
64
+ args: JSON.parse(item.arguments ?? '{}'),
65
+ },
66
+ },
67
+ ],
68
+ },
63
69
  {
64
70
  role: 'function',
65
- name: item.id,
66
- content: item.result ?? 'No result',
71
+ parts: [
72
+ {
73
+ functionResponse: {
74
+ id: item.id,
75
+ name: item.name,
76
+ response: { output: item.result ?? '' },
77
+ },
78
+ },
79
+ ],
67
80
  },
68
81
  ];
69
82
  }
70
83
  mapTool(tool) {
71
84
  return {
72
- type: 'function',
73
- function: {
74
- name: tool.name,
75
- description: tool.description,
76
- parameters: {
77
- type: 'object',
78
- properties: tool.parameters.reduce((prev, param) => ({
79
- ...prev,
80
- [param.name]: {
81
- type: param.type,
82
- description: param.description,
83
- },
84
- }), {}),
85
- required: tool.parameters.map((param) => param.name),
86
- additionalProperties: false,
87
- }
85
+ name: tool.name,
86
+ description: tool.description,
87
+ parametersJsonSchema: {
88
+ type: 'object',
89
+ properties: tool.parameters.reduce((prev, param) => ({
90
+ ...prev,
91
+ [param.name]: { type: param.type, description: param.description },
92
+ }), {}),
93
+ required: tool.parameters.map((param) => param.name),
94
+ additionalProperties: false,
88
95
  },
89
96
  };
90
97
  }
91
98
  mapResponse(response) {
92
- let chatItem;
93
- const { tool_calls: responseFunctionCall, content: responseText } = response.choices?.[0]?.message ?? {};
94
- if (responseText) {
95
- chatItem = { type: 'botMessage', botMessage: { text: responseText } };
99
+ if (!response.candidates || !response.candidates.length) {
100
+ throw new Error('No candidates in response');
96
101
  }
97
- else if (responseFunctionCall && responseFunctionCall[0]?.type === 'function') {
98
- chatItem = {
99
- type: 'functionCall',
100
- functionCall: {
101
- id: responseFunctionCall[0].id,
102
- name: responseFunctionCall[0].function.name,
103
- arguments: responseFunctionCall[0].function.arguments,
104
- },
105
- };
102
+ if (!response.usageMetadata ||
103
+ !response.usageMetadata.promptTokenCount ||
104
+ !response.usageMetadata.candidatesTokenCount) {
105
+ throw new Error('Not usage metadata');
106
106
  }
107
- else {
108
- throw new Error('Not supported Gemini Response');
107
+ const content = response.candidates.find((x) => x.content)?.content;
108
+ if (!content) {
109
+ throw new Error('Candidates has no content');
109
110
  }
110
- let usage;
111
- if (response.usage) {
112
- usage = {
113
- inputTokens: response.usage.prompt_tokens,
114
- outputTokens: response.usage.completion_tokens,
115
- };
116
- }
117
- else {
118
- throw new Error('Unable to found usage info');
111
+ const nextItems = [];
112
+ for (const part of content.parts ?? []) {
113
+ if (part.text) {
114
+ nextItems.push({ type: 'botMessage', botMessage: { text: part.text } });
115
+ }
116
+ if (part.functionCall) {
117
+ const { id, name, args } = part.functionCall;
118
+ if (!name) {
119
+ throw new Error('invalid function call');
120
+ }
121
+ nextItems.push({
122
+ type: 'functionCall',
123
+ functionCall: { id: id ?? Random.alphaNumericLowerCase(10), name, arguments: args && JSON.stringify(args) },
124
+ });
125
+ }
119
126
  }
120
- return { chatItem, usage };
127
+ let usage = {
128
+ inputTokens: response.usageMetadata.promptTokenCount,
129
+ outputTokens: response.usageMetadata.candidatesTokenCount,
130
+ };
131
+ return { usage, nextItems };
121
132
  }
122
133
  };
123
134
  GoogleChatAdapter = __decorate([
@@ -6,7 +6,7 @@ import { singleton } from '../../../core/injection/index.js';
6
6
  let OpenaiChatAdapter = class OpenaiChatAdapter {
7
7
  openai = new OpenAI();
8
8
  logger = new Logger('wabot:openai-chat-adapter');
9
- async nextItem(req) {
9
+ async nextItems(req) {
10
10
  const openIaInput = [];
11
11
  openIaInput.push({ role: 'system', content: req.systemPrompt });
12
12
  openIaInput.push(...this.mapChatItems(req.prevItems));
@@ -80,23 +80,6 @@ let OpenaiChatAdapter = class OpenaiChatAdapter {
80
80
  };
81
81
  }
82
82
  mapResponse(response) {
83
- let chatItem;
84
- if (response.output_text) {
85
- chatItem = { type: 'botMessage', botMessage: { text: response.output_text } };
86
- }
87
- else if (response.output && response.output[0]?.type == 'function_call') {
88
- chatItem = {
89
- type: 'functionCall',
90
- functionCall: {
91
- id: response.output[0].call_id,
92
- name: response.output[0].name,
93
- arguments: response.output[0].arguments,
94
- },
95
- };
96
- }
97
- else {
98
- throw new Error('Not supported OpenIA Response');
99
- }
100
83
  let usage;
101
84
  if (response.usage) {
102
85
  usage = {
@@ -107,7 +90,48 @@ let OpenaiChatAdapter = class OpenaiChatAdapter {
107
90
  else {
108
91
  throw new Error('Unable to found usage info');
109
92
  }
110
- return { chatItem, usage };
93
+ const nextItems = [];
94
+ for (const output of response.output) {
95
+ if (output.type === 'message') {
96
+ for (const content of output.content) {
97
+ if (content.type === 'output_text' && content.text) {
98
+ nextItems.push({ type: 'botMessage', botMessage: { text: content.text } });
99
+ }
100
+ }
101
+ }
102
+ else if (output.type === 'function_call') {
103
+ nextItems.push({
104
+ type: 'functionCall',
105
+ functionCall: { id: output.call_id, name: output.name, arguments: output.arguments },
106
+ });
107
+ }
108
+ }
109
+ return { usage, nextItems };
110
+ // let chatItem: IChatItem
111
+ // if (response.output_text) {
112
+ // chatItem = { type: 'botMessage', botMessage: { text: response.output_text } }
113
+ // } else if (response.output && response.output[0]?.type == 'function_call') {
114
+ // chatItem = {
115
+ // type: 'functionCall',
116
+ // functionCall: {
117
+ // id: response.output[0].call_id,
118
+ // name: response.output[0].name,
119
+ // arguments: response.output[0].arguments,
120
+ // },
121
+ // }
122
+ // } else {
123
+ // throw new Error('Not supported OpenIA Response')
124
+ // }
125
+ // let usage: ILanguageModelUsage
126
+ // if (response.usage) {
127
+ // usage = {
128
+ // inputTokens: response.usage.input_tokens,
129
+ // outputTokens: response.usage.output_tokens,
130
+ // }
131
+ // } else {
132
+ // throw new Error('Unable to found usage info')
133
+ // }
134
+ // return { chatItem, usage }
111
135
  }
112
136
  };
113
137
  OpenaiChatAdapter = __decorate([
@@ -15,7 +15,7 @@ let WabotChatAdapter = class WabotChatAdapter {
15
15
  this.baseUrl = this.baseUrl.substring(0, this.baseUrl.length - 1);
16
16
  }
17
17
  }
18
- async nextItem(req) {
18
+ async nextItems(req) {
19
19
  const response = await fetch(this.baseUrl + '/chat-bot/next-item', {
20
20
  method: 'post',
21
21
  headers: {
@@ -1,21 +1,25 @@
1
- import { __decorate } from 'tslib';
1
+ import { __decorate, __metadata } from 'tslib';
2
2
  import { injectable } from '../../../core/injection/index.js';
3
3
  import * as readline from 'readline';
4
4
  import * as fs from 'fs';
5
5
  import * as path from 'path';
6
6
  import { Random } from '../../../core/random/Random.js';
7
+ import { Auth } from '../../../core/auth/Auth.js';
7
8
 
8
9
  var CmdChannel_1;
9
10
  const chatIdPath = '.cmd-channel/id.json';
10
11
  const authInfoPath = '.cmd-channel/auth-info.json';
11
12
  let CmdChannel = CmdChannel_1 = class CmdChannel {
12
- authInfo = undefined;
13
+ auth;
13
14
  chatId = undefined;
14
15
  rl = readline.createInterface({
15
16
  input: process.stdin,
16
17
  output: process.stdout,
17
18
  });
18
19
  callBack = null;
20
+ constructor(auth) {
21
+ this.auth = auth;
22
+ }
19
23
  listen(callback) {
20
24
  this.callBack = callback;
21
25
  }
@@ -44,8 +48,11 @@ let CmdChannel = CmdChannel_1 = class CmdChannel {
44
48
  };
45
49
  if (!this.callBack)
46
50
  return;
47
- if (this.authInfo === undefined) {
48
- this.authInfo = readJsonFromFile(authInfoPath);
51
+ if (!this.auth.isAssigned()) {
52
+ const authInfo = readJsonFromFile(authInfoPath);
53
+ if (authInfo) {
54
+ this.auth.assign(authInfo);
55
+ }
49
56
  }
50
57
  this.callBack({
51
58
  chatConnection,
@@ -55,18 +62,18 @@ let CmdChannel = CmdChannel_1 = class CmdChannel {
55
62
  reply: (message) => {
56
63
  console.log(`\n[${message.senderName}]: ${message.text}\n`);
57
64
  this.rl.prompt();
65
+ if (this.auth.isAssigned()) {
66
+ writeJsonToFile(authInfoPath, this.auth.require());
67
+ }
58
68
  },
59
- authInfo: this.authInfo || undefined,
60
- setAuthInfo: (authInfo) => {
61
- this.authInfo = authInfo || null;
62
- writeJsonToFile(authInfoPath, this.authInfo);
63
- },
69
+ injectInstances: [[Auth, this.auth]],
64
70
  });
65
71
  });
66
72
  }
67
73
  };
68
74
  CmdChannel = CmdChannel_1 = __decorate([
69
- injectable()
75
+ injectable(),
76
+ __metadata("design:paramtypes", [Auth])
70
77
  ], CmdChannel);
71
78
  function writeJsonToFile(filename, data) {
72
79
  const filePath = path.resolve(process.cwd(), filename);
@@ -7,8 +7,32 @@ import '../../../feature/socket-controller/metadata/SocketControllerMetadataStor
7
7
  import { runSocketControllers } from '../../../feature/socket-controller/runSocketControllers.js';
8
8
  import { Socket } from 'socket.io';
9
9
  import { SocketChannelConfig } from './SocketChannelConfig.js';
10
+ import '../../../core/validation/metadata/ValidationMetadataStore.js';
11
+ import { isNotEmpty } from '../../../core/validation/validators/is-not-empty/@isNotEmpty.js';
12
+ import { isString } from '../../../core/validation/validators/is-string/@isString.js';
13
+ import { Auth } from '../../../core/auth/Auth.js';
10
14
 
11
15
  var SocketChannel_1;
16
+ class SocketChannelReceivedMessage {
17
+ chatId;
18
+ senderName;
19
+ text;
20
+ }
21
+ __decorate([
22
+ isString(),
23
+ isNotEmpty(),
24
+ __metadata("design:type", String)
25
+ ], SocketChannelReceivedMessage.prototype, "chatId", void 0);
26
+ __decorate([
27
+ isString(),
28
+ isNotEmpty(),
29
+ __metadata("design:type", String)
30
+ ], SocketChannelReceivedMessage.prototype, "senderName", void 0);
31
+ __decorate([
32
+ isString(),
33
+ isNotEmpty(),
34
+ __metadata("design:type", String)
35
+ ], SocketChannelReceivedMessage.prototype, "text", void 0);
12
36
  let SocketChannel = SocketChannel_1 = class SocketChannel {
13
37
  config;
14
38
  callBack = null;
@@ -20,6 +44,10 @@ let SocketChannel = SocketChannel_1 = class SocketChannel {
20
44
  configController() {
21
45
  const channel = this;
22
46
  let SocketChannelController = class SocketChannelController {
47
+ auth;
48
+ constructor(auth) {
49
+ this.auth = auth;
50
+ }
23
51
  onMessage(message, socket) {
24
52
  if (!channel.callBack)
25
53
  return;
@@ -41,22 +69,23 @@ let SocketChannel = SocketChannel_1 = class SocketChannel {
41
69
  reply: (message) => {
42
70
  socket.emit('message', message);
43
71
  },
44
- authInfo: socket.data.authInfo,
45
- setAuthInfo: (authInfo) => {
46
- socket.data.authInfo = authInfo;
47
- },
72
+ injectInstances: [
73
+ [Socket, socket],
74
+ [Auth, this.auth],
75
+ ],
48
76
  });
49
77
  }
50
78
  };
51
79
  __decorate([
52
80
  onSocketEvent('message'),
53
81
  __metadata("design:type", Function),
54
- __metadata("design:paramtypes", [Object, Socket]),
82
+ __metadata("design:paramtypes", [SocketChannelReceivedMessage, Socket]),
55
83
  __metadata("design:returntype", void 0)
56
84
  ], SocketChannelController.prototype, "onMessage", null);
57
85
  SocketChannelController = __decorate([
58
86
  socketController(channel.config.namespace),
59
- handshakeMiddlewares(channel.config.handshakeMidlewares ?? [])
87
+ handshakeMiddlewares(channel.config.handshakeMidlewares ?? []),
88
+ __metadata("design:paramtypes", [Auth])
60
89
  ], SocketChannelController);
61
90
  this.controller = SocketChannelController;
62
91
  }
@@ -74,4 +103,4 @@ SocketChannel = SocketChannel_1 = __decorate([
74
103
  __metadata("design:paramtypes", [SocketChannelConfig])
75
104
  ], SocketChannel);
76
105
 
77
- export { SocketChannel };
106
+ export { SocketChannel, SocketChannelReceivedMessage };
@@ -1,5 +1,5 @@
1
1
  class ChatAdapter {
2
- nextItem(req) {
2
+ nextItems(req) {
3
3
  throw new Error('Method not implemented.');
4
4
  }
5
5
  }
@@ -41,23 +41,27 @@ let ChatBot = class ChatBot {
41
41
  throw new Error(`Invalid ${this.mindset.constructor.name} - llms not found`);
42
42
  }
43
43
  const llm = llms[0];
44
- const { chatItem: newItemData } = await this.adapter.nextItem({
44
+ const { nextItems: newItemsData } = await this.adapter.nextItems({
45
45
  model: llm.model,
46
46
  provider: llm.provider,
47
47
  systemPrompt,
48
48
  tools,
49
49
  prevItems: prevItems.map((x) => x.getData()),
50
50
  });
51
- if (newItemData.type === 'functionCall') {
52
- newItemData.functionCall.result = await this.mindset.callFunction(newItemData.functionCall.name, newItemData.functionCall.arguments ?? '{}');
51
+ for (const newItemData of newItemsData) {
52
+ if (newItemData.type === 'functionCall') {
53
+ newItemData.functionCall.result = await this.mindset.callFunction(newItemData.functionCall.name, newItemData.functionCall.arguments ?? '{}');
54
+ }
55
+ else if (newItemData.type === 'botMessage') {
56
+ newItemData.botMessage.senderName = identity.name;
57
+ }
58
+ const newChatItem = new ChatItem(newItemData);
59
+ await this.memory.create(newChatItem);
60
+ if (newItemData.type === 'botMessage') {
61
+ callback(newChatItem.botMessage);
62
+ }
53
63
  }
54
- else if (newItemData.type === 'botMessage') {
55
- newItemData.botMessage.senderName = identity.name;
56
- }
57
- const newChatItem = new ChatItem(newItemData);
58
- await this.memory.create(newChatItem);
59
- if (newChatItem.type === 'botMessage') {
60
- callback(newChatItem.botMessage);
64
+ if (newItemsData.length == 0 || newItemsData[newItemsData.length - 1].type === 'botMessage') {
61
65
  return;
62
66
  }
63
67
  this.processLoop(callback);
@@ -62,18 +62,15 @@ function runChatControllers(controllers) {
62
62
  chat,
63
63
  ...channelMessage,
64
64
  });
65
+ if (channelMessage.injectInstances) {
66
+ for (const [token, instance] of channelMessage.injectInstances) {
67
+ chatContainer.registerInstance(token, instance);
68
+ }
69
+ }
65
70
  const chatController = chatContainer.resolve(channelMetadata.controllerConstructor);
66
71
  const receivedMessage = {
67
72
  message: channelMessage.message,
68
- reply: (message) => {
69
- channelMessage.reply(message);
70
- if (channelMessage.setAuthInfo) {
71
- const auth = chatContainer.resolve(Auth);
72
- if (auth.wasOverrided()) {
73
- channelMessage.setAuthInfo(auth['authInfo'] || undefined);
74
- }
75
- }
76
- },
73
+ reply: channelMessage.reply,
77
74
  };
78
75
  chatController[channelMetadata.functionName](receivedMessage);
79
76
  });
@@ -59,7 +59,7 @@ function runRestControllers(controllers) {
59
59
  }
60
60
  }
61
61
  const response = await controllerInstance[endPoint.functionName].apply(controllerInstance, endPointArgs);
62
- res.status(200).json(response);
62
+ res.status(200).json(response ?? null);
63
63
  }
64
64
  catch (err) {
65
65
  logger.error(err);
@@ -6,7 +6,7 @@ function handshakeMiddlewares(middlewares) {
6
6
  const store = container.resolve(SocketControllerMetadataStore);
7
7
  for (const mw of middlewares) {
8
8
  store.saveHandshakeMiddlewareMetadata({
9
- controllerConstructor: target.constructor,
9
+ controllerConstructor: target,
10
10
  middlewareConstructor: mw,
11
11
  });
12
12
  }
@@ -25,6 +25,7 @@ function runSocketControllers(controllers) {
25
25
  await middleware.handle(socket, connectionContainer);
26
26
  }
27
27
  socket.data.connectionContainer = connectionContainer;
28
+ connectionContainer.registerInstance(Socket, socket);
28
29
  next();
29
30
  }
30
31
  catch (err) {
@@ -615,24 +615,24 @@ interface ILanguageModelUsage {
615
615
  outputTokens: number;
616
616
  }
617
617
 
618
- interface IChatAdapterNextItemReq {
618
+ interface IChatAdapterNextItemsReq {
619
619
  model: string;
620
620
  systemPrompt: string;
621
621
  tools: IMindsetTool[];
622
622
  prevItems: IChatItem[];
623
623
  }
624
- interface IChatAdapterNextItemRes {
625
- chatItem: IChatItem;
624
+ interface IChatAdapterNextItemsRes {
625
+ nextItems: IChatItem[];
626
626
  usage: ILanguageModelUsage;
627
627
  }
628
628
  interface IChatAdapter {
629
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
629
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
630
630
  }
631
631
 
632
632
  declare class ChatAdapter implements IChatAdapter {
633
- nextItem(req: IChatAdapterNextItemReq & {
633
+ nextItems(req: IChatAdapterNextItemsReq & {
634
634
  provider?: string;
635
- }): Promise<IChatAdapterNextItemRes>;
635
+ }): Promise<IChatAdapterNextItemsRes>;
636
636
  }
637
637
 
638
638
  type IChatItemData = IEntityData & IChatItem;
@@ -709,8 +709,7 @@ interface IReceivedMessage {
709
709
 
710
710
  interface IChannelMessage extends IReceivedMessage {
711
711
  chatConnection: IChatConnection;
712
- authInfo?: IStorableData;
713
- setAuthInfo?: (authInfo: IStorableData | undefined) => void;
712
+ injectInstances?: [any, any][];
714
713
  }
715
714
 
716
715
  interface IChatChannel {
@@ -1176,7 +1175,7 @@ declare class AnthropicChatAdapter implements IChatAdapter {
1176
1175
  private anthropic;
1177
1176
  private logger;
1178
1177
  constructor(env: Env);
1179
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
1178
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
1180
1179
  private mapChatItems;
1181
1180
  private mapHumanMessage;
1182
1181
  private mapBotMessage;
@@ -1189,7 +1188,7 @@ declare class DeepSeekChatAdapter implements IChatAdapter {
1189
1188
  private deepSeek;
1190
1189
  private logger;
1191
1190
  constructor();
1192
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
1191
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
1193
1192
  private mapChatItems;
1194
1193
  private mapHumanMessage;
1195
1194
  private mapBotMessage;
@@ -1198,12 +1197,14 @@ declare class DeepSeekChatAdapter implements IChatAdapter {
1198
1197
  private mapResponse;
1199
1198
  }
1200
1199
 
1200
+ interface GoogleChatAdapterV2Options {
1201
+ apiKey?: string;
1202
+ }
1201
1203
  declare class GoogleChatAdapter implements IChatAdapter {
1202
- private env;
1203
- private openai;
1204
- private logger;
1204
+ private ai;
1205
+ private readonly logger;
1205
1206
  constructor(env: Env);
1206
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
1207
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
1207
1208
  private mapChatItems;
1208
1209
  private mapHumanMessage;
1209
1210
  private mapBotMessage;
@@ -1215,7 +1216,7 @@ declare class GoogleChatAdapter implements IChatAdapter {
1215
1216
  declare class OpenaiChatAdapter implements IChatAdapter {
1216
1217
  private openai;
1217
1218
  private logger;
1218
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
1219
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
1219
1220
  private mapChatItems;
1220
1221
  private mapConectionMessage;
1221
1222
  private mapBotMessage;
@@ -1257,16 +1258,17 @@ declare class WabotChatAdapter implements IChatAdapter {
1257
1258
  private baseUrl;
1258
1259
  private logger;
1259
1260
  constructor(env: Env);
1260
- nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
1261
+ nextItems(req: IChatAdapterNextItemsReq): Promise<IChatAdapterNextItemsRes>;
1261
1262
  }
1262
1263
 
1263
1264
  declare function cmd(): (target: object, propertyKey: string | symbol) => void;
1264
1265
 
1265
1266
  declare class CmdChannel implements IChatChannel {
1266
- private authInfo;
1267
+ private auth;
1267
1268
  private chatId;
1268
1269
  private rl;
1269
1270
  private callBack;
1271
+ constructor(auth: Auth<any>);
1270
1272
  listen(callback: (message: IChannelMessage) => void): void;
1271
1273
  connect(): void;
1272
1274
  }
@@ -1291,6 +1293,11 @@ interface ISocketChannelReceivedMessage {
1291
1293
  senderName: string;
1292
1294
  text: string;
1293
1295
  }
1296
+ declare class SocketChannelReceivedMessage implements ISocketChannelReceivedMessage {
1297
+ chatId: string;
1298
+ senderName: string;
1299
+ text: string;
1300
+ }
1294
1301
  declare class SocketChannel implements IChatChannel {
1295
1302
  private config;
1296
1303
  private callBack;
@@ -1618,4 +1625,4 @@ declare function HtmlModule(options: IHtmlModuleOptions): {
1618
1625
  new (): {};
1619
1626
  };
1620
1627
 
1621
- export { AnthropicChatAdapter, ApiKey, ApiKeyGuardMiddleware, ApiKeyHandshakeGuardMiddleware, ApiKeyRepository, Async, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatAdapter, EXPRESS_REQ, EXPRESS_RES, Entity, Env, EnvWhatsAppRepository, ExpressProvider, GoogleChatAdapter, HtmlModule, HttpServerProvider, type IApiKeyData, type IApiKeyRepository, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemReq, type IChatAdapterNextItemRes, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEndPointConfig, type IEndPointMetadata, type IEntityData, type IEnvType, type IFunctionCall, type IFunctionCallItem, type IGenerateApiKeyReq, type IGenerateApiKeyRes, type IGetWhatsAppTemplateRequest, type IHandshakeMiddleware, type IHandshakeMiddlewareMetadata, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobEvent, type IJobEventListener, type IJobRepository, type IJwtRefreshTokenData, type IJwtRefreshTokenRepository, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type IMessageContext, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetLlm, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IMoneyData, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IRemoteApiKeyFetcher, type IRestControllerConfig, type IRestControllerMetadata, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISocketControllerConfig, type ISocketControllerMetadata, type ISocketEventConfig, type ISocketEventMetadata, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateInputShape, type IValidateIsInOptions, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppCloudContact, type IWhatsAppCloudMessage, type IWhatsAppCloudMessageMetadata, type IWhatsAppCloudTemplate, type IWhatsAppCloudTemplateComponent, type IWhatsAppCloudTemplateMessage, type IWhatsAppCloudTemplateParameter, type IWhatsAppCloudTemplateResponse, type IWhatsAppCloudWebhookPayload, type IWhatsAppData, type IWhatsAppMessageListener, type IWhatsAppProxyListenMessageEventData, type IWhatsAppProxyListenMessageEventReq, type IWhatsAppProxyMessage, type IWhatsAppProxyMessageContent, type IWhatsAppProxyMessageEventReq, type IWhatsAppProxySendMessageEventReq, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtHandshakeGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, Money, MoneyDto, OpenaiChatAdapter, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Password, type PasswordHashOptions, Persistent, PgApiKeyRepository, PgChatMemory, PgChatRepository, PgCrudRepository, PgJobRepository, PgJwtRefreshTokenRepository, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RemoteApiKeyRepository, RestControllerMetadataStore, SocketChannel, SocketChannelConfig, SocketControllerMetadataStore, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WHATSAPP_MESSAGE_EVENT, WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT, WHATSAPP_PROXY_SEND_MESSAGE_EVENT, WabotChatAdapter, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByCloudApi, WhatsAppReceiverByWabotProxy, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByWabotProxy, WhatsAppWabotProxyConnection, WhatsappChannelConfig, apiKeyGuard, apiKeyHandshakeGuard, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, handshakeMiddlewares, inject, injectable, isArray, isBoolean, isDate, isIn, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, jwtHandshakeGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, modelInfo, onDelete, onGet, onPost, onPut, onSocketEvent, param, readJsonFromFile, restController, runAsyncCommandHandlers, runChatControllers, runRestControllers, runSocketControllers, scoped, singleton, socket, socketController, telegram, validateAndTransform, validateArray, validateIsBoolean, validateIsDate, validateIsIn, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsApp, writeJsonToFile };
1628
+ export { AnthropicChatAdapter, ApiKey, ApiKeyGuardMiddleware, ApiKeyHandshakeGuardMiddleware, ApiKeyRepository, Async, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatAdapter, EXPRESS_REQ, EXPRESS_RES, Entity, Env, EnvWhatsAppRepository, ExpressProvider, GoogleChatAdapter, type GoogleChatAdapterV2Options, HtmlModule, HttpServerProvider, type IApiKeyData, type IApiKeyRepository, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemsReq, type IChatAdapterNextItemsRes, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEndPointConfig, type IEndPointMetadata, type IEntityData, type IEnvType, type IFunctionCall, type IFunctionCallItem, type IGenerateApiKeyReq, type IGenerateApiKeyRes, type IGetWhatsAppTemplateRequest, type IHandshakeMiddleware, type IHandshakeMiddlewareMetadata, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobEvent, type IJobEventListener, type IJobRepository, type IJwtRefreshTokenData, type IJwtRefreshTokenRepository, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type IMessageContext, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetLlm, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IMoneyData, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IRemoteApiKeyFetcher, type IRestControllerConfig, type IRestControllerMetadata, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISocketControllerConfig, type ISocketControllerMetadata, type ISocketEventConfig, type ISocketEventMetadata, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateInputShape, type IValidateIsInOptions, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppCloudContact, type IWhatsAppCloudMessage, type IWhatsAppCloudMessageMetadata, type IWhatsAppCloudTemplate, type IWhatsAppCloudTemplateComponent, type IWhatsAppCloudTemplateMessage, type IWhatsAppCloudTemplateParameter, type IWhatsAppCloudTemplateResponse, type IWhatsAppCloudWebhookPayload, type IWhatsAppData, type IWhatsAppMessageListener, type IWhatsAppProxyListenMessageEventData, type IWhatsAppProxyListenMessageEventReq, type IWhatsAppProxyMessage, type IWhatsAppProxyMessageContent, type IWhatsAppProxyMessageEventReq, type IWhatsAppProxySendMessageEventReq, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtHandshakeGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, Money, MoneyDto, OpenaiChatAdapter, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Password, type PasswordHashOptions, Persistent, PgApiKeyRepository, PgChatMemory, PgChatRepository, PgCrudRepository, PgJobRepository, PgJwtRefreshTokenRepository, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RemoteApiKeyRepository, RestControllerMetadataStore, SocketChannel, SocketChannelConfig, SocketChannelReceivedMessage, SocketControllerMetadataStore, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WHATSAPP_MESSAGE_EVENT, WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT, WHATSAPP_PROXY_SEND_MESSAGE_EVENT, WabotChatAdapter, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByCloudApi, WhatsAppReceiverByWabotProxy, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByWabotProxy, WhatsAppWabotProxyConnection, WhatsappChannelConfig, apiKeyGuard, apiKeyHandshakeGuard, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, handshakeMiddlewares, inject, injectable, isArray, isBoolean, isDate, isIn, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, jwtHandshakeGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, modelInfo, onDelete, onGet, onPost, onPut, onSocketEvent, param, readJsonFromFile, restController, runAsyncCommandHandlers, runChatControllers, runRestControllers, runSocketControllers, scoped, singleton, socket, socketController, telegram, validateAndTransform, validateArray, validateIsBoolean, validateIsDate, validateIsIn, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsApp, writeJsonToFile };
package/dist/src/index.js CHANGED
@@ -122,7 +122,7 @@ export { WabotChatAdapter } from './addon/chat-bot/wabot/WabotChatAdapter.js';
122
122
  export { cmd } from './addon/chat-controller/cmd/@cmd.js';
123
123
  export { CmdChannel, readJsonFromFile, writeJsonToFile } from './addon/chat-controller/cmd/CmdChannel.js';
124
124
  export { socket } from './addon/chat-controller/socket/@socket.js';
125
- export { SocketChannel } from './addon/chat-controller/socket/SocketChannel.js';
125
+ export { SocketChannel, SocketChannelReceivedMessage } from './addon/chat-controller/socket/SocketChannel.js';
126
126
  export { SocketChannelConfig } from './addon/chat-controller/socket/SocketChannelConfig.js';
127
127
  export { telegram } from './addon/chat-controller/telegram/@telegram.js';
128
128
  export { TelegramChannelConfig } from './addon/chat-controller/telegram/TelegramChannelConfig.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.2.0-beta.9",
3
+ "version": "0.2.0",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
@@ -12,7 +12,7 @@
12
12
  "scripts": {
13
13
  "build": "rollup --config rollup.config.ts --configPlugin typescript && tsup --dts-only --format esm --out-dir dist/src src/index.ts",
14
14
  "test:units": "node --import @yucacodes/ts/src/custom-import.mjs --test './src/**/*.unit.test.ts'",
15
- "test:integration": "node --import @yucacodes/ts/src/custom-import.mjs --test './src/**/*.integration.test.ts'",
15
+ "test:integration": "node --import ./env.mjs --import @yucacodes/ts/src/custom-import.mjs --test './src/**/*.integration.test.ts'",
16
16
  "fmt": "prettier --write .",
17
17
  "fmt:check": "prettier --check .",
18
18
  "types:check": "tsc --noEmit",
@@ -24,10 +24,6 @@
24
24
  "@rollup/plugin-json": "6.1.0",
25
25
  "@rollup/plugin-node-resolve": "16.0.1",
26
26
  "@rollup/plugin-typescript": "12.1.2",
27
- "@types/big.js": "^6.2.2",
28
- "@types/html-to-text": "^9.0.4",
29
- "@types/node": "22.14.1",
30
- "@types/react": "^19.1.2",
31
27
  "@yucacodes/ts": "^0.0.4",
32
28
  "prettier": "^3.5.3",
33
29
  "resend": "^4.4.1",
@@ -38,9 +34,12 @@
38
34
  "peerDependencies": {
39
35
  "@anthropic-ai/sdk": "^0.60.0",
40
36
  "@google/genai": "^1.16.0",
37
+ "@types/big.js": "^6.2.2",
41
38
  "@types/debug": "^4.1.12",
42
39
  "@types/express": "^5.0.1",
40
+ "@types/html-to-text": "^9.0.4",
43
41
  "@types/jsonwebtoken": "^9.0.10",
42
+ "@types/node": "22.14.1",
44
43
  "@types/pg": "^8.11.14",
45
44
  "@yucacodes/ts": "^0.0.4",
46
45
  "big.js": "^7.0.1",