@axiom-lattice/gateway 2.1.20 → 2.1.22

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": "2.1.20",
3
+ "version": "2.1.22",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -17,9 +17,12 @@
17
17
  "description": "API Gateway for LangGraph agent-based applications",
18
18
  "dependencies": {
19
19
  "@fastify/cors": "^11.0.0",
20
+ "@fastify/http-proxy": "^9.5.0",
21
+ "@fastify/reply-from": "^12.5.0",
20
22
  "@fastify/sensible": "^6.0.3",
21
23
  "@fastify/swagger": "^9.5.1",
22
24
  "@fastify/swagger-ui": "^5.2.3",
25
+ "@fastify/websocket": "^11.0.1",
23
26
  "@langchain/core": "1.1.4",
24
27
  "@langchain/langgraph": "1.0.4",
25
28
  "@supabase/supabase-js": "^2.49.1",
@@ -32,15 +35,16 @@
32
35
  "pino-roll": "^3.1.0",
33
36
  "redis": "^5.0.1",
34
37
  "uuid": "^9.0.1",
35
- "@axiom-lattice/core": "2.1.15",
36
- "@axiom-lattice/protocols": "2.1.9",
37
- "@axiom-lattice/queue-redis": "1.0.8"
38
+ "@axiom-lattice/core": "2.1.17",
39
+ "@axiom-lattice/protocols": "2.1.11",
40
+ "@axiom-lattice/queue-redis": "1.0.10"
38
41
  },
39
42
  "devDependencies": {
40
43
  "@types/jest": "^29.5.14",
41
44
  "@types/lodash": "^4.17.16",
42
45
  "@types/node": "^20.17.23",
43
46
  "@types/uuid": "^9.0.8",
47
+ "@types/ws": "^8.18.1",
44
48
  "@typescript-eslint/eslint-plugin": "^7.2.0",
45
49
  "@typescript-eslint/parser": "^7.2.0",
46
50
  "eslint": "^8.57.0",
@@ -0,0 +1,150 @@
1
+ import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
2
+ // import { WebSocket, createWebSocketStream } from "ws";
3
+ import { pipeline } from "stream/promises";
4
+ import { sandboxService } from "../services/sandbox_service";
5
+ const SANDBOX_BASE_URL = process.env.SANDBOX_BASE_URL || "http://localhost:8080";
6
+
7
+ interface SandboxParams {
8
+ assistantId: string;
9
+ threadId: string;
10
+ }
11
+
12
+ interface ProxyParams extends SandboxParams {
13
+ "*": string;
14
+ }
15
+
16
+ interface ResourceParams extends SandboxParams {
17
+ resourcePath: string;
18
+ }
19
+
20
+ export async function registerSandboxProxyRoutes(app: FastifyInstance): Promise<void> {
21
+ app.get<{ Params: SandboxParams }>(
22
+ "/api/assistants/:assistantId/threads/:threadId/sandbox",
23
+ async (request, reply) => {
24
+ const { assistantId, threadId } = request.params;
25
+
26
+ const sandboxConfig = sandboxService.getSandboxConfig(assistantId);
27
+ if (!sandboxConfig) {
28
+ const errorHtml = sandboxService.generateErrorHtml(
29
+ assistantId,
30
+ threadId,
31
+ "unknown",
32
+ `Assistant ${assistantId} not found`
33
+ );
34
+ return reply.status(404).type("text/html").send(errorHtml);
35
+ }
36
+
37
+ const { isolatedLevel } = sandboxConfig;
38
+ const sandboxName = sandboxService.computeSandboxName(
39
+ assistantId,
40
+ threadId,
41
+ isolatedLevel
42
+ );
43
+
44
+ try {
45
+ const html = await sandboxService.getVncHtml(sandboxName);
46
+ const rewrittenHtml = sandboxService.rewriteHtml(html, assistantId, threadId);
47
+ return reply.type("text/html").send(rewrittenHtml);
48
+ } catch (error: any) {
49
+ const errorHtml = sandboxService.generateErrorHtml(
50
+ assistantId,
51
+ threadId,
52
+ isolatedLevel,
53
+ error.message || "Failed to connect to sandbox"
54
+ );
55
+ return reply.status(502).type("text/html").send(errorHtml);
56
+ }
57
+ }
58
+ );
59
+
60
+
61
+
62
+ // app.get<{ Params: SandboxParams }>(
63
+ // "/api/assistants/:assistantId/threads/:threadId/sandbox/websockify",
64
+ // { websocket: true },
65
+
66
+ // (connection, request) => {
67
+
68
+ // const url = (connection?.url) as string;
69
+ // console.log(`[WebSocket] Received connection from URL: ${url}`);
70
+
71
+ // const urlMatch = url.match(/\/api\/assistants\/([^/]+)\/threads\/([^/]+)\/sandbox\/websockify/);
72
+ // if (!urlMatch) {
73
+ // console.error(`[WebSocket] Failed to parse params from URL: ${url}`);
74
+ // connection.close(1008, "Invalid URL format");
75
+ // return;
76
+ // }
77
+
78
+ // const assistantId = urlMatch[1];
79
+ // const threadId = urlMatch[2];
80
+ // console.log(`[WebSocket] Parsed params - assistantId: ${assistantId}, threadId: ${threadId}`);
81
+
82
+ // const sandboxConfig = sandboxService.getSandboxConfig(assistantId);
83
+ // if (!sandboxConfig) {
84
+ // console.error(`[WebSocket] Assistant ${assistantId} not found`);
85
+ // connection.close(1008, "Assistant not found");
86
+ // return;
87
+ // }
88
+
89
+ // const { isolatedLevel } = sandboxConfig;
90
+ // const sandboxName = sandboxService.computeSandboxName(
91
+ // assistantId,
92
+ // threadId,
93
+ // isolatedLevel
94
+ // );
95
+
96
+ // const targetUrl = sandboxService.getTargetUrl(sandboxName);
97
+ // const targetWsUrl = targetUrl.replace(/^http/, "ws").replace(/^https/, "wss") + "/websockify";
98
+
99
+ // console.log(`[WebSocket] Connecting to target: ${targetWsUrl}`);
100
+
101
+ // const targetSocket = new WebSocket(targetWsUrl);
102
+ // const clientStream = createWebSocketStream(connection, { encoding: "utf8" });
103
+
104
+ // const targetStream = createWebSocketStream(targetSocket, { encoding: "utf8" });
105
+
106
+ // const forward = pipeline(clientStream, targetStream);
107
+ // const backward = pipeline(targetStream, clientStream);
108
+
109
+ // Promise.all([forward, backward]).catch((err) => {
110
+ // console.error(`[WebSocket] Proxy pipeline failed:`, err.message);
111
+ // targetSocket.terminate();
112
+ // connection.terminate();
113
+ // });
114
+ // }
115
+ // );
116
+
117
+ app.get<{ Params: ProxyParams }>(
118
+ "/api/assistants/:assistantId/threads/:threadId/sandbox/vnc/*",
119
+ async (request, reply) => {
120
+ const { assistantId, threadId, "*": restPath } = request.params;
121
+
122
+ const sandboxConfig = sandboxService.getSandboxConfig(assistantId);
123
+ if (!sandboxConfig) {
124
+ return reply.status(404).send("Assistant not found");
125
+ }
126
+
127
+ const { isolatedLevel } = sandboxConfig;
128
+ const sandboxName = sandboxService.computeSandboxName(
129
+ assistantId,
130
+ threadId,
131
+ isolatedLevel
132
+ );
133
+
134
+ const targetPath = restPath ? `/vnc/${restPath}` : "/vnc/";
135
+ const targetUrl = `${sandboxService.getTargetUrl(sandboxName)}${targetPath}`;
136
+
137
+ try {
138
+ const response = await fetch(targetUrl);
139
+ const contentType = response.headers.get("content-type") || "application/octet-stream";
140
+
141
+ const body = await response.arrayBuffer();
142
+ reply.status(response.status).type(contentType).send(Buffer.from(body));
143
+ } catch (error: any) {
144
+ reply.status(502).send(`Proxy error: ${error.message}`);
145
+ }
146
+ }
147
+ );
148
+
149
+
150
+ }
@@ -0,0 +1,474 @@
1
+ import { FastifyRequest, FastifyReply } from "fastify";
2
+ import { getStoreLattice } from "@axiom-lattice/core";
3
+ import { validateSkillName } from "@axiom-lattice/core";
4
+ import type {
5
+ Skill,
6
+ CreateSkillRequest,
7
+ } from "@axiom-lattice/protocols";
8
+
9
+ /**
10
+ * Skills Controller
11
+ * Handles skill-related CRUD operations
12
+ */
13
+
14
+ /**
15
+ * Skill list response interface
16
+ */
17
+ interface SkillListResponse {
18
+ success: boolean;
19
+ message: string;
20
+ data: {
21
+ records: Skill[];
22
+ total: number;
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Skill response interface
28
+ */
29
+ interface SkillResponse {
30
+ success: boolean;
31
+ message: string;
32
+ data?: Skill;
33
+ }
34
+
35
+ /**
36
+ * Skill update request body interface
37
+ */
38
+ interface SkillUpdateBody {
39
+ name?: string;
40
+ description?: string;
41
+ license?: string;
42
+ compatibility?: string;
43
+ metadata?: Record<string, string>;
44
+ content?: string;
45
+ subSkills?: string[];
46
+ }
47
+
48
+ /**
49
+ * Serialize Skill object for JSON response
50
+ * Converts Date objects to ISO strings
51
+ * Explicitly creates a plain object to ensure all fields are serializable
52
+ */
53
+ function serializeSkill(skill: Skill): any {
54
+ // Explicitly create a plain object with all fields
55
+ // This ensures Fastify can properly serialize the response
56
+ const serialized: any = {
57
+ id: skill.id,
58
+ name: skill.name,
59
+ description: skill.description,
60
+ license: skill.license,
61
+ compatibility: skill.compatibility,
62
+ metadata: skill.metadata || {},
63
+ content: skill.content,
64
+ subSkills: skill.subSkills,
65
+ createdAt: skill.createdAt instanceof Date ? skill.createdAt.toISOString() : (skill.createdAt ? new Date(skill.createdAt).toISOString() : new Date().toISOString()),
66
+ updatedAt: skill.updatedAt instanceof Date ? skill.updatedAt.toISOString() : (skill.updatedAt ? new Date(skill.updatedAt).toISOString() : new Date().toISOString()),
67
+ };
68
+
69
+ // Remove undefined fields to avoid serialization issues
70
+ Object.keys(serialized).forEach((key) => {
71
+ if (serialized[key] === undefined) {
72
+ delete serialized[key];
73
+ }
74
+ });
75
+
76
+ return serialized;
77
+ }
78
+
79
+ /**
80
+ * Get list of all skills
81
+ */
82
+ export async function getSkillList(
83
+ request: FastifyRequest,
84
+ reply: FastifyReply
85
+ ): Promise<SkillListResponse> {
86
+ try {
87
+ const storeLattice = getStoreLattice("default", "skill");
88
+ const skillStore = storeLattice.store;
89
+ const skills = await skillStore.getAllSkills();
90
+
91
+ // Serialize skills to convert Date objects to ISO strings
92
+ const serializedSkills = skills.map(serializeSkill);
93
+
94
+ return {
95
+ success: true,
96
+ message: "Successfully retrieved skill list",
97
+ data: {
98
+ records: serializedSkills,
99
+ total: serializedSkills.length,
100
+ },
101
+ };
102
+ } catch (error: any) {
103
+ return reply.status(500).send({
104
+ success: false,
105
+ message: `Failed to retrieve skills: ${error.message}`,
106
+ data: {
107
+ records: [],
108
+ total: 0,
109
+ },
110
+ });
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Get a single skill by ID
116
+ */
117
+ export async function getSkill(
118
+ request: FastifyRequest<{ Params: { id: string } }>,
119
+ reply: FastifyReply
120
+ ): Promise<SkillResponse> {
121
+ try {
122
+ const { id } = request.params;
123
+
124
+ const storeLattice = getStoreLattice("default", "skill");
125
+ const skillStore = storeLattice.store;
126
+ const skill = await skillStore.getSkillById(id);
127
+
128
+ if (!skill) {
129
+ return reply.status(404).send({
130
+ success: false,
131
+ message: "Skill not found",
132
+ });
133
+ }
134
+
135
+ return {
136
+ success: true,
137
+ message: "Successfully retrieved skill",
138
+ data: serializeSkill(skill),
139
+ };
140
+ } catch (error: any) {
141
+ return reply.status(500).send({
142
+ success: false,
143
+ message: `Failed to retrieve skill: ${error.message}`,
144
+ });
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Create a new skill
150
+ */
151
+ export async function createSkill(
152
+ request: FastifyRequest<{ Body: CreateSkillRequest }>,
153
+ reply: FastifyReply
154
+ ): Promise<SkillResponse> {
155
+ try {
156
+ const data = request.body;
157
+
158
+ // Validate required fields
159
+ if (!data.name) {
160
+ return reply.status(400).send({
161
+ success: false,
162
+ message: "name is required",
163
+ });
164
+ }
165
+
166
+ if (!data.description) {
167
+ return reply.status(400).send({
168
+ success: false,
169
+ message: "description is required",
170
+ });
171
+ }
172
+
173
+ // Validate name format
174
+ try {
175
+ validateSkillName(data.name);
176
+ } catch (error: any) {
177
+ return reply.status(400).send({
178
+ success: false,
179
+ message: error.message || "Invalid skill name format",
180
+ });
181
+ }
182
+
183
+ // ID must equal name (name is used for path addressing)
184
+ const id = (request.body as any).id || data.name;
185
+
186
+ if (id !== data.name) {
187
+ return reply.status(400).send({
188
+ success: false,
189
+ message: `id "${id}" must equal name "${data.name}" (name is used for path addressing)`,
190
+ });
191
+ }
192
+
193
+ const storeLattice = getStoreLattice("default", "skill");
194
+ const skillStore = storeLattice.store;
195
+
196
+ // Check if skill already exists
197
+ const exists = await skillStore.hasSkill(id);
198
+ if (exists) {
199
+ return reply.status(409).send({
200
+ success: false,
201
+ message: `Skill with id "${id}" already exists`,
202
+ });
203
+ }
204
+
205
+ // Create skill
206
+ const newSkill = await skillStore.createSkill(id, data);
207
+
208
+ return reply.status(201).send({
209
+ success: true,
210
+ message: "Successfully created skill",
211
+ data: serializeSkill(newSkill),
212
+ });
213
+ } catch (error: any) {
214
+ return reply.status(500).send({
215
+ success: false,
216
+ message: `Failed to create skill: ${error.message}`,
217
+ });
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Update an existing skill by ID
223
+ */
224
+ export async function updateSkill(
225
+ request: FastifyRequest<{
226
+ Params: { id: string };
227
+ Body: SkillUpdateBody;
228
+ }>,
229
+ reply: FastifyReply
230
+ ): Promise<SkillResponse> {
231
+ try {
232
+ const { id } = request.params;
233
+ const updates = request.body;
234
+
235
+ // Validate name format if name is being updated
236
+ if (updates.name !== undefined) {
237
+ try {
238
+ validateSkillName(updates.name);
239
+ } catch (error: any) {
240
+ return reply.status(400).send({
241
+ success: false,
242
+ message: error.message || "Invalid skill name format",
243
+ });
244
+ }
245
+ }
246
+
247
+ const storeLattice = getStoreLattice("default", "skill");
248
+ const skillStore = storeLattice.store;
249
+
250
+ // Check if skill exists
251
+ const exists = await skillStore.hasSkill(id);
252
+ if (!exists) {
253
+ return reply.status(404).send({
254
+ success: false,
255
+ message: "Skill not found",
256
+ });
257
+ }
258
+
259
+ // Update skill
260
+ const updatedSkill = await skillStore.updateSkill(id, updates);
261
+
262
+ if (!updatedSkill) {
263
+ return reply.status(500).send({
264
+ success: false,
265
+ message: "Failed to update skill",
266
+ });
267
+ }
268
+
269
+ return {
270
+ success: true,
271
+ message: "Successfully updated skill",
272
+ data: serializeSkill(updatedSkill),
273
+ };
274
+ } catch (error: any) {
275
+ return reply.status(500).send({
276
+ success: false,
277
+ message: `Failed to update skill: ${error.message}`,
278
+ });
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Delete a skill by ID
284
+ */
285
+ export async function deleteSkill(
286
+ request: FastifyRequest<{ Params: { id: string } }>,
287
+ reply: FastifyReply
288
+ ): Promise<{ success: boolean; message: string }> {
289
+ try {
290
+ const { id } = request.params;
291
+
292
+ const storeLattice = getStoreLattice("default", "skill");
293
+ const skillStore = storeLattice.store;
294
+
295
+ // Check if skill exists
296
+ const exists = await skillStore.hasSkill(id);
297
+ if (!exists) {
298
+ return reply.status(404).send({
299
+ success: false,
300
+ message: "Skill not found",
301
+ });
302
+ }
303
+
304
+ // Delete the skill
305
+ const deleted = await skillStore.deleteSkill(id);
306
+
307
+ if (!deleted) {
308
+ return reply.status(500).send({
309
+ success: false,
310
+ message: "Failed to delete skill",
311
+ });
312
+ }
313
+
314
+ return {
315
+ success: true,
316
+ message: "Successfully deleted skill",
317
+ };
318
+ } catch (error: any) {
319
+ return reply.status(500).send({
320
+ success: false,
321
+ message: `Failed to delete skill: ${error.message}`,
322
+ });
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Search skills by metadata
328
+ */
329
+ export async function searchSkillsByMetadata(
330
+ request: FastifyRequest<{
331
+ Querystring: { key: string; value: string };
332
+ }>,
333
+ reply: FastifyReply
334
+ ): Promise<SkillListResponse> {
335
+ try {
336
+ const { key, value } = request.query;
337
+
338
+ if (!key || !value) {
339
+ return reply.status(400).send({
340
+ success: false,
341
+ message: "key and value query parameters are required",
342
+ data: {
343
+ records: [],
344
+ total: 0,
345
+ },
346
+ });
347
+ }
348
+
349
+ const storeLattice = getStoreLattice("default", "skill");
350
+ const skillStore = storeLattice.store;
351
+ const skills = await skillStore.searchByMetadata(key, value);
352
+
353
+ // Serialize skills to convert Date objects to ISO strings
354
+ const serializedSkills = skills.map(serializeSkill);
355
+
356
+ return {
357
+ success: true,
358
+ message: "Successfully searched skills",
359
+ data: {
360
+ records: serializedSkills,
361
+ total: serializedSkills.length,
362
+ },
363
+ };
364
+ } catch (error: any) {
365
+ return reply.status(500).send({
366
+ success: false,
367
+ message: `Failed to search skills: ${error.message}`,
368
+ data: {
369
+ records: [],
370
+ total: 0,
371
+ },
372
+ });
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Filter skills by compatibility
378
+ */
379
+ export async function filterSkillsByCompatibility(
380
+ request: FastifyRequest<{
381
+ Querystring: { compatibility: string };
382
+ }>,
383
+ reply: FastifyReply
384
+ ): Promise<SkillListResponse> {
385
+ try {
386
+ const { compatibility } = request.query;
387
+
388
+ if (!compatibility) {
389
+ return reply.status(400).send({
390
+ success: false,
391
+ message: "compatibility query parameter is required",
392
+ data: {
393
+ records: [],
394
+ total: 0,
395
+ },
396
+ });
397
+ }
398
+
399
+ const storeLattice = getStoreLattice("default", "skill");
400
+ const skillStore = storeLattice.store;
401
+ const skills = await skillStore.filterByCompatibility(compatibility);
402
+
403
+ // Serialize skills to convert Date objects to ISO strings
404
+ const serializedSkills = skills.map(serializeSkill);
405
+
406
+ return {
407
+ success: true,
408
+ message: "Successfully filtered skills",
409
+ data: {
410
+ records: serializedSkills,
411
+ total: serializedSkills.length,
412
+ },
413
+ };
414
+ } catch (error: any) {
415
+ return reply.status(500).send({
416
+ success: false,
417
+ message: `Failed to filter skills: ${error.message}`,
418
+ data: {
419
+ records: [],
420
+ total: 0,
421
+ },
422
+ });
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Filter skills by license
428
+ */
429
+ export async function filterSkillsByLicense(
430
+ request: FastifyRequest<{
431
+ Querystring: { license: string };
432
+ }>,
433
+ reply: FastifyReply
434
+ ): Promise<SkillListResponse> {
435
+ try {
436
+ const { license } = request.query;
437
+
438
+ if (!license) {
439
+ return reply.status(400).send({
440
+ success: false,
441
+ message: "license query parameter is required",
442
+ data: {
443
+ records: [],
444
+ total: 0,
445
+ },
446
+ });
447
+ }
448
+
449
+ const storeLattice = getStoreLattice("default", "skill");
450
+ const skillStore = storeLattice.store;
451
+ const skills = await skillStore.filterByLicense(license);
452
+
453
+ // Serialize skills to convert Date objects to ISO strings
454
+ const serializedSkills = skills.map(serializeSkill);
455
+
456
+ return {
457
+ success: true,
458
+ message: "Successfully filtered skills",
459
+ data: {
460
+ records: serializedSkills,
461
+ total: serializedSkills.length,
462
+ },
463
+ };
464
+ } catch (error: any) {
465
+ return reply.status(500).send({
466
+ success: false,
467
+ message: `Failed to filter skills: ${error.message}`,
468
+ data: {
469
+ records: [],
470
+ total: 0,
471
+ },
472
+ });
473
+ }
474
+ }