@sermas/sermas-toolkit-node-sdk 1.0.0-alpha.30 → 1.0.0-alpha.31
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/.eslintrc.cjs +32 -0
- package/.github/workflows/npm-publish.yml +22 -0
- package/.prettierrc +0 -0
- package/package.json +1 -4
- package/src/config/defaults.ts +15 -0
- package/src/config/util.ts +35 -0
- package/src/dto/session.ts +7 -0
- package/src/index.ts +14 -0
- package/src/modules/auth.ts +300 -0
- package/src/modules/openai.ts +69 -0
- package/src/modules/sermas.ts +260 -0
- package/src/modules/store.ts +217 -0
- package/src/modules/tools.ts +62 -0
- package/src/modules/ui.ts +204 -0
- package/tsconfig.json +14 -0
- package/tsup.config.ts +14 -0
- package/dist/LICENSE +0 -201
- package/dist/README.md +0 -5
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -148
- package/dist/index.d.ts +0 -148
- package/dist/index.js +0 -2
- package/dist/index.js.map +0 -1
- package/dist/package.json +0 -52
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ButtonDto,
|
|
3
|
+
ButtonsUIContentDto,
|
|
4
|
+
Logger,
|
|
5
|
+
SessionChangedDto,
|
|
6
|
+
SupportedContentTypes,
|
|
7
|
+
UIContentDto,
|
|
8
|
+
UIContentOptionsDto,
|
|
9
|
+
} from "@sermas/api-client";
|
|
10
|
+
import { sleep } from "openai/core";
|
|
11
|
+
import { ulid } from "ulidx";
|
|
12
|
+
import { BaseSessionWrapper } from "../dto/session.js";
|
|
13
|
+
import { SermasApp } from "./sermas.js";
|
|
14
|
+
import { Store } from "./store.js";
|
|
15
|
+
|
|
16
|
+
class UI {
|
|
17
|
+
private sermas: SermasApp;
|
|
18
|
+
private store: Store;
|
|
19
|
+
|
|
20
|
+
private readonly logger: Logger;
|
|
21
|
+
private backMenuOptions: string[] = [];
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
sermas: SermasApp,
|
|
25
|
+
store: Store,
|
|
26
|
+
logger: Logger | undefined = undefined,
|
|
27
|
+
) {
|
|
28
|
+
this.sermas = sermas;
|
|
29
|
+
this.store = store;
|
|
30
|
+
|
|
31
|
+
this.logger = logger || new Logger(`SERMAS SDK UI`);
|
|
32
|
+
|
|
33
|
+
this.sermas.emitter.on("session", this.onSessionChange.bind(this));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// @OnEvent("session")
|
|
37
|
+
async onSessionChange(ev: SessionChangedDto) {
|
|
38
|
+
if (!ev.record.sessionId) return;
|
|
39
|
+
const session = await this.store.getSessionWrapper(ev.record.sessionId);
|
|
40
|
+
switch (ev.operation) {
|
|
41
|
+
case "removed":
|
|
42
|
+
if (!session) return;
|
|
43
|
+
await this.sendClearScreen(session);
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
createBackButton(value: string) {
|
|
49
|
+
this.backMenuOptions = Array.from(
|
|
50
|
+
new Set([...this.backMenuOptions, value]),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const button: ButtonDto = {
|
|
54
|
+
value,
|
|
55
|
+
classes: ["is-light"],
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
return button;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async sendBackMenu(session: BaseSessionWrapper, labels: string | string[]) {
|
|
62
|
+
labels = typeof labels === "string" ? [labels] : labels;
|
|
63
|
+
await this.sendButtons(
|
|
64
|
+
session,
|
|
65
|
+
"",
|
|
66
|
+
labels.map((value) => this.createBackButton(value)),
|
|
67
|
+
undefined,
|
|
68
|
+
{
|
|
69
|
+
ttsEnabled: false,
|
|
70
|
+
},
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async sendMenuButtons(session: BaseSessionWrapper, buttons: ButtonDto[]) {
|
|
75
|
+
await this.sendButtons(session, "", buttons, undefined, {
|
|
76
|
+
ttsEnabled: false,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async sendAgentMessage(
|
|
81
|
+
session: BaseSessionWrapper,
|
|
82
|
+
message: string,
|
|
83
|
+
messageLanguage: string,
|
|
84
|
+
) {
|
|
85
|
+
const app = await this.sermas.getApp();
|
|
86
|
+
|
|
87
|
+
if (!app) {
|
|
88
|
+
this.logger.warn(`app is not available`);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const filtered = app.repository?.avatars?.filter(
|
|
93
|
+
(a) => a.name === app.settings!.avatar,
|
|
94
|
+
);
|
|
95
|
+
const gender = filtered.length ? filtered[0].gender : undefined;
|
|
96
|
+
|
|
97
|
+
await this.sermas.sendChatMessage({
|
|
98
|
+
...session,
|
|
99
|
+
text: message,
|
|
100
|
+
appId: app.appId,
|
|
101
|
+
actor: "agent",
|
|
102
|
+
gender,
|
|
103
|
+
language: messageLanguage,
|
|
104
|
+
chunkId: this.getChunkId(),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async sendButtons(
|
|
109
|
+
session: BaseSessionWrapper,
|
|
110
|
+
label: string,
|
|
111
|
+
list: (string | ButtonDto)[],
|
|
112
|
+
metadata: { [key: string]: unknown } = {},
|
|
113
|
+
options: UIContentOptionsDto = {
|
|
114
|
+
clearScreen: false,
|
|
115
|
+
ttsEnabled: true,
|
|
116
|
+
stopSpeech: false,
|
|
117
|
+
},
|
|
118
|
+
) {
|
|
119
|
+
if (!session) {
|
|
120
|
+
this.logger.warn(`[sendButtons] Session is empty`);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const ev: ButtonsUIContentDto = {
|
|
125
|
+
...session,
|
|
126
|
+
metadata,
|
|
127
|
+
options,
|
|
128
|
+
content: {
|
|
129
|
+
label,
|
|
130
|
+
list: list.map((button) => {
|
|
131
|
+
if (typeof button === "string") return { value: button };
|
|
132
|
+
return button;
|
|
133
|
+
}),
|
|
134
|
+
},
|
|
135
|
+
contentType: "buttons",
|
|
136
|
+
chunkId: this.getChunkId(),
|
|
137
|
+
};
|
|
138
|
+
await this.sermas.sendUiContent(ev);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async sendClearScreen<T extends BaseSessionWrapper>(session: T) {
|
|
142
|
+
const ev: UIContentDto = {
|
|
143
|
+
...session,
|
|
144
|
+
metadata: {},
|
|
145
|
+
options: {
|
|
146
|
+
clearScreen: true,
|
|
147
|
+
stopSpeech: true,
|
|
148
|
+
},
|
|
149
|
+
content: {},
|
|
150
|
+
contentType: "clear-screen",
|
|
151
|
+
};
|
|
152
|
+
await this.sermas.sendUiContent(ev);
|
|
153
|
+
await sleep(500);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async sendImage(
|
|
157
|
+
session: BaseSessionWrapper,
|
|
158
|
+
data: string,
|
|
159
|
+
width: number,
|
|
160
|
+
height: number,
|
|
161
|
+
) {
|
|
162
|
+
this.logger.debug(
|
|
163
|
+
`Send image sessionId=${session.sessionId} appId=${session.appId}`,
|
|
164
|
+
);
|
|
165
|
+
const ev: UIContentDto = {
|
|
166
|
+
...session,
|
|
167
|
+
metadata: {},
|
|
168
|
+
options: {
|
|
169
|
+
clearScreen: false,
|
|
170
|
+
stopSpeech: false,
|
|
171
|
+
},
|
|
172
|
+
content: { src: data, alt: "no image", width, height },
|
|
173
|
+
contentType: "image",
|
|
174
|
+
};
|
|
175
|
+
await this.sermas.sendUiContent(ev);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async sendQrCodeScanner(session: BaseSessionWrapper) {
|
|
179
|
+
this.logger.debug(
|
|
180
|
+
`Send image sessionId=${session.sessionId} appId=${session.appId}`,
|
|
181
|
+
);
|
|
182
|
+
const ev: UIContentDto = {
|
|
183
|
+
...session,
|
|
184
|
+
metadata: {},
|
|
185
|
+
options: {
|
|
186
|
+
clearScreen: false,
|
|
187
|
+
stopSpeech: false,
|
|
188
|
+
},
|
|
189
|
+
content: {},
|
|
190
|
+
contentType: "qrcode-scanner" as SupportedContentTypes,
|
|
191
|
+
};
|
|
192
|
+
await this.sermas.sendUiContent(ev);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
getChunkId(ts?: Date) {
|
|
196
|
+
return ulid(ts ? new Date(ts).getTime() : undefined);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
matchBackMenu(selection: string) {
|
|
200
|
+
return selection && this.backMenuOptions.indexOf(selection) > -1;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export { UI };
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2015",
|
|
4
|
+
"moduleResolution": "NodeNext",
|
|
5
|
+
"module": "NodeNext",
|
|
6
|
+
"esModuleInterop": true,
|
|
7
|
+
"forceConsistentCasingInFileNames": true,
|
|
8
|
+
"declaration": false,
|
|
9
|
+
"strict": true,
|
|
10
|
+
"skipLibCheck": true,
|
|
11
|
+
"outDir": "./dist"
|
|
12
|
+
},
|
|
13
|
+
"include": ["src"]
|
|
14
|
+
}
|
package/tsup.config.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineConfig } from "tsup";
|
|
2
|
+
|
|
3
|
+
export default defineConfig((options) => ({
|
|
4
|
+
entry: ["./src/index.ts"],
|
|
5
|
+
target: "es2020",
|
|
6
|
+
format: ["cjs", "esm"],
|
|
7
|
+
splitting: false,
|
|
8
|
+
sourcemap: true,
|
|
9
|
+
clean: true,
|
|
10
|
+
minify: !options.watch,
|
|
11
|
+
dts: true,
|
|
12
|
+
silent: !options.watch,
|
|
13
|
+
cjsInterop: false,
|
|
14
|
+
}));
|
package/dist/LICENSE
DELETED
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
Apache License
|
|
2
|
-
Version 2.0, January 2004
|
|
3
|
-
http://www.apache.org/licenses/
|
|
4
|
-
|
|
5
|
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
-
|
|
7
|
-
1. Definitions.
|
|
8
|
-
|
|
9
|
-
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
-
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
-
|
|
12
|
-
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
-
the copyright owner that is granting the License.
|
|
14
|
-
|
|
15
|
-
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
-
other entities that control, are controlled by, or are under common
|
|
17
|
-
control with that entity. For the purposes of this definition,
|
|
18
|
-
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
-
direction or management of such entity, whether by contract or
|
|
20
|
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|
|
177
|
-
|
|
178
|
-
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
-
|
|
180
|
-
To apply the Apache License to your work, attach the following
|
|
181
|
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
-
replaced with your own identifying information. (Don't include
|
|
183
|
-
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
-
comment syntax for the file format. We also recommend that a
|
|
185
|
-
file or class name and description of purpose be included on the
|
|
186
|
-
same "printed page" as the copyright notice for easier
|
|
187
|
-
identification within third-party archives.
|
|
188
|
-
|
|
189
|
-
Copyright [yyyy] [name of copyright owner]
|
|
190
|
-
|
|
191
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
-
you may not use this file except in compliance with the License.
|
|
193
|
-
You may obtain a copy of the License at
|
|
194
|
-
|
|
195
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
-
|
|
197
|
-
Unless required by applicable law or agreed to in writing, software
|
|
198
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
-
See the License for the specific language governing permissions and
|
|
201
|
-
limitations under the License.
|
package/dist/README.md
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
# SERMAS toolkit node SDK
|
|
2
|
-
|
|
3
|
-
**The readme is in progress. Please open an issue to report a problem or ask anything**
|
|
4
|
-
|
|
5
|
-
This repository contains the source for the backend tools of the SERMAS Toolkit. It exports some common functionalities needed for the correct implementation of the backend.
|
package/dist/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var J=Object.create;var _=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var Z=(i,e)=>{for(var s in e)_(i,s,{get:e[s],enumerable:!0})},B=(i,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of G(e))!Y.call(i,r)&&r!==s&&_(i,r,{get:()=>e[r],enumerable:!(t=Q(e,r))||t.enumerable});return i};var k=(i,e,s)=>(s=i!=null?J(X(i)):{},B(e||!i||!i.__esModule?_(s,"default",{value:i,enumerable:!0}):s,i)),ee=i=>B(_({},"__esModule",{value:!0}),i);var se={};Z(se,{OpenAIClient:()=>E,SermasApp:()=>C,Store:()=>w,Tools:()=>R,UI:()=>y,getAvatarToken:()=>W,getAvatarTokenWithClientSecret:()=>M});module.exports=ee(se);var I=k(require("axios"),1),P=k(require("https"),1);var c={auth:{PUBLIC_AUTH_URL:"http://172.17.0.1:8080/keycloak",PUBLIC_AUTH_REALM:"sermas-local",PRIVATE_AUTH_CLIENT_ID:"platform",PRIVATE_AUTH_CLIENT_SECRET:"platform",PRIVATE_API_BASE_URL:"http://api:3000/api"},sermas:{SERMAS_BASE_URL:"http://localhost:8080",SERMAS_CLIENT_ID:"sermas-client",SERMAS_CLIENT_SECRET:"s3cr3t",SERMAS_APPID:"sermas"}};var U=require("@sermas/api-client"),v=new P.Agent({rejectUnauthorized:process.env.NODE_ENV!=="development"}),W=async(i=null,e=c.auth)=>{let s=new U.Logger("getAvatarToken"),t={},r=null,n=e.PUBLIC_AUTH_URL||c.auth.PUBLIC_AUTH_URL,g=e.PUBLIC_AUTH_REALM||c.auth.PUBLIC_AUTH_REALM,l=e.PRIVATE_AUTH_CLIENT_ID||c.auth.PRIVATE_AUTH_CLIENT_ID,$=e.PRIVATE_AUTH_CLIENT_SECRET||c.auth.PRIVATE_AUTH_CLIENT_SECRET,h=e.PRIVATE_API_BASE_URL||c.auth.PRIVATE_API_BASE_URL,m=async(o=null)=>{await p();let u=null;return o&&(u=await f(o)),{...u||{},appId:o}},f=async(o,u="avatar")=>{s.debug(`Fetch app token for appId=${o} clientId=${u}`);let d=`${o}-${u}`;if(t[d]=t[d]||null,t[d]){let a=t[d]?.expiresIn;(!a||new Date(a).getTime()-3e4<Date.now())&&(t[d]=null)}if(t[d])return s.debug(`Using cached token for ${d}`),t[d];try{let a=`${h}/platform/token`,T={appId:o,clientId:u};s.debug(`Requesting to ${a}`);let A=await I.default.post(a,T,{httpsAgent:v,headers:{Authorization:`Bearer ${r?.accessToken}`}}),S=A.data.expires_in*1e3;s.debug(`Token for ${o} expires in ${Math.round(S/60/60/1e3)}min`);let{access_token:z,refresh_token:j}=A.data,b={accessToken:z,refreshToken:j,expiresIn:new Date(Date.now()+S)};return t[d]=b,b}catch(a){a instanceof Error&&s.error(`Request failed ${a?.message}`),(0,I.isAxiosError)(a)&&(s.error(a.response?.data),delete t[d])}return null},p=async()=>{let o="___kiosk___";if(t[o]){let a=t[o]?.expiresIn;(!a||new Date(a).getTime()-3e4<Date.now())&&(t[o]=null)}if(t[o])return t[o];s.debug("Load kiosk access token");let u=`${n}/realms/${g}/protocol/openid-connect/token`,d={client_id:l,client_secret:$,grant_type:"client_credentials"};try{s.debug(`Requesting to ${u}`);let a=await I.default.post(u,d,{headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${btoa(l+":"+$)}`}}),T=a.data.expires_in*1e3;s.debug(`kioskToken expires in ${Math.round(T/60/60/1e3)}min`);let{access_token:A,refresh_token:S}=a.data;return r={accessToken:A,refreshToken:S,expiresIn:new Date(Date.now()+T)},t.__kiosk=r,r}catch(a){r=null,a instanceof Error&&s.error(`Request failed ${a.message}`),(0,I.isAxiosError)(a)&&s.error(a.response?.data)}return null};return await m(i)},M=async(i=null,e=c.auth,s="")=>{let t=new U.Logger("getAvatarTokenWithClientSecret"),r={},n=e.PRIVATE_API_BASE_URL||c.auth.PRIVATE_API_BASE_URL,g=e.PRIVATE_AUTH_CLIENT_ID||c.auth.PRIVATE_AUTH_CLIENT_ID,l=async(h,m="avatar",f="")=>{t.debug(`Fetch app token for appId=${h} clientId=${m} clientSecret=${f}`);let p=`${h}-${m}`;if(r[p]=r[p]||null,r[p]){let o=r[p]?.expiresIn;(!o||new Date(o).getTime()-60*1e3<Date.now())&&(r[p]=null)}if(r[p])return t.debug(`Using cached token for ${p}`),r[p];try{let o=`${n}/platform/token/access_token`;t.debug(`Requesting to ${o}`);let u={appId:h,clientId:m,clientSecret:f};t.debug(`get token from ${o}`);let d=await I.default.post(o,u,{httpsAgent:v}),a=d.data.expires_in*1e3;t.debug(`Token for ${h} expires in ${Math.round(a/60/60/1e3)}min`);let{access_token:T,refresh_token:A}=d.data,S={accessToken:T,refreshToken:A,expiresIn:new Date(Date.now()+a)};return r[p]=S,S}catch(o){o instanceof Error&&t.error(`Request failed ${o.message}`),(0,I.isAxiosError)(o)&&(t.error(o.response?.data),delete r[p])}return null};return await(async(h=null,m="",f="")=>{let p=null;return h&&(p=await l(h,m,f)),{...p||{},appId:h}})(i,g,s)};var x=require("@sermas/api-client"),O=k(require("openai"),1),E=class{constructor(e){this.logger=new x.Logger("SERMAS SDK OpenAIClient");e.apiKey||this.logger.warn("No API key provided for OpenAIClient"),this.openAI=new O.default(e)}async chat(e,s){try{return(await this.openAI.chat.completions.create({model:"gpt-3.5-turbo",...typeof e=="string"?{messages:[{role:"user",content:e}]}:e},s)).choices[0].message.content}catch(t){return t instanceof Error&&this.logger.error(`OpenAI request failed: ${t.stack}`),null}}async json(e,s){let t=await this.chat(e,s);if(t!==null)try{return t.startsWith("```json")&&(t=t.replace("```json","").replace("```","")),JSON.parse(t)}catch(r){return r instanceof Error&&this.logger.error(`Failed to parse content: ${r.stack}`),this.logger.debug(`Content: ${t}`),null}}};var V=require("@sermas/api-client");var N=require("@sermas/api-client"),L=require("uuid"),pe=new N.Logger("util");var w=class{constructor(e,s=void 0){this.sessions={};this.locks={};this.sermas=e,this.logger=s||new V.Logger("SERMAS SDK Store"),this.sermas.emitter.on("session",this.onSessionChange.bind(this))}async onSessionChange(e){if(!e.record.sessionId)return;let s=await this.saveSessionWrapper(e);switch(e.operation){case"created":if(!s){this.logger.warn(`Failed to get session for sessionId=${e.record.sessionId}`);return}this.sermas.emitter.emit("session.started",s);break;case"updated":await this.saveSessionWrapper(e);break;case"removed":if(!this.sessions[e.record.sessionId])return;delete this.sessions[e.record.sessionId];break}}async lock(e,s){this.locks[e]=new Promise(async(t,r)=>{try{t(await s())}catch(n){r(n)}});try{return await this.locks[e]}catch(t){return t instanceof Error&&this.logger.error(`lock failure: ${t.stack}`),null}finally{delete this.locks[e]}}async loadSessionWrapper(e){let s=`[${performance.now()}] `;return await this.locks[e.sessionId]&&(this.logger.debug(`${s} Wait lock for sessionId=${e.sessionId}`),await this.locks[e.sessionId],this.logger.debug(`${s} Lock released for sessionId=${e.sessionId}`)),await this.lock(e.sessionId,async()=>{this.logger.debug(`${s} Loading wrapper for sessionId=${e.sessionId}`);let t=await this.sermas.findRecords({appId:"",sessionId:[e.sessionId],userId:void 0});if(t&&t.length)return this.logger.debug(`${s} Wrapper exists for sessionId=${e.sessionId}`),t[0].data;this.logger.debug(`${s} Wrapper not found for sessionId=${e.sessionId}`),this.logger.debug(`${s} Creating new session wrapper store sessionId=${e.sessionId} appId=${e.appId} userId=${e.userId}`);let r=(0,L.v4)(),n={...e,appId:e.appId,sessionId:e.sessionId,userId:e.userId,storageId:r};if(!n.appId||!n.userId){this.logger.debug(`${s} Load session record sessionId=${n.sessionId}`);let l=await this.sermas.readSession(n.sessionId);l?(n.appId||(n.appId=l.appId),n.userId||(n.userId=l.userId)):this.logger.warn(`${s} Failed to load sessionId=${n.sessionId}`)}let g={appId:n.appId,sessionId:n.sessionId,data:n,userId:n.userId||void 0,storageId:r};return await this.sermas.setRecord(g),this.logger.debug(`${s} Saved store storageId=${g.storageId} for sessionId=${g.sessionId} appId=${g.appId} userId=${g.userId}`),n})}async saveSession(e){let s=await this.sermas.getRecord(e.storageId);if(!s){this.logger.warn(`sessionId=${e.sessionId} storageId=${e.storageId} not found, creating new record`);let r=await this.loadSessionWrapper({...e});s=await this.sermas.getRecord(r.storageId)}if(!s)return this.logger.error(`Cannot save sessionId=${e.sessionId}, storage not found`),null;s.data={...e,storageId:s.storageId};let t=await this.sermas.setRecord(s);return this.logger.debug(`Saved record for sessionId=${s.sessionId} storageId=${s.storageId}`),t?.data}async getSessionWrapper(e){if(!e){this.logger.debug("sessionId is empty");return}if(!this.sessions[e]){let s=await this.loadSessionWrapper({sessionId:e});this.logger.debug(`loaded sessionId=${e}`),this.sessions[e]=s}return this.sessions[e]}async saveSessionWrapper(e){if(!e.appId||!e.record.sessionId||this.sessions[e.record.sessionId])return;let s=await this.loadSessionWrapper({userId:e.userId,appId:e.appId,sessionId:e.record.sessionId});return this.sessions[s.sessionId]=s,this.logger.debug(`Added session ${s.sessionId}`),this.sessions[s.sessionId]}};var H=require("@sermas/api-client"),F=require("openai/core"),q=require("ulidx"),y=class{constructor(e,s,t=void 0){this.backMenuOptions=[];this.sermas=e,this.store=s,this.logger=t||new H.Logger("SERMAS SDK UI"),this.sermas.emitter.on("session",this.onSessionChange.bind(this))}async onSessionChange(e){if(!e.record.sessionId)return;let s=await this.store.getSessionWrapper(e.record.sessionId);switch(e.operation){case"removed":if(!s)return;await this.sendClearScreen(s);break}}createBackButton(e){return this.backMenuOptions=Array.from(new Set([...this.backMenuOptions,e])),{value:e,classes:["is-light"]}}async sendBackMenu(e,s){s=typeof s=="string"?[s]:s,await this.sendButtons(e,"",s.map(t=>this.createBackButton(t)),void 0,{ttsEnabled:!1})}async sendMenuButtons(e,s){await this.sendButtons(e,"",s,void 0,{ttsEnabled:!1})}async sendAgentMessage(e,s,t){let r=await this.sermas.getApp();if(!r){this.logger.warn("app is not available");return}let n=r.repository?.avatars?.filter(l=>l.name===r.settings.avatar),g=n.length?n[0].gender:void 0;await this.sermas.sendChatMessage({...e,text:s,appId:r.appId,actor:"agent",gender:g,language:t,chunkId:this.getChunkId()})}async sendButtons(e,s,t,r={},n={clearScreen:!1,ttsEnabled:!0,stopSpeech:!1}){if(!e){this.logger.warn("[sendButtons] Session is empty");return}let g={...e,metadata:r,options:n,content:{label:s,list:t.map(l=>typeof l=="string"?{value:l}:l)},contentType:"buttons",chunkId:this.getChunkId()};await this.sermas.sendUiContent(g)}async sendClearScreen(e){let s={...e,metadata:{},options:{clearScreen:!0,stopSpeech:!0},content:{},contentType:"clear-screen"};await this.sermas.sendUiContent(s),await(0,F.sleep)(500)}async sendImage(e,s,t,r){this.logger.debug(`Send image sessionId=${e.sessionId} appId=${e.appId}`);let n={...e,metadata:{},options:{clearScreen:!1,stopSpeech:!1},content:{src:s,alt:"no image",width:t,height:r},contentType:"image"};await this.sermas.sendUiContent(n)}async sendQrCodeScanner(e){this.logger.debug(`Send image sessionId=${e.sessionId} appId=${e.appId}`);let s={...e,metadata:{},options:{clearScreen:!1,stopSpeech:!1},content:{},contentType:"qrcode-scanner"};await this.sermas.sendUiContent(s)}getChunkId(e){return(0,q.ulid)(e?new Date(e).getTime():void 0)}matchBackMenu(e){return e&&this.backMenuOptions.indexOf(e)>-1}};var R=class{constructor(e){this.sermas=e}async reset(e){await this.sermas.setTools({appId:e.appId,sessionId:e.sessionId,repositoryId:e.sessionId,tools:[]})}async set(e,s){s.sessionId=e.sessionId,s.repositoryId=e.repositoryId||e.sessionId,await this.sermas.setTools(s)}async add(e,s){s.sessionId=e.sessionId,s.repositoryId=e.repositoryId||e.sessionId,await this.sermas.addTools(s)}getSchemaValues(e){let s={};return e.schema&&e.schema.forEach(t=>s[t.parameter]=t.value),s}getSchemaValue(e,s){return this.getSchemaValues(e)[s]}};var K=k(require("eventemitter2"),1),D=require("@sermas/api-client");var C=class{constructor(e,s,t=new D.Logger("SERMAS SDK")){this.app=null;this.subs=[];this.baseUrl=e.SERMAS_BASE_URL||c.sermas.SERMAS_BASE_URL,this.appId=e.SERMAS_APPID||c.sermas.SERMAS_CLIENT_ID,this.clientId=e.SERMAS_CLIENT_ID||c.sermas.SERMAS_CLIENT_SECRET,this.clientSecret=e.SERMAS_CLIENT_SECRET||c.sermas.SERMAS_APPID,this.logger=t,this.emitter=s||new K.default.EventEmitter2,this.client=new D.SermasApiClient({baseURL:this.getBaseUrl(),appId:this.appId,logger:t}),this.initialize()}getBaseUrl(){return this.baseUrl}async initialize(){await this.setupSermasClient(),this.addSub(async()=>await this.client.events.session.onSessionChanged(e=>{this.logger.debug(`session changed ${e.operation.toUpperCase()} sessionId=${e.record.sessionId}`),this.emitter.emit("session",e)})),this.addSub(async()=>await this.client.events.dialogue.onToolTriggered(e=>{this.logger.debug("Tool triggered: "+e.name),this.emitter.emit("tool",e)})),this.addSub(async()=>await this.client.events.ui.onInteraction(e=>{this.emitter.emit("ui.interaction",e)})),this.addSub(async()=>await this.client.events.session.onAgentChanged(e=>{this.logger.debug("Agent changed: "+e.operation),this.emitter.emit("agent.changed",e)})),await this.getApp(),this.logger.debug("Sermas initialization completed")}async setupSermasClient(){this.logger.debug("Initializing sermas client.");try{this.logger.debug("Loading token"),await this.client.loadToken(this.clientId,this.clientSecret)}catch(e){this.logger.error("Failed to load token, retrying"),e instanceof Error&&this.logger.debug(e.stack),setTimeout(()=>this.setupSermasClient(),1e3);return}this.logger.debug("sermas client ready"),this.emitter.emit("sermas.ready")}addSub(e){e().then(s=>{this.subs.push(s)}).catch(s=>{this.logger.error(`Subscribe failed: ${s.stack}`)})}async prompt(e){return await this.client.api.session.prompt({requestBody:e})}async sendChatMessage(e){await this.client.api.dialogue.chatMessage({appId:e.appId,sessionId:e.sessionId,requestBody:e})}async sendUiContent(e){await this.client.events.ui.content(e)}async getApp(){if(this.app)return this.app;this.logger.debug(`Load app ${this.appId}`);try{return this.app=await this.client.api.platform.readApp({appId:this.appId}),this.app}catch(e){return e instanceof Error&&this.logger.error(`Failed to load app ${this.appId}: ${e.stack}`),null}}async updateAppTools(e){await this.client.api.platform.updateAppTools({appId:this.appId,requestBody:e}),this.logger.debug("Updated tools")}async setTools(e){await this.client.api.dialogue.setTools({repositoryId:e.repositoryId,requestBody:e}),this.logger.debug("Updated tools")}async addTools(e){await this.client.api.dialogue.addTools({repositoryId:e.repositoryId,requestBody:e}),this.logger.debug("Add tools")}async readSession(e){try{return await this.client.api.session.readSession({sessionId:e})}catch(s){return s instanceof Error&&this.logger.error(`Failed to readSession: ${s.stack}`),null}}async getRecord(e){try{return await this.client.api.session.getRecord({storageId:e})}catch(s){return s instanceof Error&&s.message.indexOf("Not Found")===-1&&this.logger.error(`Failed to getRecord: ${s.stack}`),null}}async findRecords(e){try{return await this.client.api.session.findRecords({requestBody:e})}catch(s){return s instanceof Error&&this.logger.error(`Failed to findRecords: ${s.stack}`),null}}async setRecord(e){try{return await this.client.api.session.setRecord({requestBody:e})}catch(s){return s instanceof Error&&this.logger.error(`Failed to setRecord: ${s.stack}`),null}}async generateQRCode(e){try{return await this.client.api.ui.generateQrCode({requestBody:{version:5,data:e}})}catch(s){return s instanceof Error&&this.logger.error(`Failed to generate QR code: ${s.stack}`),null}}};0&&(module.exports={OpenAIClient,SermasApp,Store,Tools,UI,getAvatarToken,getAvatarTokenWithClientSecret});
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/modules/auth.ts","../src/config/defaults.ts","../src/modules/openai.ts","../src/modules/store.ts","../src/config/util.ts","../src/modules/ui.ts","../src/modules/tools.ts","../src/modules/sermas.ts"],"sourcesContent":["export {\n getAvatarToken,\n getAvatarTokenWithClientSecret,\n} from \"./modules/auth.js\";\nexport { OpenAIClient } from \"./modules/openai.js\";\nexport { Store } from \"./modules/store.js\";\nexport { UI } from \"./modules/ui.js\";\nexport { Tools } from \"./modules/tools.js\";\nexport { SermasApp } from \"./modules/sermas.js\";\n\nexport type { OpenAIConfig } from \"./modules/openai.js\";\nexport type { SermasConfig } from \"./modules/sermas.js\";\n\nexport { BaseSessionWrapper } from \"./dto/session.js\";\n","import axios, { isAxiosError } from \"axios\";\nimport * as https from \"https\";\nimport { defaults } from \"../config/defaults.js\";\nimport { Logger } from \"@sermas/api-client\";\n\nexport type AuthConfig = {\n PUBLIC_AUTH_URL?: string;\n PUBLIC_AUTH_REALM?: string;\n PRIVATE_AUTH_CLIENT_ID?: string;\n PRIVATE_AUTH_CLIENT_SECRET?: string;\n PRIVATE_API_BASE_URL?: string;\n};\n\ntype TokenResponse = {\n accessToken: string;\n refreshToken: string;\n expiresIn: Date;\n};\n\nconst httpsAgent = new https.Agent({\n rejectUnauthorized: process.env.NODE_ENV !== \"development\",\n});\n\n/**\n * Returns access and refresh tokens for the given appId\n * @param {string} appId null by default\n * @param {AuthConfig} authConfig\n */\nexport const getAvatarToken = async (\n appId: string | null = null,\n authConfig: AuthConfig = defaults.auth,\n) => {\n const logger = new Logger(\"getAvatarToken\");\n const tokens: Record<string, TokenResponse | null> = {};\n let kioskToken: TokenResponse | null = null;\n\n const PUBLIC_AUTH_URL =\n authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;\n const PUBLIC_AUTH_REALM =\n authConfig.PUBLIC_AUTH_REALM || defaults.auth.PUBLIC_AUTH_REALM;\n const PRIVATE_AUTH_CLIENT_ID =\n authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;\n const PRIVATE_AUTH_CLIENT_SECRET =\n authConfig.PRIVATE_AUTH_CLIENT_SECRET ||\n defaults.auth.PRIVATE_AUTH_CLIENT_SECRET;\n const PRIVATE_API_BASE_URL =\n authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;\n\n const getAvatarToken = async (appId: string | null = null) => {\n await getSystemAccessToken();\n\n let appToken: TokenResponse | null = null;\n if (appId) {\n appToken = await getAppAccessToken(appId);\n }\n\n return {\n ...(appToken || {}),\n appId,\n };\n };\n\n const getAppAccessToken = async (\n appId: string,\n clientId = \"avatar\",\n ): Promise<TokenResponse | null> => {\n logger.debug(`Fetch app token for appId=${appId} clientId=${clientId}`);\n\n const cacheKey = `${appId}-${clientId}`;\n\n tokens[cacheKey] = tokens[cacheKey] || null;\n\n if (tokens[cacheKey]) {\n const expiresIn = tokens[cacheKey]?.expiresIn;\n if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {\n tokens[cacheKey] = null;\n }\n }\n\n if (tokens[cacheKey]) {\n logger.debug(`Using cached token for ${cacheKey}`);\n return tokens[cacheKey];\n }\n\n try {\n const url = `${PRIVATE_API_BASE_URL}/platform/token`;\n const data = {\n appId,\n clientId,\n };\n\n logger.debug(`Requesting to ${url}`);\n const res = await axios.post(url, data, {\n httpsAgent,\n headers: {\n Authorization: `Bearer ${kioskToken?.accessToken}`,\n },\n });\n\n // expires 1min before\n const expiresIn = res.data.expires_in * 1000;\n logger.debug(\n `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,\n );\n\n const { access_token, refresh_token } = res.data;\n\n const token = {\n accessToken: access_token,\n refreshToken: refresh_token,\n expiresIn: new Date(Date.now() + expiresIn),\n };\n\n tokens[cacheKey] = token;\n\n return token;\n } catch (e) {\n if (e instanceof Error) logger.error(`Request failed ${e?.message}`);\n if (isAxiosError(e)) {\n logger.error(e.response?.data);\n delete tokens[cacheKey];\n }\n }\n return null;\n };\n\n const getSystemAccessToken = async (): Promise<TokenResponse | null> => {\n const cacheKey = \"___kiosk___\";\n\n if (tokens[cacheKey]) {\n const expiresIn = tokens[cacheKey]?.expiresIn;\n if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {\n tokens[cacheKey] = null;\n }\n }\n\n if (tokens[cacheKey]) return tokens[cacheKey];\n\n logger.debug(`Load kiosk access token`);\n\n const url = `${PUBLIC_AUTH_URL}/realms/${PUBLIC_AUTH_REALM}/protocol/openid-connect/token`;\n const data = {\n client_id: PRIVATE_AUTH_CLIENT_ID,\n client_secret: PRIVATE_AUTH_CLIENT_SECRET,\n grant_type: \"client_credentials\",\n };\n\n try {\n logger.debug(`Requesting to ${url}`);\n const res = await axios.post(url, data, {\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Authorization: `Bearer ${btoa(PRIVATE_AUTH_CLIENT_ID + \":\" + PRIVATE_AUTH_CLIENT_SECRET)}`,\n },\n });\n\n // expires 1min before\n const expiresIn = res.data.expires_in * 1000;\n logger.debug(\n `kioskToken expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,\n );\n\n // const access_token = await getAuthorizationToken(res.data.access_token)\n const { access_token, refresh_token } = res.data;\n\n kioskToken = {\n accessToken: access_token,\n refreshToken: refresh_token,\n expiresIn: new Date(Date.now() + expiresIn),\n };\n\n tokens[\"__kiosk\"] = kioskToken;\n\n return kioskToken;\n } catch (e) {\n kioskToken = null;\n if (e instanceof Error) logger.error(`Request failed ${e.message}`);\n if (isAxiosError(e)) {\n logger.error(e.response?.data);\n }\n }\n return null;\n };\n\n return await getAvatarToken(appId);\n};\n\n/**\n * Returns access and refresh tokens for the given appId\n * @param {string} appId null by default\n * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used\n * @param {string} clientSecret needed for server2server authentication\n */\nexport const getAvatarTokenWithClientSecret = async (\n appId: string | null = null,\n authConfig: AuthConfig = defaults.auth,\n clientSecret: string = \"\",\n) => {\n const logger = new Logger(\"getAvatarTokenWithClientSecret\");\n const tokens: Record<string, TokenResponse | null> = {};\n\n const PRIVATE_API_BASE_URL =\n authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;\n const PRIVATE_AUTH_CLIENT_ID =\n authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;\n\n const getAppAccessTokenWithClientSecret = async (\n appId: string,\n clientId = \"avatar\",\n clientSecret = \"\",\n ): Promise<TokenResponse | null> => {\n logger.debug(\n `Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`,\n );\n\n const cacheKey = `${appId}-${clientId}`;\n\n tokens[cacheKey] = tokens[cacheKey] || null;\n\n if (tokens[cacheKey]) {\n const expiresIn = tokens[cacheKey]?.expiresIn;\n if (\n !expiresIn ||\n new Date(expiresIn).getTime() - 60 * 1000 < Date.now()\n ) {\n tokens[cacheKey] = null;\n }\n }\n\n if (tokens[cacheKey]) {\n logger.debug(`Using cached token for ${cacheKey}`);\n return tokens[cacheKey];\n }\n\n try {\n const url = `${PRIVATE_API_BASE_URL}/platform/token/access_token`;\n logger.debug(`Requesting to ${url}`);\n const data = {\n appId,\n clientId,\n clientSecret,\n };\n logger.debug(`get token from ${url}`);\n const res = await axios.post(url, data, {\n httpsAgent,\n });\n\n // expires 1min before\n const expiresIn = res.data.expires_in * 1000;\n logger.debug(\n `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,\n );\n\n const { access_token, refresh_token } = res.data;\n\n const token = {\n accessToken: access_token,\n refreshToken: refresh_token,\n expiresIn: new Date(Date.now() + expiresIn),\n };\n\n tokens[cacheKey] = token;\n\n return token;\n } catch (e) {\n if (e instanceof Error) logger.error(`Request failed ${e.message}`);\n if (isAxiosError(e)) {\n logger.error(e.response?.data);\n delete tokens[cacheKey];\n }\n }\n return null;\n };\n\n const getAvatarTokenWithClientSecret = async (\n appId: string | null = null,\n clientId: string = \"\",\n clientSecret = \"\",\n ) => {\n let appToken: TokenResponse | null = null;\n if (appId) {\n appToken = await getAppAccessTokenWithClientSecret(\n appId,\n clientId,\n clientSecret,\n );\n }\n\n return {\n ...(appToken || {}),\n appId,\n };\n };\n\n return await getAvatarTokenWithClientSecret(\n appId,\n PRIVATE_AUTH_CLIENT_ID,\n clientSecret,\n );\n};\n","export const defaults = {\n auth: {\n PUBLIC_AUTH_URL: \"http://172.17.0.1:8080/keycloak\",\n PUBLIC_AUTH_REALM: \"sermas-local\",\n PRIVATE_AUTH_CLIENT_ID: \"platform\",\n PRIVATE_AUTH_CLIENT_SECRET: \"platform\",\n PRIVATE_API_BASE_URL: \"http://api:3000/api\",\n },\n sermas: {\n SERMAS_BASE_URL: \"http://localhost:8080\",\n SERMAS_CLIENT_ID: \"sermas-client\",\n SERMAS_CLIENT_SECRET: \"s3cr3t\",\n SERMAS_APPID: \"sermas\",\n },\n} as const;\n","import { Logger } from \"@sermas/api-client\";\nimport OpenAI, { ClientOptions } from \"openai\";\n\nexport type OpenAIConfig = {\n apiKey: string;\n} & ClientOptions;\n\ntype ChatCompletionMessage = {\n messages: Array<OpenAI.Chat.ChatCompletionMessageParam>;\n};\n\n/**\n * Wrapper for OpenAI client to implement sermas functionalities\n */\nclass OpenAIClient {\n private logger = new Logger(`SERMAS SDK OpenAIClient`);\n private openAI: OpenAI;\n\n constructor(openAIConfig: OpenAIConfig) {\n if (!openAIConfig.apiKey)\n this.logger.warn(\"No API key provided for OpenAIClient\");\n this.openAI = new OpenAI(openAIConfig);\n }\n\n async chat(\n body: string | ChatCompletionMessage,\n options?: OpenAI.RequestOptions<unknown>,\n ) {\n try {\n const result: OpenAI.Chat.ChatCompletion =\n await this.openAI.chat.completions.create(\n {\n model: \"gpt-3.5-turbo\",\n ...(typeof body === \"string\"\n ? { messages: [{ role: \"user\", content: body }] }\n : body),\n },\n options,\n );\n return result.choices[0].message.content;\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`OpenAI request failed: ${e.stack}`);\n return null;\n }\n }\n\n async json<T = Record<string, unknown>>(\n body: string | OpenAI.Chat.ChatCompletionCreateParams,\n options?: OpenAI.RequestOptions<unknown>,\n ) {\n let text = await this.chat(body, options);\n if (text === null) return;\n try {\n if (text.startsWith(\"```json\")) {\n text = text.replace(\"```json\", \"\").replace(\"```\", \"\");\n }\n\n return JSON.parse(text) as T;\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to parse content: ${e.stack}`);\n this.logger.debug(`Content: ${text}`);\n return null;\n }\n }\n}\n\nexport { OpenAIClient };\n","import {\n Logger,\n SessionChangedDto,\n SessionStorageRecordDto,\n} from \"@sermas/api-client\";\nimport { SermasApp } from \"./sermas.js\";\nimport { uuidv4 } from \"../config/util.js\";\nimport { BaseSessionWrapper } from \"../dto/session.js\";\n\nclass Store {\n private readonly logger: Logger;\n\n private sermas: SermasApp;\n private sessions: Record<string, unknown> = {};\n\n private locks: { [sessionId: string]: Promise<any> } = {};\n\n constructor(sermas: SermasApp, logger: Logger | undefined = undefined) {\n this.sermas = sermas;\n this.logger = logger || new Logger(`SERMAS SDK Store`);\n\n this.sermas.emitter.on(\"session\", this.onSessionChange.bind(this));\n }\n\n // @OnEvent(\"session\")\n async onSessionChange(ev: SessionChangedDto) {\n if (!ev.record.sessionId) return;\n const session = await this.saveSessionWrapper(ev);\n switch (ev.operation) {\n case \"created\":\n if (!session) {\n this.logger.warn(\n `Failed to get session for sessionId=${ev.record.sessionId}`,\n );\n return;\n }\n this.sermas.emitter.emit(\"session.started\", session);\n break;\n case \"updated\":\n await this.saveSessionWrapper(ev);\n break;\n case \"removed\":\n if (!this.sessions[ev.record.sessionId]) return;\n delete this.sessions[ev.record.sessionId];\n break;\n }\n }\n\n private async lock<T = any>(sessionId: string, fn: () => Promise<any>) {\n // eslint-disable-next-line no-async-promise-executor\n this.locks[sessionId] = new Promise<T>(async (resolve, reject) => {\n try {\n resolve(await fn());\n } catch (e) {\n reject(e);\n }\n });\n try {\n const res = await this.locks[sessionId];\n return res;\n } catch (e) {\n if (e instanceof Error) this.logger.error(`lock failure: ${e.stack}`);\n return null;\n } finally {\n delete this.locks[sessionId];\n }\n }\n\n async loadSessionWrapper<SessionWrapper extends BaseSessionWrapper>(context: {\n sessionId: string;\n appId?: string;\n userId?: string;\n }): Promise<SessionWrapper> {\n const opId = `[${performance.now()}] `;\n if (await this.locks[context.sessionId]) {\n this.logger.debug(`${opId} Wait lock for sessionId=${context.sessionId}`);\n await this.locks[context.sessionId];\n this.logger.debug(\n `${opId} Lock released for sessionId=${context.sessionId}`,\n );\n }\n\n return await this.lock<SessionWrapper>(context.sessionId, async () => {\n this.logger.debug(\n `${opId} Loading wrapper for sessionId=${context.sessionId}`,\n );\n const records = await this.sermas.findRecords({\n appId: \"\",\n sessionId: [context.sessionId],\n userId: undefined,\n });\n\n if (records && records.length) {\n this.logger.debug(\n `${opId} Wrapper exists for sessionId=${context.sessionId}`,\n );\n return records[0].data as SessionWrapper;\n } else {\n this.logger.debug(\n `${opId} Wrapper not found for sessionId=${context.sessionId}`,\n );\n }\n\n this.logger.debug(\n `${opId} Creating new session wrapper store sessionId=${context.sessionId} appId=${context.appId} userId=${context.userId}`,\n );\n\n const storageId = uuidv4();\n const sessionWrapper = {\n ...context,\n appId: context.appId,\n sessionId: context.sessionId,\n userId: context.userId,\n storageId,\n };\n\n if (!sessionWrapper.appId || !sessionWrapper.userId) {\n this.logger.debug(\n `${opId} Load session record sessionId=${sessionWrapper.sessionId}`,\n );\n const session = await this.sermas.readSession(sessionWrapper.sessionId);\n if (session) {\n if (!sessionWrapper.appId) sessionWrapper.appId = session.appId;\n if (!sessionWrapper.userId) sessionWrapper.userId = session.userId;\n } else {\n this.logger.warn(\n `${opId} Failed to load sessionId=${sessionWrapper.sessionId}`,\n );\n }\n }\n\n const record: SessionStorageRecordDto = {\n appId: sessionWrapper.appId!,\n sessionId: sessionWrapper.sessionId,\n data: sessionWrapper,\n userId: sessionWrapper.userId || undefined,\n storageId,\n };\n\n await this.sermas.setRecord(record);\n this.logger.debug(\n `${opId} Saved store storageId=${record.storageId} for sessionId=${record.sessionId} appId=${record.appId} userId=${record.userId}`,\n );\n\n return sessionWrapper;\n });\n }\n\n async saveSession<SessionWrapper extends BaseSessionWrapper>(\n session: SessionWrapper,\n ): Promise<SessionWrapper | null> {\n let record = await this.sermas.getRecord(session.storageId);\n if (!record) {\n this.logger.warn(\n `sessionId=${session.sessionId} storageId=${session.storageId} not found, creating new record`,\n );\n const newSession = await this.loadSessionWrapper({ ...session });\n record = await this.sermas.getRecord(newSession.storageId);\n }\n\n if (!record) {\n this.logger.error(\n `Cannot save sessionId=${session.sessionId}, storage not found`,\n );\n return null;\n }\n\n record.data = {\n ...session,\n storageId: record.storageId,\n } as SessionWrapper;\n\n const res = await this.sermas.setRecord(record);\n this.logger.debug(\n `Saved record for sessionId=${record.sessionId} storageId=${record.storageId}`,\n );\n return res?.data as SessionWrapper;\n }\n\n async getSessionWrapper(\n sessionId: string,\n ): Promise<BaseSessionWrapper | undefined> {\n if (!sessionId) {\n this.logger.debug(`sessionId is empty`);\n return;\n }\n\n if (!this.sessions[sessionId]) {\n const session = await this.loadSessionWrapper({\n sessionId,\n });\n this.logger.debug(`loaded sessionId=${sessionId}`);\n this.sessions[sessionId] = session;\n }\n return this.sessions[sessionId] as BaseSessionWrapper;\n }\n\n async saveSessionWrapper(ev: SessionChangedDto) {\n if (!ev.appId) return;\n if (!ev.record.sessionId) return;\n\n if (this.sessions[ev.record.sessionId]) return;\n\n const wrapper = await this.loadSessionWrapper({\n userId: ev.userId,\n appId: ev.appId,\n sessionId: ev.record.sessionId,\n });\n\n this.sessions[wrapper.sessionId] = wrapper;\n this.logger.debug(`Added session ${wrapper.sessionId}`);\n\n return this.sessions[wrapper.sessionId];\n }\n}\n\nexport { Store };\n","import * as fs from \"fs/promises\";\nimport { Logger } from \"@sermas/api-client\";\n\nexport { v4 as uuidv4 } from \"uuid\";\n\nconst logger = new Logger(\"util\");\n\nexport const saveJSON = (filename: string, dataset: Record<string, unknown>) =>\n fs.writeFile(filename, JSON.stringify(dataset, null, 2));\n\nexport const loadJSON = async <T = Record<string, unknown>>(\n filename: string,\n) => {\n try {\n const raw = await loadFile(filename);\n if (raw === null) return null;\n return JSON.parse(raw) as T;\n } catch (e: unknown) {\n if (e instanceof Error) logger.error(`Failed to load dataset: ${e.stack}`);\n return null;\n }\n};\n\nexport const loadFile = async (filename: string) => {\n try {\n const raw = await fs.readFile(filename);\n return raw.toString();\n } catch (e: unknown) {\n if (e instanceof Error) logger.error(`Failed to load dataset: ${e.stack}`);\n return null;\n }\n};\n\nexport const saveFile = (filename: string, dataset: string | Buffer) =>\n fs.writeFile(filename, dataset);\n","import {\n ButtonDto,\n ButtonsUIContentDto,\n Logger,\n SessionChangedDto,\n SupportedContentTypes,\n UIContentDto,\n UIContentOptionsDto,\n} from \"@sermas/api-client\";\nimport { sleep } from \"openai/core\";\nimport { ulid } from \"ulidx\";\nimport { BaseSessionWrapper } from \"../dto/session.js\";\nimport { SermasApp } from \"./sermas.js\";\nimport { Store } from \"./store.js\";\n\nclass UI {\n private sermas: SermasApp;\n private store: Store;\n\n private readonly logger: Logger;\n private backMenuOptions: string[] = [];\n\n constructor(\n sermas: SermasApp,\n store: Store,\n logger: Logger | undefined = undefined,\n ) {\n this.sermas = sermas;\n this.store = store;\n\n this.logger = logger || new Logger(`SERMAS SDK UI`);\n\n this.sermas.emitter.on(\"session\", this.onSessionChange.bind(this));\n }\n\n // @OnEvent(\"session\")\n async onSessionChange(ev: SessionChangedDto) {\n if (!ev.record.sessionId) return;\n const session = await this.store.getSessionWrapper(ev.record.sessionId);\n switch (ev.operation) {\n case \"removed\":\n if (!session) return;\n await this.sendClearScreen(session);\n break;\n }\n }\n\n createBackButton(value: string) {\n this.backMenuOptions = Array.from(\n new Set([...this.backMenuOptions, value]),\n );\n\n const button: ButtonDto = {\n value,\n classes: [\"is-light\"],\n };\n\n return button;\n }\n\n async sendBackMenu(session: BaseSessionWrapper, labels: string | string[]) {\n labels = typeof labels === \"string\" ? [labels] : labels;\n await this.sendButtons(\n session,\n \"\",\n labels.map((value) => this.createBackButton(value)),\n undefined,\n {\n ttsEnabled: false,\n },\n );\n }\n\n async sendMenuButtons(session: BaseSessionWrapper, buttons: ButtonDto[]) {\n await this.sendButtons(session, \"\", buttons, undefined, {\n ttsEnabled: false,\n });\n }\n\n async sendAgentMessage(\n session: BaseSessionWrapper,\n message: string,\n messageLanguage: string,\n ) {\n const app = await this.sermas.getApp();\n\n if (!app) {\n this.logger.warn(`app is not available`);\n return;\n }\n\n const filtered = app.repository?.avatars?.filter(\n (a) => a.name === app.settings!.avatar,\n );\n const gender = filtered.length ? filtered[0].gender : undefined;\n\n await this.sermas.sendChatMessage({\n ...session,\n text: message,\n appId: app.appId,\n actor: \"agent\",\n gender,\n language: messageLanguage,\n chunkId: this.getChunkId(),\n });\n }\n\n async sendButtons(\n session: BaseSessionWrapper,\n label: string,\n list: (string | ButtonDto)[],\n metadata: { [key: string]: unknown } = {},\n options: UIContentOptionsDto = {\n clearScreen: false,\n ttsEnabled: true,\n stopSpeech: false,\n },\n ) {\n if (!session) {\n this.logger.warn(`[sendButtons] Session is empty`);\n return;\n }\n\n const ev: ButtonsUIContentDto = {\n ...session,\n metadata,\n options,\n content: {\n label,\n list: list.map((button) => {\n if (typeof button === \"string\") return { value: button };\n return button;\n }),\n },\n contentType: \"buttons\",\n chunkId: this.getChunkId(),\n };\n await this.sermas.sendUiContent(ev);\n }\n\n async sendClearScreen<T extends BaseSessionWrapper>(session: T) {\n const ev: UIContentDto = {\n ...session,\n metadata: {},\n options: {\n clearScreen: true,\n stopSpeech: true,\n },\n content: {},\n contentType: \"clear-screen\",\n };\n await this.sermas.sendUiContent(ev);\n await sleep(500);\n }\n\n async sendImage(\n session: BaseSessionWrapper,\n data: string,\n width: number,\n height: number,\n ) {\n this.logger.debug(\n `Send image sessionId=${session.sessionId} appId=${session.appId}`,\n );\n const ev: UIContentDto = {\n ...session,\n metadata: {},\n options: {\n clearScreen: false,\n stopSpeech: false,\n },\n content: { src: data, alt: \"no image\", width, height },\n contentType: \"image\",\n };\n await this.sermas.sendUiContent(ev);\n }\n\n async sendQrCodeScanner(session: BaseSessionWrapper) {\n this.logger.debug(\n `Send image sessionId=${session.sessionId} appId=${session.appId}`,\n );\n const ev: UIContentDto = {\n ...session,\n metadata: {},\n options: {\n clearScreen: false,\n stopSpeech: false,\n },\n content: {},\n contentType: \"qrcode-scanner\" as SupportedContentTypes,\n };\n await this.sermas.sendUiContent(ev);\n }\n\n getChunkId(ts?: Date) {\n return ulid(ts ? new Date(ts).getTime() : undefined);\n }\n\n matchBackMenu(selection: string) {\n return selection && this.backMenuOptions.indexOf(selection) > -1;\n }\n}\n\nexport { UI };\n","import { AppToolsDTO, DialogueToolsRepositoryDto } from \"@sermas/api-client\";\nimport { BaseSessionWrapper } from \"../dto/session.js\";\nimport { SermasApp } from \"./sermas.js\";\n\ntype ToolsSchemaValues = string | number | boolean | undefined;\ntype ToolsSchemaParameters = Record<string, ToolsSchemaValues>;\n\nclass Tools {\n private sermas: SermasApp;\n\n constructor(sermasApp: SermasApp) {\n this.sermas = sermasApp;\n }\n\n async reset(session: BaseSessionWrapper) {\n await this.sermas.setTools({\n appId: session.appId,\n sessionId: session.sessionId,\n repositoryId: session.sessionId,\n tools: [],\n });\n }\n\n async set(\n session: BaseSessionWrapper,\n repository: DialogueToolsRepositoryDto,\n ) {\n repository.sessionId = session.sessionId;\n repository.repositoryId =\n (session.repositoryId as string) || session.sessionId;\n await this.sermas.setTools(repository);\n }\n\n async add(\n session: BaseSessionWrapper,\n repository: DialogueToolsRepositoryDto,\n ) {\n repository.sessionId = session.sessionId;\n repository.repositoryId =\n (session.repositoryId as string) || session.sessionId;\n await this.sermas.addTools(repository);\n }\n\n getSchemaValues<T extends ToolsSchemaParameters = ToolsSchemaParameters>(\n tool: AppToolsDTO,\n ): T {\n const values: ToolsSchemaParameters = {};\n\n if (!tool.schema) return values as T;\n\n tool.schema.forEach((schema) => (values[schema.parameter] = schema.value));\n\n return values as T;\n }\n\n getSchemaValue(tool: AppToolsDTO, parameterName: string) {\n const values = this.getSchemaValues(tool);\n return values[parameterName];\n }\n}\n\nexport { Tools };\n","import ee2 from \"eventemitter2\";\nimport {\n AgentChangedDto,\n AgentEvaluatePromptDto,\n AppToolsDTO,\n DialogueMessageDto,\n DialogueToolTriggeredEventDto,\n DialogueToolsRepositoryDto,\n PlatformAppDto,\n SermasApiClient,\n SessionChangedDto,\n SessionDto,\n SessionStorageRecordDto,\n SessionStorageSearchDto,\n UIContentDto,\n UIInteractionEventDto,\n Logger,\n} from \"@sermas/api-client\";\nimport { defaults } from \"../config/defaults.js\";\n\nexport type SermasConfig = {\n SERMAS_BASE_URL: string;\n SERMAS_CLIENT_ID: string;\n SERMAS_CLIENT_SECRET: string;\n SERMAS_APPID: string;\n};\n\nclass SermasApp {\n private logger: Logger;\n private baseUrl: string;\n\n private app: PlatformAppDto | null = null;\n public client: SermasApiClient;\n\n private clientId: string;\n private clientSecret: string;\n private appId: string;\n\n public emitter: ee2.EventEmitter2;\n public subs: (() => void)[] = [];\n\n constructor(\n sermasConfig: SermasConfig,\n emitter: ee2.EventEmitter2,\n logger: Logger = new Logger(\"SERMAS SDK\"),\n ) {\n this.baseUrl =\n sermasConfig.SERMAS_BASE_URL || defaults.sermas.SERMAS_BASE_URL;\n this.appId = sermasConfig.SERMAS_APPID || defaults.sermas.SERMAS_CLIENT_ID;\n this.clientId =\n sermasConfig.SERMAS_CLIENT_ID || defaults.sermas.SERMAS_CLIENT_SECRET;\n this.clientSecret =\n sermasConfig.SERMAS_CLIENT_SECRET || defaults.sermas.SERMAS_APPID;\n\n this.logger = logger;\n\n this.emitter = emitter || new ee2.EventEmitter2();\n\n this.client = new SermasApiClient({\n baseURL: this.getBaseUrl(),\n appId: this.appId,\n logger,\n });\n this.initialize();\n }\n\n getBaseUrl() {\n return this.baseUrl;\n }\n\n async initialize() {\n // return await this.getClientCredentials();\n\n await this.setupSermasClient();\n\n this.addSub(\n async () =>\n await this.client.events.session.onSessionChanged(\n (ev: SessionChangedDto) => {\n this.logger.debug(\n `session changed ${ev.operation.toUpperCase()} sessionId=${ev.record.sessionId}`,\n );\n this.emitter.emit(`session`, ev);\n },\n ),\n );\n\n this.addSub(\n async () =>\n await this.client.events.dialogue.onToolTriggered(\n (event: DialogueToolTriggeredEventDto) => {\n this.logger.debug(\"Tool triggered: \" + event.name);\n this.emitter.emit(`tool`, event);\n },\n ),\n );\n\n this.addSub(\n async () =>\n await this.client.events.ui.onInteraction(\n (event: UIInteractionEventDto) => {\n // this.logger.debug('UI interaction: ' + event.interaction);\n this.emitter.emit(`ui.interaction`, event);\n },\n ),\n );\n\n this.addSub(\n async () =>\n await this.client.events.session.onAgentChanged(\n (event: AgentChangedDto) => {\n this.logger.debug(\"Agent changed: \" + event.operation);\n this.emitter.emit(`agent.changed`, event);\n },\n ),\n );\n\n await this.getApp();\n this.logger.debug(\"Sermas initialization completed\");\n }\n\n private async setupSermasClient() {\n this.logger.debug(\"Initializing sermas client.\");\n\n try {\n this.logger.debug(`Loading token`);\n await this.client.loadToken(this.clientId, this.clientSecret);\n } catch (e: unknown) {\n this.logger.error(`Failed to load token, retrying`);\n if (e instanceof Error) this.logger.debug(e.stack);\n setTimeout(() => this.setupSermasClient(), 1000);\n return;\n }\n\n this.logger.debug(`sermas client ready`);\n this.emitter.emit(\"sermas.ready\");\n }\n\n addSub(sub: () => Promise<() => void>) {\n sub()\n .then((fn) => {\n this.subs.push(fn);\n })\n .catch((e) => {\n this.logger.error(`Subscribe failed: ${e.stack}`);\n });\n }\n async prompt(prompt: AgentEvaluatePromptDto) {\n return await this.client.api.session.prompt({\n requestBody: prompt,\n });\n }\n\n async sendChatMessage(ev: DialogueMessageDto) {\n await this.client.api.dialogue.chatMessage({\n appId: ev.appId,\n sessionId: ev.sessionId!,\n requestBody: ev,\n });\n }\n\n async sendUiContent(ev: UIContentDto) {\n await this.client.events.ui.content(ev);\n }\n\n async getApp() {\n if (this.app) return this.app;\n this.logger.debug(`Load app ${this.appId}`);\n try {\n this.app = await this.client.api.platform.readApp({ appId: this.appId });\n return this.app;\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to load app ${this.appId}: ${e.stack}`);\n return null;\n }\n }\n\n async updateAppTools(tools: AppToolsDTO[]) {\n await this.client.api.platform.updateAppTools({\n appId: this.appId,\n requestBody: tools,\n });\n this.logger.debug(\"Updated tools\");\n }\n\n async setTools(repository: DialogueToolsRepositoryDto) {\n await this.client.api.dialogue.setTools({\n repositoryId: repository.repositoryId!,\n requestBody: repository,\n });\n this.logger.debug(\"Updated tools\");\n }\n\n async addTools(repository: DialogueToolsRepositoryDto) {\n await this.client.api.dialogue.addTools({\n repositoryId: repository.repositoryId!,\n requestBody: repository,\n });\n this.logger.debug(\"Add tools\");\n }\n\n async readSession(sessionId: string): Promise<SessionDto | null> {\n try {\n return await this.client.api.session.readSession({ sessionId });\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to readSession: ${e.stack}`);\n return null;\n }\n }\n\n async getRecord(storageId: string) {\n try {\n return await this.client.api.session.getRecord({ storageId });\n } catch (e: unknown) {\n if (e instanceof Error && e.message.indexOf(\"Not Found\") === -1)\n this.logger.error(`Failed to getRecord: ${e.stack}`);\n return null;\n }\n }\n\n async findRecords(query: SessionStorageSearchDto) {\n try {\n return await this.client.api.session.findRecords({\n requestBody: query,\n });\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to findRecords: ${e.stack}`);\n return null;\n }\n }\n\n async setRecord(storage: SessionStorageRecordDto) {\n try {\n return await this.client.api.session.setRecord({\n requestBody: storage,\n });\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to setRecord: ${e.stack}`);\n return null;\n }\n }\n\n async generateQRCode(data: string) {\n try {\n return await this.client.api.ui.generateQrCode({\n requestBody: { version: 5, data },\n });\n } catch (e: unknown) {\n if (e instanceof Error)\n this.logger.error(`Failed to generate QR code: ${e.stack}`);\n return null;\n }\n }\n}\n\nexport { SermasApp };\n"],"mappings":"2jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,kBAAAE,EAAA,cAAAC,EAAA,UAAAC,EAAA,UAAAC,EAAA,OAAAC,EAAA,mBAAAC,EAAA,mCAAAC,IAAA,eAAAC,GAAAT,ICAA,IAAAU,EAAoC,sBACpCC,EAAuB,sBCDhB,IAAMC,EAAW,CACtB,KAAM,CACJ,gBAAiB,kCACjB,kBAAmB,eACnB,uBAAwB,WACxB,2BAA4B,WAC5B,qBAAsB,qBACxB,EACA,OAAQ,CACN,gBAAiB,wBACjB,iBAAkB,gBAClB,qBAAsB,SACtB,aAAc,QAChB,CACF,EDXA,IAAAC,EAAuB,8BAgBjBC,EAAa,IAAU,QAAM,CACjC,mBAAoB,QAAQ,IAAI,WAAa,aAC/C,CAAC,EAOYC,EAAiB,MAC5BC,EAAuB,KACvBC,EAAyBC,EAAS,OAC/B,CACH,IAAMC,EAAS,IAAI,SAAO,gBAAgB,EACpCC,EAA+C,CAAC,EAClDC,EAAmC,KAEjCC,EACJL,EAAW,iBAAmBC,EAAS,KAAK,gBACxCK,EACJN,EAAW,mBAAqBC,EAAS,KAAK,kBAC1CM,EACJP,EAAW,wBAA0BC,EAAS,KAAK,uBAC/CO,EACJR,EAAW,4BACXC,EAAS,KAAK,2BACVQ,EACJT,EAAW,sBAAwBC,EAAS,KAAK,qBAE7CH,EAAiB,MAAOC,EAAuB,OAAS,CAC5D,MAAMW,EAAqB,EAE3B,IAAIC,EAAiC,KACrC,OAAIZ,IACFY,EAAW,MAAMC,EAAkBb,CAAK,GAGnC,CACL,GAAIY,GAAY,CAAC,EACjB,MAAAZ,CACF,CACF,EAEMa,EAAoB,MACxB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IAAI,QAAQ,UAAU,CAAE,UAAAA,CAAU,CAAC,CAC9D,OAASL,EAAY,CACnB,OAAIA,aAAa,OAASA,EAAE,QAAQ,QAAQ,WAAW,IAAM,IAC3D,KAAK,OAAO,MAAM,wBAAwBA,EAAE,KAAK,EAAE,EAC9C,IACT,CACF,CAEA,MAAM,YAAYM,EAAgC,CAChD,GAAI,CACF,OAAO,MAAM,KAAK,OAAO,IAAI,QAAQ,YAAY,CAC/C,YAAaA,CACf,CAAC,CACH,OAASN,EAAY,CACnB,OAAIA,aAAa,OACf,KAAK,OAAO,MAAM,0BAA0BA,EAAE,KAAK,EAAE,EAChD,IACT,CACF,CAEA,MAAM,UAAUO,EAAkC,CAChD,GAAI,CACF,OAAO,MAAM,KAAK,OAAO,IAAI,QAAQ,UAAU,CAC7C,YAAaA,CACf,CAAC,CACH,OAASP,EAAY,CACnB,OAAIA,aAAa,OACf,KAAK,OAAO,MAAM,wBAAwBA,EAAE,KAAK,EAAE,EAC9C,IACT,CACF,CAEA,MAAM,eAAeQ,EAAc,CACjC,GAAI,CACF,OAAO,MAAM,KAAK,OAAO,IAAI,GAAG,eAAe,CAC7C,YAAa,CAAE,QAAS,EAAG,KAAAA,CAAK,CAClC,CAAC,CACH,OAASR,EAAY,CACnB,OAAIA,aAAa,OACf,KAAK,OAAO,MAAM,+BAA+BA,EAAE,KAAK,EAAE,EACrD,IACT,CACF,CACF","names":["src_exports","__export","OpenAIClient","SermasApp","Store","Tools","UI","getAvatarToken","getAvatarTokenWithClientSecret","__toCommonJS","import_axios","https","defaults","import_api_client","httpsAgent","getAvatarToken","appId","authConfig","defaults","logger","tokens","kioskToken","PUBLIC_AUTH_URL","PUBLIC_AUTH_REALM","PRIVATE_AUTH_CLIENT_ID","PRIVATE_AUTH_CLIENT_SECRET","PRIVATE_API_BASE_URL","getSystemAccessToken","appToken","getAppAccessToken","clientId","cacheKey","expiresIn","url","data","res","axios","access_token","refresh_token","token","e","getAvatarTokenWithClientSecret","clientSecret","getAppAccessTokenWithClientSecret","import_api_client","import_openai","OpenAIClient","openAIConfig","OpenAI","body","options","e","text","import_api_client","import_api_client","import_uuid","logger","Store","sermas","logger","ev","session","sessionId","fn","resolve","reject","e","context","opId","records","storageId","sessionWrapper","record","newSession","res","wrapper","import_api_client","import_core","import_ulidx","UI","sermas","store","logger","ev","session","value","labels","buttons","message","messageLanguage","app","filtered","a","gender","label","list","metadata","options","button","data","width","height","ts","selection","Tools","sermasApp","session","repository","tool","values","schema","parameterName","import_eventemitter2","import_api_client","SermasApp","sermasConfig","emitter","logger","defaults","ee2","ev","event","sub","fn","e","prompt","tools","repository","sessionId","storageId","query","storage","data"]}
|