cognitive-modules-cli 2.2.0 → 2.2.5

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 (94) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +35 -29
  4. package/dist/cli.js +572 -28
  5. package/dist/commands/add.d.ts +33 -14
  6. package/dist/commands/add.js +222 -13
  7. package/dist/commands/compose.d.ts +31 -0
  8. package/dist/commands/compose.js +185 -0
  9. package/dist/commands/index.d.ts +5 -0
  10. package/dist/commands/index.js +5 -0
  11. package/dist/commands/init.js +23 -1
  12. package/dist/commands/migrate.d.ts +30 -0
  13. package/dist/commands/migrate.js +650 -0
  14. package/dist/commands/pipe.d.ts +1 -0
  15. package/dist/commands/pipe.js +31 -11
  16. package/dist/commands/remove.js +33 -2
  17. package/dist/commands/run.d.ts +1 -0
  18. package/dist/commands/run.js +37 -27
  19. package/dist/commands/search.d.ts +28 -0
  20. package/dist/commands/search.js +143 -0
  21. package/dist/commands/test.d.ts +65 -0
  22. package/dist/commands/test.js +454 -0
  23. package/dist/commands/update.d.ts +1 -0
  24. package/dist/commands/update.js +106 -14
  25. package/dist/commands/validate.d.ts +36 -0
  26. package/dist/commands/validate.js +97 -0
  27. package/dist/errors/index.d.ts +218 -0
  28. package/dist/errors/index.js +412 -0
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +5 -1
  31. package/dist/mcp/server.js +84 -79
  32. package/dist/modules/composition.d.ts +251 -0
  33. package/dist/modules/composition.js +1330 -0
  34. package/dist/modules/index.d.ts +2 -0
  35. package/dist/modules/index.js +2 -0
  36. package/dist/modules/loader.d.ts +22 -2
  37. package/dist/modules/loader.js +171 -6
  38. package/dist/modules/runner.d.ts +422 -1
  39. package/dist/modules/runner.js +1472 -71
  40. package/dist/modules/subagent.d.ts +6 -1
  41. package/dist/modules/subagent.js +20 -13
  42. package/dist/modules/validator.d.ts +28 -0
  43. package/dist/modules/validator.js +637 -0
  44. package/dist/providers/anthropic.d.ts +15 -0
  45. package/dist/providers/anthropic.js +147 -5
  46. package/dist/providers/base.d.ts +11 -0
  47. package/dist/providers/base.js +18 -0
  48. package/dist/providers/gemini.d.ts +15 -0
  49. package/dist/providers/gemini.js +122 -5
  50. package/dist/providers/ollama.d.ts +15 -0
  51. package/dist/providers/ollama.js +111 -3
  52. package/dist/providers/openai.d.ts +11 -0
  53. package/dist/providers/openai.js +133 -0
  54. package/dist/registry/client.d.ts +204 -0
  55. package/dist/registry/client.js +356 -0
  56. package/dist/registry/index.d.ts +4 -0
  57. package/dist/registry/index.js +4 -0
  58. package/dist/server/http.js +173 -42
  59. package/dist/types.d.ts +123 -8
  60. package/dist/types.js +4 -1
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +4 -0
  63. package/package.json +32 -7
  64. package/src/cli.ts +0 -410
  65. package/src/commands/add.ts +0 -315
  66. package/src/commands/index.ts +0 -12
  67. package/src/commands/init.ts +0 -94
  68. package/src/commands/list.ts +0 -33
  69. package/src/commands/pipe.ts +0 -76
  70. package/src/commands/remove.ts +0 -57
  71. package/src/commands/run.ts +0 -80
  72. package/src/commands/update.ts +0 -130
  73. package/src/commands/versions.ts +0 -79
  74. package/src/index.ts +0 -55
  75. package/src/mcp/index.ts +0 -5
  76. package/src/mcp/server.ts +0 -403
  77. package/src/modules/index.ts +0 -7
  78. package/src/modules/loader.ts +0 -318
  79. package/src/modules/runner.ts +0 -495
  80. package/src/modules/subagent.ts +0 -275
  81. package/src/providers/anthropic.ts +0 -89
  82. package/src/providers/base.ts +0 -29
  83. package/src/providers/deepseek.ts +0 -83
  84. package/src/providers/gemini.ts +0 -117
  85. package/src/providers/index.ts +0 -78
  86. package/src/providers/minimax.ts +0 -81
  87. package/src/providers/moonshot.ts +0 -82
  88. package/src/providers/ollama.ts +0 -83
  89. package/src/providers/openai.ts +0 -84
  90. package/src/providers/qwen.ts +0 -82
  91. package/src/server/http.ts +0 -316
  92. package/src/server/index.ts +0 -6
  93. package/src/types.ts +0 -495
  94. package/tsconfig.json +0 -17
@@ -1,14 +1,435 @@
1
1
  /**
2
2
  * Module Runner - Execute Cognitive Modules
3
3
  * v2.2: Envelope format with meta/data separation, risk_rule, repair pass
4
+ * v2.2.1: Version field, enhanced error taxonomy, observability hooks, streaming
4
5
  */
5
- import type { Provider, CognitiveModule, ModuleResult, ModuleInput } from '../types.js';
6
+ import type { Provider, CognitiveModule, ModuleResult, ModuleInput, EnvelopeResponseV22, EnvelopeMeta, RiskLevel } from '../types.js';
7
+ /**
8
+ * Validate data against JSON schema. Returns list of errors.
9
+ */
10
+ export declare function validateData(data: unknown, schema: object, label?: string): string[];
11
+ /** Action types that can be checked against policies */
12
+ export type PolicyAction = 'network' | 'filesystem_write' | 'side_effects' | 'code_execution';
13
+ /** Result of a policy check */
14
+ export interface PolicyCheckResult {
15
+ allowed: boolean;
16
+ reason?: string;
17
+ policy?: string;
18
+ }
19
+ /**
20
+ * Check if a tool is allowed by the module's tools policy.
21
+ *
22
+ * @param toolName The name of the tool to check
23
+ * @param module The cognitive module config
24
+ * @returns PolicyCheckResult indicating if the tool is allowed
25
+ *
26
+ * @example
27
+ * const result = checkToolPolicy('write_file', module);
28
+ * if (!result.allowed) {
29
+ * throw new Error(result.reason);
30
+ * }
31
+ */
32
+ export declare function checkToolPolicy(toolName: string, module: CognitiveModule): PolicyCheckResult;
33
+ /**
34
+ * Check if an action is allowed by the module's policies.
35
+ *
36
+ * @param action The action to check (network, filesystem_write, etc.)
37
+ * @param module The cognitive module config
38
+ * @returns PolicyCheckResult indicating if the action is allowed
39
+ *
40
+ * @example
41
+ * const result = checkPolicy('network', module);
42
+ * if (!result.allowed) {
43
+ * throw new Error(result.reason);
44
+ * }
45
+ */
46
+ export declare function checkPolicy(action: PolicyAction, module: CognitiveModule): PolicyCheckResult;
47
+ /**
48
+ * Check if a tool is allowed considering both tools policy and general policies.
49
+ * This performs a comprehensive check that:
50
+ * 1. Checks the tools policy (allowed/denied lists)
51
+ * 2. Maps the tool to policy actions and checks those
52
+ *
53
+ * @param toolName The name of the tool to check
54
+ * @param module The cognitive module config
55
+ * @returns PolicyCheckResult with detailed information
56
+ *
57
+ * @example
58
+ * const result = checkToolAllowed('write_file', module);
59
+ * if (!result.allowed) {
60
+ * return makeErrorResponse({
61
+ * code: 'POLICY_VIOLATION',
62
+ * message: result.reason,
63
+ * });
64
+ * }
65
+ */
66
+ export declare function checkToolAllowed(toolName: string, module: CognitiveModule): PolicyCheckResult;
67
+ /**
68
+ * Validate that a list of tools are all allowed by the module's policies.
69
+ * Returns all violations found.
70
+ *
71
+ * @param toolNames List of tool names to check
72
+ * @param module The cognitive module config
73
+ * @returns Array of PolicyCheckResult for denied tools
74
+ */
75
+ export declare function validateToolsAllowed(toolNames: string[], module: CognitiveModule): PolicyCheckResult[];
76
+ /**
77
+ * Get all denied actions for a module based on its policies.
78
+ * Useful for informing LLM about restrictions.
79
+ */
80
+ export declare function getDeniedActions(module: CognitiveModule): PolicyAction[];
81
+ /**
82
+ * Get all denied tools for a module based on its tools policy.
83
+ */
84
+ export declare function getDeniedTools(module: CognitiveModule): string[];
85
+ /**
86
+ * Get all allowed tools for a module (only meaningful in deny_by_default mode).
87
+ */
88
+ export declare function getAllowedTools(module: CognitiveModule): string[] | null;
89
+ /** Tool call request from LLM */
90
+ export interface ToolCallRequest {
91
+ name: string;
92
+ arguments: Record<string, unknown>;
93
+ }
94
+ /** Tool call result */
95
+ export interface ToolCallResult {
96
+ success: boolean;
97
+ result?: unknown;
98
+ error?: {
99
+ code: string;
100
+ message: string;
101
+ };
102
+ }
103
+ /** Tool executor function type */
104
+ export type ToolExecutor = (args: Record<string, unknown>) => Promise<unknown>;
105
+ /**
106
+ * ToolCallInterceptor - Intercepts and validates tool calls against module policies.
107
+ *
108
+ * Use this class to wrap tool execution with policy enforcement:
109
+ *
110
+ * @example
111
+ * const interceptor = new ToolCallInterceptor(module);
112
+ *
113
+ * // Register tool executors
114
+ * interceptor.registerTool('read_file', async (args) => {
115
+ * return fs.readFile(args.path as string, 'utf-8');
116
+ * });
117
+ *
118
+ * // Execute tool with policy check
119
+ * const result = await interceptor.execute({
120
+ * name: 'write_file',
121
+ * arguments: { path: '/tmp/test.txt', content: 'hello' }
122
+ * });
123
+ *
124
+ * if (!result.success) {
125
+ * console.error('Tool blocked:', result.error);
126
+ * }
127
+ */
128
+ export declare class ToolCallInterceptor {
129
+ private module;
130
+ private tools;
131
+ private callLog;
132
+ constructor(module: CognitiveModule);
133
+ /**
134
+ * Register a tool executor.
135
+ */
136
+ registerTool(name: string, executor: ToolExecutor): void;
137
+ /**
138
+ * Register multiple tools at once.
139
+ */
140
+ registerTools(tools: Record<string, ToolExecutor>): void;
141
+ /**
142
+ * Check if a tool call is allowed without executing it.
143
+ */
144
+ checkAllowed(toolName: string): PolicyCheckResult;
145
+ /**
146
+ * Execute a tool call with policy enforcement.
147
+ *
148
+ * @param request The tool call request
149
+ * @returns ToolCallResult with success/error
150
+ */
151
+ execute(request: ToolCallRequest): Promise<ToolCallResult>;
152
+ /**
153
+ * Execute multiple tool calls in sequence.
154
+ * Stops on first policy violation.
155
+ */
156
+ executeMany(requests: ToolCallRequest[]): Promise<ToolCallResult[]>;
157
+ /**
158
+ * Get the call log for auditing.
159
+ */
160
+ getCallLog(): Array<{
161
+ tool: string;
162
+ allowed: boolean;
163
+ timestamp: number;
164
+ }>;
165
+ /**
166
+ * Get summary of denied calls.
167
+ */
168
+ getDeniedCalls(): Array<{
169
+ tool: string;
170
+ timestamp: number;
171
+ }>;
172
+ /**
173
+ * Clear the call log.
174
+ */
175
+ clearLog(): void;
176
+ /**
177
+ * Get policy summary for this module.
178
+ */
179
+ getPolicySummary(): {
180
+ deniedActions: PolicyAction[];
181
+ deniedTools: string[];
182
+ allowedTools: string[] | null;
183
+ toolsPolicy: 'allow_by_default' | 'deny_by_default' | undefined;
184
+ };
185
+ }
186
+ /**
187
+ * Create a policy-aware tool executor wrapper.
188
+ *
189
+ * @example
190
+ * const safeExecutor = createPolicyAwareExecutor(module, 'write_file', async (args) => {
191
+ * return fs.writeFile(args.path, args.content);
192
+ * });
193
+ *
194
+ * // This will throw if write_file is denied
195
+ * await safeExecutor({ path: '/tmp/test.txt', content: 'hello' });
196
+ */
197
+ export declare function createPolicyAwareExecutor(module: CognitiveModule, toolName: string, executor: ToolExecutor): ToolExecutor;
198
+ /**
199
+ * Validate overflow.insights against module's max_items config.
200
+ *
201
+ * @param data The response data object
202
+ * @param module The cognitive module config
203
+ * @returns Array of errors if insights exceed limit
204
+ */
205
+ export declare function validateOverflowLimits(data: Record<string, unknown>, module: CognitiveModule): string[];
206
+ /**
207
+ * Validate enum values against module's enum strategy.
208
+ * For strict mode, custom enum objects are not allowed.
209
+ *
210
+ * @param data The response data object
211
+ * @param module The cognitive module config
212
+ * @returns Array of errors if enum violations found
213
+ */
214
+ export declare function validateEnumStrategy(data: Record<string, unknown>, module: CognitiveModule): string[];
215
+ /** Hook called before module execution */
216
+ export type BeforeCallHook = (moduleName: string, inputData: ModuleInput, moduleConfig: CognitiveModule) => void;
217
+ /** Hook called after successful module execution */
218
+ export type AfterCallHook = (moduleName: string, result: EnvelopeResponseV22<unknown>, latencyMs: number) => void;
219
+ /** Hook called when an error occurs */
220
+ export type ErrorHook = (moduleName: string, error: Error, partialResult: unknown | null) => void;
221
+ /**
222
+ * Decorator to register a before-call hook.
223
+ *
224
+ * @example
225
+ * onBeforeCall((moduleName, inputData, config) => {
226
+ * console.log(`Calling ${moduleName} with`, inputData);
227
+ * });
228
+ */
229
+ export declare function onBeforeCall(hook: BeforeCallHook): BeforeCallHook;
230
+ /**
231
+ * Decorator to register an after-call hook.
232
+ *
233
+ * @example
234
+ * onAfterCall((moduleName, result, latencyMs) => {
235
+ * console.log(`${moduleName} completed in ${latencyMs}ms`);
236
+ * });
237
+ */
238
+ export declare function onAfterCall(hook: AfterCallHook): AfterCallHook;
239
+ /**
240
+ * Decorator to register an error hook.
241
+ *
242
+ * @example
243
+ * onError((moduleName, error, partialResult) => {
244
+ * console.error(`Error in ${moduleName}:`, error);
245
+ * });
246
+ */
247
+ export declare function onError(hook: ErrorHook): ErrorHook;
248
+ /**
249
+ * Register a hook programmatically.
250
+ */
251
+ export declare function registerHook(hookType: 'before_call' | 'after_call' | 'error', hook: BeforeCallHook | AfterCallHook | ErrorHook): void;
252
+ /**
253
+ * Unregister a hook. Returns true if found and removed.
254
+ */
255
+ export declare function unregisterHook(hookType: 'before_call' | 'after_call' | 'error', hook: BeforeCallHook | AfterCallHook | ErrorHook): boolean;
256
+ /**
257
+ * Clear all registered hooks.
258
+ */
259
+ export declare function clearHooks(): void;
260
+ /**
261
+ * Error code taxonomy following CONFORMANCE.md E1xxx-E4xxx structure.
262
+ *
263
+ * E1xxx: Input errors (caller errors, fixable by modifying input)
264
+ * E2xxx: Processing errors (module understood input but couldn't complete)
265
+ * E3xxx: Output errors (generated output doesn't meet requirements)
266
+ * E4xxx: Runtime errors (infrastructure/system-level failures)
267
+ */
268
+ /** Standard error codes with E-format (as per ERROR-CODES.md) */
269
+ export declare const ERROR_CODES: {
270
+ readonly E1000: "PARSE_ERROR";
271
+ readonly E1001: "INVALID_INPUT";
272
+ readonly E1002: "MISSING_REQUIRED_FIELD";
273
+ readonly E1003: "TYPE_MISMATCH";
274
+ readonly E1004: "UNSUPPORTED_VALUE";
275
+ readonly E1005: "INPUT_TOO_LARGE";
276
+ readonly E1006: "INVALID_REFERENCE";
277
+ readonly E2001: "LOW_CONFIDENCE";
278
+ readonly E2002: "TIMEOUT";
279
+ readonly E2003: "TOKEN_LIMIT";
280
+ readonly E2004: "NO_ACTION_POSSIBLE";
281
+ readonly E2005: "SEMANTIC_CONFLICT";
282
+ readonly E2006: "AMBIGUOUS_INPUT";
283
+ readonly E2007: "INSUFFICIENT_CONTEXT";
284
+ readonly E3001: "OUTPUT_SCHEMA_VIOLATION";
285
+ readonly E3002: "PARTIAL_RESULT";
286
+ readonly E3003: "MISSING_RATIONALE";
287
+ readonly E3004: "OVERFLOW_LIMIT";
288
+ readonly E3005: "INVALID_ENUM";
289
+ readonly E3006: "CONSTRAINT_VIOLATION";
290
+ readonly E4000: "INTERNAL_ERROR";
291
+ readonly E4001: "PROVIDER_UNAVAILABLE";
292
+ readonly E4002: "RATE_LIMITED";
293
+ readonly E4003: "CONTEXT_OVERFLOW";
294
+ readonly E4004: "CIRCULAR_DEPENDENCY";
295
+ readonly E4005: "MAX_DEPTH_EXCEEDED";
296
+ readonly E4006: "MODULE_NOT_FOUND";
297
+ readonly E4007: "PERMISSION_DENIED";
298
+ };
299
+ /** Reverse mapping: legacy code -> E-format code */
300
+ export declare const LEGACY_TO_E_CODE: Record<string, string>;
301
+ /** Error codes and their default properties */
302
+ export declare const ERROR_PROPERTIES: Record<string, {
303
+ recoverable: boolean;
304
+ retry_after_ms: number | null;
305
+ }>;
306
+ /**
307
+ * Normalize error code to E-format.
308
+ * Accepts both E-format (E1001) and legacy format (INVALID_INPUT).
309
+ *
310
+ * @param code Error code in any format
311
+ * @returns E-format code (e.g., "E1001")
312
+ */
313
+ export declare function normalizeErrorCode(code: string): string;
314
+ /**
315
+ * Get error category from E-format code.
316
+ *
317
+ * @param code E-format error code (e.g., "E1001")
318
+ * @returns Category: 'input' | 'processing' | 'output' | 'runtime'
319
+ */
320
+ export declare function getErrorCategory(code: string): 'input' | 'processing' | 'output' | 'runtime';
321
+ export interface MakeErrorResponseOptions {
322
+ /** Error code - accepts both E-format (E1001) and legacy format (INVALID_INPUT) */
323
+ code: string;
324
+ message: string;
325
+ explain?: string;
326
+ partialData?: unknown;
327
+ details?: Record<string, unknown>;
328
+ recoverable?: boolean;
329
+ retryAfterMs?: number;
330
+ confidence?: number;
331
+ risk?: RiskLevel;
332
+ /** Suggestion for how to fix the error */
333
+ suggestion?: string;
334
+ /** Whether to use E-format codes in output (default: true) */
335
+ useEFormat?: boolean;
336
+ }
337
+ /**
338
+ * Build a standardized error response with enhanced taxonomy.
339
+ * Supports both E-format (E1001) and legacy format (INVALID_INPUT) error codes.
340
+ *
341
+ * @param options Error response options
342
+ * @returns Standardized error envelope
343
+ */
344
+ export declare function makeErrorResponse(options: MakeErrorResponseOptions): EnvelopeResponseV22<unknown>;
345
+ export interface MakeSuccessResponseOptions {
346
+ data: unknown;
347
+ confidence: number;
348
+ risk: RiskLevel;
349
+ explain: string;
350
+ latencyMs?: number;
351
+ model?: string;
352
+ traceId?: string;
353
+ }
354
+ /**
355
+ * Build a standardized success response.
356
+ */
357
+ export declare function makeSuccessResponse(options: MakeSuccessResponseOptions): EnvelopeResponseV22<unknown>;
6
358
  export interface RunOptions {
7
359
  input?: ModuleInput;
8
360
  args?: string;
9
361
  verbose?: boolean;
362
+ validateInput?: boolean;
363
+ validateOutput?: boolean;
10
364
  useEnvelope?: boolean;
11
365
  useV22?: boolean;
12
366
  enableRepair?: boolean;
367
+ traceId?: string;
368
+ model?: string;
13
369
  }
14
370
  export declare function runModule(module: CognitiveModule, provider: Provider, options?: RunOptions): Promise<ModuleResult>;
371
+ /** Event types emitted during streaming execution */
372
+ export type StreamEventType = 'start' | 'chunk' | 'meta' | 'complete' | 'error';
373
+ /** Event emitted during streaming execution */
374
+ export interface StreamEvent {
375
+ type: StreamEventType;
376
+ timestamp_ms: number;
377
+ module_name: string;
378
+ chunk?: string;
379
+ meta?: EnvelopeMeta;
380
+ result?: EnvelopeResponseV22<unknown>;
381
+ error?: {
382
+ code: string;
383
+ message: string;
384
+ };
385
+ }
386
+ export interface StreamOptions {
387
+ input?: ModuleInput;
388
+ args?: string;
389
+ validateInput?: boolean;
390
+ validateOutput?: boolean;
391
+ useV22?: boolean;
392
+ enableRepair?: boolean;
393
+ traceId?: string;
394
+ model?: string;
395
+ }
396
+ /**
397
+ * Run a cognitive module with streaming output.
398
+ *
399
+ * Yields StreamEvent objects as the module executes:
400
+ * - type="start": Module execution started
401
+ * - type="chunk": Incremental data chunk (if LLM supports streaming)
402
+ * - type="meta": Meta information available early
403
+ * - type="complete": Final complete result
404
+ * - type="error": Error occurred
405
+ *
406
+ * @example
407
+ * for await (const event of runModuleStream(module, provider, options)) {
408
+ * if (event.type === 'chunk') {
409
+ * process.stdout.write(event.chunk);
410
+ * } else if (event.type === 'complete') {
411
+ * console.log('Result:', event.result);
412
+ * }
413
+ * }
414
+ */
415
+ export declare function runModuleStream(module: CognitiveModule, provider: Provider, options?: StreamOptions): AsyncGenerator<StreamEvent>;
416
+ export interface RunModuleLegacyOptions {
417
+ validateInput?: boolean;
418
+ validateOutput?: boolean;
419
+ model?: string;
420
+ }
421
+ /**
422
+ * Run a cognitive module (legacy API, returns raw output).
423
+ * For backward compatibility. Throws on error instead of returning error envelope.
424
+ */
425
+ export declare function runModuleLegacy(module: CognitiveModule, provider: Provider, input: ModuleInput, options?: RunModuleLegacyOptions): Promise<unknown>;
426
+ /**
427
+ * Extract meta from v2.2 envelope for routing/logging.
428
+ */
429
+ export declare function extractMeta(result: EnvelopeResponseV22<unknown>): EnvelopeMeta;
430
+ export declare const extractMetaV22: typeof extractMeta;
431
+ /**
432
+ * Determine if result should be escalated to human review based on meta.
433
+ */
434
+ export declare function shouldEscalate(result: EnvelopeResponseV22<unknown>, confidenceThreshold?: number): boolean;
435
+ export declare const shouldEscalateV22: typeof shouldEscalate;