@wabot-dev/framework 0.2.0-beta.8 → 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.
Files changed (29) hide show
  1. package/dist/src/addon/auth/api-key/@apiKeyHandshakeGuard.js +16 -0
  2. package/dist/src/addon/auth/api-key/{ApiKeyConnectionGuardMiddleware.js → ApiKeyHandshakeGuardMiddleware.js} +4 -4
  3. package/dist/src/addon/auth/jwt/@jwtHandshakeGuard.js +16 -0
  4. package/dist/src/addon/auth/jwt/{JwtConnectionGuardMiddleware.js → JwtHandshakeGuardMiddleware.js} +4 -4
  5. package/dist/src/addon/chat-bot/anthropic/AnthropicChatAdapter.js +18 -20
  6. package/dist/src/addon/chat-bot/deepseek/DeepSeekChatAdapter.js +2 -2
  7. package/dist/src/addon/chat-bot/google/GoogleChatAdapter.js +81 -70
  8. package/dist/src/addon/chat-bot/openia/OpenaiChatAdapter.js +43 -19
  9. package/dist/src/addon/chat-bot/wabot/WabotChatAdapter.js +1 -1
  10. package/dist/src/addon/chat-controller/cmd/CmdChannel.js +17 -10
  11. package/dist/src/addon/chat-controller/socket/@socket.js +1 -1
  12. package/dist/src/addon/chat-controller/socket/SocketChannel.js +74 -33
  13. package/dist/src/addon/chat-controller/socket/SocketChannelConfig.js +6 -4
  14. package/dist/src/core/auth/Auth.js +6 -0
  15. package/dist/src/feature/chat-bot/ChatAdapter.js +1 -1
  16. package/dist/src/feature/chat-bot/ChatBot.js +14 -10
  17. package/dist/src/feature/chat-controller/runChatControllers.js +6 -7
  18. package/dist/src/feature/rest-controller/runRestControllers.js +1 -1
  19. package/dist/src/feature/socket-controller/metadata/@handshakeMiddlewares.js +16 -0
  20. package/dist/src/feature/socket-controller/metadata/{@socketEvent.js → @onSocketEvent.js} +2 -2
  21. package/dist/src/feature/socket-controller/metadata/SocketControllerMetadataStore.js +12 -34
  22. package/dist/src/feature/socket-controller/runSocketControllers.js +96 -77
  23. package/dist/src/index.d.ts +50 -61
  24. package/dist/src/index.js +7 -8
  25. package/package.json +5 -6
  26. package/dist/src/addon/auth/api-key/@apiKeyConnectionGuard.js +0 -16
  27. package/dist/src/addon/auth/jwt/@jwtConnectionGuard.js +0 -16
  28. package/dist/src/feature/socket-controller/metadata/@connectionMiddleware.js +0 -16
  29. package/dist/src/feature/socket-controller/metadata/@socketConnection.js +0 -18
@@ -0,0 +1,16 @@
1
+ import { handshakeMiddlewares } from '../../../feature/socket-controller/metadata/@handshakeMiddlewares.js';
2
+ import '../../../feature/socket-controller/metadata/SocketControllerMetadataStore.js';
3
+ import '../../../core/injection/index.js';
4
+ import 'debug';
5
+ import '../../../core/validation/metadata/ValidationMetadataStore.js';
6
+ import 'socket.io';
7
+ import '../../../feature/socket/SocketServerProvider.js';
8
+ import { ApiKeyHandshakeGuardMiddleware } from './ApiKeyHandshakeGuardMiddleware.js';
9
+
10
+ function apiKeyHandshakeGuard() {
11
+ return function (target) {
12
+ handshakeMiddlewares([ApiKeyHandshakeGuardMiddleware])(target);
13
+ };
14
+ }
15
+
16
+ export { apiKeyHandshakeGuard };
@@ -4,7 +4,7 @@ import { CustomError } from '../../../core/error/CustomError.js';
4
4
  import { injectable } from '../../../core/injection/index.js';
5
5
  import { ApiKeyRepository } from './ApiKeyRepository.js';
6
6
 
7
- let ApiKeyConnectionGuardMiddleware = class ApiKeyConnectionGuardMiddleware {
7
+ let ApiKeyHandshakeGuardMiddleware = class ApiKeyHandshakeGuardMiddleware {
8
8
  apiKeyRepository;
9
9
  auth;
10
10
  constructor(apiKeyRepository, auth) {
@@ -45,10 +45,10 @@ let ApiKeyConnectionGuardMiddleware = class ApiKeyConnectionGuardMiddleware {
45
45
  }
46
46
  }
47
47
  };
48
- ApiKeyConnectionGuardMiddleware = __decorate([
48
+ ApiKeyHandshakeGuardMiddleware = __decorate([
49
49
  injectable(),
50
50
  __metadata("design:paramtypes", [ApiKeyRepository,
51
51
  Auth])
52
- ], ApiKeyConnectionGuardMiddleware);
52
+ ], ApiKeyHandshakeGuardMiddleware);
53
53
 
54
- export { ApiKeyConnectionGuardMiddleware };
54
+ export { ApiKeyHandshakeGuardMiddleware };
@@ -0,0 +1,16 @@
1
+ import { handshakeMiddlewares } from '../../../feature/socket-controller/metadata/@handshakeMiddlewares.js';
2
+ import '../../../feature/socket-controller/metadata/SocketControllerMetadataStore.js';
3
+ import '../../../core/injection/index.js';
4
+ import 'debug';
5
+ import '../../../core/validation/metadata/ValidationMetadataStore.js';
6
+ import 'socket.io';
7
+ import '../../../feature/socket/SocketServerProvider.js';
8
+ import { JwtHandshakeGuardMiddleware } from './JwtHandshakeGuardMiddleware.js';
9
+
10
+ function jwtHandshakeGuard() {
11
+ return function (target) {
12
+ handshakeMiddlewares([JwtHandshakeGuardMiddleware])(target);
13
+ };
14
+ }
15
+
16
+ export { jwtHandshakeGuard };
@@ -5,7 +5,7 @@ import { Auth } from '../../../core/auth/Auth.js';
5
5
  import { CustomError } from '../../../core/error/CustomError.js';
6
6
  import { JwtConfig } from './JwtConfig.js';
7
7
 
8
- let JwtConnectionGuardMiddleware = class JwtConnectionGuardMiddleware {
8
+ let JwtHandshakeGuardMiddleware = class JwtHandshakeGuardMiddleware {
9
9
  config;
10
10
  auth;
11
11
  constructor(config, auth) {
@@ -48,10 +48,10 @@ let JwtConnectionGuardMiddleware = class JwtConnectionGuardMiddleware {
48
48
  }
49
49
  }
50
50
  };
51
- JwtConnectionGuardMiddleware = __decorate([
51
+ JwtHandshakeGuardMiddleware = __decorate([
52
52
  injectable(),
53
53
  __metadata("design:paramtypes", [JwtConfig,
54
54
  Auth])
55
- ], JwtConnectionGuardMiddleware);
55
+ ], JwtHandshakeGuardMiddleware);
56
56
 
57
- export { JwtConnectionGuardMiddleware };
57
+ export { JwtHandshakeGuardMiddleware };
@@ -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);
@@ -18,7 +18,7 @@ function socket(config) {
18
18
  channelConstructor: SocketChannel,
19
19
  functionName: propertyKey.toString(),
20
20
  controllerConstructor: target.constructor,
21
- channelConfig: new SocketChannelConfig(config.channel),
21
+ channelConfig: new SocketChannelConfig(config.namespace, config.handshakeMidlewares),
22
22
  });
23
23
  };
24
24
  }