@cogitator-ai/fastify 0.1.1

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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +380 -0
  3. package/dist/hooks/auth.d.ts +4 -0
  4. package/dist/hooks/auth.d.ts.map +1 -0
  5. package/dist/hooks/auth.js +23 -0
  6. package/dist/hooks/auth.js.map +1 -0
  7. package/dist/hooks/error-handler.d.ts +3 -0
  8. package/dist/hooks/error-handler.d.ts.map +1 -0
  9. package/dist/hooks/error-handler.js +24 -0
  10. package/dist/hooks/error-handler.js.map +1 -0
  11. package/dist/hooks/index.d.ts +3 -0
  12. package/dist/hooks/index.d.ts.map +1 -0
  13. package/dist/hooks/index.js +3 -0
  14. package/dist/hooks/index.js.map +1 -0
  15. package/dist/index.d.ts +8 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +6 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/plugin.d.ts +4 -0
  20. package/dist/plugin.d.ts.map +1 -0
  21. package/dist/plugin.js +90 -0
  22. package/dist/plugin.js.map +1 -0
  23. package/dist/routes/agents.d.ts +3 -0
  24. package/dist/routes/agents.d.ts.map +1 -0
  25. package/dist/routes/agents.js +125 -0
  26. package/dist/routes/agents.js.map +1 -0
  27. package/dist/routes/health.d.ts +3 -0
  28. package/dist/routes/health.d.ts.map +1 -0
  29. package/dist/routes/health.js +15 -0
  30. package/dist/routes/health.js.map +1 -0
  31. package/dist/routes/index.d.ts +7 -0
  32. package/dist/routes/index.d.ts.map +1 -0
  33. package/dist/routes/index.js +7 -0
  34. package/dist/routes/index.js.map +1 -0
  35. package/dist/routes/swarms.d.ts +3 -0
  36. package/dist/routes/swarms.d.ts.map +1 -0
  37. package/dist/routes/swarms.js +193 -0
  38. package/dist/routes/swarms.js.map +1 -0
  39. package/dist/routes/threads.d.ts +3 -0
  40. package/dist/routes/threads.d.ts.map +1 -0
  41. package/dist/routes/threads.js +122 -0
  42. package/dist/routes/threads.js.map +1 -0
  43. package/dist/routes/tools.d.ts +3 -0
  44. package/dist/routes/tools.d.ts.map +1 -0
  45. package/dist/routes/tools.js +26 -0
  46. package/dist/routes/tools.js.map +1 -0
  47. package/dist/routes/workflows.d.ts +3 -0
  48. package/dist/routes/workflows.d.ts.map +1 -0
  49. package/dist/routes/workflows.js +120 -0
  50. package/dist/routes/workflows.js.map +1 -0
  51. package/dist/streaming/fastify-stream-writer.d.ts +24 -0
  52. package/dist/streaming/fastify-stream-writer.d.ts.map +1 -0
  53. package/dist/streaming/fastify-stream-writer.js +75 -0
  54. package/dist/streaming/fastify-stream-writer.js.map +1 -0
  55. package/dist/streaming/helpers.d.ts +2 -0
  56. package/dist/streaming/helpers.d.ts.map +1 -0
  57. package/dist/streaming/helpers.js +2 -0
  58. package/dist/streaming/helpers.js.map +1 -0
  59. package/dist/streaming/index.d.ts +4 -0
  60. package/dist/streaming/index.d.ts.map +1 -0
  61. package/dist/streaming/index.js +4 -0
  62. package/dist/streaming/index.js.map +1 -0
  63. package/dist/streaming/protocol.d.ts +3 -0
  64. package/dist/streaming/protocol.d.ts.map +1 -0
  65. package/dist/streaming/protocol.js +2 -0
  66. package/dist/streaming/protocol.js.map +1 -0
  67. package/dist/types.d.ts +344 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +59 -0
  70. package/dist/types.js.map +1 -0
  71. package/dist/websocket/handler.d.ts +7 -0
  72. package/dist/websocket/handler.d.ts.map +1 -0
  73. package/dist/websocket/handler.js +132 -0
  74. package/dist/websocket/handler.js.map +1 -0
  75. package/package.json +70 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Cogitator Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,380 @@
1
+ # @cogitator-ai/fastify
2
+
3
+ Fastify server adapter for Cogitator AI runtime. Automatically generates REST API endpoints for agents, workflows, and swarms with SSE streaming, WebSocket support, and Swagger documentation.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @cogitator-ai/fastify fastify
9
+ # or
10
+ pnpm add @cogitator-ai/fastify fastify
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import Fastify from 'fastify';
17
+ import { Cogitator, Agent } from '@cogitator-ai/core';
18
+ import { cogitatorPlugin } from '@cogitator-ai/fastify';
19
+
20
+ const fastify = Fastify({ logger: true });
21
+
22
+ const cogitator = new Cogitator({
23
+ defaultBackend: 'openai',
24
+ backends: { openai: { apiKey: process.env.OPENAI_API_KEY } },
25
+ });
26
+
27
+ const chatAgent = new Agent({
28
+ name: 'chat',
29
+ instructions: 'You are a helpful assistant.',
30
+ model: 'gpt-4o-mini',
31
+ });
32
+
33
+ await fastify.register(cogitatorPlugin, {
34
+ cogitator,
35
+ agents: { chat: chatAgent },
36
+ prefix: '/api',
37
+ enableSwagger: true,
38
+ });
39
+
40
+ await fastify.listen({ port: 3000 });
41
+ console.log('Server running on http://localhost:3000');
42
+ ```
43
+
44
+ ## Auto-generated Endpoints
45
+
46
+ ### Agents
47
+
48
+ ```
49
+ GET /api/agents - List all agents
50
+ POST /api/agents/:name/run - Run agent (JSON response)
51
+ POST /api/agents/:name/stream - Run agent (SSE stream)
52
+ ```
53
+
54
+ ### Threads (Memory)
55
+
56
+ ```
57
+ GET /api/threads/:id - Get thread messages
58
+ POST /api/threads/:id/messages - Add message to thread
59
+ DELETE /api/threads/:id - Delete thread
60
+ ```
61
+
62
+ ### Workflows
63
+
64
+ ```
65
+ GET /api/workflows - List all workflows
66
+ POST /api/workflows/:name/run - Run workflow
67
+ POST /api/workflows/:name/stream - Stream workflow events
68
+ ```
69
+
70
+ ### Swarms
71
+
72
+ ```
73
+ GET /api/swarms - List all swarms
74
+ POST /api/swarms/:name/run - Run swarm
75
+ POST /api/swarms/:name/stream - Stream swarm events
76
+ GET /api/swarms/:name/blackboard - Get shared state
77
+ ```
78
+
79
+ ### Tools & Docs
80
+
81
+ ```
82
+ GET /api/tools - List all tools
83
+ GET /api/health - Health check
84
+ GET /api/docs - Swagger UI
85
+ ```
86
+
87
+ ## Configuration
88
+
89
+ ```typescript
90
+ await fastify.register(cogitatorPlugin, {
91
+ cogitator,
92
+ agents: { chat: chatAgent, research: researchAgent },
93
+ workflows: { 'code-review': codeReviewWorkflow },
94
+ swarms: { 'dev-team': devTeamSwarm },
95
+ prefix: '/cogitator',
96
+ enableWebSocket: true,
97
+ enableSwagger: true,
98
+
99
+ // Authentication
100
+ auth: async (request) => {
101
+ const token = request.headers.authorization?.replace('Bearer ', '');
102
+ const user = await validateToken(token);
103
+ return { userId: user.id, roles: user.roles };
104
+ },
105
+
106
+ // Rate limiting (requires @fastify/rate-limit)
107
+ rateLimit: {
108
+ max: 100,
109
+ timeWindow: '1 minute',
110
+ },
111
+
112
+ // Swagger customization
113
+ swagger: {
114
+ title: 'My AI API',
115
+ description: 'AI-powered API endpoints',
116
+ version: '1.0.0',
117
+ },
118
+
119
+ // WebSocket options
120
+ websocket: {
121
+ path: '/ws',
122
+ pingInterval: 30000,
123
+ },
124
+ });
125
+ ```
126
+
127
+ ## SSE Streaming
128
+
129
+ The `/agents/:name/stream` endpoint returns Server-Sent Events:
130
+
131
+ ```typescript
132
+ const response = await fetch('/api/agents/chat/stream', {
133
+ method: 'POST',
134
+ headers: { 'Content-Type': 'application/json' },
135
+ body: JSON.stringify({ input: 'Hello!' }),
136
+ });
137
+
138
+ const reader = response.body.getReader();
139
+ const decoder = new TextDecoder();
140
+
141
+ while (true) {
142
+ const { done, value } = await reader.read();
143
+ if (done) break;
144
+
145
+ const lines = decoder.decode(value).split('\n');
146
+ for (const line of lines) {
147
+ if (line.startsWith('data: ')) {
148
+ const event = JSON.parse(line.slice(6));
149
+ console.log(event);
150
+ // { type: 'text-delta', id: '...', delta: 'Hello' }
151
+ }
152
+ }
153
+ }
154
+ ```
155
+
156
+ ### Stream Events
157
+
158
+ | Event Type | Description |
159
+ | ----------------- | --------------------------------------- |
160
+ | `start` | Stream started, includes message ID |
161
+ | `text-start` | Text generation started |
162
+ | `text-delta` | Text chunk received |
163
+ | `text-end` | Text generation finished |
164
+ | `tool-call-start` | Tool execution started |
165
+ | `tool-call-end` | Tool execution finished |
166
+ | `tool-result` | Tool returned result |
167
+ | `workflow` | Workflow event (node started/completed) |
168
+ | `swarm` | Swarm event (agent started/completed) |
169
+ | `error` | Error occurred |
170
+ | `finish` | Stream finished, includes usage stats |
171
+
172
+ ## WebSocket Support
173
+
174
+ Enable real-time bidirectional communication:
175
+
176
+ ```typescript
177
+ await fastify.register(cogitatorPlugin, {
178
+ // ...
179
+ enableWebSocket: true,
180
+ });
181
+ ```
182
+
183
+ Client usage:
184
+
185
+ ```typescript
186
+ const ws = new WebSocket('ws://localhost:3000/api/ws');
187
+
188
+ ws.onmessage = (event) => {
189
+ const message = JSON.parse(event.data);
190
+ console.log(message);
191
+ };
192
+
193
+ // Run agent
194
+ ws.send(
195
+ JSON.stringify({
196
+ type: 'run',
197
+ id: 'req-1',
198
+ payload: {
199
+ type: 'agent',
200
+ name: 'chat',
201
+ input: 'Hello!',
202
+ },
203
+ })
204
+ );
205
+
206
+ // Subscribe to channel
207
+ ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));
208
+
209
+ // Ping/pong
210
+ ws.send(JSON.stringify({ type: 'ping' }));
211
+ ```
212
+
213
+ ### WebSocket Message Types
214
+
215
+ | Type | Direction | Description |
216
+ | ------------- | ------------- | ------------------------ |
217
+ | `ping` | Client→Server | Heartbeat |
218
+ | `pong` | Server→Client | Heartbeat response |
219
+ | `subscribe` | Client→Server | Subscribe to channel |
220
+ | `subscribed` | Server→Client | Subscription confirmed |
221
+ | `unsubscribe` | Client→Server | Unsubscribe from channel |
222
+ | `run` | Client→Server | Run agent/workflow/swarm |
223
+ | `stop` | Client→Server | Cancel running operation |
224
+ | `event` | Server→Client | Stream event |
225
+ | `error` | Server→Client | Error message |
226
+
227
+ ## Custom Streaming
228
+
229
+ Use `FastifyStreamWriter` for custom streaming routes:
230
+
231
+ ```typescript
232
+ import { FastifyStreamWriter, generateId } from '@cogitator-ai/fastify';
233
+
234
+ fastify.post('/custom/stream', async (request, reply) => {
235
+ const writer = new FastifyStreamWriter(reply);
236
+ const messageId = generateId('msg');
237
+
238
+ writer.start(messageId);
239
+ const textId = generateId('txt');
240
+ writer.textStart(textId);
241
+
242
+ // Your streaming logic
243
+ writer.textDelta(textId, 'Hello ');
244
+ writer.textDelta(textId, 'World!');
245
+
246
+ writer.textEnd(textId);
247
+ writer.finish(messageId);
248
+ writer.close();
249
+ });
250
+ ```
251
+
252
+ ## Optional Dependencies
253
+
254
+ Install these packages to enable additional features:
255
+
256
+ ```bash
257
+ # Swagger UI
258
+ pnpm add @fastify/swagger @fastify/swagger-ui
259
+
260
+ # Rate limiting
261
+ pnpm add @fastify/rate-limit
262
+
263
+ # WebSocket support
264
+ pnpm add @fastify/websocket
265
+
266
+ # Workflows support
267
+ pnpm add @cogitator-ai/workflows
268
+
269
+ # Swarms support
270
+ pnpm add @cogitator-ai/swarms
271
+ ```
272
+
273
+ ## API Reference
274
+
275
+ ### cogitatorPlugin
276
+
277
+ ```typescript
278
+ import { cogitatorPlugin } from '@cogitator-ai/fastify';
279
+
280
+ await fastify.register(cogitatorPlugin, options);
281
+ ```
282
+
283
+ ### CogitatorPluginOptions
284
+
285
+ ```typescript
286
+ interface CogitatorPluginOptions {
287
+ cogitator: Cogitator;
288
+ agents?: Record<string, Agent>;
289
+ workflows?: Record<string, Workflow>;
290
+ swarms?: Record<string, SwarmConfig>;
291
+ prefix?: string; // Default: '/cogitator'
292
+ auth?: AuthFunction;
293
+ rateLimit?: RateLimitConfig;
294
+ enableSwagger?: boolean; // Default: false
295
+ enableWebSocket?: boolean; // Default: false
296
+ swagger?: SwaggerConfig;
297
+ websocket?: WebSocketConfig;
298
+ requestTimeout?: number;
299
+ }
300
+ ```
301
+
302
+ ### FastifyStreamWriter
303
+
304
+ ```typescript
305
+ class FastifyStreamWriter {
306
+ constructor(reply: FastifyReply);
307
+ start(messageId: string): void;
308
+ textStart(id: string): void;
309
+ textDelta(id: string, delta: string): void;
310
+ textEnd(id: string): void;
311
+ toolCallStart(id: string, toolName: string): void;
312
+ toolCallDelta(id: string, argsTextDelta: string): void;
313
+ toolCallEnd(id: string): void;
314
+ toolResult(id: string, toolCallId: string, result: unknown): void;
315
+ workflowEvent(event: string, data: unknown): void;
316
+ swarmEvent(event: string, data: unknown): void;
317
+ error(message: string, code?: string): void;
318
+ finish(messageId: string, usage?: Usage): void;
319
+ close(): void;
320
+ }
321
+ ```
322
+
323
+ ## Fastify Decorators
324
+
325
+ The plugin adds decorators to the Fastify instance:
326
+
327
+ ```typescript
328
+ // Access cogitator context
329
+ fastify.cogitator.runtime; // Cogitator instance
330
+ fastify.cogitator.agents; // Registered agents
331
+ fastify.cogitator.workflows; // Registered workflows
332
+ fastify.cogitator.swarms; // Registered swarms
333
+
334
+ // Request decorators (in handlers)
335
+ request.cogitatorAuth; // Auth context from auth hook
336
+ request.cogitatorRequestId; // Unique request ID
337
+ request.cogitatorStartTime; // Request start timestamp
338
+ ```
339
+
340
+ ## Error Handling
341
+
342
+ All endpoints return consistent error responses:
343
+
344
+ ```json
345
+ {
346
+ "error": {
347
+ "message": "Agent 'unknown' not found",
348
+ "code": "NOT_FOUND"
349
+ }
350
+ }
351
+ ```
352
+
353
+ Error codes map to HTTP status codes:
354
+
355
+ - `INVALID_INPUT` → 400
356
+ - `UNAUTHORIZED` → 401
357
+ - `PERMISSION_DENIED` → 403
358
+ - `NOT_FOUND` → 404
359
+ - `RATE_LIMIT_EXCEEDED` → 429
360
+ - `INTERNAL` → 500
361
+ - `UNAVAILABLE` → 503
362
+ - `UNIMPLEMENTED` → 501
363
+
364
+ ## JSON Schema Validation
365
+
366
+ Fastify's built-in validation is used for all endpoints. Request schemas are exported:
367
+
368
+ ```typescript
369
+ import {
370
+ AgentRunRequestSchema,
371
+ AgentRunResponseSchema,
372
+ AddMessageRequestSchema,
373
+ WorkflowRunRequestSchema,
374
+ SwarmRunRequestSchema,
375
+ } from '@cogitator-ai/fastify';
376
+ ```
377
+
378
+ ## License
379
+
380
+ MIT
@@ -0,0 +1,4 @@
1
+ import type { onRequestHookHandler } from 'fastify';
2
+ import type { AuthFunction } from '../types.js';
3
+ export declare function createAuthHook(authFn?: AuthFunction): onRequestHookHandler;
4
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/hooks/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgC,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,YAAY,GAAG,oBAAoB,CAqB1E"}
@@ -0,0 +1,23 @@
1
+ import { generateId } from '../streaming/helpers.js';
2
+ export function createAuthHook(authFn) {
3
+ return async (request, reply) => {
4
+ request.cogitatorRequestId = generateId('req');
5
+ request.cogitatorStartTime = Date.now();
6
+ if (!authFn) {
7
+ return;
8
+ }
9
+ try {
10
+ const auth = await authFn(request);
11
+ request.cogitatorAuth = auth;
12
+ }
13
+ catch {
14
+ return reply.status(401).send({
15
+ error: {
16
+ message: 'Unauthorized',
17
+ code: 'UNAUTHORIZED',
18
+ },
19
+ });
20
+ }
21
+ };
22
+ }
23
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/hooks/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAErD,MAAM,UAAU,cAAc,CAAC,MAAqB;IAClD,OAAO,KAAK,EAAE,OAAuB,EAAE,KAAmB,EAAE,EAAE;QAC5D,OAAO,CAAC,kBAAkB,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;QAC/C,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAExC,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO;QACT,CAAC;QAED,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,CAAC;YACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBAC5B,KAAK,EAAE;oBACL,OAAO,EAAE,cAAc;oBACvB,IAAI,EAAE,cAAc;iBACrB;aACF,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { FastifyError, FastifyRequest, FastifyReply } from 'fastify';
2
+ export declare function errorHandler(error: FastifyError, _request: FastifyRequest, reply: FastifyReply): void;
3
+ //# sourceMappingURL=error-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-handler.d.ts","sourceRoot":"","sources":["../../src/hooks/error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG1E,wBAAgB,YAAY,CAC1B,KAAK,EAAE,YAAY,EACnB,QAAQ,EAAE,cAAc,EACxB,KAAK,EAAE,YAAY,GAClB,IAAI,CAwBN"}
@@ -0,0 +1,24 @@
1
+ import { CogitatorError, ERROR_STATUS_CODES, ErrorCode } from '@cogitator-ai/types';
2
+ export function errorHandler(error, _request, reply) {
3
+ if (reply.sent) {
4
+ return;
5
+ }
6
+ if (CogitatorError.isCogitatorError(error)) {
7
+ const statusCode = ERROR_STATUS_CODES[error.code] || 500;
8
+ reply.status(statusCode).send({
9
+ error: {
10
+ message: error.message,
11
+ code: error.code,
12
+ },
13
+ });
14
+ return;
15
+ }
16
+ console.error('[CogitatorPlugin] Unhandled error:', error);
17
+ reply.status(500).send({
18
+ error: {
19
+ message: 'Internal server error',
20
+ code: ErrorCode.INTERNAL_ERROR,
21
+ },
22
+ });
23
+ }
24
+ //# sourceMappingURL=error-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-handler.js","sourceRoot":"","sources":["../../src/hooks/error-handler.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEpF,MAAM,UAAU,YAAY,CAC1B,KAAmB,EACnB,QAAwB,EACxB,KAAmB;IAEnB,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IAED,IAAI,cAAc,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3C,MAAM,UAAU,GAAG,kBAAkB,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC;QACzD,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC5B,KAAK,EAAE;gBACL,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,IAAI,EAAE,KAAK,CAAC,IAAI;aACjB;SACF,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;IAE3D,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACrB,KAAK,EAAE;YACL,OAAO,EAAE,uBAAuB;YAChC,IAAI,EAAE,SAAS,CAAC,cAAc;SAC/B;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createAuthHook } from './auth.js';
2
+ export { errorHandler } from './error-handler.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createAuthHook } from './auth.js';
2
+ export { errorHandler } from './error-handler.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { cogitatorPlugin } from './plugin.js';
2
+ export type { CogitatorPluginOptions, CogitatorContext, AuthContext, AuthFunction, RateLimitConfig, SwaggerConfig, WebSocketConfig, AgentListResponse, AgentRunRequest, AgentRunResponse, ThreadResponse, AddMessageRequest, ToolListResponse, WorkflowListResponse, WorkflowRunRequest, WorkflowRunResponse, WorkflowStatusResponse, SwarmListResponse, SwarmRunRequest, SwarmRunResponse, BlackboardResponse, HealthResponse, ErrorResponse, WebSocketMessage, WebSocketResponse, OpenAPISpec, } from './types.js';
3
+ export { AgentRunRequestSchema, AgentRunResponseSchema, AddMessageRequestSchema, WorkflowRunRequestSchema, SwarmRunRequestSchema, } from './types.js';
4
+ export { FastifyStreamWriter } from './streaming/index.js';
5
+ export type { StreamEvent, Usage } from './streaming/protocol.js';
6
+ export { createStartEvent, createTextStartEvent, createTextDeltaEvent, createTextEndEvent, createToolCallStartEvent, createToolCallDeltaEvent, createToolCallEndEvent, createToolResultEvent, createErrorEvent, createFinishEvent, createWorkflowEvent, createSwarmEvent, } from './streaming/protocol.js';
7
+ export { generateId, encodeSSE, encodeDone } from './streaming/helpers.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,YAAY,EACV,sBAAsB,EACtB,gBAAgB,EAChB,WAAW,EACX,YAAY,EACZ,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,GACZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,YAAY,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { cogitatorPlugin } from './plugin.js';
2
+ export { AgentRunRequestSchema, AgentRunResponseSchema, AddMessageRequestSchema, WorkflowRunRequestSchema, SwarmRunRequestSchema, } from './types.js';
3
+ export { FastifyStreamWriter } from './streaming/index.js';
4
+ export { createStartEvent, createTextStartEvent, createTextDeltaEvent, createTextEndEvent, createToolCallStartEvent, createToolCallDeltaEvent, createToolCallEndEvent, createToolResultEvent, createErrorEvent, createFinishEvent, createWorkflowEvent, createSwarmEvent, } from './streaming/protocol.js';
5
+ export { generateId, encodeSSE, encodeDone } from './streaming/helpers.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AA+B9C,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAI3D,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { FastifyPluginAsync } from 'fastify';
2
+ import type { CogitatorPluginOptions } from './types.js';
3
+ export declare const cogitatorPlugin: FastifyPluginAsync<CogitatorPluginOptions>;
4
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAgB,MAAM,SAAS,CAAC;AAChE,OAAO,KAAK,EAAE,sBAAsB,EAAoB,MAAM,YAAY,CAAC;AA0G3E,eAAO,MAAM,eAAe,4CAG1B,CAAC"}
package/dist/plugin.js ADDED
@@ -0,0 +1,90 @@
1
+ import fp from 'fastify-plugin';
2
+ import { createAuthHook, errorHandler } from './hooks/index.js';
3
+ import { healthRoutes, agentRoutes, threadRoutes, toolRoutes, workflowRoutes, swarmRoutes, } from './routes/index.js';
4
+ const cogitatorPluginImpl = async (fastify, opts) => {
5
+ const context = {
6
+ runtime: opts.cogitator,
7
+ agents: opts.agents ?? {},
8
+ workflows: opts.workflows ?? {},
9
+ swarms: opts.swarms ?? {},
10
+ };
11
+ fastify.decorate('cogitator', context);
12
+ fastify.decorateRequest('cogitatorAuth', undefined);
13
+ fastify.decorateRequest('cogitatorRequestId', '');
14
+ fastify.decorateRequest('cogitatorStartTime', 0);
15
+ fastify.addHook('onRequest', createAuthHook(opts.auth));
16
+ if (opts.rateLimit) {
17
+ try {
18
+ const rateLimitModule = await import('@fastify/rate-limit');
19
+ await fastify.register(rateLimitModule.default, {
20
+ max: opts.rateLimit.max,
21
+ timeWindow: opts.rateLimit.timeWindow,
22
+ keyGenerator: opts.rateLimit.keyGenerator,
23
+ errorResponseBuilder: opts.rateLimit.errorResponseBuilder,
24
+ });
25
+ }
26
+ catch {
27
+ fastify.log.warn('@fastify/rate-limit not installed, skipping rate limiting');
28
+ }
29
+ }
30
+ const prefix = opts.prefix ?? '/cogitator';
31
+ await fastify.register(async (instance) => {
32
+ await instance.register(healthRoutes);
33
+ await instance.register(agentRoutes);
34
+ await instance.register(threadRoutes);
35
+ await instance.register(toolRoutes);
36
+ await instance.register(workflowRoutes);
37
+ await instance.register(swarmRoutes);
38
+ if (opts.enableSwagger) {
39
+ try {
40
+ const swaggerModule = await import('@fastify/swagger');
41
+ const swaggerUiModule = await import('@fastify/swagger-ui');
42
+ await instance.register(swaggerModule.default, {
43
+ openapi: {
44
+ info: {
45
+ title: opts.swagger?.title ?? 'Cogitator API',
46
+ description: opts.swagger?.description ?? 'AI Agent Runtime API',
47
+ version: opts.swagger?.version ?? '1.0.0',
48
+ contact: opts.swagger?.contact,
49
+ license: opts.swagger?.license,
50
+ },
51
+ servers: opts.swagger?.servers ?? [{ url: '/', description: 'Current server' }],
52
+ tags: [
53
+ { name: 'agents', description: 'Agent operations' },
54
+ { name: 'threads', description: 'Thread/memory operations' },
55
+ { name: 'tools', description: 'Tool operations' },
56
+ { name: 'workflows', description: 'Workflow operations' },
57
+ { name: 'swarms', description: 'Swarm operations' },
58
+ { name: 'health', description: 'Health check endpoints' },
59
+ ],
60
+ },
61
+ });
62
+ await instance.register(swaggerUiModule.default, {
63
+ routePrefix: '/docs',
64
+ });
65
+ }
66
+ catch {
67
+ fastify.log.warn('@fastify/swagger not installed, skipping Swagger UI');
68
+ }
69
+ }
70
+ if (opts.enableWebSocket) {
71
+ try {
72
+ const websocketModule = await import('@fastify/websocket');
73
+ await instance.register(websocketModule.default);
74
+ const { websocketRoutes } = await import('./websocket/handler.js');
75
+ await instance.register(websocketRoutes, { path: opts.websocket?.path });
76
+ }
77
+ catch {
78
+ fastify.log.warn('@fastify/websocket not installed, skipping WebSocket support');
79
+ }
80
+ }
81
+ }, { prefix });
82
+ fastify.setErrorHandler((error, request, reply) => {
83
+ errorHandler(error, request, reply);
84
+ });
85
+ };
86
+ export const cogitatorPlugin = fp(cogitatorPluginImpl, {
87
+ fastify: '5.x',
88
+ name: '@cogitator-ai/fastify',
89
+ });
90
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAGhC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,UAAU,EACV,cAAc,EACd,WAAW,GACZ,MAAM,mBAAmB,CAAC;AAE3B,MAAM,mBAAmB,GAA+C,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;IAC9F,MAAM,OAAO,GAAqB;QAChC,OAAO,EAAE,IAAI,CAAC,SAAS;QACvB,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,EAAE;QACzB,SAAS,EAAE,IAAI,CAAC,SAAS,IAAI,EAAE;QAC/B,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,EAAE;KAC1B,CAAC;IAEF,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IAEvC,OAAO,CAAC,eAAe,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;IACpD,OAAO,CAAC,eAAe,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;IAClD,OAAO,CAAC,eAAe,CAAC,oBAAoB,EAAE,CAAC,CAAC,CAAC;IAEjD,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAExD,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;QACnB,IAAI,CAAC;YACH,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAC5D,MAAM,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,OAAO,EAAE;gBAC9C,GAAG,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,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC3E,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,8DAA8D,CAAC,CAAC;YACnF,CAAC;QACH,CAAC;IACH,CAAC,EACD,EAAE,MAAM,EAAE,CACX,CAAC;IAEF,OAAO,CAAC,eAAe,CAAC,CAAC,KAAmB,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QAC9D,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC,mBAAmB,EAAE;IACrD,OAAO,EAAE,KAAK;IACd,IAAI,EAAE,uBAAuB;CAC9B,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { FastifyPluginAsync } from 'fastify';
2
+ export declare const agentRoutes: FastifyPluginAsync;
3
+ //# sourceMappingURL=agents.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../../src/routes/agents.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAUlD,eAAO,MAAM,WAAW,EAAE,kBA6IzB,CAAC"}