cognitive-modules-cli 1.2.0 → 1.4.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.
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Cognitive Modules HTTP API Server
3
+ *
4
+ * Provides RESTful API interface for workflow platform integration.
5
+ *
6
+ * Start with:
7
+ * cog serve --port 8000
8
+ *
9
+ * Environment variables:
10
+ * COGNITIVE_API_KEY - API Key authentication (optional)
11
+ * OPENAI_API_KEY, ANTHROPIC_API_KEY, etc. - LLM provider keys
12
+ */
13
+
14
+ import http from 'node:http';
15
+ import { URL } from 'node:url';
16
+ import { loadModule, findModule, listModules, getDefaultSearchPaths } from '../modules/loader.js';
17
+ import { runModule } from '../modules/runner.js';
18
+ import { getProvider } from '../providers/index.js';
19
+ import type { CognitiveModule, Provider } from '../types.js';
20
+
21
+ // =============================================================================
22
+ // Types
23
+ // =============================================================================
24
+
25
+ interface RunRequest {
26
+ module: string;
27
+ args: string;
28
+ provider?: string;
29
+ model?: string;
30
+ }
31
+
32
+ interface RunResponse {
33
+ ok: boolean;
34
+ data?: unknown;
35
+ meta?: unknown;
36
+ error?: string;
37
+ module: string;
38
+ provider?: string;
39
+ }
40
+
41
+ interface ModuleInfo {
42
+ name: string;
43
+ version?: string;
44
+ description?: string;
45
+ format: string;
46
+ path: string;
47
+ responsibility?: string;
48
+ tier?: string;
49
+ }
50
+
51
+ // =============================================================================
52
+ // Helpers
53
+ // =============================================================================
54
+
55
+ function jsonResponse(res: http.ServerResponse, status: number, data: unknown): void {
56
+ res.writeHead(status, {
57
+ 'Content-Type': 'application/json',
58
+ 'Access-Control-Allow-Origin': '*',
59
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
60
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
61
+ });
62
+ res.end(JSON.stringify(data, null, 2));
63
+ }
64
+
65
+ function parseBody(req: http.IncomingMessage): Promise<string> {
66
+ return new Promise((resolve, reject) => {
67
+ let body = '';
68
+ req.on('data', (chunk) => (body += chunk));
69
+ req.on('end', () => resolve(body));
70
+ req.on('error', reject);
71
+ });
72
+ }
73
+
74
+ function verifyApiKey(req: http.IncomingMessage): boolean {
75
+ const expectedKey = process.env.COGNITIVE_API_KEY;
76
+ if (!expectedKey) return true; // No auth required
77
+
78
+ const authHeader = req.headers.authorization;
79
+ if (!authHeader) return false;
80
+
81
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : authHeader;
82
+ return token === expectedKey;
83
+ }
84
+
85
+ // =============================================================================
86
+ // Request Handlers
87
+ // =============================================================================
88
+
89
+ async function handleRoot(res: http.ServerResponse): Promise<void> {
90
+ jsonResponse(res, 200, {
91
+ name: 'Cognitive Modules API',
92
+ version: '1.3.0',
93
+ docs: '/docs',
94
+ endpoints: {
95
+ run: 'POST /run',
96
+ modules: 'GET /modules',
97
+ module_info: 'GET /modules/{name}',
98
+ health: 'GET /health',
99
+ },
100
+ });
101
+ }
102
+
103
+ async function handleHealth(res: http.ServerResponse): Promise<void> {
104
+ const providers = {
105
+ openai: Boolean(process.env.OPENAI_API_KEY),
106
+ anthropic: Boolean(process.env.ANTHROPIC_API_KEY),
107
+ minimax: Boolean(process.env.MINIMAX_API_KEY),
108
+ deepseek: Boolean(process.env.DEEPSEEK_API_KEY),
109
+ gemini: Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY),
110
+ qwen: Boolean(process.env.QWEN_API_KEY || process.env.DASHSCOPE_API_KEY),
111
+ };
112
+
113
+ jsonResponse(res, 200, {
114
+ status: 'healthy',
115
+ version: '1.3.0',
116
+ providers,
117
+ });
118
+ }
119
+
120
+ async function handleModules(
121
+ res: http.ServerResponse,
122
+ searchPaths: string[]
123
+ ): Promise<void> {
124
+ const modules = await listModules(searchPaths);
125
+
126
+ const moduleInfos: ModuleInfo[] = modules.map((m) => ({
127
+ name: m.name,
128
+ version: m.version,
129
+ description: m.responsibility,
130
+ format: m.format,
131
+ path: m.location,
132
+ responsibility: m.responsibility,
133
+ tier: m.tier,
134
+ }));
135
+
136
+ jsonResponse(res, 200, {
137
+ modules: moduleInfos,
138
+ count: moduleInfos.length,
139
+ });
140
+ }
141
+
142
+ async function handleModuleInfo(
143
+ res: http.ServerResponse,
144
+ moduleName: string,
145
+ searchPaths: string[]
146
+ ): Promise<void> {
147
+ const moduleData = await findModule(moduleName, searchPaths);
148
+
149
+ if (!moduleData) {
150
+ jsonResponse(res, 404, { error: `Module '${moduleName}' not found` });
151
+ return;
152
+ }
153
+
154
+ jsonResponse(res, 200, {
155
+ name: moduleData.name,
156
+ version: moduleData.version,
157
+ description: moduleData.responsibility,
158
+ format: moduleData.format,
159
+ path: moduleData.location,
160
+ responsibility: moduleData.responsibility,
161
+ tier: moduleData.tier,
162
+ inputSchema: moduleData.inputSchema,
163
+ outputSchema: moduleData.outputSchema,
164
+ });
165
+ }
166
+
167
+ async function handleRun(
168
+ req: http.IncomingMessage,
169
+ res: http.ServerResponse,
170
+ searchPaths: string[]
171
+ ): Promise<void> {
172
+ // Verify API key
173
+ if (!verifyApiKey(req)) {
174
+ jsonResponse(res, 401, {
175
+ error: 'Missing or invalid API Key. Use header: Authorization: Bearer <your-api-key>',
176
+ });
177
+ return;
178
+ }
179
+
180
+ // Parse request body
181
+ let request: RunRequest;
182
+ try {
183
+ const body = await parseBody(req);
184
+ request = JSON.parse(body);
185
+ } catch {
186
+ jsonResponse(res, 400, { error: 'Invalid JSON body' });
187
+ return;
188
+ }
189
+
190
+ // Validate request
191
+ if (!request.module || !request.args) {
192
+ jsonResponse(res, 400, { error: 'Missing required fields: module, args' });
193
+ return;
194
+ }
195
+
196
+ // Find module
197
+ const moduleData = await findModule(request.module, searchPaths);
198
+ if (!moduleData) {
199
+ jsonResponse(res, 404, { error: `Module '${request.module}' not found` });
200
+ return;
201
+ }
202
+
203
+ try {
204
+ // Create provider
205
+ const provider = getProvider(request.provider, request.model);
206
+
207
+ // Run module
208
+ const result = await runModule(moduleData, provider, {
209
+ input: { query: request.args, code: request.args },
210
+ useV22: true,
211
+ });
212
+
213
+ const response: RunResponse = {
214
+ ok: result.ok,
215
+ module: request.module,
216
+ provider: request.provider || process.env.LLM_PROVIDER || 'openai',
217
+ };
218
+
219
+ if (result.ok) {
220
+ if ('meta' in result) response.meta = result.meta;
221
+ if ('data' in result) response.data = result.data;
222
+ } else {
223
+ if ('error' in result) response.error = result.error?.message;
224
+ }
225
+
226
+ jsonResponse(res, 200, response);
227
+ } catch (error) {
228
+ jsonResponse(res, 500, {
229
+ ok: false,
230
+ error: error instanceof Error ? error.message : String(error),
231
+ module: request.module,
232
+ });
233
+ }
234
+ }
235
+
236
+ // =============================================================================
237
+ // Server
238
+ // =============================================================================
239
+
240
+ export interface ServeOptions {
241
+ host?: string;
242
+ port?: number;
243
+ cwd?: string;
244
+ }
245
+
246
+ export function createServer(options: ServeOptions = {}): http.Server {
247
+ const { cwd = process.cwd() } = options;
248
+ const searchPaths = getDefaultSearchPaths(cwd);
249
+
250
+ const server = http.createServer(async (req, res) => {
251
+ const url = new URL(req.url || '/', `http://${req.headers.host}`);
252
+ const path = url.pathname;
253
+ const method = req.method?.toUpperCase();
254
+
255
+ // Handle CORS preflight
256
+ if (method === 'OPTIONS') {
257
+ res.writeHead(204, {
258
+ 'Access-Control-Allow-Origin': '*',
259
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
260
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
261
+ });
262
+ res.end();
263
+ return;
264
+ }
265
+
266
+ try {
267
+ // Route requests
268
+ if (path === '/' && method === 'GET') {
269
+ await handleRoot(res);
270
+ } else if (path === '/health' && method === 'GET') {
271
+ await handleHealth(res);
272
+ } else if (path === '/modules' && method === 'GET') {
273
+ await handleModules(res, searchPaths);
274
+ } else if (path.startsWith('/modules/') && method === 'GET') {
275
+ const moduleName = path.slice('/modules/'.length);
276
+ await handleModuleInfo(res, moduleName, searchPaths);
277
+ } else if (path === '/run' && method === 'POST') {
278
+ await handleRun(req, res, searchPaths);
279
+ } else {
280
+ jsonResponse(res, 404, { error: 'Not found' });
281
+ }
282
+ } catch (error) {
283
+ console.error('Server error:', error);
284
+ jsonResponse(res, 500, {
285
+ error: error instanceof Error ? error.message : 'Internal server error',
286
+ });
287
+ }
288
+ });
289
+
290
+ return server;
291
+ }
292
+
293
+ export async function serve(options: ServeOptions = {}): Promise<void> {
294
+ const { host = '0.0.0.0', port = 8000 } = options;
295
+
296
+ const server = createServer(options);
297
+
298
+ return new Promise((resolve, reject) => {
299
+ server.on('error', reject);
300
+ server.listen(port, host, () => {
301
+ console.log(`Cognitive Modules HTTP Server running at http://${host}:${port}`);
302
+ console.log('Endpoints:');
303
+ console.log(' GET / - API info');
304
+ console.log(' GET /health - Health check');
305
+ console.log(' GET /modules - List modules');
306
+ console.log(' GET /modules/:name - Module info');
307
+ console.log(' POST /run - Run module');
308
+ resolve();
309
+ });
310
+ });
311
+ }
312
+
313
+ // Allow running directly
314
+ if (import.meta.url === `file://${process.argv[1]}`) {
315
+ serve().catch(console.error);
316
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Server - Re-export all server functionality
3
+ */
4
+
5
+ export { serve, createServer } from './http.js';
6
+ export type { ServeOptions } from './http.js';
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Cognitive Runtime - Core Types
3
- * Version 2.2 - With Control/Data plane separation, tier, overflow, extensible enums
3
+ * Version 2.5 - With streaming response and multimodal support
4
4
  */
5
5
 
6
6
  // =============================================================================
@@ -493,3 +493,321 @@ export function shouldEscalate<T>(
493
493
 
494
494
  return false;
495
495
  }
496
+
497
+ // =============================================================================
498
+ // v2.5 Streaming Types
499
+ // =============================================================================
500
+
501
+ /** Response mode configuration */
502
+ export type ResponseMode = 'sync' | 'streaming' | 'both';
503
+
504
+ /** Chunk type for streaming */
505
+ export type ChunkType = 'delta' | 'snapshot';
506
+
507
+ /** Response configuration in module.yaml */
508
+ export interface ResponseConfig {
509
+ mode: ResponseMode;
510
+ chunk_type?: ChunkType;
511
+ buffer_size?: number;
512
+ heartbeat_interval_ms?: number;
513
+ max_duration_ms?: number;
514
+ }
515
+
516
+ /** Meta chunk - initial streaming response */
517
+ export interface MetaChunk {
518
+ ok: true;
519
+ streaming: true;
520
+ session_id: string;
521
+ meta: Partial<EnvelopeMeta>;
522
+ }
523
+
524
+ /** Delta chunk - incremental content */
525
+ export interface DeltaChunk {
526
+ chunk: {
527
+ seq: number;
528
+ type: 'delta';
529
+ field?: string;
530
+ delta: string;
531
+ };
532
+ }
533
+
534
+ /** Snapshot chunk - full state replacement */
535
+ export interface SnapshotChunk {
536
+ chunk: {
537
+ seq: number;
538
+ type: 'snapshot';
539
+ field?: string;
540
+ data: unknown;
541
+ };
542
+ }
543
+
544
+ /** Progress chunk - progress update */
545
+ export interface ProgressChunk {
546
+ progress: {
547
+ percent: number;
548
+ stage?: string;
549
+ message?: string;
550
+ };
551
+ }
552
+
553
+ /** Final chunk - completion signal */
554
+ export interface FinalChunk {
555
+ final: true;
556
+ meta: EnvelopeMeta;
557
+ data: ModuleResultData;
558
+ usage?: {
559
+ input_tokens: number;
560
+ output_tokens: number;
561
+ total_tokens: number;
562
+ };
563
+ }
564
+
565
+ /** Error chunk during streaming */
566
+ export interface ErrorChunk {
567
+ ok: false;
568
+ streaming: true;
569
+ session_id?: string;
570
+ error: {
571
+ code: string;
572
+ message: string;
573
+ recoverable?: boolean;
574
+ };
575
+ partial_data?: unknown;
576
+ }
577
+
578
+ /** Union of all streaming chunk types */
579
+ export type StreamingChunk =
580
+ | MetaChunk
581
+ | DeltaChunk
582
+ | SnapshotChunk
583
+ | ProgressChunk
584
+ | FinalChunk
585
+ | ErrorChunk;
586
+
587
+ /** Streaming session state */
588
+ export interface StreamingSession {
589
+ session_id: string;
590
+ module_name: string;
591
+ started_at: number;
592
+ chunks_sent: number;
593
+ accumulated_data: Record<string, unknown>;
594
+ accumulated_text: Record<string, string>;
595
+ }
596
+
597
+ // =============================================================================
598
+ // v2.5 Multimodal Types
599
+ // =============================================================================
600
+
601
+ /** Supported modality types */
602
+ export type ModalityType = 'text' | 'image' | 'audio' | 'video' | 'document';
603
+
604
+ /** Modalities configuration in module.yaml */
605
+ export interface ModalitiesConfig {
606
+ input: ModalityType[];
607
+ output: ModalityType[];
608
+ constraints?: MediaConstraints;
609
+ }
610
+
611
+ /** Media size/duration constraints */
612
+ export interface MediaConstraints {
613
+ max_image_size_mb?: number;
614
+ max_audio_size_mb?: number;
615
+ max_video_size_mb?: number;
616
+ max_audio_duration_s?: number;
617
+ max_video_duration_s?: number;
618
+ allowed_image_types?: string[];
619
+ allowed_audio_types?: string[];
620
+ allowed_video_types?: string[];
621
+ }
622
+
623
+ /** Media input - URL reference */
624
+ export interface UrlMediaInput {
625
+ type: 'url';
626
+ url: string;
627
+ media_type?: string;
628
+ }
629
+
630
+ /** Media input - Base64 inline */
631
+ export interface Base64MediaInput {
632
+ type: 'base64';
633
+ media_type: string;
634
+ data: string;
635
+ }
636
+
637
+ /** Media input - File path */
638
+ export interface FileMediaInput {
639
+ type: 'file';
640
+ path: string;
641
+ }
642
+
643
+ /** Union of media input types */
644
+ export type MediaInput = UrlMediaInput | Base64MediaInput | FileMediaInput;
645
+
646
+ /** Media output with metadata */
647
+ export interface MediaOutput {
648
+ type: 'url' | 'base64' | 'file';
649
+ media_type: string;
650
+ url?: string;
651
+ data?: string;
652
+ path?: string;
653
+ width?: number;
654
+ height?: number;
655
+ duration_ms?: number;
656
+ expires_at?: string;
657
+ generation_params?: Record<string, unknown>;
658
+ }
659
+
660
+ /** Supported image MIME types */
661
+ export const SUPPORTED_IMAGE_TYPES = [
662
+ 'image/jpeg',
663
+ 'image/png',
664
+ 'image/webp',
665
+ 'image/gif'
666
+ ] as const;
667
+
668
+ /** Supported audio MIME types */
669
+ export const SUPPORTED_AUDIO_TYPES = [
670
+ 'audio/mpeg',
671
+ 'audio/wav',
672
+ 'audio/ogg',
673
+ 'audio/webm'
674
+ ] as const;
675
+
676
+ /** Supported video MIME types */
677
+ export const SUPPORTED_VIDEO_TYPES = [
678
+ 'video/mp4',
679
+ 'video/webm',
680
+ 'video/quicktime'
681
+ ] as const;
682
+
683
+ // =============================================================================
684
+ // v2.5 Error Codes
685
+ // =============================================================================
686
+
687
+ /** v2.5 Error codes for streaming and multimodal */
688
+ export const ErrorCodesV25 = {
689
+ // Media errors (E1xxx)
690
+ UNSUPPORTED_MEDIA_TYPE: 'E1010',
691
+ MEDIA_TOO_LARGE: 'E1011',
692
+ MEDIA_FETCH_FAILED: 'E1012',
693
+ MEDIA_DECODE_FAILED: 'E1013',
694
+
695
+ // Streaming errors (E2xxx)
696
+ STREAM_INTERRUPTED: 'E2010',
697
+ STREAM_TIMEOUT: 'E2011',
698
+
699
+ // Capability errors (E4xxx)
700
+ STREAMING_NOT_SUPPORTED: 'E4010',
701
+ MULTIMODAL_NOT_SUPPORTED: 'E4011',
702
+ } as const;
703
+
704
+ export type ErrorCodeV25 = typeof ErrorCodesV25[keyof typeof ErrorCodesV25];
705
+
706
+ // =============================================================================
707
+ // v2.5 Runtime Capabilities
708
+ // =============================================================================
709
+
710
+ /** Runtime capability declaration */
711
+ export interface RuntimeCapabilities {
712
+ streaming: boolean;
713
+ multimodal: {
714
+ input: ModalityType[];
715
+ output: ModalityType[];
716
+ };
717
+ max_media_size_mb: number;
718
+ supported_transports: ('sse' | 'websocket' | 'ndjson')[];
719
+ }
720
+
721
+ /** Default runtime capabilities */
722
+ export const DEFAULT_RUNTIME_CAPABILITIES: RuntimeCapabilities = {
723
+ streaming: true,
724
+ multimodal: {
725
+ input: ['text', 'image'],
726
+ output: ['text']
727
+ },
728
+ max_media_size_mb: 20,
729
+ supported_transports: ['sse', 'ndjson']
730
+ };
731
+
732
+ // =============================================================================
733
+ // v2.5 Extended Provider Interface
734
+ // =============================================================================
735
+
736
+ /** Extended invoke params with streaming support */
737
+ export interface InvokeParamsV25 extends InvokeParams {
738
+ stream?: boolean;
739
+ images?: MediaInput[];
740
+ audio?: MediaInput[];
741
+ video?: MediaInput[];
742
+ }
743
+
744
+ /** Streaming invoke result */
745
+ export interface StreamingInvokeResult {
746
+ stream: AsyncIterable<string>;
747
+ usage?: {
748
+ promptTokens: number;
749
+ completionTokens: number;
750
+ totalTokens: number;
751
+ };
752
+ }
753
+
754
+ /** Extended provider interface for v2.5 */
755
+ export interface ProviderV25 extends Provider {
756
+ /** Check if provider supports streaming */
757
+ supportsStreaming?(): boolean;
758
+
759
+ /** Check if provider supports multimodal input */
760
+ supportsMultimodal?(): { input: ModalityType[]; output: ModalityType[] };
761
+
762
+ /** Invoke with streaming */
763
+ invokeStream?(params: InvokeParamsV25): Promise<StreamingInvokeResult>;
764
+ }
765
+
766
+ /** Type guard for v2.5 provider */
767
+ export function isProviderV25(provider: Provider): provider is ProviderV25 {
768
+ return 'invokeStream' in provider || 'supportsStreaming' in provider;
769
+ }
770
+
771
+ // =============================================================================
772
+ // v2.5 Module Configuration Extensions
773
+ // =============================================================================
774
+
775
+ /** Extended module interface for v2.5 */
776
+ export interface CognitiveModuleV25 extends CognitiveModule {
777
+ /** v2.5: Response configuration */
778
+ response?: ResponseConfig;
779
+
780
+ /** v2.5: Modalities configuration */
781
+ modalities?: ModalitiesConfig;
782
+ }
783
+
784
+ /** Type guard for v2.5 module */
785
+ export function isModuleV25(module: CognitiveModule): module is CognitiveModuleV25 {
786
+ return 'response' in module || 'modalities' in module;
787
+ }
788
+
789
+ /** Check if module supports streaming */
790
+ export function moduleSupportsStreaming(module: CognitiveModule): boolean {
791
+ if (!isModuleV25(module)) return false;
792
+ const mode = module.response?.mode;
793
+ return mode === 'streaming' || mode === 'both';
794
+ }
795
+
796
+ /** Check if module supports multimodal input */
797
+ export function moduleSupportsMultimodal(module: CognitiveModule): boolean {
798
+ if (!isModuleV25(module)) return false;
799
+ const modalities = module.modalities?.input ?? ['text'];
800
+ return modalities.some(m => m !== 'text');
801
+ }
802
+
803
+ /** Get supported input modalities for module */
804
+ export function getModuleInputModalities(module: CognitiveModule): ModalityType[] {
805
+ if (!isModuleV25(module)) return ['text'];
806
+ return module.modalities?.input ?? ['text'];
807
+ }
808
+
809
+ /** Get supported output modalities for module */
810
+ export function getModuleOutputModalities(module: CognitiveModule): ModalityType[] {
811
+ if (!isModuleV25(module)) return ['text'];
812
+ return module.modalities?.output ?? ['text'];
813
+ }