-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatSurfaceService.ts
More file actions
312 lines (275 loc) · 8.98 KB
/
chatSurfaceService.ts
File metadata and controls
312 lines (275 loc) · 8.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import type {
AdminUser,
ChatSurfaceAdapter,
ChatSurfaceEventSink,
ChatSurfaceIncomingMessage,
IAdminForth,
} from "adminforth";
import { Filters, logger } from "adminforth";
import type { AgentEventEmitter } from "./agentEvents.js";
import type {
HandleTurnInput,
RunAndPersistAgentResponseInput,
RunAndPersistAgentResponseResult,
} from "./agentTurnService.js";
import { getErrorMessage, isAbortError } from "./errors.js";
import type { AgentSessionStore } from "./sessionStore.js";
import { sanitizeSpeechText } from "./sanitizeSpeechText.js";
import type { PluginOptions } from "./types.js";
type ChatSurfaceIncomingMessageWithAudio = ChatSurfaceIncomingMessage & {
audio?: {
buffer: Buffer;
filename: string;
mimeType: string;
};
};
type ChatSurfaceEventSinkWithAudio = ChatSurfaceEventSink & {
emit(event: Parameters<ChatSurfaceEventSink["emit"]>[0] | {
type: "audio";
audio: Buffer;
filename: string;
mimeType: string;
}): void | Promise<void>;
};
export class ChatSurfaceService {
constructor(
private getAdminforth: () => IAdminForth,
private options: PluginOptions,
private sessionStore: AgentSessionStore,
private handleTurn: (input: HandleTurnInput) => Promise<unknown>,
private runAndPersistAgentResponse: (
input: RunAndPersistAgentResponseInput,
) => Promise<RunAndPersistAgentResponseResult>,
) {}
private createEventEmitter(sink: ChatSurfaceEventSink): AgentEventEmitter {
return async (event) => {
if (event.type === "text-delta") {
await sink.emit({
type: "text_delta",
delta: event.delta,
});
return;
}
if (event.type === "response") {
await sink.emit({
type: "done",
text: event.text,
});
return;
}
if (event.type === "error") {
await sink.emit({
type: "error",
message: event.error,
});
}
};
}
private async handleLink(
incoming: ChatSurfaceIncomingMessage,
sink: ChatSurfaceEventSink,
) {
if (incoming.metadata?.isStartCommand !== true) {
return false;
}
await sink.emit({
type: "done",
text: `Open AdminForth and connect your ${incoming.surface} account from Connected Accounts settings.`,
});
return true;
}
private async handleAudioMessage(
incoming: ChatSurfaceIncomingMessageWithAudio,
sink: ChatSurfaceEventSinkWithAudio,
adminUser: AdminUser,
) {
const audioAdapter = this.options.audioAdapter;
if (!audioAdapter) {
await sink.emit({
type: "error",
message: "Audio adapter is not configured for AdminForth Agent.",
});
return;
}
let transcription;
try {
transcription = await audioAdapter.transcribe({
buffer: incoming.audio!.buffer,
filename: incoming.audio!.filename,
mimeType: incoming.audio!.mimeType,
language: "auto",
});
} catch (error) {
if (isAbortError(error)) {
logger.info(`Agent ${incoming.surface} surface speech transcription aborted`);
return;
}
logger.error(`Agent ${incoming.surface} surface speech transcription failed:\n${getErrorMessage(error)}`);
await sink.emit({
type: "error",
message: "Speech transcription failed. Check server logs for details.",
});
return;
}
if (!transcription.text) {
await sink.emit({
type: "error",
message: "Speech transcription is empty",
});
return;
}
const agentResponse = await this.handleAgentSurfaceResponse(
incoming,
sink,
adminUser,
transcription.text,
{ emitDone: false },
);
if (!agentResponse || agentResponse.aborted || agentResponse.failed) {
return;
}
await sink.emit({
type: "done",
text: agentResponse.text,
});
try {
const speech = await audioAdapter.synthesize({
text: sanitizeSpeechText(agentResponse.text),
stream: false,
format: "opus",
});
await sink.emit({
type: "audio",
audio: speech.audio,
filename: "agent-response.ogg",
mimeType: speech.mimeType,
});
} catch (error) {
if (isAbortError(error)) {
logger.info(`Agent ${incoming.surface} surface speech synthesis aborted`);
return;
}
logger.error(`Agent ${incoming.surface} surface speech synthesis failed:\n${getErrorMessage(error)}`);
await sink.emit({
type: "error",
message: getErrorMessage(error),
});
}
}
private async handleAgentSurfaceResponse(
incoming: ChatSurfaceIncomingMessage,
sink: ChatSurfaceEventSink,
adminUser: AdminUser,
prompt: string,
options?: { emitDone?: boolean },
) {
const emitDone = options?.emitDone ?? true;
const sessionId = await this.sessionStore.getOrCreateChatSurfaceSession(
{ ...incoming, prompt },
adminUser,
);
if (emitDone) {
await this.handleTurn({
prompt,
sessionId,
modeName: incoming.modeName,
userTimeZone: incoming.userTimeZone ?? "UTC",
adminUser,
emit: this.createEventEmitter(sink),
failureLogMessage: `Agent ${incoming.surface} surface response failed`,
abortLogMessage: `Agent ${incoming.surface} surface response aborted`,
});
return null;
}
const agentResponse = await this.runAndPersistAgentResponse({
prompt,
sessionId,
modeName: incoming.modeName,
userTimeZone: incoming.userTimeZone ?? "UTC",
adminUser,
emit: this.createEventEmitter(sink),
failureLogMessage: `Agent ${incoming.surface} surface response failed`,
abortLogMessage: `Agent ${incoming.surface} surface response aborted`,
});
if (agentResponse.failed) {
await sink.emit({
type: "error",
message: agentResponse.text,
});
}
return agentResponse;
}
private async getAdminUserRecordForChatSurface(
adapter: ChatSurfaceAdapter,
incoming: ChatSurfaceIncomingMessage,
) {
const adminforth = this.getAdminforth();
const authResourceId = adminforth.config.auth!.usersResourceId!;
const externalIdentityResource = this.options.chatExternalIdentityResource;
if (!externalIdentityResource) {
return null;
}
const surfaceIdentityConfig = externalIdentityResource.surfaces[adapter.name];
if (!surfaceIdentityConfig) {
return null;
}
const providerField = externalIdentityResource.providerField ?? 'provider';
const subjectField = externalIdentityResource.subjectField ?? 'subject';
const adminUserIdField = externalIdentityResource.adminUserIdField ?? 'adminUserId';
const externalUserIdField = externalIdentityResource.externalUserIdField ?? 'externalUserId';
const identityFilters = [
Filters.EQ(providerField, surfaceIdentityConfig.provider),
Filters.EQ(externalUserIdField, incoming.externalUserId),
];
const identities = await adminforth.resource(externalIdentityResource.resourceId).list(identityFilters);
const identity = identities.find((identity) => {
if (String(identity[externalUserIdField]) === incoming.externalUserId) {
return true;
}
if (String(identity[subjectField]) === incoming.externalUserId) {
return true;
}
return false;
});
if (!identity) {
return null;
}
const authResource = adminforth.config.resources.find((resource) => resource.resourceId === authResourceId)!;
const primaryKeyField = authResource.columns.find((column) => column.primaryKey)!.name!;
return adminforth.resource(authResourceId).get([
Filters.EQ(primaryKeyField, identity[adminUserIdField]),
]);
}
async handleMessage(
adapter: ChatSurfaceAdapter,
incoming: ChatSurfaceIncomingMessage,
sink: ChatSurfaceEventSink,
) {
if (await this.handleLink(incoming, sink)) {
return;
}
const adminforth = this.getAdminforth();
const authResourceId = adminforth.config.auth!.usersResourceId!;
const authResource = adminforth.config.resources.find((resource) => resource.resourceId === authResourceId)!;
const primaryKeyField = authResource.columns.find((column) => column.primaryKey)!.name!;
const adminUserRecord = await this.getAdminUserRecordForChatSurface(adapter, incoming);
if (!adminUserRecord) {
await sink.emit({
type: "error",
message: "This chat account is not authorized to use AdminForth Agent.",
});
return;
}
const adminUser = {
pk: adminUserRecord[primaryKeyField],
username: adminUserRecord[adminforth.config.auth!.usernameField],
dbUser: adminUserRecord,
};
const incomingWithAudio = incoming as ChatSurfaceIncomingMessageWithAudio;
if (incomingWithAudio.audio) {
await this.handleAudioMessage(incomingWithAudio, sink as ChatSurfaceEventSinkWithAudio, adminUser);
return;
}
await this.handleAgentSurfaceResponse(incoming, sink, adminUser, incoming.prompt);
}
}