cognitive-runtime 0.1.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.
Files changed (51) hide show
  1. package/README.md +124 -0
  2. package/dist/cli.d.ts +10 -0
  3. package/dist/cli.js +200 -0
  4. package/dist/commands/index.d.ts +7 -0
  5. package/dist/commands/index.js +7 -0
  6. package/dist/commands/init.d.ts +5 -0
  7. package/dist/commands/init.js +78 -0
  8. package/dist/commands/list.d.ts +5 -0
  9. package/dist/commands/list.js +28 -0
  10. package/dist/commands/pipe.d.ts +9 -0
  11. package/dist/commands/pipe.js +57 -0
  12. package/dist/commands/run.d.ts +12 -0
  13. package/dist/commands/run.js +48 -0
  14. package/dist/index.d.ts +9 -0
  15. package/dist/index.js +11 -0
  16. package/dist/modules/index.d.ts +5 -0
  17. package/dist/modules/index.js +5 -0
  18. package/dist/modules/loader.d.ts +8 -0
  19. package/dist/modules/loader.js +91 -0
  20. package/dist/modules/runner.d.ts +12 -0
  21. package/dist/modules/runner.js +93 -0
  22. package/dist/providers/anthropic.d.ts +14 -0
  23. package/dist/providers/anthropic.js +70 -0
  24. package/dist/providers/base.d.ts +11 -0
  25. package/dist/providers/base.js +19 -0
  26. package/dist/providers/gemini.d.ts +19 -0
  27. package/dist/providers/gemini.js +94 -0
  28. package/dist/providers/index.d.ts +13 -0
  29. package/dist/providers/index.js +38 -0
  30. package/dist/providers/openai.d.ts +14 -0
  31. package/dist/providers/openai.js +67 -0
  32. package/dist/types.d.ts +53 -0
  33. package/dist/types.js +4 -0
  34. package/package.json +33 -0
  35. package/src/cli.ts +223 -0
  36. package/src/commands/index.ts +8 -0
  37. package/src/commands/init.ts +94 -0
  38. package/src/commands/list.ts +33 -0
  39. package/src/commands/pipe.ts +74 -0
  40. package/src/commands/run.ts +65 -0
  41. package/src/index.ts +39 -0
  42. package/src/modules/index.ts +6 -0
  43. package/src/modules/loader.ts +106 -0
  44. package/src/modules/runner.ts +121 -0
  45. package/src/providers/anthropic.ts +89 -0
  46. package/src/providers/base.ts +29 -0
  47. package/src/providers/gemini.ts +117 -0
  48. package/src/providers/index.ts +43 -0
  49. package/src/providers/openai.ts +84 -0
  50. package/src/types.ts +64 -0
  51. package/tsconfig.json +17 -0
package/src/cli.ts ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Cognitive Runtime CLI
4
+ *
5
+ * cog run <module> --args "..." - Run a module
6
+ * cog list - List available modules
7
+ * cog pipe --module <name> - Pipe mode (stdin/stdout)
8
+ * cog doctor - Check configuration
9
+ */
10
+
11
+ import { parseArgs } from 'node:util';
12
+ import { getProvider, listProviders } from './providers/index.js';
13
+ import { run, list, pipe, init } from './commands/index.js';
14
+ import type { CommandContext } from './types.js';
15
+
16
+ const VERSION = '0.1.0';
17
+
18
+ async function main() {
19
+ const args = process.argv.slice(2);
20
+ const command = args[0];
21
+
22
+ if (!command || command === '--help' || command === '-h') {
23
+ printHelp();
24
+ process.exit(0);
25
+ }
26
+
27
+ if (command === '--version' || command === '-v') {
28
+ console.log(`Cognitive Runtime v${VERSION}`);
29
+ process.exit(0);
30
+ }
31
+
32
+ // Parse common options
33
+ const { values } = parseArgs({
34
+ args: args.slice(1),
35
+ options: {
36
+ args: { type: 'string', short: 'a' },
37
+ input: { type: 'string', short: 'i' },
38
+ module: { type: 'string', short: 'm' },
39
+ provider: { type: 'string', short: 'p' },
40
+ pretty: { type: 'boolean', default: false },
41
+ verbose: { type: 'boolean', short: 'V', default: false },
42
+ 'no-validate': { type: 'boolean', default: false },
43
+ },
44
+ allowPositionals: true,
45
+ });
46
+
47
+ // Get provider
48
+ let provider;
49
+ try {
50
+ provider = getProvider(values.provider);
51
+ } catch (e) {
52
+ console.error(`Error: ${e instanceof Error ? e.message : e}`);
53
+ process.exit(1);
54
+ }
55
+
56
+ const ctx: CommandContext = {
57
+ cwd: process.cwd(),
58
+ provider,
59
+ verbose: values.verbose,
60
+ };
61
+
62
+ try {
63
+ switch (command) {
64
+ case 'run': {
65
+ const moduleName = args[1];
66
+ if (!moduleName || moduleName.startsWith('-')) {
67
+ console.error('Usage: cog run <module> [--args "..."]');
68
+ process.exit(1);
69
+ }
70
+
71
+ const result = await run(moduleName, ctx, {
72
+ args: values.args,
73
+ input: values.input,
74
+ noValidate: values['no-validate'],
75
+ pretty: values.pretty,
76
+ verbose: values.verbose,
77
+ });
78
+
79
+ if (!result.success) {
80
+ console.error(`Error: ${result.error}`);
81
+ process.exit(1);
82
+ }
83
+
84
+ console.log(JSON.stringify(result.data, null, values.pretty ? 2 : 0));
85
+ break;
86
+ }
87
+
88
+ case 'list': {
89
+ const result = await list(ctx);
90
+ if (!result.success) {
91
+ console.error(`Error: ${result.error}`);
92
+ process.exit(1);
93
+ }
94
+
95
+ const data = result.data as { modules: Array<{ name: string; version: string; responsibility: string; location: string }> };
96
+
97
+ if (data.modules.length === 0) {
98
+ console.log('No modules found.');
99
+ } else {
100
+ console.log('Available Modules:');
101
+ console.log('');
102
+ for (const m of data.modules) {
103
+ console.log(` ${m.name} (v${m.version})`);
104
+ console.log(` ${m.responsibility}`);
105
+ console.log(` ${m.location}`);
106
+ console.log('');
107
+ }
108
+ }
109
+ break;
110
+ }
111
+
112
+ case 'pipe': {
113
+ const moduleName = values.module || args[1];
114
+ if (!moduleName) {
115
+ console.error('Usage: cog pipe --module <name>');
116
+ process.exit(1);
117
+ }
118
+
119
+ await pipe(ctx, {
120
+ module: moduleName,
121
+ noValidate: values['no-validate'],
122
+ });
123
+ break;
124
+ }
125
+
126
+ case 'init': {
127
+ const moduleName = args[1];
128
+ const result = await init(ctx, moduleName);
129
+
130
+ if (!result.success) {
131
+ console.error(`Error: ${result.error}`);
132
+ process.exit(1);
133
+ }
134
+
135
+ const data = result.data as { message: string; location: string; files?: string[]; hint?: string };
136
+ console.log(data.message);
137
+ console.log(` Location: ${data.location}`);
138
+ if (data.files) {
139
+ console.log(` Files: ${data.files.join(', ')}`);
140
+ }
141
+ if (data.hint) {
142
+ console.log(` ${data.hint}`);
143
+ }
144
+ break;
145
+ }
146
+
147
+ case 'doctor': {
148
+ console.log('Cognitive Runtime - Environment Check\n');
149
+
150
+ console.log('Providers:');
151
+ for (const p of listProviders()) {
152
+ const status = p.configured ? '✓ configured' : '– not configured';
153
+ console.log(` ${p.name}: ${status}`);
154
+ }
155
+ console.log('');
156
+
157
+ try {
158
+ const provider = getProvider();
159
+ console.log(`Active provider: ${provider.name}`);
160
+ } catch {
161
+ console.log('Active provider: none (set an API key)');
162
+ }
163
+ break;
164
+ }
165
+
166
+ default:
167
+ console.error(`Unknown command: ${command}`);
168
+ console.error('Run "cog --help" for usage.');
169
+ process.exit(1);
170
+ }
171
+ } catch (e) {
172
+ console.error(`Error: ${e instanceof Error ? e.message : e}`);
173
+ if (values.verbose && e instanceof Error) {
174
+ console.error(e.stack);
175
+ }
176
+ process.exit(1);
177
+ }
178
+ }
179
+
180
+ function printHelp() {
181
+ console.log(`
182
+ Cognitive Runtime v${VERSION}
183
+ Structured AI Task Execution
184
+
185
+ USAGE:
186
+ cog <command> [options]
187
+
188
+ COMMANDS:
189
+ run <module> Run a Cognitive Module
190
+ list List available modules
191
+ pipe Pipe mode (stdin/stdout)
192
+ init [name] Initialize project or create module
193
+ doctor Check configuration
194
+
195
+ OPTIONS:
196
+ -a, --args <str> Arguments to pass to module
197
+ -i, --input <json> JSON input for module
198
+ -m, --module <name> Module name (for pipe)
199
+ -p, --provider <name> LLM provider (gemini, openai, anthropic)
200
+ --pretty Pretty-print JSON output
201
+ -V, --verbose Verbose output
202
+ --no-validate Skip schema validation
203
+ -v, --version Show version
204
+ -h, --help Show this help
205
+
206
+ EXAMPLES:
207
+ cog run code-reviewer --args "def foo(): pass"
208
+ cog list
209
+ echo "review this code" | cog pipe --module code-reviewer
210
+ cog init my-module
211
+ cog doctor
212
+
213
+ ENVIRONMENT:
214
+ GEMINI_API_KEY Google Gemini API key
215
+ OPENAI_API_KEY OpenAI API key
216
+ ANTHROPIC_API_KEY Anthropic API key
217
+ `);
218
+ }
219
+
220
+ main().catch(e => {
221
+ console.error('Fatal error:', e);
222
+ process.exit(1);
223
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Commands - Re-export all commands
3
+ */
4
+
5
+ export * from './run.js';
6
+ export * from './list.js';
7
+ export * from './pipe.js';
8
+ export * from './init.js';
@@ -0,0 +1,94 @@
1
+ /**
2
+ * cog init - Initialize a new Cognitive project
3
+ */
4
+
5
+ import * as fs from 'node:fs/promises';
6
+ import * as path from 'node:path';
7
+ import type { CommandContext, CommandResult } from '../types.js';
8
+
9
+ const EXAMPLE_MODULE_MD = `---
10
+ name: my-module
11
+ version: 1.0.0
12
+ responsibility: Describe what this module does
13
+ excludes:
14
+ - Do not do X
15
+ - Do not do Y
16
+ ---
17
+
18
+ Analyze the following input and provide a structured response:
19
+
20
+ $ARGUMENTS
21
+
22
+ Return a JSON object with your analysis.
23
+ `;
24
+
25
+ const EXAMPLE_SCHEMA_JSON = `{
26
+ "type": "object",
27
+ "properties": {
28
+ "result": {
29
+ "type": "string",
30
+ "description": "The main result of the analysis"
31
+ },
32
+ "confidence": {
33
+ "type": "number",
34
+ "minimum": 0,
35
+ "maximum": 1,
36
+ "description": "Confidence score"
37
+ },
38
+ "rationale": {
39
+ "type": "string",
40
+ "description": "Explanation of the reasoning"
41
+ }
42
+ },
43
+ "required": ["result", "confidence", "rationale"]
44
+ }
45
+ `;
46
+
47
+ export async function init(ctx: CommandContext, moduleName?: string): Promise<CommandResult> {
48
+ const cognitiveDir = path.join(ctx.cwd, 'cognitive', 'modules');
49
+
50
+ try {
51
+ // Create directory structure
52
+ await fs.mkdir(cognitiveDir, { recursive: true });
53
+
54
+ // If module name provided, create a new module
55
+ if (moduleName) {
56
+ const moduleDir = path.join(cognitiveDir, moduleName);
57
+ await fs.mkdir(moduleDir, { recursive: true });
58
+
59
+ await fs.writeFile(
60
+ path.join(moduleDir, 'MODULE.md'),
61
+ EXAMPLE_MODULE_MD.replace('my-module', moduleName)
62
+ );
63
+
64
+ await fs.writeFile(
65
+ path.join(moduleDir, 'schema.json'),
66
+ EXAMPLE_SCHEMA_JSON
67
+ );
68
+
69
+ return {
70
+ success: true,
71
+ data: {
72
+ message: `Created module: ${moduleName}`,
73
+ location: moduleDir,
74
+ files: ['MODULE.md', 'schema.json'],
75
+ },
76
+ };
77
+ }
78
+
79
+ // Just initialize the directory
80
+ return {
81
+ success: true,
82
+ data: {
83
+ message: 'Cognitive project initialized',
84
+ location: cognitiveDir,
85
+ hint: 'Run "cog init <module-name>" to create a new module',
86
+ },
87
+ };
88
+ } catch (e) {
89
+ return {
90
+ success: false,
91
+ error: e instanceof Error ? e.message : String(e),
92
+ };
93
+ }
94
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * cog list - List available Cognitive Modules
3
+ */
4
+
5
+ import type { CommandContext, CommandResult } from '../types.js';
6
+ import { listModules, getDefaultSearchPaths } from '../modules/index.js';
7
+
8
+ export async function list(ctx: CommandContext): Promise<CommandResult> {
9
+ const searchPaths = getDefaultSearchPaths(ctx.cwd);
10
+ const modules = await listModules(searchPaths);
11
+
12
+ if (modules.length === 0) {
13
+ return {
14
+ success: true,
15
+ data: {
16
+ modules: [],
17
+ message: `No modules found in: ${searchPaths.join(', ')}`,
18
+ },
19
+ };
20
+ }
21
+
22
+ return {
23
+ success: true,
24
+ data: {
25
+ modules: modules.map(m => ({
26
+ name: m.name,
27
+ version: m.version,
28
+ responsibility: m.responsibility,
29
+ location: m.location,
30
+ })),
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * cog pipe - Pipe mode for stdin/stdout integration
3
+ */
4
+
5
+ import * as readline from 'node:readline';
6
+ import type { CommandContext, CommandResult } from '../types.js';
7
+ import { findModule, getDefaultSearchPaths, runModule } from '../modules/index.js';
8
+
9
+ export interface PipeOptions {
10
+ module: string;
11
+ noValidate?: boolean;
12
+ }
13
+
14
+ export async function pipe(
15
+ ctx: CommandContext,
16
+ options: PipeOptions
17
+ ): Promise<CommandResult> {
18
+ const searchPaths = getDefaultSearchPaths(ctx.cwd);
19
+
20
+ // Find module
21
+ const module = await findModule(options.module, searchPaths);
22
+ if (!module) {
23
+ return {
24
+ success: false,
25
+ error: `Module not found: ${options.module}`,
26
+ };
27
+ }
28
+
29
+ // Read from stdin
30
+ const rl = readline.createInterface({
31
+ input: process.stdin,
32
+ output: process.stdout,
33
+ terminal: false,
34
+ });
35
+
36
+ const lines: string[] = [];
37
+ for await (const line of rl) {
38
+ lines.push(line);
39
+ }
40
+
41
+ const input = lines.join('\n');
42
+
43
+ try {
44
+ // Check if input is JSON
45
+ let inputData: Record<string, unknown> | undefined;
46
+ try {
47
+ inputData = JSON.parse(input);
48
+ } catch {
49
+ // Not JSON, use as args
50
+ }
51
+
52
+ const result = await runModule(module, ctx.provider, {
53
+ args: inputData ? undefined : input,
54
+ input: inputData,
55
+ validateInput: !options.noValidate,
56
+ validateOutput: !options.noValidate,
57
+ });
58
+
59
+ // Output JSON to stdout
60
+ console.log(JSON.stringify(result.output));
61
+
62
+ return {
63
+ success: true,
64
+ data: result,
65
+ };
66
+ } catch (e) {
67
+ const error = e instanceof Error ? e.message : String(e);
68
+ console.error(JSON.stringify({ error }));
69
+ return {
70
+ success: false,
71
+ error,
72
+ };
73
+ }
74
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * cog run - Run a Cognitive Module
3
+ */
4
+
5
+ import type { CommandContext, CommandResult } from '../types.js';
6
+ import { findModule, getDefaultSearchPaths, runModule } from '../modules/index.js';
7
+
8
+ export interface RunOptions {
9
+ args?: string;
10
+ input?: string;
11
+ noValidate?: boolean;
12
+ pretty?: boolean;
13
+ verbose?: boolean;
14
+ }
15
+
16
+ export async function run(
17
+ moduleName: string,
18
+ ctx: CommandContext,
19
+ options: RunOptions = {}
20
+ ): Promise<CommandResult> {
21
+ const searchPaths = getDefaultSearchPaths(ctx.cwd);
22
+
23
+ // Find module
24
+ const module = await findModule(moduleName, searchPaths);
25
+ if (!module) {
26
+ return {
27
+ success: false,
28
+ error: `Module not found: ${moduleName}\nSearch paths: ${searchPaths.join(', ')}`,
29
+ };
30
+ }
31
+
32
+ try {
33
+ // Parse input if provided as JSON
34
+ let inputData: Record<string, unknown> | undefined;
35
+ if (options.input) {
36
+ try {
37
+ inputData = JSON.parse(options.input);
38
+ } catch {
39
+ return {
40
+ success: false,
41
+ error: `Invalid JSON input: ${options.input}`,
42
+ };
43
+ }
44
+ }
45
+
46
+ // Run module
47
+ const result = await runModule(module, ctx.provider, {
48
+ args: options.args,
49
+ input: inputData,
50
+ validateInput: !options.noValidate,
51
+ validateOutput: !options.noValidate,
52
+ verbose: options.verbose || ctx.verbose,
53
+ });
54
+
55
+ return {
56
+ success: true,
57
+ data: options.pretty ? result : result.output,
58
+ };
59
+ } catch (e) {
60
+ return {
61
+ success: false,
62
+ error: e instanceof Error ? e.message : String(e),
63
+ };
64
+ }
65
+ }
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Cognitive Runtime - Main Entry Point
3
+ *
4
+ * Exports all public APIs for programmatic use.
5
+ */
6
+
7
+ // Types
8
+ export type {
9
+ Provider,
10
+ InvokeParams,
11
+ InvokeResult,
12
+ Message,
13
+ CognitiveModule,
14
+ ModuleResult,
15
+ CommandContext,
16
+ CommandResult,
17
+ } from './types.js';
18
+
19
+ // Providers
20
+ export {
21
+ getProvider,
22
+ listProviders,
23
+ GeminiProvider,
24
+ OpenAIProvider,
25
+ AnthropicProvider,
26
+ BaseProvider,
27
+ } from './providers/index.js';
28
+
29
+ // Modules
30
+ export {
31
+ loadModule,
32
+ findModule,
33
+ listModules,
34
+ getDefaultSearchPaths,
35
+ runModule,
36
+ } from './modules/index.js';
37
+
38
+ // Commands
39
+ export { run, list, pipe } from './commands/index.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Modules - Re-export all module functionality
3
+ */
4
+
5
+ export * from './loader.js';
6
+ export * from './runner.js';
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Module Loader - Load and parse Cognitive Modules
3
+ */
4
+
5
+ import * as fs from 'node:fs/promises';
6
+ import * as path from 'node:path';
7
+ import yaml from 'js-yaml';
8
+ import type { CognitiveModule } from '../types.js';
9
+
10
+ const FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?/;
11
+
12
+ export async function loadModule(modulePath: string): Promise<CognitiveModule> {
13
+ const moduleFile = path.join(modulePath, 'MODULE.md');
14
+ const schemaFile = path.join(modulePath, 'schema.json');
15
+
16
+ // Read MODULE.md
17
+ const moduleContent = await fs.readFile(moduleFile, 'utf-8');
18
+
19
+ // Parse frontmatter
20
+ const match = moduleContent.match(FRONTMATTER_REGEX);
21
+ if (!match) {
22
+ throw new Error(`Invalid MODULE.md: missing YAML frontmatter in ${moduleFile}`);
23
+ }
24
+
25
+ const frontmatter = yaml.load(match[1]) as Record<string, unknown>;
26
+ const prompt = (match[2] || '').trim();
27
+
28
+ // Read schema.json
29
+ let inputSchema: object | undefined;
30
+ let outputSchema: object | undefined;
31
+
32
+ try {
33
+ const schemaContent = await fs.readFile(schemaFile, 'utf-8');
34
+ const schema = JSON.parse(schemaContent);
35
+ inputSchema = schema.input;
36
+ outputSchema = schema.output;
37
+ } catch {
38
+ // Schema file is optional
39
+ }
40
+
41
+ return {
42
+ name: frontmatter.name as string || path.basename(modulePath),
43
+ version: frontmatter.version as string || '1.0.0',
44
+ responsibility: frontmatter.responsibility as string || '',
45
+ excludes: (frontmatter.excludes as string[]) || [],
46
+ context: frontmatter.context as 'fork' | 'main' | undefined,
47
+ prompt,
48
+ inputSchema,
49
+ outputSchema,
50
+ location: modulePath,
51
+ };
52
+ }
53
+
54
+ export async function findModule(name: string, searchPaths: string[]): Promise<CognitiveModule | null> {
55
+ for (const basePath of searchPaths) {
56
+ const modulePath = path.join(basePath, name);
57
+ const moduleFile = path.join(modulePath, 'MODULE.md');
58
+
59
+ try {
60
+ await fs.access(moduleFile);
61
+ return await loadModule(modulePath);
62
+ } catch {
63
+ // Module not found in this path, continue
64
+ }
65
+ }
66
+
67
+ return null;
68
+ }
69
+
70
+ export async function listModules(searchPaths: string[]): Promise<CognitiveModule[]> {
71
+ const modules: CognitiveModule[] = [];
72
+
73
+ for (const basePath of searchPaths) {
74
+ try {
75
+ const entries = await fs.readdir(basePath, { withFileTypes: true });
76
+
77
+ for (const entry of entries) {
78
+ if (entry.isDirectory()) {
79
+ const modulePath = path.join(basePath, entry.name);
80
+ const moduleFile = path.join(modulePath, 'MODULE.md');
81
+
82
+ try {
83
+ await fs.access(moduleFile);
84
+ const module = await loadModule(modulePath);
85
+ modules.push(module);
86
+ } catch {
87
+ // Not a valid module, skip
88
+ }
89
+ }
90
+ }
91
+ } catch {
92
+ // Path doesn't exist, skip
93
+ }
94
+ }
95
+
96
+ return modules;
97
+ }
98
+
99
+ export function getDefaultSearchPaths(cwd: string): string[] {
100
+ const home = process.env.HOME || '';
101
+ return [
102
+ path.join(cwd, 'cognitive', 'modules'),
103
+ path.join(cwd, '.cognitive', 'modules'),
104
+ path.join(home, '.cognitive', 'modules'),
105
+ ];
106
+ }