@sermas/sermas-toolkit-node-sdk 1.0.0-alpha.5 → 1.0.0-alpha.7
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.
- package/dist/config/defaults.d.ts +6 -0
- package/dist/config/defaults.js +6 -0
- package/dist/config/logger.d.ts +1 -0
- package/dist/config/logger.js +6 -0
- package/dist/config/util.d.ts +6 -0
- package/dist/config/util.js +39 -0
- package/dist/dto/session.d.ts +7 -0
- package/dist/dto/session.js +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/modules/auth.js +9 -8
- package/dist/modules/openai.d.ts +18 -0
- package/dist/modules/openai.js +56 -0
- package/dist/modules/sermas.d.ts +35 -0
- package/dist/modules/sermas.js +228 -0
- package/dist/modules/store.d.ts +20 -0
- package/dist/modules/store.js +173 -0
- package/dist/modules/tools.d.ts +15 -0
- package/dist/modules/tools.js +40 -0
- package/dist/modules/ui.d.ts +23 -0
- package/dist/modules/ui.js +119 -0
- package/package.json +12 -3
|
@@ -6,4 +6,10 @@ export declare const defaults: {
|
|
|
6
6
|
readonly PRIVATE_AUTH_CLIENT_SECRET: "platform";
|
|
7
7
|
readonly PRIVATE_API_BASE_URL: "http://api:3000/api";
|
|
8
8
|
};
|
|
9
|
+
readonly sermas: {
|
|
10
|
+
readonly SERMAS_BASE_URL: "http://localhost:8080";
|
|
11
|
+
readonly SERMAS_CLIENT_ID: "sermas-client";
|
|
12
|
+
readonly SERMAS_CLIENT_SECRET: "s3cr3t";
|
|
13
|
+
readonly SERMAS_APPID: "sermas";
|
|
14
|
+
};
|
|
9
15
|
};
|
package/dist/config/defaults.js
CHANGED
|
@@ -6,4 +6,10 @@ export const defaults = {
|
|
|
6
6
|
PRIVATE_AUTH_CLIENT_SECRET: "platform",
|
|
7
7
|
PRIVATE_API_BASE_URL: "http://api:3000/api",
|
|
8
8
|
},
|
|
9
|
+
sermas: {
|
|
10
|
+
SERMAS_BASE_URL: "http://localhost:8080",
|
|
11
|
+
SERMAS_CLIENT_ID: "sermas-client",
|
|
12
|
+
SERMAS_CLIENT_SECRET: "s3cr3t",
|
|
13
|
+
SERMAS_APPID: "sermas",
|
|
14
|
+
},
|
|
9
15
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const createLogger: (name: string) => import("winston").Logger;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
export { v4 as uuidv4 } from "uuid";
|
|
3
|
+
export declare const saveJSON: (filename: string, dataset: Record<string, unknown>) => Promise<void>;
|
|
4
|
+
export declare const loadJSON: <T = Record<string, unknown>>(filename: string) => Promise<T | null>;
|
|
5
|
+
export declare const loadFile: (filename: string) => Promise<string | null>;
|
|
6
|
+
export declare const saveFile: (filename: string, dataset: string | Buffer) => Promise<void>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import * as fs from "fs/promises";
|
|
11
|
+
import { createLogger } from "./logger.js";
|
|
12
|
+
export { v4 as uuidv4 } from "uuid";
|
|
13
|
+
const logger = createLogger("util");
|
|
14
|
+
export const saveJSON = (filename, dataset) => fs.writeFile(filename, JSON.stringify(dataset, null, 2));
|
|
15
|
+
export const loadJSON = (filename) => __awaiter(void 0, void 0, void 0, function* () {
|
|
16
|
+
try {
|
|
17
|
+
const raw = yield loadFile(filename);
|
|
18
|
+
if (raw === null)
|
|
19
|
+
return null;
|
|
20
|
+
return JSON.parse(raw);
|
|
21
|
+
}
|
|
22
|
+
catch (e) {
|
|
23
|
+
if (e instanceof Error)
|
|
24
|
+
logger.error(`Failed to load dataset: ${e.stack}`);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
export const loadFile = (filename) => __awaiter(void 0, void 0, void 0, function* () {
|
|
29
|
+
try {
|
|
30
|
+
const raw = yield fs.readFile(filename);
|
|
31
|
+
return raw.toString();
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (e instanceof Error)
|
|
35
|
+
logger.error(`Failed to load dataset: ${e.stack}`);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
export const saveFile = (filename, dataset) => fs.writeFile(filename, dataset);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
1
|
export { getAvatarToken, getAvatarTokenWithClientSecret, } from "./modules/auth.js";
|
|
2
|
+
export { OpenAIClient } from "./modules/openai.js";
|
|
3
|
+
export { Store } from "./modules/store.js";
|
|
4
|
+
export { UI } from "./modules/ui.js";
|
|
5
|
+
export { Tools } from "./modules/tools.js";
|
|
6
|
+
export { SermasApp, SermasConfig } from "./modules/sermas.js";
|
package/dist/index.js
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
1
|
export { getAvatarToken, getAvatarTokenWithClientSecret, } from "./modules/auth.js";
|
|
2
|
+
export { OpenAIClient } from "./modules/openai.js";
|
|
3
|
+
export { Store } from "./modules/store.js";
|
|
4
|
+
export { UI } from "./modules/ui.js";
|
|
5
|
+
export { Tools } from "./modules/tools.js";
|
|
6
|
+
export { SermasApp } from "./modules/sermas.js";
|
package/dist/modules/auth.js
CHANGED
|
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
import axios, { isAxiosError } from "axios";
|
|
11
11
|
import * as https from "https";
|
|
12
12
|
import { defaults } from "../config/defaults.js";
|
|
13
|
+
import { createLogger } from "../config/logger.js";
|
|
13
14
|
const httpsAgent = new https.Agent({
|
|
14
15
|
rejectUnauthorized: process.env.NODE_ENV !== "development",
|
|
15
16
|
});
|
|
@@ -19,7 +20,7 @@ const httpsAgent = new https.Agent({
|
|
|
19
20
|
* @param {AuthConfig} authConfig
|
|
20
21
|
*/
|
|
21
22
|
export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (appId = null, authConfig = defaults.auth) {
|
|
22
|
-
const logger =
|
|
23
|
+
const logger = createLogger("getAvatarToken");
|
|
23
24
|
const tokens = {};
|
|
24
25
|
let kioskToken = null;
|
|
25
26
|
const PUBLIC_AUTH_URL = authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;
|
|
@@ -38,7 +39,7 @@ export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void
|
|
|
38
39
|
});
|
|
39
40
|
const getAppAccessToken = (appId_1, ...args_3) => __awaiter(void 0, [appId_1, ...args_3], void 0, function* (appId, clientId = "avatar") {
|
|
40
41
|
var _a, _b;
|
|
41
|
-
logger.
|
|
42
|
+
logger.info(`Fetch app token for appId=${appId} clientId=${clientId}`);
|
|
42
43
|
const cacheKey = `${appId}-${clientId}`;
|
|
43
44
|
tokens[cacheKey] = tokens[cacheKey] || null;
|
|
44
45
|
if (tokens[cacheKey]) {
|
|
@@ -48,7 +49,7 @@ export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void
|
|
|
48
49
|
}
|
|
49
50
|
}
|
|
50
51
|
if (tokens[cacheKey]) {
|
|
51
|
-
logger.
|
|
52
|
+
logger.info(`Using cached token for ${cacheKey}`);
|
|
52
53
|
return tokens[cacheKey];
|
|
53
54
|
}
|
|
54
55
|
try {
|
|
@@ -66,7 +67,7 @@ export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void
|
|
|
66
67
|
});
|
|
67
68
|
// expires 1min before
|
|
68
69
|
const expiresIn = res.data.expires_in * 1000;
|
|
69
|
-
logger.
|
|
70
|
+
logger.info(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
|
|
70
71
|
const { access_token, refresh_token } = res.data;
|
|
71
72
|
const token = {
|
|
72
73
|
accessToken: access_token,
|
|
@@ -144,13 +145,13 @@ export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void
|
|
|
144
145
|
* @param {string} clientSecret needed for server2server authentication
|
|
145
146
|
*/
|
|
146
147
|
export const getAvatarTokenWithClientSecret = (...args_4) => __awaiter(void 0, [...args_4], void 0, function* (appId = null, authConfig = defaults.auth, clientSecret = "") {
|
|
147
|
-
const logger =
|
|
148
|
+
const logger = createLogger("getAvatarTokenWithClientSecret");
|
|
148
149
|
const tokens = {};
|
|
149
150
|
const PRIVATE_API_BASE_URL = authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
|
|
150
151
|
const PRIVATE_AUTH_CLIENT_ID = authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
|
|
151
152
|
const getAppAccessTokenWithClientSecret = (appId_2, ...args_5) => __awaiter(void 0, [appId_2, ...args_5], void 0, function* (appId, clientId = "avatar", clientSecret = "") {
|
|
152
153
|
var _e, _f;
|
|
153
|
-
logger.
|
|
154
|
+
logger.info(`Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`);
|
|
154
155
|
const cacheKey = `${appId}-${clientId}`;
|
|
155
156
|
tokens[cacheKey] = tokens[cacheKey] || null;
|
|
156
157
|
if (tokens[cacheKey]) {
|
|
@@ -161,7 +162,7 @@ export const getAvatarTokenWithClientSecret = (...args_4) => __awaiter(void 0, [
|
|
|
161
162
|
}
|
|
162
163
|
}
|
|
163
164
|
if (tokens[cacheKey]) {
|
|
164
|
-
logger.
|
|
165
|
+
logger.info(`Using cached token for ${cacheKey}`);
|
|
165
166
|
return tokens[cacheKey];
|
|
166
167
|
}
|
|
167
168
|
try {
|
|
@@ -178,7 +179,7 @@ export const getAvatarTokenWithClientSecret = (...args_4) => __awaiter(void 0, [
|
|
|
178
179
|
});
|
|
179
180
|
// expires 1min before
|
|
180
181
|
const expiresIn = res.data.expires_in * 1000;
|
|
181
|
-
logger.
|
|
182
|
+
logger.info(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
|
|
182
183
|
const { access_token, refresh_token } = res.data;
|
|
183
184
|
const token = {
|
|
184
185
|
accessToken: access_token,
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import OpenAI, { ClientOptions } from "openai";
|
|
2
|
+
export type OpenAIConfig = {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
} & ClientOptions;
|
|
5
|
+
type ChatCompletionMessage = {
|
|
6
|
+
messages: Array<OpenAI.Chat.ChatCompletionMessageParam>;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Wrapper for OpenAI client to implement sermas functionalities
|
|
10
|
+
*/
|
|
11
|
+
export declare class OpenAIClient {
|
|
12
|
+
private logger;
|
|
13
|
+
private openAI;
|
|
14
|
+
constructor(openAIConfig: OpenAIConfig);
|
|
15
|
+
chat(body: string | ChatCompletionMessage, options?: OpenAI.RequestOptions<unknown>): Promise<string | null>;
|
|
16
|
+
json<T = Record<string, unknown>>(body: string | OpenAI.Chat.ChatCompletionCreateParams, options?: OpenAI.RequestOptions<unknown>): Promise<T | null | undefined>;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { createLogger } from "../config/logger.js";
|
|
11
|
+
import OpenAI from "openai";
|
|
12
|
+
/**
|
|
13
|
+
* Wrapper for OpenAI client to implement sermas functionalities
|
|
14
|
+
*/
|
|
15
|
+
export class OpenAIClient {
|
|
16
|
+
constructor(openAIConfig) {
|
|
17
|
+
this.logger = createLogger(OpenAIClient.name);
|
|
18
|
+
if (!openAIConfig.apiKey)
|
|
19
|
+
this.logger.warn("No API key provided for OpenAIClient");
|
|
20
|
+
this.openAI = new OpenAI(openAIConfig);
|
|
21
|
+
}
|
|
22
|
+
chat(body, options) {
|
|
23
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
24
|
+
try {
|
|
25
|
+
const result = yield this.openAI.chat.completions.create(Object.assign({ model: "gpt-3.5-turbo" }, (typeof body === "string"
|
|
26
|
+
? { messages: [{ role: "user", content: body }] }
|
|
27
|
+
: body)), options);
|
|
28
|
+
return result.choices[0].message.content;
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
if (e instanceof Error)
|
|
32
|
+
this.logger.error(`OpenAI request failed: ${e.stack}`);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
json(body, options) {
|
|
38
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
39
|
+
let text = yield this.chat(body, options);
|
|
40
|
+
if (text === null)
|
|
41
|
+
return;
|
|
42
|
+
try {
|
|
43
|
+
if (text.startsWith("```json")) {
|
|
44
|
+
text = text.replace("```json", "").replace("```", "");
|
|
45
|
+
}
|
|
46
|
+
return JSON.parse(text);
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
if (e instanceof Error)
|
|
50
|
+
this.logger.error(`Failed to parse content: ${e.stack}`);
|
|
51
|
+
this.logger.debug(`Content: ${text}`);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { EventEmitter2 } from "eventemitter2";
|
|
2
|
+
import { AppToolsDTO, DialogueMessageDto, DialogueToolsRepositoryOptionsDto, PlatformAppDto, SessionDto, SessionStorageRecordDto, SessionStorageSearchDto, UIContentDto } from "@sermas/api-client";
|
|
3
|
+
export type SermasConfig = {
|
|
4
|
+
SERMAS_BASE_URL: string;
|
|
5
|
+
SERMAS_CLIENT_ID: string;
|
|
6
|
+
SERMAS_CLIENT_SECRET: string;
|
|
7
|
+
SERMAS_APPID: string;
|
|
8
|
+
};
|
|
9
|
+
export declare class SermasApp {
|
|
10
|
+
private logger;
|
|
11
|
+
private baseUrl;
|
|
12
|
+
private app;
|
|
13
|
+
private client;
|
|
14
|
+
private clientId;
|
|
15
|
+
private clientSecret;
|
|
16
|
+
private appId;
|
|
17
|
+
emitter: EventEmitter2;
|
|
18
|
+
subs: (() => void)[];
|
|
19
|
+
constructor(sermasConfig: SermasConfig);
|
|
20
|
+
getBaseUrl(): string;
|
|
21
|
+
initialize(): Promise<void>;
|
|
22
|
+
private setupSermasClient;
|
|
23
|
+
addSub(sub: () => Promise<() => void>): void;
|
|
24
|
+
sendChatMessage(ev: DialogueMessageDto): Promise<void>;
|
|
25
|
+
sendUiContent(ev: UIContentDto): Promise<void>;
|
|
26
|
+
getApp(): Promise<PlatformAppDto | null>;
|
|
27
|
+
updateAppTools(tools: AppToolsDTO[]): Promise<void>;
|
|
28
|
+
setTools(repositoryId: string, tools: AppToolsDTO[]): Promise<void>;
|
|
29
|
+
addTools(repositoryId: string, tools: AppToolsDTO[], options?: DialogueToolsRepositoryOptionsDto): Promise<void>;
|
|
30
|
+
readSession(sessionId: string): Promise<SessionDto | null>;
|
|
31
|
+
getRecord(storageId: string): Promise<SessionStorageRecordDto | null>;
|
|
32
|
+
findRecords(query: SessionStorageSearchDto): Promise<SessionStorageRecordDto[] | null>;
|
|
33
|
+
setRecord(storage: SessionStorageRecordDto): Promise<SessionStorageRecordDto | null>;
|
|
34
|
+
generateQRCode(data: string): Promise<any>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { createLogger } from "../config/logger.js";
|
|
11
|
+
import { EventEmitter2 } from "eventemitter2";
|
|
12
|
+
import { SermasApiClient, } from "@sermas/api-client";
|
|
13
|
+
import { defaults } from "../config/defaults.js";
|
|
14
|
+
export class SermasApp {
|
|
15
|
+
constructor(sermasConfig) {
|
|
16
|
+
this.logger = createLogger(SermasApp.name);
|
|
17
|
+
this.app = null;
|
|
18
|
+
this.subs = [];
|
|
19
|
+
this.baseUrl =
|
|
20
|
+
sermasConfig.SERMAS_BASE_URL || defaults.sermas.SERMAS_BASE_URL;
|
|
21
|
+
this.appId = sermasConfig.SERMAS_APPID || defaults.sermas.SERMAS_CLIENT_ID;
|
|
22
|
+
this.clientId =
|
|
23
|
+
sermasConfig.SERMAS_CLIENT_ID || defaults.sermas.SERMAS_CLIENT_SECRET;
|
|
24
|
+
this.clientSecret =
|
|
25
|
+
sermasConfig.SERMAS_CLIENT_SECRET || defaults.sermas.SERMAS_APPID;
|
|
26
|
+
this.emitter = new EventEmitter2();
|
|
27
|
+
this.initialize();
|
|
28
|
+
this.client = new SermasApiClient({
|
|
29
|
+
baseURL: this.getBaseUrl(),
|
|
30
|
+
appId: this.appId,
|
|
31
|
+
logger: createLogger("sermas-api-client"),
|
|
32
|
+
});
|
|
33
|
+
this.getApp();
|
|
34
|
+
}
|
|
35
|
+
getBaseUrl() {
|
|
36
|
+
return this.baseUrl;
|
|
37
|
+
}
|
|
38
|
+
initialize() {
|
|
39
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
40
|
+
// return await this.getClientCredentials();
|
|
41
|
+
yield this.setupSermasClient();
|
|
42
|
+
this.addSub(() => __awaiter(this, void 0, void 0, function* () {
|
|
43
|
+
return yield this.client.events.auth.onUserLogin((ev) => {
|
|
44
|
+
this.logger.debug(`User login: ${ev}`);
|
|
45
|
+
});
|
|
46
|
+
}));
|
|
47
|
+
this.addSub(() => __awaiter(this, void 0, void 0, function* () {
|
|
48
|
+
return yield this.client.events.session.onSessionChanged((ev) => {
|
|
49
|
+
this.logger.debug(`session changed ${ev.operation.toUpperCase()} sessionId=${ev.record.sessionId}`);
|
|
50
|
+
this.emitter.emit(`session`, ev);
|
|
51
|
+
});
|
|
52
|
+
}));
|
|
53
|
+
this.addSub(() => __awaiter(this, void 0, void 0, function* () {
|
|
54
|
+
return yield this.client.events.dialogue.onToolTriggered((event) => {
|
|
55
|
+
this.logger.debug("Tool triggered: " + event.name);
|
|
56
|
+
this.emitter.emit(`tool`, event);
|
|
57
|
+
});
|
|
58
|
+
}));
|
|
59
|
+
this.addSub(() => __awaiter(this, void 0, void 0, function* () {
|
|
60
|
+
return yield this.client.events.ui.onInteraction((event) => {
|
|
61
|
+
// this.logger.debug('UI interaction: ' + event.interaction);
|
|
62
|
+
this.emitter.emit(`ui.interaction`, event);
|
|
63
|
+
});
|
|
64
|
+
}));
|
|
65
|
+
this.addSub(() => __awaiter(this, void 0, void 0, function* () {
|
|
66
|
+
return yield this.client.events.session.onAgentChanged((event) => {
|
|
67
|
+
this.logger.debug("Agent changed: " + event.operation);
|
|
68
|
+
this.emitter.emit(`agent.changed`, event);
|
|
69
|
+
});
|
|
70
|
+
}));
|
|
71
|
+
this.logger.info("Sermas initialization completed");
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
setupSermasClient() {
|
|
75
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
76
|
+
this.logger.debug("Initializing sermas client.");
|
|
77
|
+
try {
|
|
78
|
+
this.logger.debug(`Loading token`);
|
|
79
|
+
yield this.client.loadToken(this.clientId, this.clientSecret);
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
this.logger.error(`Failed to load token, retrying`);
|
|
83
|
+
if (e instanceof Error)
|
|
84
|
+
this.logger.debug(e.stack);
|
|
85
|
+
setTimeout(() => this.setupSermasClient(), 1000);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
this.logger.debug(`sermas client ready`);
|
|
89
|
+
this.emitter.emit("sermas.ready");
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
addSub(sub) {
|
|
93
|
+
sub()
|
|
94
|
+
.then((fn) => {
|
|
95
|
+
this.subs.push(fn);
|
|
96
|
+
})
|
|
97
|
+
.catch((e) => {
|
|
98
|
+
this.logger.error(`Subscribe failed: ${e.stack}`);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
sendChatMessage(ev) {
|
|
102
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
103
|
+
yield this.client.api.dialogue.chatMessage({
|
|
104
|
+
appId: ev.appId,
|
|
105
|
+
sessionId: ev.sessionId,
|
|
106
|
+
requestBody: ev,
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
sendUiContent(ev) {
|
|
111
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
112
|
+
yield this.client.events.ui.content(ev);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
getApp() {
|
|
116
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
117
|
+
if (this.app)
|
|
118
|
+
return this.app;
|
|
119
|
+
this.logger.debug(`Load app ${this.appId}`);
|
|
120
|
+
try {
|
|
121
|
+
this.app = yield this.client.api.platform.readApp({ appId: this.appId });
|
|
122
|
+
return this.app;
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
if (e instanceof Error)
|
|
126
|
+
this.logger.error(`Failed to load app ${this.appId}: ${e.stack}`);
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
updateAppTools(tools) {
|
|
132
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
133
|
+
yield this.client.api.platform.updateAppTools({
|
|
134
|
+
appId: this.appId,
|
|
135
|
+
requestBody: tools,
|
|
136
|
+
});
|
|
137
|
+
this.logger.debug("Updated tools");
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
setTools(repositoryId, tools) {
|
|
141
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
142
|
+
yield this.client.api.dialogue.setTools({
|
|
143
|
+
repositoryId,
|
|
144
|
+
requestBody: {
|
|
145
|
+
repositoryId,
|
|
146
|
+
appId: this.appId,
|
|
147
|
+
tools,
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
this.logger.debug("Updated tools");
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
addTools(repositoryId, tools, options) {
|
|
154
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
155
|
+
yield this.client.api.dialogue.addTools({
|
|
156
|
+
repositoryId,
|
|
157
|
+
requestBody: { repositoryId, appId: this.appId, tools, options },
|
|
158
|
+
});
|
|
159
|
+
this.logger.debug("Updated tools");
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
readSession(sessionId) {
|
|
163
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
164
|
+
try {
|
|
165
|
+
return yield this.client.api.session.readSession({ sessionId });
|
|
166
|
+
}
|
|
167
|
+
catch (e) {
|
|
168
|
+
if (e instanceof Error)
|
|
169
|
+
this.logger.error(`Failed to readSession: ${e.stack}`);
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
getRecord(storageId) {
|
|
175
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
176
|
+
try {
|
|
177
|
+
return yield this.client.api.session.getRecord({ storageId });
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
if (e instanceof Error && e.message.indexOf("Not Found") === -1)
|
|
181
|
+
this.logger.error(`Failed to getRecord: ${e.stack}`);
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
findRecords(query) {
|
|
187
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
188
|
+
try {
|
|
189
|
+
return yield this.client.api.session.findRecords({
|
|
190
|
+
requestBody: query,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
if (e instanceof Error)
|
|
195
|
+
this.logger.error(`Failed to findRecords: ${e.stack}`);
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
setRecord(storage) {
|
|
201
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
202
|
+
try {
|
|
203
|
+
return yield this.client.api.session.setRecord({
|
|
204
|
+
requestBody: storage,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
if (e instanceof Error)
|
|
209
|
+
this.logger.error(`Failed to setRecord: ${e.stack}`);
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
generateQRCode(data) {
|
|
215
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
216
|
+
try {
|
|
217
|
+
return yield this.client.api.ui.generateQrCode({
|
|
218
|
+
requestBody: { version: 5, data },
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
if (e instanceof Error)
|
|
223
|
+
this.logger.error(`Failed to generate QR code: ${e.stack}`);
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { SessionChangedDto } from "@sermas/api-client";
|
|
2
|
+
import { SermasApp } from "./sermas.js";
|
|
3
|
+
import { BaseSessionWrapper } from "../dto/session.js";
|
|
4
|
+
export declare class Store {
|
|
5
|
+
private readonly logger;
|
|
6
|
+
private sermas;
|
|
7
|
+
private sessions;
|
|
8
|
+
private locks;
|
|
9
|
+
constructor(sermas: SermasApp);
|
|
10
|
+
onSessionChange(ev: SessionChangedDto): Promise<void>;
|
|
11
|
+
private lock;
|
|
12
|
+
loadSessionWrapper<SessionWrapper extends BaseSessionWrapper>(context: {
|
|
13
|
+
sessionId: string;
|
|
14
|
+
appId?: string;
|
|
15
|
+
userId?: string;
|
|
16
|
+
}): Promise<SessionWrapper>;
|
|
17
|
+
saveSession<SessionWrapper extends BaseSessionWrapper>(session: SessionWrapper): Promise<SessionWrapper | null>;
|
|
18
|
+
getSessionWrapper(sessionId: string): Promise<BaseSessionWrapper | undefined>;
|
|
19
|
+
saveSessionWrapper(ev: SessionChangedDto): Promise<unknown>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { createLogger } from "../config/logger.js";
|
|
11
|
+
import { uuidv4 } from "../config/util.js";
|
|
12
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
13
|
+
export class Store {
|
|
14
|
+
constructor(sermas) {
|
|
15
|
+
this.logger = createLogger(Store.name);
|
|
16
|
+
this.sessions = {};
|
|
17
|
+
this.locks = {};
|
|
18
|
+
this.sermas = sermas;
|
|
19
|
+
}
|
|
20
|
+
// @OnEvent("session")
|
|
21
|
+
onSessionChange(ev) {
|
|
22
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
23
|
+
if (!ev.record.sessionId)
|
|
24
|
+
return;
|
|
25
|
+
const session = yield this.saveSessionWrapper(ev);
|
|
26
|
+
switch (ev.operation) {
|
|
27
|
+
case "created":
|
|
28
|
+
if (!session) {
|
|
29
|
+
this.logger.warn(`Failed to get session for sessionId=${ev.record.sessionId}`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
this.sermas.emitter.emit("session.started", session);
|
|
33
|
+
break;
|
|
34
|
+
case "updated":
|
|
35
|
+
yield this.saveSessionWrapper(ev);
|
|
36
|
+
break;
|
|
37
|
+
case "removed":
|
|
38
|
+
if (!this.sessions[ev.record.sessionId])
|
|
39
|
+
return;
|
|
40
|
+
delete this.sessions[ev.record.sessionId];
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
lock(sessionId, fn) {
|
|
46
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
47
|
+
// eslint-disable-next-line no-async-promise-executor
|
|
48
|
+
this.locks[sessionId] = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
|
49
|
+
try {
|
|
50
|
+
resolve(yield fn());
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
reject(e);
|
|
54
|
+
}
|
|
55
|
+
}));
|
|
56
|
+
try {
|
|
57
|
+
const res = yield this.locks[sessionId];
|
|
58
|
+
return res;
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
if (e instanceof Error)
|
|
62
|
+
this.logger.error(`lock failure: ${e.stack}`);
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
delete this.locks[sessionId];
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
loadSessionWrapper(context) {
|
|
71
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
const opId = `[${performance.now()}] `;
|
|
73
|
+
if (yield this.locks[context.sessionId]) {
|
|
74
|
+
this.logger.debug(`${opId} Wait lock for sessionId=${context.sessionId}`);
|
|
75
|
+
yield this.locks[context.sessionId];
|
|
76
|
+
this.logger.debug(`${opId} Lock released for sessionId=${context.sessionId}`);
|
|
77
|
+
}
|
|
78
|
+
return yield this.lock(context.sessionId, () => __awaiter(this, void 0, void 0, function* () {
|
|
79
|
+
this.logger.debug(`${opId} Loading wrapper for sessionId=${context.sessionId}`);
|
|
80
|
+
const records = yield this.sermas.findRecords({
|
|
81
|
+
appId: "",
|
|
82
|
+
sessionId: [context.sessionId],
|
|
83
|
+
userId: undefined,
|
|
84
|
+
});
|
|
85
|
+
if (records && records.length) {
|
|
86
|
+
this.logger.debug(`${opId} Wrapper exists for sessionId=${context.sessionId}`);
|
|
87
|
+
return records[0].data;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
this.logger.debug(`${opId} Wrapper not found for sessionId=${context.sessionId}`);
|
|
91
|
+
}
|
|
92
|
+
this.logger.debug(`${opId} Creating new session wrapper store sessionId=${context.sessionId} appId=${context.appId} userId=${context.userId}`);
|
|
93
|
+
const storageId = uuidv4();
|
|
94
|
+
const sessionWrapper = Object.assign(Object.assign({}, context), { appId: context.appId, sessionId: context.sessionId, userId: context.userId, storageId });
|
|
95
|
+
if (!sessionWrapper.appId || !sessionWrapper.userId) {
|
|
96
|
+
this.logger.debug(`${opId} Load session record sessionId=${sessionWrapper.sessionId}`);
|
|
97
|
+
const session = yield this.sermas.readSession(sessionWrapper.sessionId);
|
|
98
|
+
if (session) {
|
|
99
|
+
if (!sessionWrapper.appId)
|
|
100
|
+
sessionWrapper.appId = session.appId;
|
|
101
|
+
if (!sessionWrapper.userId)
|
|
102
|
+
sessionWrapper.userId = session.userId;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
this.logger.warn(`${opId} Failed to load sessionId=${sessionWrapper.sessionId}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const record = {
|
|
109
|
+
appId: sessionWrapper.appId,
|
|
110
|
+
sessionId: sessionWrapper.sessionId,
|
|
111
|
+
data: sessionWrapper,
|
|
112
|
+
userId: sessionWrapper.userId || undefined,
|
|
113
|
+
storageId,
|
|
114
|
+
};
|
|
115
|
+
yield this.sermas.setRecord(record);
|
|
116
|
+
this.logger.debug(`${opId} Saved store storageId=${record.storageId} for sessionId=${record.sessionId} appId=${record.appId} userId=${record.userId}`);
|
|
117
|
+
return sessionWrapper;
|
|
118
|
+
}));
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
saveSession(session) {
|
|
122
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
123
|
+
let record = yield this.sermas.getRecord(session.storageId);
|
|
124
|
+
if (!record) {
|
|
125
|
+
this.logger.warn(`sessionId=${session.sessionId} storageId=${session.storageId} not found, creating new record`);
|
|
126
|
+
const newSession = yield this.loadSessionWrapper(Object.assign({}, session));
|
|
127
|
+
record = yield this.sermas.getRecord(newSession.storageId);
|
|
128
|
+
}
|
|
129
|
+
if (!record) {
|
|
130
|
+
this.logger.error(`Cannot save sessionId=${session.sessionId}, storage not found`);
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
record.data = Object.assign(Object.assign({}, session), { storageId: record.storageId });
|
|
134
|
+
const res = yield this.sermas.setRecord(record);
|
|
135
|
+
this.logger.debug(`Saved record for sessionId=${record.sessionId} storageId=${record.storageId}`);
|
|
136
|
+
return res === null || res === void 0 ? void 0 : res.data;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
getSessionWrapper(sessionId) {
|
|
140
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
141
|
+
if (!sessionId) {
|
|
142
|
+
this.logger.debug(`sessionId is empty`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (!this.sessions[sessionId]) {
|
|
146
|
+
const session = yield this.loadSessionWrapper({
|
|
147
|
+
sessionId,
|
|
148
|
+
});
|
|
149
|
+
this.logger.debug(`loaded sessionId=${sessionId}`);
|
|
150
|
+
this.sessions[sessionId] = session;
|
|
151
|
+
}
|
|
152
|
+
return this.sessions[sessionId];
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
saveSessionWrapper(ev) {
|
|
156
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
157
|
+
if (!ev.appId)
|
|
158
|
+
return;
|
|
159
|
+
if (!ev.record.sessionId)
|
|
160
|
+
return;
|
|
161
|
+
if (this.sessions[ev.record.sessionId])
|
|
162
|
+
return;
|
|
163
|
+
const wrapper = yield this.loadSessionWrapper({
|
|
164
|
+
userId: ev.userId,
|
|
165
|
+
appId: ev.appId,
|
|
166
|
+
sessionId: ev.record.sessionId,
|
|
167
|
+
});
|
|
168
|
+
this.sessions[wrapper.sessionId] = wrapper;
|
|
169
|
+
this.logger.info(`Added session ${wrapper.sessionId}`);
|
|
170
|
+
return this.sessions[wrapper.sessionId];
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AppToolsDTO, DialogueToolsRepositoryOptionsDto } from "@sermas/api-client";
|
|
2
|
+
import { BaseSessionWrapper } from "../dto/session.js";
|
|
3
|
+
import { SermasApp } from "./sermas.js";
|
|
4
|
+
type ToolsSchemaValues = string | number | boolean | undefined;
|
|
5
|
+
type ToolsSchemaParameters = Record<string, ToolsSchemaValues>;
|
|
6
|
+
export declare class Tools {
|
|
7
|
+
private sermas;
|
|
8
|
+
constructor(sermasApp: SermasApp);
|
|
9
|
+
reset(session: BaseSessionWrapper): Promise<void>;
|
|
10
|
+
set(session: BaseSessionWrapper, tools: AppToolsDTO[]): Promise<void>;
|
|
11
|
+
add(session: BaseSessionWrapper, tools: AppToolsDTO[], options?: DialogueToolsRepositoryOptionsDto): Promise<void>;
|
|
12
|
+
getSchemaValues<T extends ToolsSchemaParameters = ToolsSchemaParameters>(tool: AppToolsDTO): T;
|
|
13
|
+
getSchemaValue(tool: AppToolsDTO, parameterName: string): ToolsSchemaValues;
|
|
14
|
+
}
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
export class Tools {
|
|
11
|
+
constructor(sermasApp) {
|
|
12
|
+
this.sermas = sermasApp;
|
|
13
|
+
}
|
|
14
|
+
reset(session) {
|
|
15
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
16
|
+
yield this.sermas.setTools(session.sessionId, []);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
set(session, tools) {
|
|
20
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
21
|
+
yield this.sermas.setTools(session.sessionId, tools);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
add(session, tools, options) {
|
|
25
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
26
|
+
yield this.sermas.addTools(session.sessionId, tools, options);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
getSchemaValues(tool) {
|
|
30
|
+
const values = {};
|
|
31
|
+
if (!tool.schema)
|
|
32
|
+
return values;
|
|
33
|
+
tool.schema.forEach((schema) => (values[schema.parameter] = schema.value));
|
|
34
|
+
return values;
|
|
35
|
+
}
|
|
36
|
+
getSchemaValue(tool, parameterName) {
|
|
37
|
+
const values = this.getSchemaValues(tool);
|
|
38
|
+
return values[parameterName];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ButtonDto, SessionChangedDto, UIContentOptionsDto } from "@sermas/api-client";
|
|
2
|
+
import { BaseSessionWrapper } from "../dto/session.js";
|
|
3
|
+
import { SermasApp } from "./sermas.js";
|
|
4
|
+
import { Store } from "./store.js";
|
|
5
|
+
export declare class UI {
|
|
6
|
+
private sermas;
|
|
7
|
+
private store;
|
|
8
|
+
private readonly logger;
|
|
9
|
+
private backMenuOptions;
|
|
10
|
+
constructor(sermas: SermasApp, store: Store);
|
|
11
|
+
onSessionChange(ev: SessionChangedDto): Promise<void>;
|
|
12
|
+
createBackButton(value: string): ButtonDto;
|
|
13
|
+
sendBackMenu(session: BaseSessionWrapper, labels: string | string[]): Promise<void>;
|
|
14
|
+
sendMenuButtons(session: BaseSessionWrapper, buttons: ButtonDto[]): Promise<void>;
|
|
15
|
+
sendAgentMessage(session: BaseSessionWrapper, message: string, messageLanguage: string): Promise<void>;
|
|
16
|
+
sendButtons(session: BaseSessionWrapper, label: string, list: (string | ButtonDto)[], metadata?: {
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}, options?: UIContentOptionsDto): Promise<void>;
|
|
19
|
+
sendClearScreen<T extends BaseSessionWrapper>(session: T): Promise<void>;
|
|
20
|
+
sendImage(session: BaseSessionWrapper, data: string, width: number, height: number): Promise<void>;
|
|
21
|
+
getChunkId(ts?: Date): string;
|
|
22
|
+
matchBackMenu(selection: string): boolean | "";
|
|
23
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { sleep } from "openai/core";
|
|
11
|
+
import { ulid } from "ulidx";
|
|
12
|
+
import { createLogger } from "../config/logger.js";
|
|
13
|
+
export class UI {
|
|
14
|
+
constructor(sermas, store) {
|
|
15
|
+
this.logger = createLogger(UI.name);
|
|
16
|
+
this.backMenuOptions = [];
|
|
17
|
+
this.sermas = sermas;
|
|
18
|
+
this.store = store;
|
|
19
|
+
}
|
|
20
|
+
// @OnEvent("session")
|
|
21
|
+
onSessionChange(ev) {
|
|
22
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
23
|
+
if (!ev.record.sessionId)
|
|
24
|
+
return;
|
|
25
|
+
const session = yield this.store.getSessionWrapper(ev.record.sessionId);
|
|
26
|
+
switch (ev.operation) {
|
|
27
|
+
case "removed":
|
|
28
|
+
if (!session)
|
|
29
|
+
return;
|
|
30
|
+
yield this.sendClearScreen(session);
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
createBackButton(value) {
|
|
36
|
+
this.backMenuOptions = Array.from(new Set([...this.backMenuOptions, value]));
|
|
37
|
+
const button = {
|
|
38
|
+
value,
|
|
39
|
+
classes: ["is-light"],
|
|
40
|
+
};
|
|
41
|
+
return button;
|
|
42
|
+
}
|
|
43
|
+
sendBackMenu(session, labels) {
|
|
44
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
45
|
+
labels = typeof labels === "string" ? [labels] : labels;
|
|
46
|
+
yield this.sendButtons(session, "", labels.map((value) => this.createBackButton(value)), undefined, {
|
|
47
|
+
ttsEnabled: false,
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
sendMenuButtons(session, buttons) {
|
|
52
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
53
|
+
yield this.sendButtons(session, "", buttons, undefined, {
|
|
54
|
+
ttsEnabled: false,
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
sendAgentMessage(session, message, messageLanguage) {
|
|
59
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
60
|
+
var _a, _b;
|
|
61
|
+
const app = yield this.sermas.getApp();
|
|
62
|
+
if (!app) {
|
|
63
|
+
this.logger.warn(`app is not available`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const filtered = (_b = (_a = app.repository) === null || _a === void 0 ? void 0 : _a.avatars) === null || _b === void 0 ? void 0 : _b.filter((a) => a.name === app.settings.avatar);
|
|
67
|
+
const gender = filtered.length ? filtered[0].gender : undefined;
|
|
68
|
+
yield this.sermas.sendChatMessage(Object.assign(Object.assign({}, session), { text: message, appId: app.appId, actor: "agent", gender, language: messageLanguage, chunkId: this.getChunkId() }));
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
sendButtons(session_1, label_1, list_1) {
|
|
72
|
+
return __awaiter(this, arguments, void 0, function* (session, label, list, metadata = {}, options = {
|
|
73
|
+
clearScreen: false,
|
|
74
|
+
ttsEnabled: true,
|
|
75
|
+
stopSpeech: false,
|
|
76
|
+
}) {
|
|
77
|
+
if (!session) {
|
|
78
|
+
this.logger.warn(`[sendButtons] Session is empty`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const ev = Object.assign(Object.assign({}, session), { metadata,
|
|
82
|
+
options, content: {
|
|
83
|
+
label,
|
|
84
|
+
list: list.map((button) => {
|
|
85
|
+
if (typeof button === "string")
|
|
86
|
+
return { value: button };
|
|
87
|
+
return button;
|
|
88
|
+
}),
|
|
89
|
+
}, contentType: "buttons", chunkId: this.getChunkId() });
|
|
90
|
+
yield this.sermas.sendUiContent(ev);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
sendClearScreen(session) {
|
|
94
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
95
|
+
const ev = Object.assign(Object.assign({}, session), { metadata: {}, options: {
|
|
96
|
+
clearScreen: true,
|
|
97
|
+
stopSpeech: true,
|
|
98
|
+
}, content: {}, contentType: "clear-screen" });
|
|
99
|
+
yield this.sermas.sendUiContent(ev);
|
|
100
|
+
yield sleep(500);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
sendImage(session, data, width, height) {
|
|
104
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
105
|
+
this.logger.info(`Send image sessionId=${session.sessionId} appId=${session.appId}`);
|
|
106
|
+
const ev = Object.assign(Object.assign({}, session), { metadata: {}, options: {
|
|
107
|
+
clearScreen: false,
|
|
108
|
+
stopSpeech: false,
|
|
109
|
+
}, content: { src: data, alt: "no image", width, height }, contentType: "image" });
|
|
110
|
+
yield this.sermas.sendUiContent(ev);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
getChunkId(ts) {
|
|
114
|
+
return ulid(ts ? new Date(ts).getTime() : undefined);
|
|
115
|
+
}
|
|
116
|
+
matchBackMenu(selection) {
|
|
117
|
+
return selection && this.backMenuOptions.indexOf(selection) > -1;
|
|
118
|
+
}
|
|
119
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sermas/sermas-toolkit-node-sdk",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.7",
|
|
4
4
|
"description": "Sermas toolkit node SDK",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"files": [
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
7
9
|
"exports": "./dist/index.js",
|
|
8
10
|
"main": "./dist/index.js",
|
|
9
11
|
"types": "./dist/index.d.ts",
|
|
@@ -18,10 +20,17 @@
|
|
|
18
20
|
"dev": "tsx watch src/index.ts"
|
|
19
21
|
},
|
|
20
22
|
"dependencies": {
|
|
21
|
-
"
|
|
23
|
+
"@sermas/api-client": "^1.0.0-alpha.54",
|
|
24
|
+
"axios": "^1.7.1",
|
|
25
|
+
"eventemitter2": "^6.4.9",
|
|
26
|
+
"openai": "^4.47.2",
|
|
27
|
+
"ulidx": "^2.3.0",
|
|
28
|
+
"uuid": "^9.0.1",
|
|
29
|
+
"winston": "^3.13.0"
|
|
22
30
|
},
|
|
23
31
|
"devDependencies": {
|
|
24
32
|
"@types/node": "^20.12.12",
|
|
33
|
+
"@types/uuid": "^9.0.8",
|
|
25
34
|
"@typescript-eslint/eslint-plugin": "^7.9.0",
|
|
26
35
|
"@typescript-eslint/parser": "^7.9.0",
|
|
27
36
|
"eslint": "^8.57.0",
|