cognitive-modules-cli 1.4.1 → 2.2.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 (45) hide show
  1. package/dist/cli.js +65 -12
  2. package/dist/commands/compose.d.ts +31 -0
  3. package/dist/commands/compose.js +148 -0
  4. package/dist/commands/index.d.ts +1 -0
  5. package/dist/commands/index.js +1 -0
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +5 -1
  8. package/dist/modules/composition.d.ts +251 -0
  9. package/dist/modules/composition.js +1265 -0
  10. package/dist/modules/composition.test.d.ts +11 -0
  11. package/dist/modules/composition.test.js +450 -0
  12. package/dist/modules/index.d.ts +2 -0
  13. package/dist/modules/index.js +2 -0
  14. package/dist/modules/loader.d.ts +22 -2
  15. package/dist/modules/loader.js +167 -4
  16. package/dist/modules/policy.test.d.ts +10 -0
  17. package/dist/modules/policy.test.js +369 -0
  18. package/dist/modules/runner.d.ts +348 -34
  19. package/dist/modules/runner.js +1263 -708
  20. package/dist/modules/subagent.js +2 -0
  21. package/dist/modules/validator.d.ts +28 -0
  22. package/dist/modules/validator.js +629 -0
  23. package/dist/providers/base.d.ts +1 -45
  24. package/dist/providers/base.js +0 -67
  25. package/dist/providers/openai.d.ts +3 -27
  26. package/dist/providers/openai.js +3 -175
  27. package/dist/types.d.ts +93 -316
  28. package/dist/types.js +1 -120
  29. package/package.json +2 -1
  30. package/src/cli.ts +73 -12
  31. package/src/commands/compose.ts +185 -0
  32. package/src/commands/index.ts +1 -0
  33. package/src/index.ts +35 -0
  34. package/src/modules/composition.test.ts +558 -0
  35. package/src/modules/composition.ts +1674 -0
  36. package/src/modules/index.ts +2 -0
  37. package/src/modules/loader.ts +196 -6
  38. package/src/modules/policy.test.ts +455 -0
  39. package/src/modules/runner.ts +1692 -998
  40. package/src/modules/subagent.ts +2 -0
  41. package/src/modules/validator.ts +700 -0
  42. package/src/providers/base.ts +1 -86
  43. package/src/providers/openai.ts +4 -226
  44. package/src/types.ts +113 -462
  45. package/tsconfig.json +1 -1
package/src/cli.ts CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { parseArgs } from 'node:util';
18
18
  import { getProvider, listProviders } from './providers/index.js';
19
- import { run, list, pipe, init, add, update, remove, versions } from './commands/index.js';
19
+ import { run, list, pipe, init, add, update, remove, versions, compose, composeInfo } from './commands/index.js';
20
20
  import type { CommandContext } from './types.js';
21
21
 
22
22
  const VERSION = '1.3.0';
@@ -55,6 +55,10 @@ async function main() {
55
55
  // Server options
56
56
  host: { type: 'string', short: 'H' },
57
57
  port: { type: 'string', short: 'P' },
58
+ // Compose options
59
+ 'max-depth': { type: 'string', short: 'd' },
60
+ timeout: { type: 'string', short: 'T' },
61
+ trace: { type: 'boolean', default: false },
58
62
  },
59
63
  allowPositionals: true,
60
64
  });
@@ -291,6 +295,53 @@ async function main() {
291
295
  break;
292
296
  }
293
297
 
298
+ case 'compose': {
299
+ const moduleName = args[1];
300
+ if (!moduleName || moduleName.startsWith('-')) {
301
+ console.error('Usage: cog compose <module> [--args "..."] [--timeout <ms>] [--max-depth <n>]');
302
+ process.exit(1);
303
+ }
304
+
305
+ const result = await compose(moduleName, ctx, {
306
+ args: values.args,
307
+ input: values.input,
308
+ maxDepth: values['max-depth'] ? parseInt(values['max-depth'] as string, 10) : undefined,
309
+ timeout: values.timeout ? parseInt(values.timeout as string, 10) : undefined,
310
+ trace: values.trace,
311
+ pretty: values.pretty,
312
+ verbose: values.verbose,
313
+ });
314
+
315
+ if (!result.success) {
316
+ console.error(`Error: ${result.error}`);
317
+ if (result.data) {
318
+ console.error('Partial results:', JSON.stringify(result.data, null, 2));
319
+ }
320
+ process.exit(1);
321
+ }
322
+
323
+ console.log(JSON.stringify(result.data, null, values.pretty ? 2 : 0));
324
+ break;
325
+ }
326
+
327
+ case 'compose-info': {
328
+ const moduleName = args[1];
329
+ if (!moduleName || moduleName.startsWith('-')) {
330
+ console.error('Usage: cog compose-info <module>');
331
+ process.exit(1);
332
+ }
333
+
334
+ const result = await composeInfo(moduleName, ctx);
335
+
336
+ if (!result.success) {
337
+ console.error(`Error: ${result.error}`);
338
+ process.exit(1);
339
+ }
340
+
341
+ console.log(JSON.stringify(result.data, null, 2));
342
+ break;
343
+ }
344
+
294
345
  case 'serve': {
295
346
  const { serve } = await import('./server/http.js');
296
347
  const port = values.port ? parseInt(values.port as string, 10) : 8000;
@@ -338,17 +389,19 @@ USAGE:
338
389
  cog <command> [options]
339
390
 
340
391
  COMMANDS:
341
- run <module> Run a Cognitive Module
342
- list List available modules
343
- add <url> Add module from GitHub
344
- update <module> Update module to latest version
345
- remove <module> Remove installed module
346
- versions <url> List available versions
347
- pipe Pipe mode (stdin/stdout)
348
- init [name] Initialize project or create module
349
- serve Start HTTP API server
350
- mcp Start MCP server (for Claude Code, Cursor)
351
- doctor Check configuration
392
+ run <module> Run a Cognitive Module
393
+ compose <module> Execute a composed module workflow
394
+ compose-info <mod> Show composition configuration
395
+ list List available modules
396
+ add <url> Add module from GitHub
397
+ update <module> Update module to latest version
398
+ remove <module> Remove installed module
399
+ versions <url> List available versions
400
+ pipe Pipe mode (stdin/stdout)
401
+ init [name] Initialize project or create module
402
+ serve Start HTTP API server
403
+ mcp Start MCP server (for Claude Code, Cursor)
404
+ doctor Check configuration
352
405
 
353
406
  OPTIONS:
354
407
  -a, --args <str> Arguments to pass to module
@@ -364,6 +417,9 @@ OPTIONS:
364
417
  --no-validate Skip schema validation
365
418
  -H, --host <host> Server host (default: 0.0.0.0)
366
419
  -P, --port <port> Server port (default: 8000)
420
+ -d, --max-depth <n> Max composition depth (default: 5)
421
+ -T, --timeout <ms> Composition timeout in milliseconds
422
+ --trace Include execution trace (for compose)
367
423
  -v, --version Show version
368
424
  -h, --help Show this help
369
425
 
@@ -382,6 +438,11 @@ EXAMPLES:
382
438
  cog run code-reviewer --provider openai --model gpt-4o --args "..."
383
439
  cog list
384
440
 
441
+ # Compose modules (multi-step workflows)
442
+ cog compose code-review-pipeline --args "code to review"
443
+ cog compose smart-processor --args "input" --timeout 60000 --verbose
444
+ cog compose-info code-review-pipeline
445
+
385
446
  # Servers
386
447
  cog serve --port 8080
387
448
  cog mcp
@@ -0,0 +1,185 @@
1
+ /**
2
+ * cog compose - Execute a Composed Cognitive Module Workflow
3
+ *
4
+ * Supports all composition patterns:
5
+ * - Sequential: A → B → C
6
+ * - Parallel: A → [B, C, D] → Aggregate
7
+ * - Conditional: A → (condition) → B or C
8
+ * - Iterative: A → (check) → A → ... → Done
9
+ */
10
+
11
+ import type { CommandContext, CommandResult } from '../types.js';
12
+ import { findModule, getDefaultSearchPaths, executeComposition } from '../modules/index.js';
13
+
14
+ export interface ComposeOptions {
15
+ /** Direct text input */
16
+ args?: string;
17
+ /** JSON input data */
18
+ input?: string;
19
+ /** Maximum composition depth */
20
+ maxDepth?: number;
21
+ /** Timeout in milliseconds */
22
+ timeout?: number;
23
+ /** Include execution trace */
24
+ trace?: boolean;
25
+ /** Pretty print output */
26
+ pretty?: boolean;
27
+ /** Verbose mode */
28
+ verbose?: boolean;
29
+ }
30
+
31
+ export async function compose(
32
+ moduleName: string,
33
+ ctx: CommandContext,
34
+ options: ComposeOptions = {}
35
+ ): Promise<CommandResult> {
36
+ const searchPaths = getDefaultSearchPaths(ctx.cwd);
37
+
38
+ // Find module
39
+ const module = await findModule(moduleName, searchPaths);
40
+ if (!module) {
41
+ return {
42
+ success: false,
43
+ error: `Module not found: ${moduleName}\nSearch paths: ${searchPaths.join(', ')}`,
44
+ };
45
+ }
46
+
47
+ try {
48
+ // Parse input if provided as JSON
49
+ let inputData: Record<string, unknown> = {};
50
+ if (options.input) {
51
+ try {
52
+ inputData = JSON.parse(options.input);
53
+ } catch {
54
+ return {
55
+ success: false,
56
+ error: `Invalid JSON input: ${options.input}`,
57
+ };
58
+ }
59
+ }
60
+
61
+ // Handle --args as text input
62
+ if (options.args) {
63
+ inputData.query = options.args;
64
+ inputData.code = options.args;
65
+ }
66
+
67
+ // Execute composition
68
+ const result = await executeComposition(
69
+ moduleName,
70
+ inputData,
71
+ ctx.provider,
72
+ {
73
+ cwd: ctx.cwd,
74
+ maxDepth: options.maxDepth,
75
+ timeoutMs: options.timeout
76
+ }
77
+ );
78
+
79
+ if (options.verbose) {
80
+ console.error('--- Composition Trace ---');
81
+ for (const entry of result.trace) {
82
+ const status = entry.success
83
+ ? (entry.skipped ? '⏭️ SKIPPED' : '✅ OK')
84
+ : '❌ FAILED';
85
+ console.error(`${status} ${entry.module} (${entry.durationMs}ms)`);
86
+ if (entry.reason) {
87
+ console.error(` Reason: ${entry.reason}`);
88
+ }
89
+ }
90
+ console.error(`--- Total: ${result.totalTimeMs}ms ---`);
91
+ }
92
+
93
+ // Return result
94
+ if (options.trace) {
95
+ // Include full result with trace
96
+ return {
97
+ success: result.ok,
98
+ data: {
99
+ ok: result.ok,
100
+ result: result.result,
101
+ moduleResults: result.moduleResults,
102
+ trace: result.trace,
103
+ totalTimeMs: result.totalTimeMs,
104
+ error: result.error
105
+ }
106
+ };
107
+ } else if (options.pretty) {
108
+ return {
109
+ success: result.ok,
110
+ data: result.result,
111
+ };
112
+ } else {
113
+ // For non-pretty mode, return data (success) or error (failure)
114
+ if (result.ok && result.result) {
115
+ return {
116
+ success: true,
117
+ data: (result.result as { data?: unknown }).data,
118
+ };
119
+ } else {
120
+ return {
121
+ success: false,
122
+ error: result.error
123
+ ? `${result.error.code}: ${result.error.message}`
124
+ : 'Composition failed',
125
+ data: result.moduleResults,
126
+ };
127
+ }
128
+ }
129
+ } catch (e) {
130
+ return {
131
+ success: false,
132
+ error: e instanceof Error ? e.message : String(e),
133
+ };
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Show composition info for a module
139
+ */
140
+ export async function composeInfo(
141
+ moduleName: string,
142
+ ctx: CommandContext
143
+ ): Promise<CommandResult> {
144
+ const searchPaths = getDefaultSearchPaths(ctx.cwd);
145
+
146
+ const module = await findModule(moduleName, searchPaths);
147
+ if (!module) {
148
+ return {
149
+ success: false,
150
+ error: `Module not found: ${moduleName}`,
151
+ };
152
+ }
153
+
154
+ const composition = module.composition;
155
+ if (!composition) {
156
+ return {
157
+ success: true,
158
+ data: {
159
+ name: module.name,
160
+ hasComposition: false,
161
+ message: 'Module does not have composition configuration'
162
+ }
163
+ };
164
+ }
165
+
166
+ return {
167
+ success: true,
168
+ data: {
169
+ name: module.name,
170
+ hasComposition: true,
171
+ pattern: composition.pattern,
172
+ requires: composition.requires?.map(d => ({
173
+ name: d.name,
174
+ version: d.version,
175
+ optional: d.optional,
176
+ fallback: d.fallback
177
+ })),
178
+ dataflowSteps: composition.dataflow?.length ?? 0,
179
+ routingRules: composition.routing?.length ?? 0,
180
+ maxDepth: composition.max_depth,
181
+ timeoutMs: composition.timeout_ms,
182
+ iteration: composition.iteration
183
+ }
184
+ };
185
+ }
@@ -10,3 +10,4 @@ export * from './add.js';
10
10
  export * from './update.js';
11
11
  export * from './remove.js';
12
12
  export * from './versions.js';
13
+ export * from './compose.js';
package/src/index.ts CHANGED
@@ -19,6 +19,15 @@ export type {
19
19
  FailureContract,
20
20
  CommandContext,
21
21
  CommandResult,
22
+ // v2.2 Composition Types
23
+ CompositionConfig,
24
+ CompositionPattern,
25
+ DependencyDeclaration,
26
+ DataflowStep,
27
+ DataflowMapping,
28
+ RoutingRule,
29
+ AggregationStrategy,
30
+ IterationConfig,
22
31
  } from './types.js';
23
32
 
24
33
  // Providers
@@ -43,6 +52,32 @@ export {
43
52
  runWithSubagents,
44
53
  parseCalls,
45
54
  createContext,
55
+ // Composition
56
+ CompositionOrchestrator,
57
+ executeComposition,
58
+ validateCompositionConfig,
59
+ evaluateJsonPath,
60
+ evaluateCondition,
61
+ applyMapping,
62
+ aggregateResults,
63
+ versionMatches,
64
+ resolveDependency,
65
+ COMPOSITION_ERRORS,
66
+ // Policy Enforcement
67
+ checkToolPolicy,
68
+ checkPolicy,
69
+ checkToolAllowed,
70
+ validateToolsAllowed,
71
+ getDeniedActions,
72
+ getDeniedTools,
73
+ getAllowedTools,
74
+ ToolCallInterceptor,
75
+ createPolicyAwareExecutor,
76
+ type PolicyAction,
77
+ type PolicyCheckResult,
78
+ type ToolCallRequest,
79
+ type ToolCallResult,
80
+ type ToolExecutor,
46
81
  } from './modules/index.js';
47
82
 
48
83
  // Server