@mailmodo/a2a 0.3.3 → 0.3.7

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.
@@ -0,0 +1,1070 @@
1
+ import {
2
+ A2AError,
3
+ JsonRpcTransportHandler,
4
+ ServerCallContext,
5
+ UnauthenticatedUser
6
+ } from "../chunk-AZGEDUZX.mjs";
7
+ import "../chunk-7JFJW6P6.mjs";
8
+
9
+ // src/server/agent_execution/request_context.ts
10
+ var RequestContext = class {
11
+ userMessage;
12
+ taskId;
13
+ contextId;
14
+ task;
15
+ referenceTasks;
16
+ context;
17
+ constructor(userMessage, taskId, contextId, task, referenceTasks, context) {
18
+ this.userMessage = userMessage;
19
+ this.taskId = taskId;
20
+ this.contextId = contextId;
21
+ this.task = task;
22
+ this.referenceTasks = referenceTasks;
23
+ this.context = context;
24
+ }
25
+ };
26
+
27
+ // src/server/events/execution_event_bus.ts
28
+ var CustomEventImpl = typeof CustomEvent !== "undefined" ? CustomEvent : class CustomEventPolyfill extends Event {
29
+ detail;
30
+ constructor(type, eventInitDict) {
31
+ super(type, eventInitDict);
32
+ this.detail = eventInitDict?.detail ?? null;
33
+ }
34
+ };
35
+ function isAgentExecutionCustomEvent(e) {
36
+ return e instanceof CustomEventImpl;
37
+ }
38
+ var DefaultExecutionEventBus = class extends EventTarget {
39
+ // Separate storage for each event type - both use the interface's Listener type
40
+ // but are invoked differently (with event payload vs. no arguments)
41
+ eventListeners = /* @__PURE__ */ new Map();
42
+ finishedListeners = /* @__PURE__ */ new Map();
43
+ publish(event) {
44
+ this.dispatchEvent(new CustomEventImpl("event", { detail: event }));
45
+ }
46
+ finished() {
47
+ this.dispatchEvent(new Event("finished"));
48
+ }
49
+ /**
50
+ * EventEmitter-compatible 'on' method.
51
+ * Wraps the listener to extract event detail from CustomEvent.
52
+ * Supports multiple registrations of the same listener (like EventEmitter).
53
+ * @param eventName The event name to listen for.
54
+ * @param listener The callback function to invoke when the event is emitted.
55
+ * @returns This instance for method chaining.
56
+ */
57
+ on(eventName, listener) {
58
+ if (eventName === "event") {
59
+ this.addEventListenerInternal(listener);
60
+ } else {
61
+ this.addFinishedListenerInternal(listener);
62
+ }
63
+ return this;
64
+ }
65
+ /**
66
+ * EventEmitter-compatible 'off' method.
67
+ * Uses the stored wrapped listener for proper removal.
68
+ * Removes at most one instance of a listener per call (like EventEmitter).
69
+ * @param eventName The event name to stop listening for.
70
+ * @param listener The callback function to remove.
71
+ * @returns This instance for method chaining.
72
+ */
73
+ off(eventName, listener) {
74
+ if (eventName === "event") {
75
+ this.removeEventListenerInternal(listener);
76
+ } else {
77
+ this.removeFinishedListenerInternal(listener);
78
+ }
79
+ return this;
80
+ }
81
+ /**
82
+ * EventEmitter-compatible 'once' method.
83
+ * Listener is automatically removed after first invocation.
84
+ * Supports multiple registrations of the same listener (like EventEmitter).
85
+ * @param eventName The event name to listen for once.
86
+ * @param listener The callback function to invoke when the event is emitted.
87
+ * @returns This instance for method chaining.
88
+ */
89
+ once(eventName, listener) {
90
+ if (eventName === "event") {
91
+ this.addEventListenerOnceInternal(listener);
92
+ } else {
93
+ this.addFinishedListenerOnceInternal(listener);
94
+ }
95
+ return this;
96
+ }
97
+ /**
98
+ * EventEmitter-compatible 'removeAllListeners' method.
99
+ * Removes all listeners for a specific event or all events.
100
+ * @param eventName Optional event name to remove listeners for. If omitted, removes all.
101
+ * @returns This instance for method chaining.
102
+ */
103
+ removeAllListeners(eventName) {
104
+ if (eventName === void 0 || eventName === "event") {
105
+ for (const wrappedListeners of this.eventListeners.values()) {
106
+ for (const wrapped of wrappedListeners) {
107
+ this.removeEventListener("event", wrapped);
108
+ }
109
+ }
110
+ this.eventListeners.clear();
111
+ }
112
+ if (eventName === void 0 || eventName === "finished") {
113
+ for (const wrappedListeners of this.finishedListeners.values()) {
114
+ for (const wrapped of wrappedListeners) {
115
+ this.removeEventListener("finished", wrapped);
116
+ }
117
+ }
118
+ this.finishedListeners.clear();
119
+ }
120
+ return this;
121
+ }
122
+ // ========================
123
+ // Helper methods for listener tracking
124
+ // ========================
125
+ /**
126
+ * Adds a wrapped listener to the tracking map.
127
+ */
128
+ trackListener(listenerMap, listener, wrapped) {
129
+ const existing = listenerMap.get(listener);
130
+ if (existing) {
131
+ existing.push(wrapped);
132
+ } else {
133
+ listenerMap.set(listener, [wrapped]);
134
+ }
135
+ }
136
+ /**
137
+ * Removes a wrapped listener from the tracking map (for once cleanup).
138
+ */
139
+ untrackWrappedListener(listenerMap, listener, wrapped) {
140
+ const wrappedList = listenerMap.get(listener);
141
+ if (wrappedList && wrappedList.length > 0) {
142
+ const index = wrappedList.indexOf(wrapped);
143
+ if (index !== -1) {
144
+ wrappedList.splice(index, 1);
145
+ if (wrappedList.length === 0) {
146
+ listenerMap.delete(listener);
147
+ }
148
+ }
149
+ }
150
+ }
151
+ // ========================
152
+ // Internal methods for 'event' listeners
153
+ // ========================
154
+ addEventListenerInternal(listener) {
155
+ const wrapped = (e) => {
156
+ if (!isAgentExecutionCustomEvent(e)) {
157
+ throw new Error('Internal error: expected CustomEvent for "event" type');
158
+ }
159
+ listener.call(this, e.detail);
160
+ };
161
+ this.trackListener(this.eventListeners, listener, wrapped);
162
+ this.addEventListener("event", wrapped);
163
+ }
164
+ removeEventListenerInternal(listener) {
165
+ const wrappedList = this.eventListeners.get(listener);
166
+ if (wrappedList && wrappedList.length > 0) {
167
+ const wrapped = wrappedList.pop();
168
+ if (wrappedList.length === 0) {
169
+ this.eventListeners.delete(listener);
170
+ }
171
+ this.removeEventListener("event", wrapped);
172
+ }
173
+ }
174
+ addEventListenerOnceInternal(listener) {
175
+ const wrapped = (e) => {
176
+ if (!isAgentExecutionCustomEvent(e)) {
177
+ throw new Error('Internal error: expected CustomEvent for "event" type');
178
+ }
179
+ this.untrackWrappedListener(this.eventListeners, listener, wrapped);
180
+ listener.call(this, e.detail);
181
+ };
182
+ this.trackListener(this.eventListeners, listener, wrapped);
183
+ this.addEventListener("event", wrapped, { once: true });
184
+ }
185
+ // ========================
186
+ // Internal methods for 'finished' listeners
187
+ // ========================
188
+ // The interface declares listeners as (event: AgentExecutionEvent) => void,
189
+ // but for 'finished' events they are invoked with no arguments (EventEmitter behavior).
190
+ // We use Function.prototype.call to invoke with `this` as the event bus (matching
191
+ // EventEmitter semantics) and no arguments, which is type-safe.
192
+ addFinishedListenerInternal(listener) {
193
+ const wrapped = () => {
194
+ listener.call(this);
195
+ };
196
+ this.trackListener(this.finishedListeners, listener, wrapped);
197
+ this.addEventListener("finished", wrapped);
198
+ }
199
+ removeFinishedListenerInternal(listener) {
200
+ const wrappedList = this.finishedListeners.get(listener);
201
+ if (wrappedList && wrappedList.length > 0) {
202
+ const wrapped = wrappedList.pop();
203
+ if (wrappedList.length === 0) {
204
+ this.finishedListeners.delete(listener);
205
+ }
206
+ this.removeEventListener("finished", wrapped);
207
+ }
208
+ }
209
+ addFinishedListenerOnceInternal(listener) {
210
+ const wrapped = () => {
211
+ this.untrackWrappedListener(this.finishedListeners, listener, wrapped);
212
+ listener.call(this);
213
+ };
214
+ this.trackListener(this.finishedListeners, listener, wrapped);
215
+ this.addEventListener("finished", wrapped, { once: true });
216
+ }
217
+ };
218
+
219
+ // src/server/events/execution_event_bus_manager.ts
220
+ var DefaultExecutionEventBusManager = class {
221
+ taskIdToBus = /* @__PURE__ */ new Map();
222
+ /**
223
+ * Creates or retrieves an existing ExecutionEventBus based on the taskId.
224
+ * @param taskId The ID of the task.
225
+ * @returns An instance of ExecutionEventBus.
226
+ */
227
+ createOrGetByTaskId(taskId) {
228
+ if (!this.taskIdToBus.has(taskId)) {
229
+ this.taskIdToBus.set(taskId, new DefaultExecutionEventBus());
230
+ }
231
+ return this.taskIdToBus.get(taskId);
232
+ }
233
+ /**
234
+ * Retrieves an existing ExecutionEventBus based on the taskId.
235
+ * @param taskId The ID of the task.
236
+ * @returns An instance of ExecutionEventBus or undefined if not found.
237
+ */
238
+ getByTaskId(taskId) {
239
+ return this.taskIdToBus.get(taskId);
240
+ }
241
+ /**
242
+ * Removes the event bus for a given taskId.
243
+ * This should be called when an execution flow is complete to free resources.
244
+ * @param taskId The ID of the task.
245
+ */
246
+ cleanupByTaskId(taskId) {
247
+ const bus = this.taskIdToBus.get(taskId);
248
+ if (bus) {
249
+ bus.removeAllListeners();
250
+ }
251
+ this.taskIdToBus.delete(taskId);
252
+ }
253
+ };
254
+
255
+ // src/server/events/execution_event_queue.ts
256
+ var ExecutionEventQueue = class {
257
+ eventBus;
258
+ eventQueue = [];
259
+ resolvePromise;
260
+ stopped = false;
261
+ boundHandleEvent;
262
+ constructor(eventBus) {
263
+ this.eventBus = eventBus;
264
+ this.eventBus.on("event", this.handleEvent);
265
+ this.eventBus.on("finished", this.handleFinished);
266
+ }
267
+ handleEvent = (event) => {
268
+ if (this.stopped) return;
269
+ this.eventQueue.push(event);
270
+ if (this.resolvePromise) {
271
+ this.resolvePromise();
272
+ this.resolvePromise = void 0;
273
+ }
274
+ };
275
+ handleFinished = () => {
276
+ this.stop();
277
+ };
278
+ /**
279
+ * Provides an async generator that yields events from the event bus.
280
+ * Stops when a Message event is received or a TaskStatusUpdateEvent with final=true is received.
281
+ */
282
+ async *events() {
283
+ while (!this.stopped || this.eventQueue.length > 0) {
284
+ if (this.eventQueue.length > 0) {
285
+ const event = this.eventQueue.shift();
286
+ yield event;
287
+ if (event.kind === "message" || event.kind === "status-update" && event.final) {
288
+ this.handleFinished();
289
+ break;
290
+ }
291
+ } else if (!this.stopped) {
292
+ await new Promise((resolve) => {
293
+ this.resolvePromise = resolve;
294
+ });
295
+ }
296
+ }
297
+ }
298
+ /**
299
+ * Stops the event queue from processing further events.
300
+ */
301
+ stop() {
302
+ this.stopped = true;
303
+ if (this.resolvePromise) {
304
+ this.resolvePromise();
305
+ this.resolvePromise = void 0;
306
+ }
307
+ this.eventBus.off("event", this.handleEvent);
308
+ this.eventBus.off("finished", this.handleFinished);
309
+ }
310
+ };
311
+
312
+ // src/server/request_handler/default_request_handler.ts
313
+ import { v4 as uuidv4 } from "uuid";
314
+
315
+ // src/server/result_manager.ts
316
+ var ResultManager = class {
317
+ taskStore;
318
+ serverCallContext;
319
+ currentTask;
320
+ latestUserMessage;
321
+ // To add to history if a new task is created
322
+ finalMessageResult;
323
+ // Stores the message if it's the final result
324
+ constructor(taskStore, serverCallContext) {
325
+ this.taskStore = taskStore;
326
+ this.serverCallContext = serverCallContext;
327
+ }
328
+ setContext(latestUserMessage) {
329
+ this.latestUserMessage = latestUserMessage;
330
+ }
331
+ /**
332
+ * Processes an agent execution event and updates the task store.
333
+ * @param event The agent execution event.
334
+ */
335
+ async processEvent(event) {
336
+ if (event.kind === "message") {
337
+ this.finalMessageResult = event;
338
+ } else if (event.kind === "task") {
339
+ const taskEvent = event;
340
+ this.currentTask = { ...taskEvent };
341
+ if (this.latestUserMessage) {
342
+ if (!this.currentTask.history?.find(
343
+ (msg) => msg.messageId === this.latestUserMessage.messageId
344
+ )) {
345
+ this.currentTask.history = [this.latestUserMessage, ...this.currentTask.history || []];
346
+ }
347
+ }
348
+ await this.saveCurrentTask();
349
+ } else if (event.kind === "status-update") {
350
+ const updateEvent = event;
351
+ if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
352
+ this.currentTask.status = updateEvent.status;
353
+ if (updateEvent.status.message) {
354
+ if (!this.currentTask.history?.find(
355
+ (msg) => msg.messageId === updateEvent.status.message.messageId
356
+ )) {
357
+ this.currentTask.history = [
358
+ ...this.currentTask.history || [],
359
+ updateEvent.status.message
360
+ ];
361
+ }
362
+ }
363
+ await this.saveCurrentTask();
364
+ } else if (!this.currentTask && updateEvent.taskId) {
365
+ const loaded = await this.taskStore.load(updateEvent.taskId, this.serverCallContext);
366
+ if (loaded) {
367
+ this.currentTask = loaded;
368
+ this.currentTask.status = updateEvent.status;
369
+ if (updateEvent.status.message) {
370
+ if (!this.currentTask.history?.find(
371
+ (msg) => msg.messageId === updateEvent.status.message.messageId
372
+ )) {
373
+ this.currentTask.history = [
374
+ ...this.currentTask.history || [],
375
+ updateEvent.status.message
376
+ ];
377
+ }
378
+ }
379
+ await this.saveCurrentTask();
380
+ } else {
381
+ console.warn(
382
+ `ResultManager: Received status update for unknown task ${updateEvent.taskId}`
383
+ );
384
+ }
385
+ }
386
+ } else if (event.kind === "artifact-update") {
387
+ const artifactEvent = event;
388
+ if (this.currentTask && this.currentTask.id === artifactEvent.taskId) {
389
+ if (!this.currentTask.artifacts) {
390
+ this.currentTask.artifacts = [];
391
+ }
392
+ const existingArtifactIndex = this.currentTask.artifacts.findIndex(
393
+ (art) => art.artifactId === artifactEvent.artifact.artifactId
394
+ );
395
+ if (existingArtifactIndex !== -1) {
396
+ if (artifactEvent.append) {
397
+ const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
398
+ existingArtifact.parts.push(...artifactEvent.artifact.parts);
399
+ if (artifactEvent.artifact.description)
400
+ existingArtifact.description = artifactEvent.artifact.description;
401
+ if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
402
+ if (artifactEvent.artifact.metadata)
403
+ existingArtifact.metadata = {
404
+ ...existingArtifact.metadata,
405
+ ...artifactEvent.artifact.metadata
406
+ };
407
+ } else {
408
+ this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
409
+ }
410
+ } else {
411
+ this.currentTask.artifacts.push(artifactEvent.artifact);
412
+ }
413
+ await this.saveCurrentTask();
414
+ } else if (!this.currentTask && artifactEvent.taskId) {
415
+ const loaded = await this.taskStore.load(artifactEvent.taskId, this.serverCallContext);
416
+ if (loaded) {
417
+ this.currentTask = loaded;
418
+ if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
419
+ const existingArtifactIndex = this.currentTask.artifacts.findIndex(
420
+ (art) => art.artifactId === artifactEvent.artifact.artifactId
421
+ );
422
+ if (existingArtifactIndex !== -1) {
423
+ if (artifactEvent.append) {
424
+ this.currentTask.artifacts[existingArtifactIndex].parts.push(
425
+ ...artifactEvent.artifact.parts
426
+ );
427
+ } else {
428
+ this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
429
+ }
430
+ } else {
431
+ this.currentTask.artifacts.push(artifactEvent.artifact);
432
+ }
433
+ await this.saveCurrentTask();
434
+ } else {
435
+ console.warn(
436
+ `ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`
437
+ );
438
+ }
439
+ }
440
+ }
441
+ }
442
+ async saveCurrentTask() {
443
+ if (this.currentTask) {
444
+ await this.taskStore.save(this.currentTask, this.serverCallContext);
445
+ }
446
+ }
447
+ /**
448
+ * Gets the final result, which could be a Message or a Task.
449
+ * This should be called after the event stream has been fully processed.
450
+ * @returns The final Message or the current Task.
451
+ */
452
+ getFinalResult() {
453
+ if (this.finalMessageResult) {
454
+ return this.finalMessageResult;
455
+ }
456
+ return this.currentTask;
457
+ }
458
+ /**
459
+ * Gets the task currently being managed by this ResultManager instance.
460
+ * This task could be one that was started with or one created during agent execution.
461
+ * @returns The current Task or undefined if no task is active.
462
+ */
463
+ getCurrentTask() {
464
+ return this.currentTask;
465
+ }
466
+ };
467
+
468
+ // src/server/push_notification/push_notification_store.ts
469
+ var InMemoryPushNotificationStore = class {
470
+ store = /* @__PURE__ */ new Map();
471
+ async save(taskId, pushNotificationConfig) {
472
+ const configs = this.store.get(taskId) || [];
473
+ if (!pushNotificationConfig.id) {
474
+ pushNotificationConfig.id = taskId;
475
+ }
476
+ const existingIndex = configs.findIndex((config) => config.id === pushNotificationConfig.id);
477
+ if (existingIndex !== -1) {
478
+ configs.splice(existingIndex, 1);
479
+ }
480
+ configs.push(pushNotificationConfig);
481
+ this.store.set(taskId, configs);
482
+ }
483
+ async load(taskId) {
484
+ const configs = this.store.get(taskId);
485
+ return configs || [];
486
+ }
487
+ async delete(taskId, configId) {
488
+ if (configId === void 0) {
489
+ configId = taskId;
490
+ }
491
+ const configs = this.store.get(taskId);
492
+ if (!configs) {
493
+ return;
494
+ }
495
+ const configIndex = configs.findIndex((config) => config.id === configId);
496
+ if (configIndex !== -1) {
497
+ configs.splice(configIndex, 1);
498
+ }
499
+ if (configs.length === 0) {
500
+ this.store.delete(taskId);
501
+ } else {
502
+ this.store.set(taskId, configs);
503
+ }
504
+ }
505
+ };
506
+
507
+ // src/server/push_notification/default_push_notification_sender.ts
508
+ var DefaultPushNotificationSender = class {
509
+ pushNotificationStore;
510
+ notificationChain;
511
+ options;
512
+ constructor(pushNotificationStore, options = {}) {
513
+ this.pushNotificationStore = pushNotificationStore;
514
+ this.notificationChain = /* @__PURE__ */ new Map();
515
+ this.options = {
516
+ timeout: 5e3,
517
+ tokenHeaderName: "X-A2A-Notification-Token",
518
+ ...options
519
+ };
520
+ }
521
+ async send(task) {
522
+ const pushConfigs = await this.pushNotificationStore.load(task.id);
523
+ if (!pushConfigs || pushConfigs.length === 0) {
524
+ return;
525
+ }
526
+ const lastPromise = this.notificationChain.get(task.id) ?? Promise.resolve();
527
+ const newPromise = lastPromise.then(async () => {
528
+ const dispatches = pushConfigs.map(async (pushConfig) => {
529
+ try {
530
+ await this._dispatchNotification(task, pushConfig);
531
+ } catch (error) {
532
+ console.error(
533
+ `Error sending push notification for task_id=${task.id} to URL: ${pushConfig.url}. Error:`,
534
+ error
535
+ );
536
+ }
537
+ });
538
+ await Promise.all(dispatches);
539
+ });
540
+ this.notificationChain.set(task.id, newPromise);
541
+ newPromise.finally(() => {
542
+ if (this.notificationChain.get(task.id) === newPromise) {
543
+ this.notificationChain.delete(task.id);
544
+ }
545
+ });
546
+ }
547
+ async _dispatchNotification(task, pushConfig) {
548
+ const url = pushConfig.url;
549
+ const controller = new AbortController();
550
+ const timeoutId = setTimeout(() => controller.abort(), this.options.timeout);
551
+ try {
552
+ const headers = {
553
+ "Content-Type": "application/json"
554
+ };
555
+ if (pushConfig.token) {
556
+ headers[this.options.tokenHeaderName] = pushConfig.token;
557
+ }
558
+ const response = await fetch(url, {
559
+ method: "POST",
560
+ headers,
561
+ body: JSON.stringify(task),
562
+ signal: controller.signal
563
+ });
564
+ if (!response.ok) {
565
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
566
+ }
567
+ console.info(`Push notification sent for task_id=${task.id} to URL: ${url}`);
568
+ } finally {
569
+ clearTimeout(timeoutId);
570
+ }
571
+ }
572
+ };
573
+
574
+ // src/server/request_handler/default_request_handler.ts
575
+ var terminalStates = ["completed", "failed", "canceled", "rejected"];
576
+ var DefaultRequestHandler = class {
577
+ agentCard;
578
+ taskStore;
579
+ agentExecutor;
580
+ eventBusManager;
581
+ pushNotificationStore;
582
+ pushNotificationSender;
583
+ extendedAgentCardProvider;
584
+ constructor(agentCard, taskStore, agentExecutor, eventBusManager = new DefaultExecutionEventBusManager(), pushNotificationStore, pushNotificationSender, extendedAgentCardProvider) {
585
+ this.agentCard = agentCard;
586
+ this.taskStore = taskStore;
587
+ this.agentExecutor = agentExecutor;
588
+ this.eventBusManager = eventBusManager;
589
+ this.extendedAgentCardProvider = extendedAgentCardProvider;
590
+ if (agentCard.capabilities.pushNotifications) {
591
+ this.pushNotificationStore = pushNotificationStore || new InMemoryPushNotificationStore();
592
+ this.pushNotificationSender = pushNotificationSender || new DefaultPushNotificationSender(this.pushNotificationStore);
593
+ }
594
+ }
595
+ async getAgentCard() {
596
+ return this.agentCard;
597
+ }
598
+ async getAuthenticatedExtendedAgentCard(context) {
599
+ if (!this.agentCard.supportsAuthenticatedExtendedCard) {
600
+ throw A2AError.unsupportedOperation("Agent does not support authenticated extended card.");
601
+ }
602
+ if (!this.extendedAgentCardProvider) {
603
+ throw A2AError.authenticatedExtendedCardNotConfigured();
604
+ }
605
+ if (typeof this.extendedAgentCardProvider === "function") {
606
+ return this.extendedAgentCardProvider(context);
607
+ }
608
+ if (context?.user?.isAuthenticated) {
609
+ return this.extendedAgentCardProvider;
610
+ }
611
+ return this.agentCard;
612
+ }
613
+ async _createRequestContext(incomingMessage, context) {
614
+ let task;
615
+ let referenceTasks;
616
+ if (incomingMessage.taskId) {
617
+ task = await this.taskStore.load(incomingMessage.taskId, context);
618
+ if (!task) {
619
+ throw A2AError.taskNotFound(incomingMessage.taskId);
620
+ }
621
+ if (terminalStates.includes(task.status.state)) {
622
+ throw A2AError.invalidRequest(
623
+ `Task ${task.id} is in a terminal state (${task.status.state}) and cannot be modified.`
624
+ );
625
+ }
626
+ task.history = [...task.history || [], incomingMessage];
627
+ await this.taskStore.save(task, context);
628
+ }
629
+ const taskId = incomingMessage.taskId || uuidv4();
630
+ if (incomingMessage.referenceTaskIds && incomingMessage.referenceTaskIds.length > 0) {
631
+ referenceTasks = [];
632
+ for (const refId of incomingMessage.referenceTaskIds) {
633
+ const refTask = await this.taskStore.load(refId, context);
634
+ if (refTask) {
635
+ referenceTasks.push(refTask);
636
+ } else {
637
+ console.warn(`Reference task ${refId} not found.`);
638
+ }
639
+ }
640
+ }
641
+ const contextId = incomingMessage.contextId || task?.contextId || uuidv4();
642
+ if (context?.requestedExtensions) {
643
+ const agentCard = await this.getAgentCard();
644
+ const exposedExtensions = new Set(
645
+ agentCard.capabilities.extensions?.map((ext) => ext.uri) || []
646
+ );
647
+ const validExtensions = context.requestedExtensions.filter(
648
+ (extension) => exposedExtensions.has(extension)
649
+ );
650
+ context = new ServerCallContext(validExtensions, context.user);
651
+ }
652
+ const messageForContext = {
653
+ ...incomingMessage,
654
+ contextId,
655
+ taskId
656
+ };
657
+ return new RequestContext(messageForContext, taskId, contextId, task, referenceTasks, context);
658
+ }
659
+ async _processEvents(taskId, resultManager, eventQueue, context, options) {
660
+ let firstResultSent = false;
661
+ try {
662
+ for await (const event of eventQueue.events()) {
663
+ await resultManager.processEvent(event);
664
+ try {
665
+ await this._sendPushNotificationIfNeeded(event, context);
666
+ } catch (error) {
667
+ console.error(`Error sending push notification: ${error}`);
668
+ }
669
+ if (options?.firstResultResolver && !firstResultSent) {
670
+ let firstResult;
671
+ if (event.kind === "message") {
672
+ firstResult = event;
673
+ } else {
674
+ firstResult = resultManager.getCurrentTask();
675
+ }
676
+ if (firstResult) {
677
+ options.firstResultResolver(firstResult);
678
+ firstResultSent = true;
679
+ }
680
+ }
681
+ }
682
+ if (options?.firstResultRejector && !firstResultSent) {
683
+ options.firstResultRejector(
684
+ A2AError.internalError("Execution finished before a message or task was produced.")
685
+ );
686
+ }
687
+ } catch (error) {
688
+ console.error(`Event processing loop failed for task ${taskId}:`, error);
689
+ this._handleProcessingError(
690
+ error,
691
+ resultManager,
692
+ firstResultSent,
693
+ taskId,
694
+ options?.firstResultRejector
695
+ );
696
+ } finally {
697
+ this.eventBusManager.cleanupByTaskId(taskId);
698
+ }
699
+ }
700
+ async sendMessage(params, context) {
701
+ const incomingMessage = params.message;
702
+ if (!incomingMessage.messageId) {
703
+ throw A2AError.invalidParams("message.messageId is required.");
704
+ }
705
+ const isBlocking = params.configuration?.blocking !== false;
706
+ const resultManager = new ResultManager(this.taskStore, context);
707
+ resultManager.setContext(incomingMessage);
708
+ const requestContext = await this._createRequestContext(incomingMessage, context);
709
+ const taskId = requestContext.taskId;
710
+ const finalMessageForAgent = requestContext.userMessage;
711
+ if (params.configuration?.pushNotificationConfig && this.agentCard.capabilities.pushNotifications) {
712
+ await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
713
+ }
714
+ const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
715
+ const eventQueue = new ExecutionEventQueue(eventBus);
716
+ this.agentExecutor.execute(requestContext, eventBus).catch((err) => {
717
+ console.error(`Agent execution failed for message ${finalMessageForAgent.messageId}:`, err);
718
+ const errorTask = {
719
+ id: requestContext.task?.id || uuidv4(),
720
+ // Use existing task ID or generate new
721
+ contextId: finalMessageForAgent.contextId,
722
+ status: {
723
+ state: "failed",
724
+ message: {
725
+ kind: "message",
726
+ role: "agent",
727
+ messageId: uuidv4(),
728
+ parts: [{ kind: "text", text: `Agent execution error: ${err.message}` }],
729
+ taskId: requestContext.task?.id,
730
+ contextId: finalMessageForAgent.contextId
731
+ },
732
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
733
+ },
734
+ history: requestContext.task?.history ? [...requestContext.task.history] : [],
735
+ kind: "task"
736
+ };
737
+ if (finalMessageForAgent) {
738
+ if (!errorTask.history?.find((m) => m.messageId === finalMessageForAgent.messageId)) {
739
+ errorTask.history?.push(finalMessageForAgent);
740
+ }
741
+ }
742
+ eventBus.publish(errorTask);
743
+ eventBus.publish({
744
+ // And publish a final status update
745
+ kind: "status-update",
746
+ taskId: errorTask.id,
747
+ contextId: errorTask.contextId,
748
+ status: errorTask.status,
749
+ final: true
750
+ });
751
+ eventBus.finished();
752
+ });
753
+ if (isBlocking) {
754
+ await this._processEvents(taskId, resultManager, eventQueue, context);
755
+ const finalResult = resultManager.getFinalResult();
756
+ if (!finalResult) {
757
+ throw A2AError.internalError(
758
+ "Agent execution finished without a result, and no task context found."
759
+ );
760
+ }
761
+ return finalResult;
762
+ } else {
763
+ return new Promise((resolve, reject) => {
764
+ this._processEvents(taskId, resultManager, eventQueue, context, {
765
+ firstResultResolver: resolve,
766
+ firstResultRejector: reject
767
+ });
768
+ });
769
+ }
770
+ }
771
+ async *sendMessageStream(params, context) {
772
+ const incomingMessage = params.message;
773
+ if (!incomingMessage.messageId) {
774
+ throw A2AError.invalidParams("message.messageId is required for streaming.");
775
+ }
776
+ const resultManager = new ResultManager(this.taskStore, context);
777
+ resultManager.setContext(incomingMessage);
778
+ const requestContext = await this._createRequestContext(incomingMessage, context);
779
+ const taskId = requestContext.taskId;
780
+ const finalMessageForAgent = requestContext.userMessage;
781
+ const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
782
+ const eventQueue = new ExecutionEventQueue(eventBus);
783
+ if (params.configuration?.pushNotificationConfig && this.agentCard.capabilities.pushNotifications) {
784
+ await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
785
+ }
786
+ this.agentExecutor.execute(requestContext, eventBus).catch((err) => {
787
+ console.error(
788
+ `Agent execution failed for stream message ${finalMessageForAgent.messageId}:`,
789
+ err
790
+ );
791
+ const errorTaskStatus = {
792
+ kind: "status-update",
793
+ taskId: requestContext.task?.id || uuidv4(),
794
+ // Use existing or a placeholder
795
+ contextId: finalMessageForAgent.contextId,
796
+ status: {
797
+ state: "failed",
798
+ message: {
799
+ kind: "message",
800
+ role: "agent",
801
+ messageId: uuidv4(),
802
+ parts: [{ kind: "text", text: `Agent execution error: ${err.message}` }],
803
+ taskId: requestContext.task?.id,
804
+ contextId: finalMessageForAgent.contextId
805
+ },
806
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
807
+ },
808
+ final: true
809
+ // This will terminate the stream for the client
810
+ };
811
+ eventBus.publish(errorTaskStatus);
812
+ });
813
+ try {
814
+ for await (const event of eventQueue.events()) {
815
+ await resultManager.processEvent(event);
816
+ await this._sendPushNotificationIfNeeded(event, context);
817
+ yield event;
818
+ }
819
+ } finally {
820
+ this.eventBusManager.cleanupByTaskId(taskId);
821
+ }
822
+ }
823
+ async getTask(params, context) {
824
+ const task = await this.taskStore.load(params.id, context);
825
+ if (!task) {
826
+ throw A2AError.taskNotFound(params.id);
827
+ }
828
+ if (params.historyLength !== void 0 && params.historyLength >= 0) {
829
+ if (task.history) {
830
+ task.history = task.history.slice(-params.historyLength);
831
+ }
832
+ } else {
833
+ task.history = [];
834
+ }
835
+ return task;
836
+ }
837
+ async cancelTask(params, context) {
838
+ const task = await this.taskStore.load(params.id, context);
839
+ if (!task) {
840
+ throw A2AError.taskNotFound(params.id);
841
+ }
842
+ const nonCancelableStates = ["completed", "failed", "canceled", "rejected"];
843
+ if (nonCancelableStates.includes(task.status.state)) {
844
+ throw A2AError.taskNotCancelable(params.id);
845
+ }
846
+ const eventBus = this.eventBusManager.getByTaskId(params.id);
847
+ if (eventBus) {
848
+ const eventQueue = new ExecutionEventQueue(eventBus);
849
+ await this.agentExecutor.cancelTask(params.id, eventBus);
850
+ await this._processEvents(
851
+ params.id,
852
+ new ResultManager(this.taskStore, context),
853
+ eventQueue,
854
+ context
855
+ );
856
+ } else {
857
+ task.status = {
858
+ state: "canceled",
859
+ message: {
860
+ // Optional: Add a system message indicating cancellation
861
+ kind: "message",
862
+ role: "agent",
863
+ messageId: uuidv4(),
864
+ parts: [{ kind: "text", text: "Task cancellation requested by user." }],
865
+ taskId: task.id,
866
+ contextId: task.contextId
867
+ },
868
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
869
+ };
870
+ task.history = [...task.history || [], task.status.message];
871
+ await this.taskStore.save(task, context);
872
+ }
873
+ const latestTask = await this.taskStore.load(params.id, context);
874
+ if (!latestTask) {
875
+ throw A2AError.internalError(`Task ${params.id} not found after cancellation.`);
876
+ }
877
+ if (latestTask.status.state != "canceled") {
878
+ throw A2AError.taskNotCancelable(params.id);
879
+ }
880
+ return latestTask;
881
+ }
882
+ async setTaskPushNotificationConfig(params, context) {
883
+ if (!this.agentCard.capabilities.pushNotifications) {
884
+ throw A2AError.pushNotificationNotSupported();
885
+ }
886
+ const task = await this.taskStore.load(params.taskId, context);
887
+ if (!task) {
888
+ throw A2AError.taskNotFound(params.taskId);
889
+ }
890
+ const { taskId, pushNotificationConfig } = params;
891
+ if (!pushNotificationConfig.id) {
892
+ pushNotificationConfig.id = taskId;
893
+ }
894
+ await this.pushNotificationStore?.save(taskId, pushNotificationConfig);
895
+ return params;
896
+ }
897
+ async getTaskPushNotificationConfig(params, context) {
898
+ if (!this.agentCard.capabilities.pushNotifications) {
899
+ throw A2AError.pushNotificationNotSupported();
900
+ }
901
+ const task = await this.taskStore.load(params.id, context);
902
+ if (!task) {
903
+ throw A2AError.taskNotFound(params.id);
904
+ }
905
+ const configs = await this.pushNotificationStore?.load(params.id) || [];
906
+ if (configs.length === 0) {
907
+ throw A2AError.internalError(`Push notification config not found for task ${params.id}.`);
908
+ }
909
+ let configId;
910
+ if ("pushNotificationConfigId" in params && params.pushNotificationConfigId) {
911
+ configId = params.pushNotificationConfigId;
912
+ } else {
913
+ configId = params.id;
914
+ }
915
+ const config = configs.find((c) => c.id === configId);
916
+ if (!config) {
917
+ throw A2AError.internalError(
918
+ `Push notification config with id '${configId}' not found for task ${params.id}.`
919
+ );
920
+ }
921
+ return { taskId: params.id, pushNotificationConfig: config };
922
+ }
923
+ async listTaskPushNotificationConfigs(params, context) {
924
+ if (!this.agentCard.capabilities.pushNotifications) {
925
+ throw A2AError.pushNotificationNotSupported();
926
+ }
927
+ const task = await this.taskStore.load(params.id, context);
928
+ if (!task) {
929
+ throw A2AError.taskNotFound(params.id);
930
+ }
931
+ const configs = await this.pushNotificationStore?.load(params.id) || [];
932
+ return configs.map((config) => ({
933
+ taskId: params.id,
934
+ pushNotificationConfig: config
935
+ }));
936
+ }
937
+ async deleteTaskPushNotificationConfig(params, context) {
938
+ if (!this.agentCard.capabilities.pushNotifications) {
939
+ throw A2AError.pushNotificationNotSupported();
940
+ }
941
+ const task = await this.taskStore.load(params.id, context);
942
+ if (!task) {
943
+ throw A2AError.taskNotFound(params.id);
944
+ }
945
+ const { id: taskId, pushNotificationConfigId } = params;
946
+ await this.pushNotificationStore?.delete(taskId, pushNotificationConfigId);
947
+ }
948
+ async *resubscribe(params, context) {
949
+ if (!this.agentCard.capabilities.streaming) {
950
+ throw A2AError.unsupportedOperation("Streaming (and thus resubscription) is not supported.");
951
+ }
952
+ const task = await this.taskStore.load(params.id, context);
953
+ if (!task) {
954
+ throw A2AError.taskNotFound(params.id);
955
+ }
956
+ yield task;
957
+ const finalStates = ["completed", "failed", "canceled", "rejected"];
958
+ if (finalStates.includes(task.status.state)) {
959
+ return;
960
+ }
961
+ const eventBus = this.eventBusManager.getByTaskId(params.id);
962
+ if (!eventBus) {
963
+ console.warn(`Resubscribe: No active event bus for task ${params.id}.`);
964
+ return;
965
+ }
966
+ const eventQueue = new ExecutionEventQueue(eventBus);
967
+ try {
968
+ for await (const event of eventQueue.events()) {
969
+ if (event.kind === "status-update" && event.taskId === params.id) {
970
+ yield event;
971
+ } else if (event.kind === "artifact-update" && event.taskId === params.id) {
972
+ yield event;
973
+ } else if (event.kind === "task" && event.id === params.id) {
974
+ yield event;
975
+ }
976
+ }
977
+ } finally {
978
+ eventQueue.stop();
979
+ }
980
+ }
981
+ async _sendPushNotificationIfNeeded(event, context) {
982
+ if (!this.agentCard.capabilities.pushNotifications) {
983
+ return;
984
+ }
985
+ let taskId = "";
986
+ if (event.kind == "task") {
987
+ const task2 = event;
988
+ taskId = task2.id;
989
+ } else {
990
+ taskId = event.taskId;
991
+ }
992
+ if (!taskId) {
993
+ console.error(`Task ID not found for event ${event.kind}.`);
994
+ return;
995
+ }
996
+ const task = await this.taskStore.load(taskId, context);
997
+ if (!task) {
998
+ console.error(`Task ${taskId} not found.`);
999
+ return;
1000
+ }
1001
+ this.pushNotificationSender?.send(task);
1002
+ }
1003
+ async _handleProcessingError(error, resultManager, firstResultSent, taskId, firstResultRejector) {
1004
+ if (firstResultRejector && !firstResultSent) {
1005
+ firstResultRejector(error);
1006
+ return;
1007
+ }
1008
+ if (!firstResultRejector) {
1009
+ throw error;
1010
+ }
1011
+ const currentTask = resultManager.getCurrentTask();
1012
+ const errorMessage = error instanceof Error && error.message || "Unknown error";
1013
+ if (currentTask) {
1014
+ const statusUpdateFailed = {
1015
+ taskId: currentTask.id,
1016
+ contextId: currentTask.contextId,
1017
+ status: {
1018
+ state: "failed",
1019
+ message: {
1020
+ kind: "message",
1021
+ role: "agent",
1022
+ messageId: uuidv4(),
1023
+ parts: [{ kind: "text", text: `Event processing loop failed: ${errorMessage}` }],
1024
+ taskId: currentTask.id,
1025
+ contextId: currentTask.contextId
1026
+ },
1027
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1028
+ },
1029
+ kind: "status-update",
1030
+ final: true
1031
+ };
1032
+ try {
1033
+ await resultManager.processEvent(statusUpdateFailed);
1034
+ } catch (error2) {
1035
+ console.error(
1036
+ `Event processing loop failed for task ${taskId}: ${error2 instanceof Error && error2.message || "Unknown error"}`
1037
+ );
1038
+ }
1039
+ } else {
1040
+ console.error(`Event processing loop failed for task ${taskId}: ${errorMessage}`);
1041
+ }
1042
+ }
1043
+ };
1044
+
1045
+ // src/server/store.ts
1046
+ var InMemoryTaskStore = class {
1047
+ store = /* @__PURE__ */ new Map();
1048
+ async load(taskId) {
1049
+ const entry = this.store.get(taskId);
1050
+ return entry ? { ...entry } : void 0;
1051
+ }
1052
+ async save(task) {
1053
+ this.store.set(task.id, { ...task });
1054
+ }
1055
+ };
1056
+ export {
1057
+ A2AError,
1058
+ DefaultExecutionEventBus,
1059
+ DefaultExecutionEventBusManager,
1060
+ DefaultPushNotificationSender,
1061
+ DefaultRequestHandler,
1062
+ ExecutionEventQueue,
1063
+ InMemoryPushNotificationStore,
1064
+ InMemoryTaskStore,
1065
+ JsonRpcTransportHandler,
1066
+ RequestContext,
1067
+ ResultManager,
1068
+ ServerCallContext,
1069
+ UnauthenticatedUser
1070
+ };