@axiom-lattice/gateway 2.1.89 → 2.1.90

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,779 @@
1
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
2
+ import { v4 } from "uuid";
3
+ import {
4
+ agentInstanceManager,
5
+ } from "@axiom-lattice/core";
6
+ import { MessageChunkTypes } from "@axiom-lattice/protocols";
7
+ import type {
8
+ AgentCard,
9
+ A2ATask,
10
+ A2ATaskState,
11
+ A2ATaskSendRequest,
12
+ A2AMessage,
13
+ A2APart,
14
+ A2AAuthContext,
15
+ A2AApiKeyStore,
16
+ A2AApiKeyRecord,
17
+ CreateA2AApiKeyInput,
18
+ A2AApiKeyEntry,
19
+ } from "@axiom-lattice/protocols";
20
+
21
+ // ─── Task Tracking ────────────────────────────────────────────────────────
22
+
23
+ interface TaskRecord {
24
+ id: string;
25
+ threadId: string;
26
+ messageId?: string;
27
+ assistantId: string;
28
+ tenantId: string;
29
+ projectId?: string;
30
+ workspaceId?: string;
31
+ status: A2ATaskState;
32
+ createdAt: string;
33
+ updatedAt: string;
34
+ history: A2AMessage[];
35
+ }
36
+
37
+ const taskStore = new Map<string, TaskRecord>();
38
+
39
+ // ─── Key Store ────────────────────────────────────────────────────────────
40
+
41
+ let _a2aKeyStore: A2AApiKeyStore | null = null;
42
+ let _storeKeyMap: Map<string, A2AApiKeyEntry> = new Map();
43
+
44
+ export function setA2AKeyStore(store: A2AApiKeyStore): void {
45
+ _a2aKeyStore = store;
46
+ }
47
+
48
+ /**
49
+ * Reload the cached key map from the store.
50
+ * Call after any CRUD mutation or at startup.
51
+ */
52
+ export async function refreshStoreKeyMap(): Promise<void> {
53
+ if (!_a2aKeyStore) return;
54
+ _storeKeyMap = await _a2aKeyStore.loadIntoMap();
55
+ }
56
+
57
+ // ─── Config ───────────────────────────────────────────────────────────────
58
+
59
+ function parseEnvKeyMap(): Map<string, A2AApiKeyEntry> {
60
+ const keysEnv = process.env.A2A_API_KEYS || "";
61
+ const defaultTenantId = process.env.A2A_DEFAULT_TENANT_ID || "a2a-default-tenant";
62
+ const defaultProjectId = process.env.A2A_DEFAULT_PROJECT_ID || "";
63
+ const defaultWorkspaceId = process.env.A2A_DEFAULT_WORKSPACE_ID || "";
64
+ const map = new Map<string, A2AApiKeyEntry>();
65
+
66
+ if (keysEnv) {
67
+ keysEnv.split(",").forEach((entry) => {
68
+ const trimmed = entry.trim();
69
+ if (!trimmed) return;
70
+ const parts = trimmed.split(":");
71
+ const key = parts[0];
72
+ if (!key) return;
73
+ map.set(key, {
74
+ key,
75
+ tenantId: parts[1]?.trim() || defaultTenantId,
76
+ projectId: parts[2]?.trim() || defaultProjectId || undefined,
77
+ workspaceId: parts[3]?.trim() || defaultWorkspaceId || undefined,
78
+ });
79
+ });
80
+ }
81
+
82
+ return map;
83
+ }
84
+
85
+ function getA2AConfig() {
86
+ const envMap = parseEnvKeyMap();
87
+ // Store keys take priority; env keys serve as fallback
88
+ const apiKeyMap = new Map([..._storeKeyMap, ...envMap]);
89
+
90
+ return {
91
+ agentName: process.env.A2A_AGENT_NAME || "Axiom Lattice Agent",
92
+ agentDescription:
93
+ process.env.A2A_AGENT_DESCRIPTION ||
94
+ "AI agent powered by Axiom Lattice framework",
95
+ organization: process.env.A2A_ORGANIZATION || "Axiom Lattice",
96
+ organizationUrl: process.env.A2A_ORGANIZATION_URL || "https://axiom-lattice.ai",
97
+ version: process.env.A2A_VERSION || "1.0.0",
98
+ defaultAssistantId: process.env.A2A_DEFAULT_AGENT_ID || "",
99
+ defaultTenantId: process.env.A2A_DEFAULT_TENANT_ID || "a2a-default-tenant",
100
+ defaultProjectId: process.env.A2A_DEFAULT_PROJECT_ID || "",
101
+ defaultWorkspaceId: process.env.A2A_DEFAULT_WORKSPACE_ID || "",
102
+ apiKeyMap,
103
+ };
104
+ }
105
+
106
+ // ─── Auth ─────────────────────────────────────────────────────────────────
107
+
108
+ function authenticateA2A(
109
+ request: FastifyRequest,
110
+ ): A2AAuthContext {
111
+ const config = getA2AConfig();
112
+ const noAuthRequired = config.apiKeyMap.size === 0;
113
+
114
+ const token =
115
+ request.headers.authorization?.startsWith("Bearer ")
116
+ ? request.headers.authorization.substring(7)
117
+ : (request.headers["x-api-key"] as string | undefined);
118
+
119
+ if (!token) {
120
+ return {
121
+ authenticated: noAuthRequired,
122
+ tenantId: config.defaultTenantId,
123
+ projectId: config.defaultProjectId || undefined,
124
+ workspaceId: config.defaultWorkspaceId || undefined,
125
+ };
126
+ }
127
+
128
+ const entry = config.apiKeyMap.get(token);
129
+ if (entry) {
130
+ return {
131
+ authenticated: true,
132
+ apiKey: token,
133
+ tenantId: entry.tenantId,
134
+ projectId: entry.projectId,
135
+ workspaceId: entry.workspaceId,
136
+ source: request.headers.authorization?.startsWith("Bearer ") ? "bearer" : "x-api-key",
137
+ };
138
+ }
139
+
140
+ return { authenticated: false };
141
+ }
142
+
143
+ function requireAuth(
144
+ request: FastifyRequest,
145
+ reply: FastifyReply,
146
+ ): A2AAuthContext {
147
+ const auth = authenticateA2A(request);
148
+ if (!auth.authenticated) {
149
+ reply.status(401).send({
150
+ error: "Unauthorized",
151
+ message: "Valid API key required via Bearer token or X-API-Key header",
152
+ });
153
+ }
154
+ return auth;
155
+ }
156
+
157
+ // ─── Agent Card ───────────────────────────────────────────────────────────
158
+
159
+ function buildAgentCard(baseUrl: string): AgentCard {
160
+ const config = getA2AConfig();
161
+ return {
162
+ name: config.agentName,
163
+ description: config.agentDescription,
164
+ url: `${baseUrl}/api/a2a`,
165
+ provider: {
166
+ organization: config.organization,
167
+ url: config.organizationUrl,
168
+ },
169
+ version: config.version,
170
+ capabilities: {
171
+ streaming: true,
172
+ pushNotifications: false,
173
+ stateTransitionHistory: false,
174
+ },
175
+ defaultInputModes: ["text", "text/plain"],
176
+ defaultOutputModes: ["text", "text/plain", "text/markdown"],
177
+ skills: [],
178
+ };
179
+ }
180
+
181
+ // ─── Helpers ──────────────────────────────────────────────────────────────
182
+
183
+ function extractTextFromParts(parts: A2APart[]): string {
184
+ return parts
185
+ .filter((p): p is { type: "text"; text: string } => p.type === "text")
186
+ .map((p) => p.text)
187
+ .join("\n");
188
+ }
189
+
190
+ function buildTextPart(text: string): A2APart {
191
+ return { type: "text", text };
192
+ }
193
+
194
+ function isoNow(): string {
195
+ return new Date().toISOString();
196
+ }
197
+
198
+ type SendEventFn = (event: string, data: Record<string, unknown>) => void;
199
+
200
+ async function streamChunksAsA2A(
201
+ stream: AsyncIterable<{ type: unknown; data?: { content?: string } }>,
202
+ taskId: string,
203
+ sendEvent: SendEventFn,
204
+ onInterrupt?: () => void,
205
+ ): Promise<string> {
206
+ let accumulatedText = "";
207
+
208
+ for await (const chunk of stream) {
209
+ const chunkText = (chunk as { data?: { content?: string } }).data?.content || "";
210
+ const chunkType = (chunk as { type: string }).type;
211
+
212
+ if (chunkType === MessageChunkTypes.INTERRUPT) {
213
+ sendEvent("status-update", {
214
+ id: taskId,
215
+ status: {
216
+ state: "input-required",
217
+ message: {
218
+ role: "agent",
219
+ parts: [buildTextPart(accumulatedText)],
220
+ },
221
+ timestamp: isoNow(),
222
+ },
223
+ final: false,
224
+ });
225
+ onInterrupt?.();
226
+ continue;
227
+ }
228
+
229
+ if (
230
+ chunkType === MessageChunkTypes.AI ||
231
+ chunkType === MessageChunkTypes.TOOL
232
+ ) {
233
+ if (chunkText) {
234
+ accumulatedText += chunkText;
235
+ sendEvent("status-update", {
236
+ id: taskId,
237
+ status: {
238
+ state: "working",
239
+ message: {
240
+ role: "agent",
241
+ parts: [buildTextPart(chunkText)],
242
+ },
243
+ timestamp: isoNow(),
244
+ },
245
+ final: false,
246
+ });
247
+ }
248
+ }
249
+ }
250
+
251
+ return accumulatedText;
252
+ }
253
+
254
+ // ─── Task Status ──────────────────────────────────────────────────────────
255
+
256
+ async function getTaskStatus(taskId: string): Promise<A2ATask | null> {
257
+ const record = taskStore.get(taskId);
258
+ if (!record) return null;
259
+
260
+ return {
261
+ id: record.id,
262
+ status: {
263
+ state: record.status,
264
+ timestamp: record.updatedAt,
265
+ },
266
+ artifacts: [],
267
+ history: record.history,
268
+ };
269
+ }
270
+
271
+ // ─── Handlers ─────────────────────────────────────────────────────────────
272
+
273
+ async function handleAgentCard(
274
+ request: FastifyRequest,
275
+ reply: FastifyReply,
276
+ ): Promise<void> {
277
+ const protocol =
278
+ (request.headers["x-forwarded-proto"] as string) ||
279
+ request.protocol;
280
+ const host = request.hostname;
281
+ const baseUrl = `${protocol}://${host}`;
282
+ const card = buildAgentCard(baseUrl);
283
+ reply.status(200).send(card);
284
+ }
285
+
286
+ async function handleTasksGet(
287
+ request: FastifyRequest<{ Params: { taskId: string } }>,
288
+ reply: FastifyReply,
289
+ ): Promise<void> {
290
+ const auth = requireAuth(request, reply);
291
+ if (!auth.authenticated) return;
292
+ const task = await getTaskStatus(request.params.taskId);
293
+ if (!task) {
294
+ reply.status(404).send({ error: "Task not found" });
295
+ return;
296
+ }
297
+ reply.status(200).send(task);
298
+ }
299
+
300
+ async function handleTasksSend(
301
+ request: FastifyRequest<{ Body: A2ATaskSendRequest }>,
302
+ reply: FastifyReply,
303
+ ): Promise<void> {
304
+ const auth = requireAuth(request, reply);
305
+ if (!auth.authenticated) return;
306
+
307
+ const config = getA2AConfig();
308
+ const body = request.body as A2ATaskSendRequest;
309
+
310
+ if (!body.message || !body.message.parts || body.message.parts.length === 0) {
311
+ reply.status(400).send({ error: "message.parts is required" });
312
+ return;
313
+ }
314
+
315
+ const text = extractTextFromParts(body.message.parts);
316
+ if (!text.trim()) {
317
+ reply.status(400).send({ error: "message must contain text content" });
318
+ return;
319
+ }
320
+
321
+ const assistantId =
322
+ (request.headers["x-a2a-agent-id"] as string) ||
323
+ config.defaultAssistantId;
324
+
325
+ if (!assistantId) {
326
+ reply.status(500).send({
327
+ error: "No agent configured",
328
+ message:
329
+ "Set A2A_DEFAULT_AGENT_ID env var or provide x-a2a-agent-id header",
330
+ });
331
+ return;
332
+ }
333
+
334
+ const taskId = body.id || v4();
335
+ const threadId = v4();
336
+
337
+ const tenantId = auth.tenantId || config.defaultTenantId;
338
+
339
+ const now = isoNow();
340
+
341
+ const record: TaskRecord = {
342
+ id: taskId,
343
+ threadId,
344
+ assistantId,
345
+ tenantId,
346
+ projectId: auth.projectId || undefined,
347
+ workspaceId: auth.workspaceId || undefined,
348
+ status: "working",
349
+ createdAt: now,
350
+ updatedAt: now,
351
+ history: [
352
+ {
353
+ role: "user",
354
+ parts: body.message.parts,
355
+ },
356
+ ],
357
+ };
358
+
359
+ taskStore.set(taskId, record);
360
+
361
+ let agent;
362
+ try {
363
+ agent = agentInstanceManager.getAgent({
364
+ assistant_id: assistantId,
365
+ thread_id: threadId,
366
+ tenant_id: tenantId,
367
+ workspace_id: auth.workspaceId || undefined,
368
+ project_id: auth.projectId || undefined,
369
+ });
370
+ } catch (err) {
371
+ record.status = "failed";
372
+ record.updatedAt = isoNow();
373
+ reply.status(500).send({
374
+ id: taskId,
375
+ error: "Failed to initialize agent",
376
+ message: err instanceof Error ? err.message : String(err),
377
+ });
378
+ return;
379
+ }
380
+
381
+ reply.hijack();
382
+ reply.raw.writeHead(200, {
383
+ "Content-Type": "text/event-stream",
384
+ "Cache-Control": "no-cache",
385
+ Connection: "keep-alive",
386
+ "Access-Control-Allow-Origin": "*",
387
+ });
388
+
389
+ const sendEvent = (event: string, data: Record<string, unknown>): void => {
390
+ reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
391
+ };
392
+
393
+ try {
394
+ const result = await agent.addMessage({
395
+ input: { message: text },
396
+ });
397
+
398
+ record.messageId = result.messageId;
399
+
400
+ const stream = agent.chunkStream(result.messageId, [
401
+ MessageChunkTypes.MESSAGE_COMPLETED,
402
+ ]);
403
+
404
+ const accumulatedText = await streamChunksAsA2A(stream, taskId, sendEvent, () => {
405
+ record.status = "input-required";
406
+ record.updatedAt = isoNow();
407
+ });
408
+
409
+ record.status = "completed";
410
+ record.updatedAt = isoNow();
411
+ record.history.push({
412
+ role: "agent",
413
+ parts: [buildTextPart(accumulatedText)],
414
+ });
415
+
416
+ sendEvent("status-update", {
417
+ id: taskId,
418
+ status: {
419
+ state: "completed",
420
+ timestamp: isoNow(),
421
+ },
422
+ final: true,
423
+ });
424
+ } catch (err) {
425
+ record.status = "failed";
426
+ record.updatedAt = isoNow();
427
+
428
+ sendEvent("error", {
429
+ code: "EXECUTION_ERROR",
430
+ message: err instanceof Error ? err.message : String(err),
431
+ });
432
+
433
+ sendEvent("status-update", {
434
+ id: taskId,
435
+ status: {
436
+ state: "failed",
437
+ timestamp: isoNow(),
438
+ },
439
+ final: true,
440
+ });
441
+ } finally {
442
+ reply.raw.end();
443
+ }
444
+ }
445
+
446
+ async function handleTasksCancel(
447
+ request: FastifyRequest<{ Params: { taskId: string } }>,
448
+ reply: FastifyReply,
449
+ ): Promise<void> {
450
+ const auth = requireAuth(request, reply);
451
+ if (!auth.authenticated) return;
452
+ const { taskId } = request.params;
453
+ const record = taskStore.get(taskId);
454
+
455
+ if (!record) {
456
+ reply.status(404).send({ error: "Task not found" });
457
+ return;
458
+ }
459
+
460
+ if (record.status === "completed" || record.status === "failed" || record.status === "canceled") {
461
+ reply.status(409).send({
462
+ error: "Task is already in a terminal state",
463
+ task: { id: record.id, status: record.status },
464
+ });
465
+ return;
466
+ }
467
+
468
+ try {
469
+ const agent = agentInstanceManager.getAgent({
470
+ assistant_id: record.assistantId,
471
+ thread_id: record.threadId,
472
+ tenant_id: record.tenantId,
473
+ workspace_id: record.workspaceId,
474
+ project_id: record.projectId,
475
+ });
476
+ await agent.abort();
477
+ } catch (err) {
478
+ // Agent session may have already been cleaned up
479
+ console.warn({
480
+ event: "a2a:cancel:no_agent",
481
+ taskId,
482
+ threadId: record.threadId,
483
+ error: err instanceof Error ? err.message : String(err),
484
+ });
485
+ }
486
+
487
+ record.status = "canceled";
488
+ record.updatedAt = isoNow();
489
+
490
+ reply.status(200).send({
491
+ id: taskId,
492
+ status: {
493
+ state: "canceled",
494
+ timestamp: record.updatedAt,
495
+ },
496
+ });
497
+ }
498
+
499
+ async function handleTasksStream(
500
+ request: FastifyRequest<{ Params: { taskId: string } }>,
501
+ reply: FastifyReply,
502
+ ): Promise<void> {
503
+ const auth = requireAuth(request, reply);
504
+ if (!auth.authenticated) return;
505
+
506
+ const { taskId } = request.params;
507
+ const record = taskStore.get(taskId);
508
+
509
+ if (!record) {
510
+ reply.status(404).send({ error: "Task not found" });
511
+ return;
512
+ }
513
+
514
+ let agent;
515
+ try {
516
+ agent = agentInstanceManager.getAgent({
517
+ assistant_id: record.assistantId,
518
+ thread_id: record.threadId,
519
+ tenant_id: record.tenantId,
520
+ workspace_id: record.workspaceId,
521
+ project_id: record.projectId,
522
+ });
523
+ } catch {
524
+ reply.status(404).send({
525
+ error: "Agent session not found. The task may have already completed.",
526
+ });
527
+ return;
528
+ }
529
+
530
+ reply.hijack();
531
+ reply.raw.writeHead(200, {
532
+ "Content-Type": "text/event-stream",
533
+ "Cache-Control": "no-cache",
534
+ Connection: "keep-alive",
535
+ "Access-Control-Allow-Origin": "*",
536
+ });
537
+
538
+ const sendEvent = (event: string, data: Record<string, unknown>): void => {
539
+ reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
540
+ };
541
+
542
+ if (!record.messageId) {
543
+ sendEvent("status-update", {
544
+ id: taskId,
545
+ status: {
546
+ state: record.status,
547
+ timestamp: record.updatedAt,
548
+ },
549
+ final: true,
550
+ });
551
+ reply.raw.end();
552
+ return;
553
+ }
554
+
555
+ try {
556
+ const stream = agent.chunkStream(record.messageId, [
557
+ MessageChunkTypes.MESSAGE_COMPLETED,
558
+ ]);
559
+
560
+ await streamChunksAsA2A(stream, taskId, sendEvent);
561
+
562
+ sendEvent("status-update", {
563
+ id: taskId,
564
+ status: {
565
+ state: record.status,
566
+ timestamp: record.updatedAt,
567
+ },
568
+ final: true,
569
+ });
570
+ } catch (err) {
571
+ sendEvent("error", {
572
+ code: "STREAM_ERROR",
573
+ message: err instanceof Error ? err.message : String(err),
574
+ });
575
+ } finally {
576
+ reply.raw.end();
577
+ }
578
+ }
579
+
580
+ // ─── API Key Management Handlers ─────────────────────────────────────────
581
+
582
+ async function handleApiKeyList(
583
+ request: FastifyRequest<{ Querystring: { tenantId?: string; limit?: string; offset?: string } }>,
584
+ reply: FastifyReply,
585
+ ): Promise<void> {
586
+ const auth = requireAuth(request, reply);
587
+ if (!auth.authenticated) return;
588
+
589
+ if (!_a2aKeyStore) {
590
+ reply.status(501).send({ error: "Key store not configured" });
591
+ return;
592
+ }
593
+
594
+ const records = await _a2aKeyStore.list({
595
+ tenantId: request.query.tenantId,
596
+ limit: request.query.limit ? parseInt(request.query.limit, 10) : undefined,
597
+ offset: request.query.offset ? parseInt(request.query.offset, 10) : undefined,
598
+ });
599
+
600
+ reply.status(200).send({
601
+ success: true,
602
+ data: {
603
+ records: records.map((r) => ({ ...r, key: r.key.slice(0, 8) + "..." })),
604
+ total: records.length,
605
+ },
606
+ });
607
+ }
608
+
609
+ async function handleApiKeyCreate(
610
+ request: FastifyRequest<{ Body: Partial<CreateA2AApiKeyInput> }>,
611
+ reply: FastifyReply,
612
+ ): Promise<void> {
613
+ const auth = requireAuth(request, reply);
614
+ if (!auth.authenticated) return;
615
+
616
+ if (!_a2aKeyStore) {
617
+ reply.status(501).send({ error: "Key store not configured" });
618
+ return;
619
+ }
620
+
621
+ const body = request.body as Partial<CreateA2AApiKeyInput>;
622
+ // Scope from request body / headers; fallback to auth context
623
+ const tenantId =
624
+ body.tenantId ||
625
+ (request.headers["x-tenant-id"] as string) ||
626
+ auth.tenantId;
627
+ const projectId =
628
+ body.projectId || (request.headers["x-project-id"] as string) || auth.projectId || "default";
629
+ const workspaceId =
630
+ body.workspaceId || (request.headers["x-workspace-id"] as string) || auth.workspaceId;
631
+
632
+ if (!tenantId) {
633
+ reply.status(400).send({
634
+ error: "tenantId is required",
635
+ message: "Provide via body.tenantId, x-tenant-id header, or authenticate with a scoped API key",
636
+ });
637
+ return;
638
+ }
639
+
640
+ const record = await _a2aKeyStore.create({
641
+ tenantId,
642
+ projectId,
643
+ workspaceId,
644
+ label: body.label,
645
+ });
646
+ await refreshStoreKeyMap();
647
+
648
+ reply.status(201).send({ success: true, data: record });
649
+ }
650
+
651
+ async function handleApiKeyDelete(
652
+ request: FastifyRequest<{ Params: { id: string } }>,
653
+ reply: FastifyReply,
654
+ ): Promise<void> {
655
+ const auth = requireAuth(request, reply);
656
+ if (!auth.authenticated) return;
657
+
658
+ if (!_a2aKeyStore) {
659
+ reply.status(501).send({ error: "Key store not configured" });
660
+ return;
661
+ }
662
+
663
+ await _a2aKeyStore.delete(request.params.id);
664
+ await refreshStoreKeyMap();
665
+
666
+ reply.status(200).send({ success: true });
667
+ }
668
+
669
+ async function handleApiKeyDisable(
670
+ request: FastifyRequest<{ Params: { id: string } }>,
671
+ reply: FastifyReply,
672
+ ): Promise<void> {
673
+ const auth = requireAuth(request, reply);
674
+ if (!auth.authenticated) return;
675
+
676
+ if (!_a2aKeyStore) {
677
+ reply.status(501).send({ error: "Key store not configured" });
678
+ return;
679
+ }
680
+
681
+ await _a2aKeyStore.disable(request.params.id);
682
+ await refreshStoreKeyMap();
683
+
684
+ reply.status(200).send({ success: true });
685
+ }
686
+
687
+ async function handleApiKeyEnable(
688
+ request: FastifyRequest<{ Params: { id: string } }>,
689
+ reply: FastifyReply,
690
+ ): Promise<void> {
691
+ const auth = requireAuth(request, reply);
692
+ if (!auth.authenticated) return;
693
+
694
+ if (!_a2aKeyStore) {
695
+ reply.status(501).send({ error: "Key store not configured" });
696
+ return;
697
+ }
698
+
699
+ await _a2aKeyStore.enable(request.params.id);
700
+ await refreshStoreKeyMap();
701
+
702
+ reply.status(200).send({ success: true });
703
+ }
704
+
705
+ async function handleApiKeyRotate(
706
+ request: FastifyRequest<{ Params: { id: string } }>,
707
+ reply: FastifyReply,
708
+ ): Promise<void> {
709
+ const auth = requireAuth(request, reply);
710
+ if (!auth.authenticated) return;
711
+
712
+ if (!_a2aKeyStore) {
713
+ reply.status(501).send({ error: "Key store not configured" });
714
+ return;
715
+ }
716
+
717
+ const record = await _a2aKeyStore.rotate(request.params.id);
718
+ await refreshStoreKeyMap();
719
+
720
+ reply.status(200).send({ success: true, data: record });
721
+ }
722
+
723
+ // ─── Route Registration ───────────────────────────────────────────────────
724
+
725
+ export function registerA2ARoutes(app: FastifyInstance): void {
726
+ app.get("/api/a2a/.well-known/agent.json", handleAgentCard);
727
+ app.get("/api/a2a/.well-known/agent-card.json", handleAgentCard);
728
+
729
+ app.post<{ Body: A2ATaskSendRequest }>(
730
+ "/api/a2a/tasks/send",
731
+ handleTasksSend,
732
+ );
733
+
734
+ app.get<{ Params: { taskId: string } }>(
735
+ "/api/a2a/tasks/:taskId",
736
+ handleTasksGet,
737
+ );
738
+
739
+ app.get<{ Params: { taskId: string } }>(
740
+ "/api/a2a/tasks/:taskId/stream",
741
+ handleTasksStream,
742
+ );
743
+
744
+ app.post<{ Params: { taskId: string } }>(
745
+ "/api/a2a/tasks/:taskId/cancel",
746
+ handleTasksCancel,
747
+ );
748
+
749
+ // A2A API Key management
750
+ app.get<{ Querystring: { tenantId?: string; limit?: string; offset?: string } }>(
751
+ "/api/a2a/keys",
752
+ handleApiKeyList,
753
+ );
754
+
755
+ app.post<{ Body: Partial<CreateA2AApiKeyInput> }>(
756
+ "/api/a2a/keys",
757
+ handleApiKeyCreate,
758
+ );
759
+
760
+ app.delete<{ Params: { id: string } }>(
761
+ "/api/a2a/keys/:id",
762
+ handleApiKeyDelete,
763
+ );
764
+
765
+ app.post<{ Params: { id: string } }>(
766
+ "/api/a2a/keys/:id/disable",
767
+ handleApiKeyDisable,
768
+ );
769
+
770
+ app.post<{ Params: { id: string } }>(
771
+ "/api/a2a/keys/:id/enable",
772
+ handleApiKeyEnable,
773
+ );
774
+
775
+ app.post<{ Params: { id: string } }>(
776
+ "/api/a2a/keys/:id/rotate",
777
+ handleApiKeyRotate,
778
+ );
779
+ }