-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathhandle-agent-reply.usecase.ts
More file actions
306 lines (271 loc) · 10.5 KB
/
handle-agent-reply.usecase.ts
File metadata and controls
306 lines (271 loc) · 10.5 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
import { BadRequestException, forwardRef, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { PinoLogger, shortId } from '@novu/application-generic';
import {
ConversationActivityRepository,
ConversationActivityTypeEnum,
ConversationChannel,
ConversationEntity,
ConversationRepository,
ConversationStatusEnum,
SubscriberRepository,
} from '@novu/dal';
import { AgentEventEnum } from '../../dtos/agent-event.enum';
import { AgentConfigResolver, ResolvedAgentConfig } from '../../services/agent-config-resolver.service';
import { AgentConversationService } from '../../services/agent-conversation.service';
import { BridgeExecutorService } from '../../services/bridge-executor.service';
import { ChatSdkService } from '../../services/chat-sdk.service';
import type { ReplyContentDto } from '../../dtos/agent-reply-payload.dto';
import { HandleAgentReplyCommand } from './handle-agent-reply.command';
@Injectable()
export class HandleAgentReply {
constructor(
private readonly conversationRepository: ConversationRepository,
private readonly activityRepository: ConversationActivityRepository,
private readonly subscriberRepository: SubscriberRepository,
@Inject(forwardRef(() => ChatSdkService))
private readonly chatSdkService: ChatSdkService,
private readonly bridgeExecutor: BridgeExecutorService,
private readonly agentConfigResolver: AgentConfigResolver,
private readonly conversationService: AgentConversationService,
private readonly logger: PinoLogger
) {}
async execute(command: HandleAgentReplyCommand): Promise<{ status: string }> {
if (command.reply && command.update) {
throw new BadRequestException('Only one of reply or update can be provided');
}
if (!command.reply && !command.update && !command.resolve && !command.signals?.length) {
throw new BadRequestException('At least one of reply, update, resolve, or signals must be provided');
}
const conversation = await this.conversationRepository.findOne(
{
_id: command.conversationId,
_environmentId: command.environmentId,
_organizationId: command.organizationId,
},
'*'
);
if (!conversation) {
throw new NotFoundException('Conversation not found');
}
const channel = this.getPrimaryChannel(conversation);
if (command.update) {
await this.deliverMessage(command, conversation, channel, command.update, ConversationActivityTypeEnum.UPDATE);
return { status: 'update_sent' };
}
const needsConfig = !!(command.reply || command.resolve);
const config = needsConfig
? await this.agentConfigResolver.resolve(conversation._agentId, command.integrationIdentifier)
: null;
if (command.reply) {
await this.deliverMessage(command, conversation, channel, command.reply, ConversationActivityTypeEnum.MESSAGE);
this.removeAckReaction(config!, conversation, channel).catch((err) => {
this.logger.warn(err, `[agent:${command.agentIdentifier}] Failed to remove ack reaction`);
});
}
if (command.signals?.length) {
await this.executeSignals(command, conversation, channel, command.signals);
}
if (command.resolve) {
await this.executeResolveSignal(command, config!, conversation, channel, command.resolve);
}
return { status: 'ok' };
}
private getPrimaryChannel(conversation: ConversationEntity): ConversationChannel {
const channel = conversation.channels[0];
if (!channel?.serializedThread) {
throw new BadRequestException('Conversation has no serialized thread — unable to deliver reply');
}
return channel;
}
private async deliverMessage(
command: HandleAgentReplyCommand,
conversation: ConversationEntity,
channel: ConversationChannel,
content: ReplyContentDto,
type: ConversationActivityTypeEnum
): Promise<void> {
const textFallback = this.extractTextFallback(content);
await Promise.all([
this.chatSdkService.postToConversation(
conversation._agentId,
command.integrationIdentifier,
channel.platform,
channel.serializedThread!,
content
),
this.activityRepository.createAgentActivity({
identifier: `act-${shortId(8)}`,
conversationId: conversation._id,
platform: channel.platform,
integrationId: channel._integrationId,
platformThreadId: channel.platformThreadId,
agentId: command.agentIdentifier,
content: textFallback,
richContent: (content.card || content.files?.length) ? (content as Record<string, unknown>) : undefined,
type,
environmentId: command.environmentId,
organizationId: command.organizationId,
}),
this.conversationRepository.touchActivity(
command.environmentId,
command.organizationId,
conversation._id,
textFallback
),
]);
}
private extractTextFallback(content: ReplyContentDto): string {
if (content.text) return content.text;
if (content.markdown) return content.markdown;
if (content.card) {
const title = (content.card as { title?: string }).title;
return title ?? '[Card]';
}
return '';
}
private async executeSignals(
command: HandleAgentReplyCommand,
conversation: ConversationEntity,
channel: ConversationChannel,
signals: HandleAgentReplyCommand['signals']
): Promise<void> {
const metadataSignals = (signals ?? []).filter(
(s): s is Extract<NonNullable<HandleAgentReplyCommand['signals']>[number], { type: 'metadata' }> => s.type === 'metadata'
);
if (metadataSignals.length) {
await this.executeMetadataSignals(command, conversation, channel, metadataSignals);
}
const triggerSignals = (signals ?? []).filter((s) => s.type === 'trigger');
if (triggerSignals.length) {
// TODO: execute trigger signals — requires wiring TriggerEvent or ParseEventRequest from EventsModule
}
}
private async executeMetadataSignals(
command: HandleAgentReplyCommand,
conversation: ConversationEntity,
channel: ConversationChannel,
signals: Array<{ type: 'metadata'; key: string; value: unknown }>
): Promise<void> {
const merged = { ...(conversation.metadata ?? {}) };
for (const signal of signals) {
merged[signal.key] = signal.value;
}
const serialized = JSON.stringify(merged);
if (Buffer.byteLength(serialized) > 65_536) {
throw new BadRequestException('Conversation metadata exceeds 64KB limit');
}
await Promise.all([
this.conversationRepository.updateMetadata(
command.environmentId,
command.organizationId,
conversation._id,
merged
),
this.activityRepository.createSignalActivity({
identifier: `act-${shortId(8)}`,
conversationId: conversation._id,
platform: channel.platform,
integrationId: channel._integrationId,
platformThreadId: channel.platformThreadId,
agentId: command.agentIdentifier,
content: `Metadata updated: ${signals.map((s) => s.key).join(', ')}`,
signalData: { type: 'metadata', payload: merged },
environmentId: command.environmentId,
organizationId: command.organizationId,
}),
]);
}
private async executeResolveSignal(
command: HandleAgentReplyCommand,
config: ResolvedAgentConfig,
conversation: ConversationEntity,
channel: ConversationChannel,
signal: { summary?: string }
): Promise<void> {
await Promise.all([
this.conversationRepository.updateStatus(
command.environmentId,
command.organizationId,
conversation._id,
ConversationStatusEnum.RESOLVED
),
this.activityRepository.createSignalActivity({
identifier: `act-${shortId(8)}`,
conversationId: conversation._id,
platform: channel.platform,
integrationId: channel._integrationId,
platformThreadId: channel.platformThreadId,
agentId: command.agentIdentifier,
content: signal.summary ?? 'Conversation resolved',
signalData: { type: 'resolve', payload: signal.summary ? { summary: signal.summary } : undefined },
environmentId: command.environmentId,
organizationId: command.organizationId,
}),
]);
this.reactOnResolve(config, conversation, channel).catch((err) => {
this.logger.warn(err, `[agent:${command.agentIdentifier}] Failed to add resolve reaction`);
});
this.fireOnResolveBridgeCall(command, config, conversation).catch((err) => {
this.logger.error(err, `[agent:${command.agentIdentifier}] Failed to fire onResolve bridge call`);
});
}
private async removeAckReaction(
config: ResolvedAgentConfig,
conversation: ConversationEntity,
channel: ConversationChannel
): Promise<void> {
const firstMessageId = channel.firstPlatformMessageId;
if (!firstMessageId || !config.reactionOnMessageReceived) return;
await this.chatSdkService.removeReaction(
conversation._agentId,
config.integrationIdentifier,
channel.platform,
channel.platformThreadId,
firstMessageId,
config.reactionOnMessageReceived
);
}
private async reactOnResolve(
config: ResolvedAgentConfig,
conversation: ConversationEntity,
channel: ConversationChannel
): Promise<void> {
const firstMessageId = channel.firstPlatformMessageId;
if (!firstMessageId || !config.reactionOnResolved) return;
await this.chatSdkService.reactToMessage(
conversation._agentId,
config.integrationIdentifier,
channel.platform,
channel.platformThreadId,
firstMessageId,
config.reactionOnResolved
);
}
private async fireOnResolveBridgeCall(
command: HandleAgentReplyCommand,
config: ResolvedAgentConfig,
conversation: ConversationEntity
): Promise<void> {
const subscriberParticipant = conversation.participants.find((p) => p.type === 'subscriber');
const [subscriber, history] = await Promise.all([
subscriberParticipant
? this.subscriberRepository.findBySubscriberId(command.environmentId, subscriberParticipant.id)
: Promise.resolve(null),
this.conversationService.getHistory(command.environmentId, conversation._id),
]);
const channel = conversation.channels[0];
await this.bridgeExecutor.execute({
event: AgentEventEnum.ON_RESOLVE,
config,
conversation,
subscriber,
history,
message: null,
platformContext: {
threadId: channel?.platformThreadId ?? '',
channelId: '',
isDM: false,
},
});
}
}