-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathdefault_request_handler.ts
More file actions
601 lines (525 loc) · 24.6 KB
/
Copy pathdefault_request_handler.ts
File metadata and controls
601 lines (525 loc) · 24.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import { Message, AgentCard, PushNotificationConfig, Task, MessageSendParams, TaskState, TaskStatusUpdateEvent, TaskArtifactUpdateEvent, TaskQueryParams, TaskIdParams, TaskPushNotificationConfig, DeleteTaskPushNotificationConfigParams, GetTaskPushNotificationConfigParams, ListTaskPushNotificationConfigParams, ListTasksParams, ListTasksResult } from "../../types.js";
import { AgentExecutor } from "../agent_execution/agent_executor.js";
import { RequestContext } from "../agent_execution/request_context.js";
import { A2AError } from "../error.js";
import { ExecutionEventBusManager, DefaultExecutionEventBusManager } from "../events/execution_event_bus_manager.js";
import { AgentExecutionEvent, ExecutionEventBus } from "../events/execution_event_bus.js";
import { ExecutionEventQueue } from "../events/execution_event_queue.js";
import { ResultManager } from "../result_manager.js";
import { TaskStore } from "../store.js";
import { A2ARequestHandler } from "./a2a_request_handler.js";
import { InMemoryPushNotificationStore, PushNotificationStore } from '../push_notification/push_notification_store.js';
import { PushNotificationSender } from '../push_notification/push_notification_sender.js';
import { DefaultPushNotificationSender } from '../push_notification/default_push_notification_sender.js';
import { DEFAULT_PAGE_SIZE } from '../../constants.js';
import { isValidUnixTimestampMs } from '../utils.js';
const terminalStates: TaskState[] = ["completed", "failed", "canceled", "rejected"];
export class DefaultRequestHandler implements A2ARequestHandler {
private readonly agentCard: AgentCard;
private readonly extendedAgentCard?: AgentCard;
private readonly taskStore: TaskStore;
private readonly agentExecutor: AgentExecutor;
private readonly eventBusManager: ExecutionEventBusManager;
private readonly pushNotificationStore ?: PushNotificationStore;
private readonly pushNotificationSender ?: PushNotificationSender;
constructor(
agentCard: AgentCard,
taskStore: TaskStore,
agentExecutor: AgentExecutor,
eventBusManager: ExecutionEventBusManager = new DefaultExecutionEventBusManager(),
pushNotificationStore?: PushNotificationStore,
pushNotificationSender?: PushNotificationSender,
extendedAgentCard?: AgentCard,
) {
this.agentCard = agentCard;
this.taskStore = taskStore;
this.agentExecutor = agentExecutor;
this.eventBusManager = eventBusManager;
this.extendedAgentCard = extendedAgentCard;
// If push notifications are supported, use the provided store and sender.
// Otherwise, use the default in-memory store and sender.
if (agentCard.capabilities.pushNotifications) {
this.pushNotificationStore = pushNotificationStore || new InMemoryPushNotificationStore();
this.pushNotificationSender = pushNotificationSender || new DefaultPushNotificationSender(this.pushNotificationStore);
}
}
async getAgentCard(): Promise<AgentCard> {
return this.agentCard;
}
async getAuthenticatedExtendedAgentCard(): Promise<AgentCard> {
if(!this.extendedAgentCard) {
throw A2AError.authenticatedExtendedCardNotConfigured()
}
return this.extendedAgentCard;
}
private async _createRequestContext(
incomingMessage: Message,
taskId: string,
isStream: boolean,
): Promise<RequestContext> {
let task: Task | undefined;
let referenceTasks: Task[] | undefined;
// incomingMessage would contain taskId, if a task already exists.
if (incomingMessage.taskId) {
task = await this.taskStore.load(incomingMessage.taskId);
if (!task) {
throw A2AError.taskNotFound(incomingMessage.taskId);
}
if (terminalStates.includes(task.status.state)) {
// Throw an error that conforms to the JSON-RPC Invalid Request error specification.
throw A2AError.invalidRequest(`Task ${task.id} is in a terminal state (${task.status.state}) and cannot be modified.`)
}
// Add incomingMessage to history and save the task.
task.history = [...(task.history || []), incomingMessage];
await this.taskStore.save(task);
}
if (incomingMessage.referenceTaskIds && incomingMessage.referenceTaskIds.length > 0) {
referenceTasks = [];
for (const refId of incomingMessage.referenceTaskIds) {
const refTask = await this.taskStore.load(refId);
if (refTask) {
referenceTasks.push(refTask);
} else {
console.warn(`Reference task ${refId} not found.`);
// Optionally, throw an error or handle as per specific requirements
}
}
}
// Ensure contextId is present
const contextId = incomingMessage.contextId || task?.contextId || uuidv4();
const messageForContext = {
...incomingMessage,
contextId,
};
return new RequestContext(
messageForContext,
taskId,
contextId,
task,
referenceTasks
);
}
private async _processEvents(
taskId: string,
resultManager: ResultManager,
eventQueue: ExecutionEventQueue,
options?: {
firstResultResolver?: (value: Message | Task | PromiseLike<Message | Task>) => void;
firstResultRejector?: (reason?: any) => void;
}
): Promise<void> {
let firstResultSent = false;
try {
for await (const event of eventQueue.events()) {
await resultManager.processEvent(event);
await this._sendPushNotificationIfNeeded(event);
if (options?.firstResultResolver && !firstResultSent) {
let firstResult: Message | Task | undefined;
if (event.kind === 'message') {
firstResult = event;
} else {
firstResult = resultManager.getCurrentTask();
}
if (firstResult) {
options.firstResultResolver(firstResult);
firstResultSent = true;
}
}
}
if (options?.firstResultRejector && !firstResultSent) {
options.firstResultRejector(A2AError.internalError('Execution finished before a message or task was produced.'));
}
} catch (error) {
console.error(`Event processing loop failed for task ${taskId}:`, error);
if (options?.firstResultRejector && !firstResultSent) {
options.firstResultRejector(error);
}
// re-throw error for blocking case to catch
throw error;
} finally {
this.eventBusManager.cleanupByTaskId(taskId);
}
}
async sendMessage(
params: MessageSendParams
): Promise<Message | Task> {
const incomingMessage = params.message;
if (!incomingMessage.messageId) {
throw A2AError.invalidParams('message.messageId is required.');
}
// Default to blocking behavior if 'blocking' is not explicitly false.
const isBlocking = params.configuration?.blocking !== false;
const taskId = incomingMessage.taskId || uuidv4();
// Instantiate ResultManager before creating RequestContext
const resultManager = new ResultManager(this.taskStore);
resultManager.setContext(incomingMessage); // Set context for ResultManager
const requestContext = await this._createRequestContext(incomingMessage, taskId, false);
// Use the (potentially updated) contextId from requestContext
const finalMessageForAgent = requestContext.userMessage;
// If push notification config is provided, save it to the store.
if (params.configuration?.pushNotificationConfig && this.agentCard.capabilities.pushNotifications) {
await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
}
const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
// EventQueue should be attached to the bus, before the agent execution begins.
const eventQueue = new ExecutionEventQueue(eventBus);
// Start agent execution (non-blocking).
// It runs in the background and publishes events to the eventBus.
this.agentExecutor.execute(requestContext, eventBus).catch(err => {
console.error(`Agent execution failed for message ${finalMessageForAgent.messageId}:`, err);
// Publish a synthetic error event, which will be handled by the ResultManager
// and will also settle the firstResultPromise for non-blocking calls.
const errorTask: Task = {
id: requestContext.task?.id || uuidv4(), // Use existing task ID or generate new
contextId: finalMessageForAgent.contextId!,
status: {
state: "failed",
message: {
kind: "message",
role: "agent",
messageId: uuidv4(),
parts: [{ kind: "text", text: `Agent execution error: ${err.message}` }],
taskId: requestContext.task?.id,
contextId: finalMessageForAgent.contextId!,
},
timestamp: new Date().toISOString(),
},
history: requestContext.task?.history ? [...requestContext.task.history] : [],
kind: "task",
};
if (finalMessageForAgent) { // Add incoming message to history
if (!errorTask.history?.find(m => m.messageId === finalMessageForAgent.messageId)) {
errorTask.history?.push(finalMessageForAgent);
}
}
eventBus.publish(errorTask);
eventBus.publish({ // And publish a final status update
kind: "status-update",
taskId: errorTask.id,
contextId: errorTask.contextId,
status: errorTask.status,
final: true,
} as TaskStatusUpdateEvent);
eventBus.finished();
});
if (isBlocking) {
// In blocking mode, wait for the full processing to complete.
await this._processEvents(taskId, resultManager, eventQueue);
const finalResult = resultManager.getFinalResult();
if (!finalResult) {
throw A2AError.internalError('Agent execution finished without a result, and no task context found.');
}
return finalResult;
} else {
// In non-blocking mode, return a promise that will be settled by fullProcessing.
return new Promise<Message | Task>((resolve, reject) => {
this._processEvents(taskId, resultManager, eventQueue, {
firstResultResolver: resolve,
firstResultRejector: reject,
});
});
}
}
async *sendMessageStream(
params: MessageSendParams
): AsyncGenerator<
| Message
| Task
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent,
void,
undefined
> {
const incomingMessage = params.message;
if (!incomingMessage.messageId) {
// For streams, messageId might be set by client, or server can generate if not present.
// Let's assume client provides it or throw for now.
throw A2AError.invalidParams('message.messageId is required for streaming.');
}
const taskId = incomingMessage.taskId || uuidv4();
// Instantiate ResultManager before creating RequestContext
const resultManager = new ResultManager(this.taskStore);
resultManager.setContext(incomingMessage); // Set context for ResultManager
const requestContext = await this._createRequestContext(incomingMessage, taskId, true);
const finalMessageForAgent = requestContext.userMessage;
const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
const eventQueue = new ExecutionEventQueue(eventBus);
// If push notification config is provided, save it to the store.
if (params.configuration?.pushNotificationConfig && this.agentCard.capabilities.pushNotifications) {
await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
}
// Start agent execution (non-blocking)
this.agentExecutor.execute(requestContext, eventBus).catch(err => {
console.error(`Agent execution failed for stream message ${finalMessageForAgent.messageId}:`, err);
// Publish a synthetic error event if needed
const errorTaskStatus: TaskStatusUpdateEvent = {
kind: "status-update",
taskId: requestContext.task?.id || uuidv4(), // Use existing or a placeholder
contextId: finalMessageForAgent.contextId!,
status: {
state: "failed",
message: {
kind: "message",
role: "agent",
messageId: uuidv4(),
parts: [{ kind: "text", text: `Agent execution error: ${err.message}` }],
taskId: requestContext.task?.id,
contextId: finalMessageForAgent.contextId!,
},
timestamp: new Date().toISOString(),
},
final: true, // This will terminate the stream for the client
};
eventBus.publish(errorTaskStatus);
});
try {
for await (const event of eventQueue.events()) {
await resultManager.processEvent(event); // Update store in background
await this._sendPushNotificationIfNeeded(event);
yield event; // Stream the event to the client
}
} finally {
// Cleanup when the stream is fully consumed or breaks
this.eventBusManager.cleanupByTaskId(taskId);
}
}
async getTask(params: TaskQueryParams): Promise<Task> {
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
if (params.historyLength !== undefined && params.historyLength >= 0) {
if (task.history) {
task.history = task.history.slice(-params.historyLength);
}
} else {
// Negative or invalid historyLength means no history
task.history = [];
}
return task;
}
async listTasks(
params: ListTasksParams
): Promise<ListTasksResult> {
if (!this.paramsTasksListAreValid(params)) {
throw A2AError.invalidParams(`Invalid method parameters.`);
}
return await this.taskStore.list(params);
}
async cancelTask(params: TaskIdParams): Promise<Task> {
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
// Check if task is in a cancelable state
const nonCancelableStates = ["completed", "failed", "canceled", "rejected"];
if (nonCancelableStates.includes(task.status.state)) {
throw A2AError.taskNotCancelable(params.id);
}
const eventBus = this.eventBusManager.getByTaskId(params.id);
if(eventBus) {
const eventQueue = new ExecutionEventQueue(eventBus);
await this.agentExecutor.cancelTask(params.id, eventBus);
// Consume all the events until the task reaches a terminal state.
await this._processEvents(params.id, new ResultManager(this.taskStore), eventQueue);
}
else {
// Here we are marking task as cancelled. We are not waiting for the executor to actually cancel processing.
task.status = {
state: "canceled",
message: { // Optional: Add a system message indicating cancellation
kind: "message",
role: "agent",
messageId: uuidv4(),
parts: [{ kind: "text", text: "Task cancellation requested by user." }],
taskId: task.id,
contextId: task.contextId,
},
timestamp: new Date().toISOString(),
};
// Add cancellation message to history
task.history = [...(task.history || []), task.status.message];
await this.taskStore.save(task);
}
const latestTask = await this.taskStore.load(params.id);
if (!latestTask) {
throw A2AError.internalError(`Task ${params.id} not found after cancellation.`);
}
if (latestTask.status.state != "canceled") {
throw A2AError.taskNotCancelable(params.id);
}
return latestTask;
}
async setTaskPushNotificationConfig(
params: TaskPushNotificationConfig
): Promise<TaskPushNotificationConfig> {
if (!this.agentCard.capabilities.pushNotifications) {
throw A2AError.pushNotificationNotSupported();
}
const task = await this.taskStore.load(params.taskId);
if (!task) {
throw A2AError.taskNotFound(params.taskId);
}
const { taskId, pushNotificationConfig } = params;
// Default the config ID to the task ID if not provided for backward compatibility.
if (!pushNotificationConfig.id) {
pushNotificationConfig.id = taskId;
}
await this.pushNotificationStore?.save(taskId, pushNotificationConfig);
return params;
}
async getTaskPushNotificationConfig(
params: TaskIdParams | GetTaskPushNotificationConfigParams
): Promise<TaskPushNotificationConfig> {
if (!this.agentCard.capabilities.pushNotifications) {
throw A2AError.pushNotificationNotSupported();
}
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
const configs = await this.pushNotificationStore?.load(params.id) || [];
if (configs.length === 0) {
throw A2AError.internalError(`Push notification config not found for task ${params.id}.`);
}
let configId: string;
if ('pushNotificationConfigId' in params && params.pushNotificationConfigId) {
configId = params.pushNotificationConfigId;
} else {
// For backward compatibility, if no config ID is given, assume it's the task ID.
configId = params.id;
}
const config = configs.find(c => c.id === configId);
if (!config) {
throw A2AError.internalError(`Push notification config with id '${configId}' not found for task ${params.id}.`);
}
return { taskId: params.id, pushNotificationConfig: config };
}
async listTaskPushNotificationConfigs(
params: ListTaskPushNotificationConfigParams
): Promise<TaskPushNotificationConfig[]> {
if (!this.agentCard.capabilities.pushNotifications) {
throw A2AError.pushNotificationNotSupported();
}
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
const configs = await this.pushNotificationStore?.load(params.id) || [];
return configs.map(config => ({
taskId: params.id,
pushNotificationConfig: config,
}));
}
async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigParams
): Promise<void> {
if (!this.agentCard.capabilities.pushNotifications) {
throw A2AError.pushNotificationNotSupported();
}
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
const { id: taskId, pushNotificationConfigId } = params;
await this.pushNotificationStore?.delete(taskId, pushNotificationConfigId);
}
async *resubscribe(
params: TaskIdParams
): AsyncGenerator<
| Task // Initial task state
| TaskStatusUpdateEvent
| TaskArtifactUpdateEvent,
void,
undefined
> {
if (!this.agentCard.capabilities.streaming) {
throw A2AError.unsupportedOperation("Streaming (and thus resubscription) is not supported.");
}
const task = await this.taskStore.load(params.id);
if (!task) {
throw A2AError.taskNotFound(params.id);
}
// Yield the current task state first
yield task;
// If task is already in a final state, no more events will come.
const finalStates = ["completed", "failed", "canceled", "rejected"];
if (finalStates.includes(task.status.state)) {
return;
}
const eventBus = this.eventBusManager.getByTaskId(params.id);
if (!eventBus) {
// No active execution for this task, so no live events.
console.warn(`Resubscribe: No active event bus for task ${params.id}.`);
return;
}
// Attach a new queue to the existing bus for this resubscription
const eventQueue = new ExecutionEventQueue(eventBus);
// Note: The ResultManager part is already handled by the original execution flow.
// Resubscribe just listens for new events.
try {
for await (const event of eventQueue.events()) {
// We only care about updates related to *this* task.
// The event bus might be shared if messageId was reused, though
// ExecutionEventBusManager tries to give one bus per original message.
if (event.kind === 'status-update' && event.taskId === params.id) {
yield event as TaskStatusUpdateEvent;
} else if (event.kind === 'artifact-update' && event.taskId === params.id) {
yield event as TaskArtifactUpdateEvent;
} else if (event.kind === 'task' && event.id === params.id) {
// This implies the task was re-emitted, yield it.
yield event as Task;
}
// We don't yield 'message' events on resubscribe typically,
// as those signal the end of an interaction for the *original* request.
// If a 'message' event for the original request terminates the bus, this loop will also end.
}
} finally {
eventQueue.stop();
}
}
private async _sendPushNotificationIfNeeded(event: AgentExecutionEvent): Promise<void> {
if (!this.agentCard.capabilities.pushNotifications) {
return;
}
let taskId: string = "";
if (event.kind == "task") {
const task = event as Task;
taskId = task.id;
} else {
taskId = event.taskId;
}
if (!taskId) {
console.error(`Task ID not found for event ${event.kind}.`);
return;
}
const task = await this.taskStore.load(taskId);
if (!task) {
console.error(`Task ${taskId} not found.`);
return;
}
// Send push notification in the background.
this.pushNotificationSender?.send(task);
}
// Check if the params for the TasksList function are valid
private paramsTasksListAreValid(params: ListTasksParams): boolean {
if(params.pageSize !== undefined && (params.pageSize > 100 || params.pageSize < 1)) {
return false;
}
if(params.pageToken !== undefined && Buffer.from(params.pageToken, 'base64').toString('base64') !== params.pageToken){
return false;
}
if(params.historyLength !== undefined && params.historyLength<0){
return false;
}
if(params.lastUpdatedAfter !== undefined && !isValidUnixTimestampMs(params.lastUpdatedAfter)){
return false;
}
const terminalStates: string[] = ["completed", "failed", "canceled", "rejected"];
if(params.status !== undefined && !terminalStates.includes(params.status)){
return false;
}
return true;
}
}