@a2a-js/sdk 0.3.5 → 0.3.6

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.
@@ -29,23 +29,27 @@ __export(server_exports, {
29
29
  InMemoryTaskStore: () => InMemoryTaskStore,
30
30
  JsonRpcTransportHandler: () => JsonRpcTransportHandler,
31
31
  RequestContext: () => RequestContext,
32
- ResultManager: () => ResultManager
32
+ ResultManager: () => ResultManager,
33
+ ServerCallContext: () => ServerCallContext,
34
+ UnauthenticatedUser: () => UnauthenticatedUser
33
35
  });
34
36
  module.exports = __toCommonJS(server_exports);
35
37
 
36
38
  // src/server/agent_execution/request_context.ts
37
39
  var RequestContext = class {
38
40
  userMessage;
39
- task;
40
- referenceTasks;
41
41
  taskId;
42
42
  contextId;
43
- constructor(userMessage, taskId, contextId, task, referenceTasks) {
43
+ task;
44
+ referenceTasks;
45
+ context;
46
+ constructor(userMessage, taskId, contextId, task, referenceTasks, context) {
44
47
  this.userMessage = userMessage;
45
48
  this.taskId = taskId;
46
49
  this.contextId = contextId;
47
50
  this.task = task;
48
51
  this.referenceTasks = referenceTasks;
52
+ this.context = context;
49
53
  }
50
54
  };
51
55
 
@@ -69,7 +73,7 @@ var DefaultExecutionEventBusManager = class {
69
73
  /**
70
74
  * Creates or retrieves an existing ExecutionEventBus based on the taskId.
71
75
  * @param taskId The ID of the task.
72
- * @returns An instance of IExecutionEventBus.
76
+ * @returns An instance of ExecutionEventBus.
73
77
  */
74
78
  createOrGetByTaskId(taskId) {
75
79
  if (!this.taskIdToBus.has(taskId)) {
@@ -80,7 +84,7 @@ var DefaultExecutionEventBusManager = class {
80
84
  /**
81
85
  * Retrieves an existing ExecutionEventBus based on the taskId.
82
86
  * @param taskId The ID of the task.
83
- * @returns An instance of IExecutionEventBus or undefined if not found.
87
+ * @returns An instance of ExecutionEventBus or undefined if not found.
84
88
  */
85
89
  getByTaskId(taskId) {
86
90
  return this.taskIdToBus.get(taskId);
@@ -193,10 +197,7 @@ var A2AError = class _A2AError extends Error {
193
197
  return new _A2AError(-32600, message, data);
194
198
  }
195
199
  static methodNotFound(method) {
196
- return new _A2AError(
197
- -32601,
198
- `Method not found: ${method}`
199
- );
200
+ return new _A2AError(-32601, `Method not found: ${method}`);
200
201
  }
201
202
  static invalidParams(message, data) {
202
203
  return new _A2AError(-32602, message, data);
@@ -205,51 +206,34 @@ var A2AError = class _A2AError extends Error {
205
206
  return new _A2AError(-32603, message, data);
206
207
  }
207
208
  static taskNotFound(taskId) {
208
- return new _A2AError(
209
- -32001,
210
- `Task not found: ${taskId}`,
211
- void 0,
212
- taskId
213
- );
209
+ return new _A2AError(-32001, `Task not found: ${taskId}`, void 0, taskId);
214
210
  }
215
211
  static taskNotCancelable(taskId) {
216
- return new _A2AError(
217
- -32002,
218
- `Task not cancelable: ${taskId}`,
219
- void 0,
220
- taskId
221
- );
212
+ return new _A2AError(-32002, `Task not cancelable: ${taskId}`, void 0, taskId);
222
213
  }
223
214
  static pushNotificationNotSupported() {
224
- return new _A2AError(
225
- -32003,
226
- "Push Notification is not supported"
227
- );
215
+ return new _A2AError(-32003, "Push Notification is not supported");
228
216
  }
229
217
  static unsupportedOperation(operation) {
230
- return new _A2AError(
231
- -32004,
232
- `Unsupported operation: ${operation}`
233
- );
218
+ return new _A2AError(-32004, `Unsupported operation: ${operation}`);
234
219
  }
235
220
  static authenticatedExtendedCardNotConfigured() {
236
- return new _A2AError(
237
- -32007,
238
- `Extended card not configured.`
239
- );
221
+ return new _A2AError(-32007, `Extended card not configured.`);
240
222
  }
241
223
  };
242
224
 
243
225
  // src/server/result_manager.ts
244
226
  var ResultManager = class {
245
227
  taskStore;
228
+ serverCallContext;
246
229
  currentTask;
247
230
  latestUserMessage;
248
231
  // To add to history if a new task is created
249
232
  finalMessageResult;
250
233
  // Stores the message if it's the final result
251
- constructor(taskStore) {
234
+ constructor(taskStore, serverCallContext) {
252
235
  this.taskStore = taskStore;
236
+ this.serverCallContext = serverCallContext;
253
237
  }
254
238
  setContext(latestUserMessage) {
255
239
  this.latestUserMessage = latestUserMessage;
@@ -265,7 +249,9 @@ var ResultManager = class {
265
249
  const taskEvent = event;
266
250
  this.currentTask = { ...taskEvent };
267
251
  if (this.latestUserMessage) {
268
- if (!this.currentTask.history?.find((msg) => msg.messageId === this.latestUserMessage.messageId)) {
252
+ if (!this.currentTask.history?.find(
253
+ (msg) => msg.messageId === this.latestUserMessage.messageId
254
+ )) {
269
255
  this.currentTask.history = [this.latestUserMessage, ...this.currentTask.history || []];
270
256
  }
271
257
  }
@@ -275,24 +261,36 @@ var ResultManager = class {
275
261
  if (this.currentTask && this.currentTask.id === updateEvent.taskId) {
276
262
  this.currentTask.status = updateEvent.status;
277
263
  if (updateEvent.status.message) {
278
- if (!this.currentTask.history?.find((msg) => msg.messageId === updateEvent.status.message.messageId)) {
279
- this.currentTask.history = [...this.currentTask.history || [], updateEvent.status.message];
264
+ if (!this.currentTask.history?.find(
265
+ (msg) => msg.messageId === updateEvent.status.message.messageId
266
+ )) {
267
+ this.currentTask.history = [
268
+ ...this.currentTask.history || [],
269
+ updateEvent.status.message
270
+ ];
280
271
  }
281
272
  }
282
273
  await this.saveCurrentTask();
283
274
  } else if (!this.currentTask && updateEvent.taskId) {
284
- const loaded = await this.taskStore.load(updateEvent.taskId);
275
+ const loaded = await this.taskStore.load(updateEvent.taskId, this.serverCallContext);
285
276
  if (loaded) {
286
277
  this.currentTask = loaded;
287
278
  this.currentTask.status = updateEvent.status;
288
279
  if (updateEvent.status.message) {
289
- if (!this.currentTask.history?.find((msg) => msg.messageId === updateEvent.status.message.messageId)) {
290
- this.currentTask.history = [...this.currentTask.history || [], updateEvent.status.message];
280
+ if (!this.currentTask.history?.find(
281
+ (msg) => msg.messageId === updateEvent.status.message.messageId
282
+ )) {
283
+ this.currentTask.history = [
284
+ ...this.currentTask.history || [],
285
+ updateEvent.status.message
286
+ ];
291
287
  }
292
288
  }
293
289
  await this.saveCurrentTask();
294
290
  } else {
295
- console.warn(`ResultManager: Received status update for unknown task ${updateEvent.taskId}`);
291
+ console.warn(
292
+ `ResultManager: Received status update for unknown task ${updateEvent.taskId}`
293
+ );
296
294
  }
297
295
  }
298
296
  } else if (event.kind === "artifact-update") {
@@ -308,9 +306,14 @@ var ResultManager = class {
308
306
  if (artifactEvent.append) {
309
307
  const existingArtifact = this.currentTask.artifacts[existingArtifactIndex];
310
308
  existingArtifact.parts.push(...artifactEvent.artifact.parts);
311
- if (artifactEvent.artifact.description) existingArtifact.description = artifactEvent.artifact.description;
309
+ if (artifactEvent.artifact.description)
310
+ existingArtifact.description = artifactEvent.artifact.description;
312
311
  if (artifactEvent.artifact.name) existingArtifact.name = artifactEvent.artifact.name;
313
- if (artifactEvent.artifact.metadata) existingArtifact.metadata = { ...existingArtifact.metadata, ...artifactEvent.artifact.metadata };
312
+ if (artifactEvent.artifact.metadata)
313
+ existingArtifact.metadata = {
314
+ ...existingArtifact.metadata,
315
+ ...artifactEvent.artifact.metadata
316
+ };
314
317
  } else {
315
318
  this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
316
319
  }
@@ -319,7 +322,7 @@ var ResultManager = class {
319
322
  }
320
323
  await this.saveCurrentTask();
321
324
  } else if (!this.currentTask && artifactEvent.taskId) {
322
- const loaded = await this.taskStore.load(artifactEvent.taskId);
325
+ const loaded = await this.taskStore.load(artifactEvent.taskId, this.serverCallContext);
323
326
  if (loaded) {
324
327
  this.currentTask = loaded;
325
328
  if (!this.currentTask.artifacts) this.currentTask.artifacts = [];
@@ -328,7 +331,9 @@ var ResultManager = class {
328
331
  );
329
332
  if (existingArtifactIndex !== -1) {
330
333
  if (artifactEvent.append) {
331
- this.currentTask.artifacts[existingArtifactIndex].parts.push(...artifactEvent.artifact.parts);
334
+ this.currentTask.artifacts[existingArtifactIndex].parts.push(
335
+ ...artifactEvent.artifact.parts
336
+ );
332
337
  } else {
333
338
  this.currentTask.artifacts[existingArtifactIndex] = artifactEvent.artifact;
334
339
  }
@@ -337,14 +342,16 @@ var ResultManager = class {
337
342
  }
338
343
  await this.saveCurrentTask();
339
344
  } else {
340
- console.warn(`ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`);
345
+ console.warn(
346
+ `ResultManager: Received artifact update for unknown task ${artifactEvent.taskId}`
347
+ );
341
348
  }
342
349
  }
343
350
  }
344
351
  }
345
352
  async saveCurrentTask() {
346
353
  if (this.currentTask) {
347
- await this.taskStore.save(this.currentTask);
354
+ await this.taskStore.save(this.currentTask, this.serverCallContext);
348
355
  }
349
356
  }
350
357
  /**
@@ -432,7 +439,10 @@ var DefaultPushNotificationSender = class {
432
439
  try {
433
440
  await this._dispatchNotification(task, pushConfig);
434
441
  } catch (error) {
435
- console.error(`Error sending push notification for task_id=${task.id} to URL: ${pushConfig.url}. Error:`, error);
442
+ console.error(
443
+ `Error sending push notification for task_id=${task.id} to URL: ${pushConfig.url}. Error:`,
444
+ error
445
+ );
436
446
  }
437
447
  });
438
448
  await Promise.all(dispatches);
@@ -471,22 +481,80 @@ var DefaultPushNotificationSender = class {
471
481
  }
472
482
  };
473
483
 
484
+ // src/extensions.ts
485
+ var Extensions = {
486
+ /**
487
+ * Creates new {@link Extensions} from `current` and `additional`.
488
+ * If `current` already contains `additional` it is returned unmodified.
489
+ */
490
+ createFrom: (current, additional) => {
491
+ if (current?.includes(additional)) {
492
+ return current;
493
+ }
494
+ return [...current ?? [], additional];
495
+ },
496
+ /**
497
+ * Creates {@link Extensions} from comma separated extensions identifiers as per
498
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
499
+ * Parses the output of `toServiceParameter`.
500
+ */
501
+ parseServiceParameter: (value) => {
502
+ if (!value) {
503
+ return [];
504
+ }
505
+ const unique = new Set(
506
+ value.split(",").map((ext) => ext.trim()).filter((ext) => ext.length > 0)
507
+ );
508
+ return Array.from(unique);
509
+ },
510
+ /**
511
+ * Converts {@link Extensions} to comma separated extensions identifiers as per
512
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
513
+ */
514
+ toServiceParameter: (value) => {
515
+ return value.join(",");
516
+ }
517
+ };
518
+
519
+ // src/server/context.ts
520
+ var ServerCallContext = class {
521
+ _requestedExtensions;
522
+ _user;
523
+ _activatedExtensions;
524
+ constructor(requestedExtensions, user) {
525
+ this._requestedExtensions = requestedExtensions;
526
+ this._user = user;
527
+ }
528
+ get user() {
529
+ return this._user;
530
+ }
531
+ get activatedExtensions() {
532
+ return this._activatedExtensions;
533
+ }
534
+ get requestedExtensions() {
535
+ return this._requestedExtensions;
536
+ }
537
+ addActivatedExtension(uri) {
538
+ this._activatedExtensions = Extensions.createFrom(this._activatedExtensions, uri);
539
+ }
540
+ };
541
+
474
542
  // src/server/request_handler/default_request_handler.ts
475
543
  var terminalStates = ["completed", "failed", "canceled", "rejected"];
476
544
  var DefaultRequestHandler = class {
477
545
  agentCard;
478
- extendedAgentCard;
479
546
  taskStore;
480
547
  agentExecutor;
481
548
  eventBusManager;
482
549
  pushNotificationStore;
483
550
  pushNotificationSender;
484
- constructor(agentCard, taskStore, agentExecutor, eventBusManager = new DefaultExecutionEventBusManager(), pushNotificationStore, pushNotificationSender, extendedAgentCard) {
551
+ extendedAgentCardProvider;
552
+ constructor(agentCard, taskStore, agentExecutor, eventBusManager = new DefaultExecutionEventBusManager(), pushNotificationStore, pushNotificationSender, extendedAgentCardProvider) {
485
553
  this.agentCard = agentCard;
486
554
  this.taskStore = taskStore;
487
555
  this.agentExecutor = agentExecutor;
488
556
  this.eventBusManager = eventBusManager;
489
- this.extendedAgentCard = extendedAgentCard;
557
+ this.extendedAgentCardProvider = extendedAgentCardProvider;
490
558
  if (agentCard.capabilities.pushNotifications) {
491
559
  this.pushNotificationStore = pushNotificationStore || new InMemoryPushNotificationStore();
492
560
  this.pushNotificationSender = pushNotificationSender || new DefaultPushNotificationSender(this.pushNotificationStore);
@@ -495,30 +563,42 @@ var DefaultRequestHandler = class {
495
563
  async getAgentCard() {
496
564
  return this.agentCard;
497
565
  }
498
- async getAuthenticatedExtendedAgentCard() {
499
- if (!this.extendedAgentCard) {
566
+ async getAuthenticatedExtendedAgentCard(context) {
567
+ if (!this.agentCard.supportsAuthenticatedExtendedCard) {
568
+ throw A2AError.unsupportedOperation("Agent does not support authenticated extended card.");
569
+ }
570
+ if (!this.extendedAgentCardProvider) {
500
571
  throw A2AError.authenticatedExtendedCardNotConfigured();
501
572
  }
502
- return this.extendedAgentCard;
573
+ if (typeof this.extendedAgentCardProvider === "function") {
574
+ return this.extendedAgentCardProvider(context);
575
+ }
576
+ if (context?.user?.isAuthenticated) {
577
+ return this.extendedAgentCardProvider;
578
+ }
579
+ return this.agentCard;
503
580
  }
504
- async _createRequestContext(incomingMessage, taskId, isStream) {
581
+ async _createRequestContext(incomingMessage, context) {
505
582
  let task;
506
583
  let referenceTasks;
507
584
  if (incomingMessage.taskId) {
508
- task = await this.taskStore.load(incomingMessage.taskId);
585
+ task = await this.taskStore.load(incomingMessage.taskId, context);
509
586
  if (!task) {
510
587
  throw A2AError.taskNotFound(incomingMessage.taskId);
511
588
  }
512
589
  if (terminalStates.includes(task.status.state)) {
513
- throw A2AError.invalidRequest(`Task ${task.id} is in a terminal state (${task.status.state}) and cannot be modified.`);
590
+ throw A2AError.invalidRequest(
591
+ `Task ${task.id} is in a terminal state (${task.status.state}) and cannot be modified.`
592
+ );
514
593
  }
515
594
  task.history = [...task.history || [], incomingMessage];
516
- await this.taskStore.save(task);
595
+ await this.taskStore.save(task, context);
517
596
  }
597
+ const taskId = incomingMessage.taskId || (0, import_uuid.v4)();
518
598
  if (incomingMessage.referenceTaskIds && incomingMessage.referenceTaskIds.length > 0) {
519
599
  referenceTasks = [];
520
600
  for (const refId of incomingMessage.referenceTaskIds) {
521
- const refTask = await this.taskStore.load(refId);
601
+ const refTask = await this.taskStore.load(refId, context);
522
602
  if (refTask) {
523
603
  referenceTasks.push(refTask);
524
604
  } else {
@@ -527,24 +607,33 @@ var DefaultRequestHandler = class {
527
607
  }
528
608
  }
529
609
  const contextId = incomingMessage.contextId || task?.contextId || (0, import_uuid.v4)();
610
+ if (context?.requestedExtensions) {
611
+ const agentCard = await this.getAgentCard();
612
+ const exposedExtensions = new Set(
613
+ agentCard.capabilities.extensions?.map((ext) => ext.uri) || []
614
+ );
615
+ const validExtensions = context.requestedExtensions.filter(
616
+ (extension) => exposedExtensions.has(extension)
617
+ );
618
+ context = new ServerCallContext(validExtensions, context.user);
619
+ }
530
620
  const messageForContext = {
531
621
  ...incomingMessage,
532
- contextId
533
- };
534
- return new RequestContext(
535
- messageForContext,
536
- taskId,
537
622
  contextId,
538
- task,
539
- referenceTasks
540
- );
623
+ taskId
624
+ };
625
+ return new RequestContext(messageForContext, taskId, contextId, task, referenceTasks, context);
541
626
  }
542
- async _processEvents(taskId, resultManager, eventQueue, options) {
627
+ async _processEvents(taskId, resultManager, eventQueue, context, options) {
543
628
  let firstResultSent = false;
544
629
  try {
545
630
  for await (const event of eventQueue.events()) {
546
631
  await resultManager.processEvent(event);
547
- await this._sendPushNotificationIfNeeded(event);
632
+ try {
633
+ await this._sendPushNotificationIfNeeded(event, context);
634
+ } catch (error) {
635
+ console.error(`Error sending push notification: ${error}`);
636
+ }
548
637
  if (options?.firstResultResolver && !firstResultSent) {
549
638
  let firstResult;
550
639
  if (event.kind === "message") {
@@ -559,28 +648,33 @@ var DefaultRequestHandler = class {
559
648
  }
560
649
  }
561
650
  if (options?.firstResultRejector && !firstResultSent) {
562
- options.firstResultRejector(A2AError.internalError("Execution finished before a message or task was produced."));
651
+ options.firstResultRejector(
652
+ A2AError.internalError("Execution finished before a message or task was produced.")
653
+ );
563
654
  }
564
655
  } catch (error) {
565
656
  console.error(`Event processing loop failed for task ${taskId}:`, error);
566
- if (options?.firstResultRejector && !firstResultSent) {
567
- options.firstResultRejector(error);
568
- }
569
- throw error;
657
+ this._handleProcessingError(
658
+ error,
659
+ resultManager,
660
+ firstResultSent,
661
+ taskId,
662
+ options?.firstResultRejector
663
+ );
570
664
  } finally {
571
665
  this.eventBusManager.cleanupByTaskId(taskId);
572
666
  }
573
667
  }
574
- async sendMessage(params) {
668
+ async sendMessage(params, context) {
575
669
  const incomingMessage = params.message;
576
670
  if (!incomingMessage.messageId) {
577
671
  throw A2AError.invalidParams("message.messageId is required.");
578
672
  }
579
673
  const isBlocking = params.configuration?.blocking !== false;
580
- const taskId = incomingMessage.taskId || (0, import_uuid.v4)();
581
- const resultManager = new ResultManager(this.taskStore);
674
+ const resultManager = new ResultManager(this.taskStore, context);
582
675
  resultManager.setContext(incomingMessage);
583
- const requestContext = await this._createRequestContext(incomingMessage, taskId, false);
676
+ const requestContext = await this._createRequestContext(incomingMessage, context);
677
+ const taskId = requestContext.taskId;
584
678
  const finalMessageForAgent = requestContext.userMessage;
585
679
  if (params.configuration?.pushNotificationConfig && this.agentCard.capabilities.pushNotifications) {
586
680
  await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
@@ -625,30 +719,32 @@ var DefaultRequestHandler = class {
625
719
  eventBus.finished();
626
720
  });
627
721
  if (isBlocking) {
628
- await this._processEvents(taskId, resultManager, eventQueue);
722
+ await this._processEvents(taskId, resultManager, eventQueue, context);
629
723
  const finalResult = resultManager.getFinalResult();
630
724
  if (!finalResult) {
631
- throw A2AError.internalError("Agent execution finished without a result, and no task context found.");
725
+ throw A2AError.internalError(
726
+ "Agent execution finished without a result, and no task context found."
727
+ );
632
728
  }
633
729
  return finalResult;
634
730
  } else {
635
731
  return new Promise((resolve, reject) => {
636
- this._processEvents(taskId, resultManager, eventQueue, {
732
+ this._processEvents(taskId, resultManager, eventQueue, context, {
637
733
  firstResultResolver: resolve,
638
734
  firstResultRejector: reject
639
735
  });
640
736
  });
641
737
  }
642
738
  }
643
- async *sendMessageStream(params) {
739
+ async *sendMessageStream(params, context) {
644
740
  const incomingMessage = params.message;
645
741
  if (!incomingMessage.messageId) {
646
742
  throw A2AError.invalidParams("message.messageId is required for streaming.");
647
743
  }
648
- const taskId = incomingMessage.taskId || (0, import_uuid.v4)();
649
- const resultManager = new ResultManager(this.taskStore);
744
+ const resultManager = new ResultManager(this.taskStore, context);
650
745
  resultManager.setContext(incomingMessage);
651
- const requestContext = await this._createRequestContext(incomingMessage, taskId, true);
746
+ const requestContext = await this._createRequestContext(incomingMessage, context);
747
+ const taskId = requestContext.taskId;
652
748
  const finalMessageForAgent = requestContext.userMessage;
653
749
  const eventBus = this.eventBusManager.createOrGetByTaskId(taskId);
654
750
  const eventQueue = new ExecutionEventQueue(eventBus);
@@ -656,7 +752,10 @@ var DefaultRequestHandler = class {
656
752
  await this.pushNotificationStore?.save(taskId, params.configuration.pushNotificationConfig);
657
753
  }
658
754
  this.agentExecutor.execute(requestContext, eventBus).catch((err) => {
659
- console.error(`Agent execution failed for stream message ${finalMessageForAgent.messageId}:`, err);
755
+ console.error(
756
+ `Agent execution failed for stream message ${finalMessageForAgent.messageId}:`,
757
+ err
758
+ );
660
759
  const errorTaskStatus = {
661
760
  kind: "status-update",
662
761
  taskId: requestContext.task?.id || (0, import_uuid.v4)(),
@@ -682,15 +781,15 @@ var DefaultRequestHandler = class {
682
781
  try {
683
782
  for await (const event of eventQueue.events()) {
684
783
  await resultManager.processEvent(event);
685
- await this._sendPushNotificationIfNeeded(event);
784
+ await this._sendPushNotificationIfNeeded(event, context);
686
785
  yield event;
687
786
  }
688
787
  } finally {
689
788
  this.eventBusManager.cleanupByTaskId(taskId);
690
789
  }
691
790
  }
692
- async getTask(params) {
693
- const task = await this.taskStore.load(params.id);
791
+ async getTask(params, context) {
792
+ const task = await this.taskStore.load(params.id, context);
694
793
  if (!task) {
695
794
  throw A2AError.taskNotFound(params.id);
696
795
  }
@@ -703,8 +802,8 @@ var DefaultRequestHandler = class {
703
802
  }
704
803
  return task;
705
804
  }
706
- async cancelTask(params) {
707
- const task = await this.taskStore.load(params.id);
805
+ async cancelTask(params, context) {
806
+ const task = await this.taskStore.load(params.id, context);
708
807
  if (!task) {
709
808
  throw A2AError.taskNotFound(params.id);
710
809
  }
@@ -716,7 +815,12 @@ var DefaultRequestHandler = class {
716
815
  if (eventBus) {
717
816
  const eventQueue = new ExecutionEventQueue(eventBus);
718
817
  await this.agentExecutor.cancelTask(params.id, eventBus);
719
- await this._processEvents(params.id, new ResultManager(this.taskStore), eventQueue);
818
+ await this._processEvents(
819
+ params.id,
820
+ new ResultManager(this.taskStore, context),
821
+ eventQueue,
822
+ context
823
+ );
720
824
  } else {
721
825
  task.status = {
722
826
  state: "canceled",
@@ -732,9 +836,9 @@ var DefaultRequestHandler = class {
732
836
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
733
837
  };
734
838
  task.history = [...task.history || [], task.status.message];
735
- await this.taskStore.save(task);
839
+ await this.taskStore.save(task, context);
736
840
  }
737
- const latestTask = await this.taskStore.load(params.id);
841
+ const latestTask = await this.taskStore.load(params.id, context);
738
842
  if (!latestTask) {
739
843
  throw A2AError.internalError(`Task ${params.id} not found after cancellation.`);
740
844
  }
@@ -743,11 +847,11 @@ var DefaultRequestHandler = class {
743
847
  }
744
848
  return latestTask;
745
849
  }
746
- async setTaskPushNotificationConfig(params) {
850
+ async setTaskPushNotificationConfig(params, context) {
747
851
  if (!this.agentCard.capabilities.pushNotifications) {
748
852
  throw A2AError.pushNotificationNotSupported();
749
853
  }
750
- const task = await this.taskStore.load(params.taskId);
854
+ const task = await this.taskStore.load(params.taskId, context);
751
855
  if (!task) {
752
856
  throw A2AError.taskNotFound(params.taskId);
753
857
  }
@@ -758,11 +862,11 @@ var DefaultRequestHandler = class {
758
862
  await this.pushNotificationStore?.save(taskId, pushNotificationConfig);
759
863
  return params;
760
864
  }
761
- async getTaskPushNotificationConfig(params) {
865
+ async getTaskPushNotificationConfig(params, context) {
762
866
  if (!this.agentCard.capabilities.pushNotifications) {
763
867
  throw A2AError.pushNotificationNotSupported();
764
868
  }
765
- const task = await this.taskStore.load(params.id);
869
+ const task = await this.taskStore.load(params.id, context);
766
870
  if (!task) {
767
871
  throw A2AError.taskNotFound(params.id);
768
872
  }
@@ -778,15 +882,17 @@ var DefaultRequestHandler = class {
778
882
  }
779
883
  const config = configs.find((c) => c.id === configId);
780
884
  if (!config) {
781
- throw A2AError.internalError(`Push notification config with id '${configId}' not found for task ${params.id}.`);
885
+ throw A2AError.internalError(
886
+ `Push notification config with id '${configId}' not found for task ${params.id}.`
887
+ );
782
888
  }
783
889
  return { taskId: params.id, pushNotificationConfig: config };
784
890
  }
785
- async listTaskPushNotificationConfigs(params) {
891
+ async listTaskPushNotificationConfigs(params, context) {
786
892
  if (!this.agentCard.capabilities.pushNotifications) {
787
893
  throw A2AError.pushNotificationNotSupported();
788
894
  }
789
- const task = await this.taskStore.load(params.id);
895
+ const task = await this.taskStore.load(params.id, context);
790
896
  if (!task) {
791
897
  throw A2AError.taskNotFound(params.id);
792
898
  }
@@ -796,22 +902,22 @@ var DefaultRequestHandler = class {
796
902
  pushNotificationConfig: config
797
903
  }));
798
904
  }
799
- async deleteTaskPushNotificationConfig(params) {
905
+ async deleteTaskPushNotificationConfig(params, context) {
800
906
  if (!this.agentCard.capabilities.pushNotifications) {
801
907
  throw A2AError.pushNotificationNotSupported();
802
908
  }
803
- const task = await this.taskStore.load(params.id);
909
+ const task = await this.taskStore.load(params.id, context);
804
910
  if (!task) {
805
911
  throw A2AError.taskNotFound(params.id);
806
912
  }
807
913
  const { id: taskId, pushNotificationConfigId } = params;
808
914
  await this.pushNotificationStore?.delete(taskId, pushNotificationConfigId);
809
915
  }
810
- async *resubscribe(params) {
916
+ async *resubscribe(params, context) {
811
917
  if (!this.agentCard.capabilities.streaming) {
812
918
  throw A2AError.unsupportedOperation("Streaming (and thus resubscription) is not supported.");
813
919
  }
814
- const task = await this.taskStore.load(params.id);
920
+ const task = await this.taskStore.load(params.id, context);
815
921
  if (!task) {
816
922
  throw A2AError.taskNotFound(params.id);
817
923
  }
@@ -840,7 +946,7 @@ var DefaultRequestHandler = class {
840
946
  eventQueue.stop();
841
947
  }
842
948
  }
843
- async _sendPushNotificationIfNeeded(event) {
949
+ async _sendPushNotificationIfNeeded(event, context) {
844
950
  if (!this.agentCard.capabilities.pushNotifications) {
845
951
  return;
846
952
  }
@@ -855,13 +961,53 @@ var DefaultRequestHandler = class {
855
961
  console.error(`Task ID not found for event ${event.kind}.`);
856
962
  return;
857
963
  }
858
- const task = await this.taskStore.load(taskId);
964
+ const task = await this.taskStore.load(taskId, context);
859
965
  if (!task) {
860
966
  console.error(`Task ${taskId} not found.`);
861
967
  return;
862
968
  }
863
969
  this.pushNotificationSender?.send(task);
864
970
  }
971
+ async _handleProcessingError(error, resultManager, firstResultSent, taskId, firstResultRejector) {
972
+ if (firstResultRejector && !firstResultSent) {
973
+ firstResultRejector(error);
974
+ return;
975
+ }
976
+ if (!firstResultRejector) {
977
+ throw error;
978
+ }
979
+ const currentTask = resultManager.getCurrentTask();
980
+ const errorMessage = error instanceof Error && error.message || "Unknown error";
981
+ if (currentTask) {
982
+ const statusUpdateFailed = {
983
+ taskId: currentTask.id,
984
+ contextId: currentTask.contextId,
985
+ status: {
986
+ state: "failed",
987
+ message: {
988
+ kind: "message",
989
+ role: "agent",
990
+ messageId: (0, import_uuid.v4)(),
991
+ parts: [{ kind: "text", text: `Event processing loop failed: ${errorMessage}` }],
992
+ taskId: currentTask.id,
993
+ contextId: currentTask.contextId
994
+ },
995
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
996
+ },
997
+ kind: "status-update",
998
+ final: true
999
+ };
1000
+ try {
1001
+ await resultManager.processEvent(statusUpdateFailed);
1002
+ } catch (error2) {
1003
+ console.error(
1004
+ `Event processing loop failed for task ${taskId}: ${error2 instanceof Error && error2.message || "Unknown error"}`
1005
+ );
1006
+ }
1007
+ } else {
1008
+ console.error(`Event processing loop failed for task ${taskId}: ${errorMessage}`);
1009
+ }
1010
+ }
865
1011
  };
866
1012
 
867
1013
  // src/server/store.ts
@@ -876,7 +1022,7 @@ var InMemoryTaskStore = class {
876
1022
  }
877
1023
  };
878
1024
 
879
- // src/server/transports/jsonrpc_transport_handler.ts
1025
+ // src/server/transports/jsonrpc/jsonrpc_transport_handler.ts
880
1026
  var JsonRpcTransportHandler = class {
881
1027
  requestHandler;
882
1028
  constructor(requestHandler) {
@@ -887,7 +1033,7 @@ var JsonRpcTransportHandler = class {
887
1033
  * For streaming methods, it returns an AsyncGenerator of JSONRPCResult.
888
1034
  * For non-streaming methods, it returns a Promise of a single JSONRPCMessage (Result or ErrorResponse).
889
1035
  */
890
- async handle(requestBody) {
1036
+ async handle(requestBody, context) {
891
1037
  let rpcRequest;
892
1038
  try {
893
1039
  if (typeof requestBody === "string") {
@@ -901,24 +1047,18 @@ var JsonRpcTransportHandler = class {
901
1047
  throw A2AError.invalidRequest("Invalid JSON-RPC Request.");
902
1048
  }
903
1049
  } catch (error) {
904
- const a2aError = error instanceof A2AError ? error : A2AError.parseError(error.message || "Failed to parse JSON request.");
1050
+ const a2aError = error instanceof A2AError ? error : A2AError.parseError(
1051
+ error instanceof SyntaxError && error.message || "Failed to parse JSON request."
1052
+ );
905
1053
  return {
906
1054
  jsonrpc: "2.0",
907
- id: typeof rpcRequest?.id !== "undefined" ? rpcRequest.id : null,
1055
+ id: rpcRequest?.id !== void 0 ? rpcRequest.id : null,
908
1056
  error: a2aError.toJSONRPCError()
909
1057
  };
910
1058
  }
911
1059
  const { method, id: requestId = null } = rpcRequest;
912
1060
  try {
913
- if (method === "agent/getAuthenticatedExtendedCard") {
914
- const result = await this.requestHandler.getAuthenticatedExtendedAgentCard();
915
- return {
916
- jsonrpc: "2.0",
917
- id: requestId,
918
- result
919
- };
920
- }
921
- if (!this.paramsAreValid(rpcRequest.params)) {
1061
+ if (method !== "agent/getAuthenticatedExtendedCard" && !this.paramsAreValid(rpcRequest.params)) {
922
1062
  throw A2AError.invalidParams(`Invalid method parameters.`);
923
1063
  }
924
1064
  if (method === "message/stream" || method === "tasks/resubscribe") {
@@ -927,8 +1067,8 @@ var JsonRpcTransportHandler = class {
927
1067
  if (!agentCard.capabilities.streaming) {
928
1068
  throw A2AError.unsupportedOperation(`Method ${method} requires streaming capability.`);
929
1069
  }
930
- const agentEventStream = method === "message/stream" ? this.requestHandler.sendMessageStream(params) : this.requestHandler.resubscribe(params);
931
- return async function* jsonRpcEventStream() {
1070
+ const agentEventStream = method === "message/stream" ? this.requestHandler.sendMessageStream(params, context) : this.requestHandler.resubscribe(params, context);
1071
+ return (async function* jsonRpcEventStream() {
932
1072
  try {
933
1073
  for await (const event of agentEventStream) {
934
1074
  yield {
@@ -939,43 +1079,50 @@ var JsonRpcTransportHandler = class {
939
1079
  };
940
1080
  }
941
1081
  } catch (streamError) {
942
- console.error(`Error in agent event stream for ${method} (request ${requestId}):`, streamError);
1082
+ console.error(
1083
+ `Error in agent event stream for ${method} (request ${requestId}):`,
1084
+ streamError
1085
+ );
943
1086
  throw streamError;
944
1087
  }
945
- }();
1088
+ })();
946
1089
  } else {
947
1090
  let result;
948
1091
  switch (method) {
949
1092
  case "message/send":
950
- result = await this.requestHandler.sendMessage(rpcRequest.params);
1093
+ result = await this.requestHandler.sendMessage(rpcRequest.params, context);
951
1094
  break;
952
1095
  case "tasks/get":
953
- result = await this.requestHandler.getTask(rpcRequest.params);
1096
+ result = await this.requestHandler.getTask(rpcRequest.params, context);
954
1097
  break;
955
1098
  case "tasks/cancel":
956
- result = await this.requestHandler.cancelTask(rpcRequest.params);
1099
+ result = await this.requestHandler.cancelTask(rpcRequest.params, context);
957
1100
  break;
958
1101
  case "tasks/pushNotificationConfig/set":
959
1102
  result = await this.requestHandler.setTaskPushNotificationConfig(
960
- rpcRequest.params
1103
+ rpcRequest.params,
1104
+ context
961
1105
  );
962
1106
  break;
963
1107
  case "tasks/pushNotificationConfig/get":
964
1108
  result = await this.requestHandler.getTaskPushNotificationConfig(
965
- rpcRequest.params
1109
+ rpcRequest.params,
1110
+ context
966
1111
  );
967
1112
  break;
968
1113
  case "tasks/pushNotificationConfig/delete":
969
- await this.requestHandler.deleteTaskPushNotificationConfig(
970
- rpcRequest.params
971
- );
1114
+ await this.requestHandler.deleteTaskPushNotificationConfig(rpcRequest.params, context);
972
1115
  result = null;
973
1116
  break;
974
1117
  case "tasks/pushNotificationConfig/list":
975
1118
  result = await this.requestHandler.listTaskPushNotificationConfigs(
976
- rpcRequest.params
1119
+ rpcRequest.params,
1120
+ context
977
1121
  );
978
1122
  break;
1123
+ case "agent/getAuthenticatedExtendedCard":
1124
+ result = await this.requestHandler.getAuthenticatedExtendedAgentCard(context);
1125
+ break;
979
1126
  default:
980
1127
  throw A2AError.methodNotFound(method);
981
1128
  }
@@ -986,7 +1133,14 @@ var JsonRpcTransportHandler = class {
986
1133
  };
987
1134
  }
988
1135
  } catch (error) {
989
- const a2aError = error instanceof A2AError ? error : A2AError.internalError(error.message || "An unexpected error occurred.");
1136
+ let a2aError;
1137
+ if (error instanceof A2AError) {
1138
+ a2aError = error;
1139
+ } else {
1140
+ a2aError = A2AError.internalError(
1141
+ error instanceof Error && error.message || "An unexpected error occurred."
1142
+ );
1143
+ }
990
1144
  return {
991
1145
  jsonrpc: "2.0",
992
1146
  id: requestId,
@@ -1026,6 +1180,16 @@ var JsonRpcTransportHandler = class {
1026
1180
  return true;
1027
1181
  }
1028
1182
  };
1183
+
1184
+ // src/server/authentication/user.ts
1185
+ var UnauthenticatedUser = class {
1186
+ get isAuthenticated() {
1187
+ return false;
1188
+ }
1189
+ get userName() {
1190
+ return "";
1191
+ }
1192
+ };
1029
1193
  // Annotate the CommonJS export names for ESM import in node:
1030
1194
  0 && (module.exports = {
1031
1195
  A2AError,
@@ -1038,5 +1202,7 @@ var JsonRpcTransportHandler = class {
1038
1202
  InMemoryTaskStore,
1039
1203
  JsonRpcTransportHandler,
1040
1204
  RequestContext,
1041
- ResultManager
1205
+ ResultManager,
1206
+ ServerCallContext,
1207
+ UnauthenticatedUser
1042
1208
  });