@axiom-lattice/gateway 3.0.9 → 4.0.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiom-lattice/gateway",
3
- "version": "3.0.9",
3
+ "version": "4.0.0",
4
4
  "main": "dist/index.js",
5
5
  "files": [
6
6
  "dist"
@@ -19,6 +19,7 @@
19
19
  "license": "ISC",
20
20
  "description": "API Gateway for LangGraph agent-based applications",
21
21
  "dependencies": {
22
+ "@a2a-js/sdk": "^0.3.13",
22
23
  "@fastify/cors": "^11.0.0",
23
24
  "@fastify/http-proxy": "^9.5.0",
24
25
  "@fastify/multipart": "^9.4.0",
@@ -42,13 +43,14 @@
42
43
  "pino-pretty": "^13.0.0",
43
44
  "pino-roll": "^3.1.0",
44
45
  "redis": "^5.0.1",
46
+ "tar": "^7.5.22",
45
47
  "uuid": "^9.0.1",
46
48
  "zod": "3.25.76",
47
- "@axiom-lattice/cli-a2a": "0.1.10",
48
- "@axiom-lattice/core": "3.1.1",
49
- "@axiom-lattice/pg-stores": "2.0.9",
50
- "@axiom-lattice/protocols": "3.0.4",
51
- "@axiom-lattice/queue-redis": "1.0.58"
49
+ "@axiom-lattice/cli-a2a": "0.1.11",
50
+ "@axiom-lattice/core": "4.0.0",
51
+ "@axiom-lattice/pg-stores": "3.0.0",
52
+ "@axiom-lattice/protocols": "4.0.0",
53
+ "@axiom-lattice/queue-redis": "1.0.59"
52
54
  },
53
55
  "devDependencies": {
54
56
  "@types/bcrypt": "^6.0.0",
@@ -1,615 +0,0 @@
1
- // src/routes/a2a.ts
2
- import { v4 } from "uuid";
3
- import {
4
- agentInstanceManager
5
- } from "@axiom-lattice/core";
6
- import { MessageChunkTypes } from "@axiom-lattice/protocols";
7
- var taskStore = /* @__PURE__ */ new Map();
8
- var contextThreadMap = /* @__PURE__ */ new Map();
9
- var _a2aKeyStore = null;
10
- var _storeKeyMap = /* @__PURE__ */ new Map();
11
- function setA2AKeyStore(store) {
12
- _a2aKeyStore = store;
13
- }
14
- async function refreshStoreKeyMap() {
15
- if (!_a2aKeyStore) return;
16
- _storeKeyMap = await _a2aKeyStore.loadIntoMap();
17
- }
18
- function parseEnvKeyMap() {
19
- const keysEnv = process.env.A2A_API_KEYS || "";
20
- const defaultTenantId = process.env.A2A_DEFAULT_TENANT_ID || "a2a-default-tenant";
21
- const defaultProjectId = process.env.A2A_DEFAULT_PROJECT_ID || "";
22
- const defaultWorkspaceId = process.env.A2A_DEFAULT_WORKSPACE_ID || "";
23
- const map = /* @__PURE__ */ new Map();
24
- if (keysEnv) {
25
- keysEnv.split(",").forEach((entry) => {
26
- const trimmed = entry.trim();
27
- if (!trimmed) return;
28
- const parts = trimmed.split(":");
29
- const key = parts[0];
30
- if (!key) return;
31
- map.set(key, {
32
- key,
33
- tenantId: parts[1]?.trim() || defaultTenantId,
34
- projectId: parts[2]?.trim() || defaultProjectId || void 0,
35
- workspaceId: parts[3]?.trim() || defaultWorkspaceId || void 0
36
- });
37
- });
38
- }
39
- return map;
40
- }
41
- function getA2AConfig() {
42
- const envMap = parseEnvKeyMap();
43
- const apiKeyMap = new Map([..._storeKeyMap, ...envMap]);
44
- return {
45
- agentName: process.env.A2A_AGENT_NAME || "Axiom Lattice Agent",
46
- agentDescription: process.env.A2A_AGENT_DESCRIPTION || "AI agent powered by Axiom Lattice framework",
47
- organization: process.env.A2A_ORGANIZATION || "Axiom Lattice",
48
- organizationUrl: process.env.A2A_ORGANIZATION_URL || "https://axiom-lattice.ai",
49
- version: process.env.A2A_VERSION || "1.0.0",
50
- defaultAssistantId: process.env.A2A_DEFAULT_AGENT_ID || "",
51
- defaultTenantId: process.env.A2A_DEFAULT_TENANT_ID || "a2a-default-tenant",
52
- defaultProjectId: process.env.A2A_DEFAULT_PROJECT_ID || "",
53
- defaultWorkspaceId: process.env.A2A_DEFAULT_WORKSPACE_ID || "",
54
- apiKeyMap
55
- };
56
- }
57
- function authenticateA2A(request) {
58
- const config = getA2AConfig();
59
- const noAuthRequired = config.apiKeyMap.size === 0;
60
- const token = request.headers.authorization?.startsWith("Bearer ") ? request.headers.authorization.substring(7) : request.headers["x-api-key"];
61
- if (!token) {
62
- return {
63
- authenticated: noAuthRequired,
64
- tenantId: config.defaultTenantId,
65
- projectId: config.defaultProjectId || void 0,
66
- workspaceId: config.defaultWorkspaceId || void 0
67
- };
68
- }
69
- const entry = config.apiKeyMap.get(token);
70
- if (entry) {
71
- return {
72
- authenticated: true,
73
- apiKey: token,
74
- tenantId: entry.tenantId,
75
- projectId: entry.projectId,
76
- workspaceId: entry.workspaceId,
77
- source: request.headers.authorization?.startsWith("Bearer ") ? "bearer" : "x-api-key"
78
- };
79
- }
80
- return { authenticated: false };
81
- }
82
- function requireAuth(request, reply) {
83
- const auth = authenticateA2A(request);
84
- if (!auth.authenticated) {
85
- reply.status(401).send({
86
- error: "Unauthorized",
87
- message: "Valid API key required via Bearer token or X-API-Key header"
88
- });
89
- }
90
- return auth;
91
- }
92
- function buildAgentCard(baseUrl) {
93
- const config = getA2AConfig();
94
- return {
95
- name: config.agentName,
96
- description: config.agentDescription,
97
- url: `${baseUrl}/api/a2a`,
98
- provider: {
99
- organization: config.organization,
100
- url: config.organizationUrl
101
- },
102
- version: config.version,
103
- capabilities: {
104
- streaming: true,
105
- pushNotifications: false,
106
- stateTransitionHistory: false
107
- },
108
- defaultInputModes: ["text", "text/plain"],
109
- defaultOutputModes: ["text", "text/plain", "text/markdown"],
110
- skills: []
111
- };
112
- }
113
- function extractTextFromParts(parts) {
114
- return parts.filter((p) => p.type === "text").map((p) => p.text).join("\n");
115
- }
116
- function buildTextPart(text) {
117
- return { type: "text", text };
118
- }
119
- function isoNow() {
120
- return (/* @__PURE__ */ new Date()).toISOString();
121
- }
122
- async function streamChunksAsA2A(stream, taskId, contextId, sendEvent, onInterrupt) {
123
- let accumulatedText = "";
124
- let interrupted = false;
125
- for await (const chunk of stream) {
126
- const chunkText = chunk.data?.content || "";
127
- const chunkType = chunk.type;
128
- if (chunkType === MessageChunkTypes.INTERRUPT) {
129
- sendEvent("status-update", {
130
- id: taskId,
131
- contextId,
132
- status: {
133
- state: "input-required",
134
- message: {
135
- role: "agent",
136
- parts: [buildTextPart(accumulatedText)]
137
- },
138
- timestamp: isoNow()
139
- },
140
- final: false
141
- });
142
- onInterrupt?.();
143
- interrupted = true;
144
- break;
145
- }
146
- if (chunkType === MessageChunkTypes.AI || chunkType === MessageChunkTypes.TOOL) {
147
- if (chunkText) {
148
- accumulatedText += chunkText;
149
- sendEvent("status-update", {
150
- id: taskId,
151
- contextId,
152
- status: {
153
- state: "working",
154
- message: {
155
- role: "agent",
156
- parts: [buildTextPart(chunkText)]
157
- },
158
- timestamp: isoNow()
159
- },
160
- final: false
161
- });
162
- }
163
- }
164
- }
165
- return { text: accumulatedText, interrupted };
166
- }
167
- async function getTaskStatus(taskId) {
168
- const record = taskStore.get(taskId);
169
- if (!record) return null;
170
- return {
171
- id: record.id,
172
- status: {
173
- state: record.status,
174
- timestamp: record.updatedAt
175
- },
176
- artifacts: [],
177
- history: record.history
178
- };
179
- }
180
- async function handleAgentCard(request, reply) {
181
- const protocol = request.headers["x-forwarded-proto"] || request.protocol;
182
- const host = request.hostname;
183
- const baseUrl = `${protocol}://${host}`;
184
- const card = buildAgentCard(baseUrl);
185
- reply.status(200).send(card);
186
- }
187
- async function handleTasksGet(request, reply) {
188
- const auth = requireAuth(request, reply);
189
- if (!auth.authenticated) return;
190
- const task = await getTaskStatus(request.params.taskId);
191
- if (!task) {
192
- reply.status(404).send({ error: "Task not found" });
193
- return;
194
- }
195
- reply.status(200).send(task);
196
- }
197
- async function handleTasksSend(request, reply) {
198
- const auth = requireAuth(request, reply);
199
- if (!auth.authenticated) return;
200
- const config = getA2AConfig();
201
- const body = request.body;
202
- if (!body.message || !body.message.parts || body.message.parts.length === 0) {
203
- reply.status(400).send({ error: "message.parts is required" });
204
- return;
205
- }
206
- const text = extractTextFromParts(body.message.parts);
207
- if (!text.trim()) {
208
- reply.status(400).send({ error: "message must contain text content" });
209
- return;
210
- }
211
- const assistantId = request.headers["x-a2a-agent-id"] || config.defaultAssistantId;
212
- if (!assistantId) {
213
- reply.status(500).send({
214
- error: "No agent configured",
215
- message: "Set A2A_DEFAULT_AGENT_ID env var or provide x-a2a-agent-id header"
216
- });
217
- return;
218
- }
219
- const contextId = body.message.contextId;
220
- const referenceTaskIds = body.message.referenceTaskIds;
221
- const taskId = body.id || v4();
222
- let threadId;
223
- let resolvedReferenceTaskIds;
224
- if (body.id) {
225
- const existingTask = taskStore.get(body.id);
226
- if (existingTask) {
227
- if (existingTask.status === "input-required") {
228
- threadId = existingTask.threadId;
229
- resolvedReferenceTaskIds = referenceTaskIds;
230
- } else if (existingTask.status === "completed" || existingTask.status === "failed" || existingTask.status === "canceled") {
231
- threadId = v4();
232
- resolvedReferenceTaskIds = referenceTaskIds ? [...referenceTaskIds, body.id] : [body.id];
233
- } else {
234
- threadId = v4();
235
- resolvedReferenceTaskIds = referenceTaskIds;
236
- }
237
- } else {
238
- threadId = v4();
239
- resolvedReferenceTaskIds = referenceTaskIds ? [...referenceTaskIds, body.id] : [body.id];
240
- }
241
- } else if (contextId && contextThreadMap.has(contextId)) {
242
- threadId = contextThreadMap.get(contextId);
243
- console.warn({
244
- event: "a2a:deprecated:contextId_thread_reuse",
245
- message: "contextId-based thread reuse is deprecated; use referenceTaskIds and application-layer conversation state instead",
246
- contextId,
247
- threadId
248
- });
249
- resolvedReferenceTaskIds = referenceTaskIds;
250
- } else {
251
- threadId = v4();
252
- resolvedReferenceTaskIds = referenceTaskIds;
253
- }
254
- const tenantId = auth.tenantId || config.defaultTenantId;
255
- const now = isoNow();
256
- const record = {
257
- id: taskId,
258
- threadId,
259
- contextId,
260
- referenceTaskIds: resolvedReferenceTaskIds,
261
- assistantId,
262
- tenantId,
263
- projectId: auth.projectId || void 0,
264
- workspaceId: auth.workspaceId || void 0,
265
- status: "working",
266
- createdAt: now,
267
- updatedAt: now,
268
- history: [
269
- {
270
- role: "user",
271
- parts: body.message.parts
272
- }
273
- ]
274
- };
275
- taskStore.set(taskId, record);
276
- let agent;
277
- try {
278
- agent = agentInstanceManager.getAgent({
279
- assistant_id: assistantId,
280
- thread_id: threadId,
281
- tenant_id: tenantId,
282
- workspace_id: auth.workspaceId || void 0,
283
- project_id: auth.projectId || void 0
284
- });
285
- } catch (err) {
286
- record.status = "failed";
287
- record.updatedAt = isoNow();
288
- reply.status(500).send({
289
- id: taskId,
290
- error: "Failed to initialize agent",
291
- message: err instanceof Error ? err.message : String(err)
292
- });
293
- return;
294
- }
295
- reply.hijack();
296
- reply.raw.writeHead(200, {
297
- "Content-Type": "text/event-stream",
298
- "Cache-Control": "no-cache",
299
- Connection: "keep-alive",
300
- "Access-Control-Allow-Origin": "*"
301
- });
302
- const sendEvent = (event, data) => {
303
- reply.raw.write(`event: ${event}
304
- data: ${JSON.stringify(data)}
305
-
306
- `);
307
- };
308
- try {
309
- const result = await agent.addMessage({
310
- input: { message: text }
311
- });
312
- record.messageId = result.messageId;
313
- const stream = agent.chunkStream(result.messageId, [
314
- MessageChunkTypes.MESSAGE_COMPLETED
315
- ]);
316
- const { text: accumulatedText, interrupted } = await streamChunksAsA2A(stream, taskId, contextId, sendEvent, () => {
317
- record.status = "input-required";
318
- record.updatedAt = isoNow();
319
- });
320
- if (!interrupted) {
321
- record.status = "completed";
322
- record.updatedAt = isoNow();
323
- record.history.push({
324
- role: "agent",
325
- parts: [buildTextPart(accumulatedText)]
326
- });
327
- sendEvent("status-update", {
328
- id: taskId,
329
- contextId,
330
- status: {
331
- state: "completed",
332
- timestamp: isoNow()
333
- },
334
- final: true
335
- });
336
- }
337
- } catch (err) {
338
- record.status = "failed";
339
- record.updatedAt = isoNow();
340
- sendEvent("error", {
341
- code: "EXECUTION_ERROR",
342
- message: err instanceof Error ? err.message : String(err)
343
- });
344
- sendEvent("status-update", {
345
- id: taskId,
346
- contextId,
347
- status: {
348
- state: "failed",
349
- timestamp: isoNow()
350
- },
351
- final: true
352
- });
353
- } finally {
354
- reply.raw.end();
355
- }
356
- }
357
- async function handleTasksCancel(request, reply) {
358
- const auth = requireAuth(request, reply);
359
- if (!auth.authenticated) return;
360
- const { taskId } = request.params;
361
- const record = taskStore.get(taskId);
362
- if (!record) {
363
- reply.status(404).send({ error: "Task not found" });
364
- return;
365
- }
366
- if (record.status === "completed" || record.status === "failed" || record.status === "canceled") {
367
- reply.status(409).send({
368
- error: "Task is already in a terminal state",
369
- task: { id: record.id, status: record.status }
370
- });
371
- return;
372
- }
373
- try {
374
- const agent = agentInstanceManager.getAgent({
375
- assistant_id: record.assistantId,
376
- thread_id: record.threadId,
377
- tenant_id: record.tenantId,
378
- workspace_id: record.workspaceId,
379
- project_id: record.projectId
380
- });
381
- await agent.abort();
382
- } catch (err) {
383
- console.warn({
384
- event: "a2a:cancel:no_agent",
385
- taskId,
386
- threadId: record.threadId,
387
- error: err instanceof Error ? err.message : String(err)
388
- });
389
- }
390
- record.status = "canceled";
391
- record.updatedAt = isoNow();
392
- reply.status(200).send({
393
- id: taskId,
394
- status: {
395
- state: "canceled",
396
- timestamp: record.updatedAt
397
- }
398
- });
399
- }
400
- async function handleTasksStream(request, reply) {
401
- const auth = requireAuth(request, reply);
402
- if (!auth.authenticated) return;
403
- const { taskId } = request.params;
404
- const record = taskStore.get(taskId);
405
- if (!record) {
406
- reply.status(404).send({ error: "Task not found" });
407
- return;
408
- }
409
- let agent;
410
- try {
411
- agent = agentInstanceManager.getAgent({
412
- assistant_id: record.assistantId,
413
- thread_id: record.threadId,
414
- tenant_id: record.tenantId,
415
- workspace_id: record.workspaceId,
416
- project_id: record.projectId
417
- });
418
- } catch {
419
- reply.status(404).send({
420
- error: "Agent session not found. The task may have already completed."
421
- });
422
- return;
423
- }
424
- reply.hijack();
425
- reply.raw.writeHead(200, {
426
- "Content-Type": "text/event-stream",
427
- "Cache-Control": "no-cache",
428
- Connection: "keep-alive",
429
- "Access-Control-Allow-Origin": "*"
430
- });
431
- const sendEvent = (event, data) => {
432
- reply.raw.write(`event: ${event}
433
- data: ${JSON.stringify(data)}
434
-
435
- `);
436
- };
437
- if (!record.messageId) {
438
- sendEvent("status-update", {
439
- id: taskId,
440
- contextId: record.contextId,
441
- status: {
442
- state: record.status,
443
- timestamp: record.updatedAt
444
- },
445
- final: true
446
- });
447
- reply.raw.end();
448
- return;
449
- }
450
- try {
451
- const stream = agent.chunkStream(record.messageId, [
452
- MessageChunkTypes.MESSAGE_COMPLETED
453
- ]);
454
- const { interrupted } = await streamChunksAsA2A(stream, taskId, record.contextId, sendEvent);
455
- if (!interrupted) {
456
- sendEvent("status-update", {
457
- id: taskId,
458
- contextId: record.contextId,
459
- status: {
460
- state: record.status,
461
- timestamp: record.updatedAt
462
- },
463
- final: true
464
- });
465
- }
466
- } catch (err) {
467
- sendEvent("error", {
468
- code: "STREAM_ERROR",
469
- message: err instanceof Error ? err.message : String(err)
470
- });
471
- } finally {
472
- reply.raw.end();
473
- }
474
- }
475
- async function handleApiKeyList(request, reply) {
476
- const auth = requireAuth(request, reply);
477
- if (!auth.authenticated) return;
478
- if (!_a2aKeyStore) {
479
- reply.status(501).send({ error: "Key store not configured" });
480
- return;
481
- }
482
- const records = await _a2aKeyStore.list({
483
- tenantId: request.query.tenantId,
484
- limit: request.query.limit ? parseInt(request.query.limit, 10) : void 0,
485
- offset: request.query.offset ? parseInt(request.query.offset, 10) : void 0
486
- });
487
- reply.status(200).send({
488
- success: true,
489
- data: {
490
- records: records.map((r) => ({ ...r, key: r.key.slice(0, 8) + "..." })),
491
- total: records.length
492
- }
493
- });
494
- }
495
- async function handleApiKeyCreate(request, reply) {
496
- const auth = requireAuth(request, reply);
497
- if (!auth.authenticated) return;
498
- if (!_a2aKeyStore) {
499
- reply.status(501).send({ error: "Key store not configured" });
500
- return;
501
- }
502
- const body = request.body;
503
- const tenantId = body.tenantId || request.headers["x-tenant-id"] || auth.tenantId;
504
- const projectId = body.projectId || request.headers["x-project-id"] || auth.projectId || "default";
505
- const workspaceId = body.workspaceId || request.headers["x-workspace-id"] || auth.workspaceId;
506
- if (!tenantId) {
507
- reply.status(400).send({
508
- error: "tenantId is required",
509
- message: "Provide via body.tenantId, x-tenant-id header, or authenticate with a scoped API key"
510
- });
511
- return;
512
- }
513
- const record = await _a2aKeyStore.create({
514
- tenantId,
515
- projectId,
516
- workspaceId,
517
- label: body.label
518
- });
519
- await refreshStoreKeyMap();
520
- reply.status(201).send({ success: true, data: record });
521
- }
522
- async function handleApiKeyDelete(request, reply) {
523
- const auth = requireAuth(request, reply);
524
- if (!auth.authenticated) return;
525
- if (!_a2aKeyStore) {
526
- reply.status(501).send({ error: "Key store not configured" });
527
- return;
528
- }
529
- await _a2aKeyStore.delete(request.params.id);
530
- await refreshStoreKeyMap();
531
- reply.status(200).send({ success: true });
532
- }
533
- async function handleApiKeyDisable(request, reply) {
534
- const auth = requireAuth(request, reply);
535
- if (!auth.authenticated) return;
536
- if (!_a2aKeyStore) {
537
- reply.status(501).send({ error: "Key store not configured" });
538
- return;
539
- }
540
- await _a2aKeyStore.disable(request.params.id);
541
- await refreshStoreKeyMap();
542
- reply.status(200).send({ success: true });
543
- }
544
- async function handleApiKeyEnable(request, reply) {
545
- const auth = requireAuth(request, reply);
546
- if (!auth.authenticated) return;
547
- if (!_a2aKeyStore) {
548
- reply.status(501).send({ error: "Key store not configured" });
549
- return;
550
- }
551
- await _a2aKeyStore.enable(request.params.id);
552
- await refreshStoreKeyMap();
553
- reply.status(200).send({ success: true });
554
- }
555
- async function handleApiKeyRotate(request, reply) {
556
- const auth = requireAuth(request, reply);
557
- if (!auth.authenticated) return;
558
- if (!_a2aKeyStore) {
559
- reply.status(501).send({ error: "Key store not configured" });
560
- return;
561
- }
562
- const record = await _a2aKeyStore.rotate(request.params.id);
563
- await refreshStoreKeyMap();
564
- reply.status(200).send({ success: true, data: record });
565
- }
566
- function registerA2ARoutes(app) {
567
- app.get("/api/a2a/.well-known/agent.json", handleAgentCard);
568
- app.get("/api/a2a/.well-known/agent-card.json", handleAgentCard);
569
- app.post(
570
- "/api/a2a/tasks/send",
571
- handleTasksSend
572
- );
573
- app.get(
574
- "/api/a2a/tasks/:taskId",
575
- handleTasksGet
576
- );
577
- app.get(
578
- "/api/a2a/tasks/:taskId/stream",
579
- handleTasksStream
580
- );
581
- app.post(
582
- "/api/a2a/tasks/:taskId/cancel",
583
- handleTasksCancel
584
- );
585
- app.get(
586
- "/api/a2a/keys",
587
- handleApiKeyList
588
- );
589
- app.post(
590
- "/api/a2a/keys",
591
- handleApiKeyCreate
592
- );
593
- app.delete(
594
- "/api/a2a/keys/:id",
595
- handleApiKeyDelete
596
- );
597
- app.post(
598
- "/api/a2a/keys/:id/disable",
599
- handleApiKeyDisable
600
- );
601
- app.post(
602
- "/api/a2a/keys/:id/enable",
603
- handleApiKeyEnable
604
- );
605
- app.post(
606
- "/api/a2a/keys/:id/rotate",
607
- handleApiKeyRotate
608
- );
609
- }
610
- export {
611
- refreshStoreKeyMap,
612
- registerA2ARoutes,
613
- setA2AKeyStore
614
- };
615
- //# sourceMappingURL=a2a-QMHEH3ZT.mjs.map