-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatSurfaceService.ts
More file actions
370 lines (322 loc) · 10.6 KB
/
chatSurfaceService.ts
File metadata and controls
370 lines (322 loc) · 10.6 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import type {
AdminUser,
ChatSurfaceAdapter,
ChatSurfaceEventSink,
ChatSurfaceIncomingMessage,
IAdminForth,
} from "adminforth";
import { Filters, logger } from "adminforth";
import { randomUUID } from "crypto";
import type { AgentEventEmitter } from "./agentEvents.js";
import type {
HandleTurnInput,
RunAndPersistAgentResponseInput,
RunAndPersistAgentResponseResult,
} from "./agentTurnService.js";
import type { PluginOptions } from "./types.js";
import type { AgentSessionStore } from "./sessionStore.js";
import { getErrorMessage, isAbortError } from "./errors.js";
import { sanitizeSpeechText } from "./sanitizeSpeechText.js";
type ChatSurfaceConnectAction = {
type: "url";
label: string;
url: string;
};
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 type ChatSurfaceAdapterWithConnectAction = ChatSurfaceAdapter & {
createConnectAction?(input: {
token: string;
}): ChatSurfaceConnectAction | Promise<ChatSurfaceConnectAction>;
};
type ChatSurfaceLinkTokenPayload = {
surface: string;
adminUserId: AdminUser["pk"];
expiresAt: number;
};
const DEFAULT_ADMIN_USER_EXTERNAL_USER_ID_FIELD = "externalUserId";
const CHAT_SURFACE_LINK_TOKEN_TTL_MS = 60 * 1000;
export class ChatSurfaceService {
private linkTokens = new Map<string, ChatSurfaceLinkTokenPayload>();
constructor(
private getAdminforth: () => IAdminForth,
private options: PluginOptions,
private sessionStore: AgentSessionStore,
private handleTurn: (input: HandleTurnInput) => Promise<unknown>,
private runAndPersistAgentResponse: (
input: RunAndPersistAgentResponseInput,
) => Promise<RunAndPersistAgentResponseResult>,
) {}
getConnectActionAdapters() {
return (this.options.chatSurfaceAdapters ?? [])
.map((adapter) => adapter as ChatSurfaceAdapterWithConnectAction)
.filter((adapter) => adapter.createConnectAction);
}
createLinkToken(surface: string, adminUser: AdminUser) {
for (const [token, payload] of this.linkTokens) {
if (payload.expiresAt <= Date.now()) {
this.linkTokens.delete(token);
}
}
const token = randomUUID();
this.linkTokens.set(token, {
surface,
adminUserId: adminUser.pk,
expiresAt: Date.now() + CHAT_SURFACE_LINK_TOKEN_TTL_MS,
});
return token;
}
private consumeLinkToken(surface: string, token: string) {
const payload = this.linkTokens.get(token);
this.linkTokens.delete(token);
if (!payload || payload.surface !== surface || payload.expiresAt <= Date.now()) {
return null;
}
return payload;
}
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;
}
const externalUserIdField = this.options.chatExternalIdsField ?? DEFAULT_ADMIN_USER_EXTERNAL_USER_ID_FIELD;
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 linkedAdminUserRecord = (
await adminforth.resource(authResourceId).list(Filters.IS_NOT_EMPTY(externalUserIdField))
).find((user) => user[externalUserIdField]?.[incoming.surface] === incoming.externalUserId);
if (linkedAdminUserRecord) {
await sink.emit({
type: "done",
text: `${incoming.surface} account is already connected to AdminForth.`,
});
return true;
}
if (typeof incoming.metadata?.startPayload !== "string") {
await sink.emit({
type: "done",
text: `Open AdminForth and connect your ${incoming.surface} account from Chat Surfaces settings.`,
});
return true;
}
const payload = this.consumeLinkToken(incoming.surface, incoming.metadata.startPayload);
if (!payload) {
await sink.emit({
type: "error",
message: "This chat surface link is expired or invalid. Please start linking again from AdminForth.",
});
return true;
}
const adminUserRecord = await adminforth.resource(authResourceId).get([
Filters.EQ(primaryKeyField, payload.adminUserId),
]);
await adminforth.resource(authResourceId).update(payload.adminUserId, {
[externalUserIdField]: {
...(adminUserRecord[externalUserIdField] ?? {}),
[incoming.surface]: incoming.externalUserId,
},
});
await sink.emit({
type: "done",
text: `${incoming.surface} account connected to AdminForth.`,
});
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;
}
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 externalUserIdField = this.options.chatExternalIdsField ?? DEFAULT_ADMIN_USER_EXTERNAL_USER_ID_FIELD;
const adminUserRecord = (
await adminforth.resource(authResourceId).list(Filters.IS_NOT_EMPTY(externalUserIdField))
).find((user) => user[externalUserIdField]?.[adapter.name] === incoming.externalUserId);
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);
}
}