cognitive-modules 0.6.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 (78) hide show
  1. package/README.md +165 -0
  2. package/dist/cli.d.ts +16 -0
  3. package/dist/cli.js +335 -0
  4. package/dist/commands/add.d.ts +34 -0
  5. package/dist/commands/add.js +229 -0
  6. package/dist/commands/index.d.ts +11 -0
  7. package/dist/commands/index.js +11 -0
  8. package/dist/commands/init.d.ts +5 -0
  9. package/dist/commands/init.js +78 -0
  10. package/dist/commands/list.d.ts +5 -0
  11. package/dist/commands/list.js +28 -0
  12. package/dist/commands/pipe.d.ts +9 -0
  13. package/dist/commands/pipe.js +59 -0
  14. package/dist/commands/remove.d.ts +10 -0
  15. package/dist/commands/remove.js +47 -0
  16. package/dist/commands/run.d.ts +12 -0
  17. package/dist/commands/run.js +65 -0
  18. package/dist/commands/update.d.ts +14 -0
  19. package/dist/commands/update.js +105 -0
  20. package/dist/commands/versions.d.ts +13 -0
  21. package/dist/commands/versions.js +60 -0
  22. package/dist/index.d.ts +9 -0
  23. package/dist/index.js +11 -0
  24. package/dist/modules/index.d.ts +5 -0
  25. package/dist/modules/index.js +5 -0
  26. package/dist/modules/loader.d.ts +12 -0
  27. package/dist/modules/loader.js +197 -0
  28. package/dist/modules/runner.d.ts +12 -0
  29. package/dist/modules/runner.js +229 -0
  30. package/dist/providers/anthropic.d.ts +14 -0
  31. package/dist/providers/anthropic.js +70 -0
  32. package/dist/providers/base.d.ts +11 -0
  33. package/dist/providers/base.js +19 -0
  34. package/dist/providers/deepseek.d.ts +14 -0
  35. package/dist/providers/deepseek.js +66 -0
  36. package/dist/providers/gemini.d.ts +19 -0
  37. package/dist/providers/gemini.js +94 -0
  38. package/dist/providers/index.d.ts +19 -0
  39. package/dist/providers/index.js +74 -0
  40. package/dist/providers/minimax.d.ts +14 -0
  41. package/dist/providers/minimax.js +64 -0
  42. package/dist/providers/moonshot.d.ts +14 -0
  43. package/dist/providers/moonshot.js +65 -0
  44. package/dist/providers/ollama.d.ts +13 -0
  45. package/dist/providers/ollama.js +64 -0
  46. package/dist/providers/openai.d.ts +14 -0
  47. package/dist/providers/openai.js +67 -0
  48. package/dist/providers/qwen.d.ts +14 -0
  49. package/dist/providers/qwen.js +65 -0
  50. package/dist/types.d.ts +136 -0
  51. package/dist/types.js +5 -0
  52. package/package.json +48 -0
  53. package/src/cli.ts +375 -0
  54. package/src/commands/add.ts +315 -0
  55. package/src/commands/index.ts +12 -0
  56. package/src/commands/init.ts +94 -0
  57. package/src/commands/list.ts +33 -0
  58. package/src/commands/pipe.ts +76 -0
  59. package/src/commands/remove.ts +57 -0
  60. package/src/commands/run.ts +80 -0
  61. package/src/commands/update.ts +130 -0
  62. package/src/commands/versions.ts +79 -0
  63. package/src/index.ts +44 -0
  64. package/src/modules/index.ts +6 -0
  65. package/src/modules/loader.ts +219 -0
  66. package/src/modules/runner.ts +278 -0
  67. package/src/providers/anthropic.ts +89 -0
  68. package/src/providers/base.ts +29 -0
  69. package/src/providers/deepseek.ts +83 -0
  70. package/src/providers/gemini.ts +117 -0
  71. package/src/providers/index.ts +78 -0
  72. package/src/providers/minimax.ts +81 -0
  73. package/src/providers/moonshot.ts +82 -0
  74. package/src/providers/ollama.ts +83 -0
  75. package/src/providers/openai.ts +84 -0
  76. package/src/providers/qwen.ts +82 -0
  77. package/src/types.ts +184 -0
  78. package/tsconfig.json +17 -0
@@ -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,76 @@
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
+ });
56
+
57
+ // Output envelope format to stdout
58
+ console.log(JSON.stringify(result));
59
+
60
+ return {
61
+ success: result.ok,
62
+ data: result,
63
+ };
64
+ } catch (e) {
65
+ const error = e instanceof Error ? e.message : String(e);
66
+ // Output error in envelope format
67
+ console.log(JSON.stringify({
68
+ ok: false,
69
+ error: { code: 'RUNTIME_ERROR', message: error }
70
+ }));
71
+ return {
72
+ success: false,
73
+ error,
74
+ };
75
+ }
76
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Remove command - Remove installed modules
3
+ *
4
+ * cog remove code-simplifier
5
+ */
6
+
7
+ import { existsSync, rmSync } from 'node:fs';
8
+ import { readFile, writeFile } from 'node:fs/promises';
9
+ import { join } from 'node:path';
10
+ import { homedir } from 'node:os';
11
+ import type { CommandContext, CommandResult } from '../types.js';
12
+
13
+ const USER_MODULES_DIR = join(homedir(), '.cognitive', 'modules');
14
+ const INSTALLED_MANIFEST = join(homedir(), '.cognitive', 'installed.json');
15
+
16
+ /**
17
+ * Remove an installed module
18
+ */
19
+ export async function remove(
20
+ moduleName: string,
21
+ ctx: CommandContext
22
+ ): Promise<CommandResult> {
23
+ const modulePath = join(USER_MODULES_DIR, moduleName);
24
+
25
+ if (!existsSync(modulePath)) {
26
+ return {
27
+ success: false,
28
+ error: `Module not found in global location: ${moduleName}. Only modules in ~/.cognitive/modules can be removed.`,
29
+ };
30
+ }
31
+
32
+ try {
33
+ // Remove module directory
34
+ rmSync(modulePath, { recursive: true, force: true });
35
+
36
+ // Remove from manifest
37
+ if (existsSync(INSTALLED_MANIFEST)) {
38
+ const content = await readFile(INSTALLED_MANIFEST, 'utf-8');
39
+ const manifest = JSON.parse(content);
40
+ delete manifest[moduleName];
41
+ await writeFile(INSTALLED_MANIFEST, JSON.stringify(manifest, null, 2));
42
+ }
43
+
44
+ return {
45
+ success: true,
46
+ data: {
47
+ message: `Removed: ${moduleName}`,
48
+ name: moduleName,
49
+ },
50
+ };
51
+ } catch (error) {
52
+ return {
53
+ success: false,
54
+ error: error instanceof Error ? error.message : String(error),
55
+ };
56
+ }
57
+ }
@@ -0,0 +1,80 @@
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
+ verbose: options.verbose || ctx.verbose,
51
+ });
52
+
53
+ // Return envelope format or extracted data
54
+ if (options.pretty) {
55
+ return {
56
+ success: result.ok,
57
+ data: result,
58
+ };
59
+ } else {
60
+ // For non-pretty mode, return data (success) or error (failure)
61
+ if (result.ok) {
62
+ return {
63
+ success: true,
64
+ data: result.data,
65
+ };
66
+ } else {
67
+ return {
68
+ success: false,
69
+ error: `${result.error?.code}: ${result.error?.message}`,
70
+ data: result.partial_data,
71
+ };
72
+ }
73
+ }
74
+ } catch (e) {
75
+ return {
76
+ success: false,
77
+ error: e instanceof Error ? e.message : String(e),
78
+ };
79
+ }
80
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Update command - Update installed modules to latest version
3
+ *
4
+ * cog update code-simplifier
5
+ * cog update code-simplifier --tag v2.0.0
6
+ */
7
+
8
+ import { existsSync, rmSync } from 'node:fs';
9
+ import { readFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { homedir } from 'node:os';
12
+ import type { CommandContext, CommandResult } from '../types.js';
13
+ import { add, getInstallInfo } from './add.js';
14
+
15
+ const USER_MODULES_DIR = join(homedir(), '.cognitive', 'modules');
16
+
17
+ export interface UpdateOptions {
18
+ tag?: string;
19
+ }
20
+
21
+ /**
22
+ * Get module version from installed module
23
+ */
24
+ async function getInstalledVersion(moduleName: string): Promise<string | undefined> {
25
+ const modulePath = join(USER_MODULES_DIR, moduleName);
26
+
27
+ if (!existsSync(modulePath)) {
28
+ return undefined;
29
+ }
30
+
31
+ const yaml = await import('js-yaml');
32
+
33
+ // Try v2 format
34
+ const yamlPath = join(modulePath, 'module.yaml');
35
+ if (existsSync(yamlPath)) {
36
+ const content = await readFile(yamlPath, 'utf-8');
37
+ const data = yaml.load(content) as { version?: string };
38
+ return data?.version;
39
+ }
40
+
41
+ // Try v1 format
42
+ const mdPath = existsSync(join(modulePath, 'MODULE.md'))
43
+ ? join(modulePath, 'MODULE.md')
44
+ : join(modulePath, 'module.md');
45
+
46
+ if (existsSync(mdPath)) {
47
+ const content = await readFile(mdPath, 'utf-8');
48
+ if (content.startsWith('---')) {
49
+ const parts = content.split('---');
50
+ if (parts.length >= 3) {
51
+ const meta = yaml.load(parts[1]) as { version?: string };
52
+ return meta?.version;
53
+ }
54
+ }
55
+ }
56
+
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * Update an installed module
62
+ */
63
+ export async function update(
64
+ moduleName: string,
65
+ ctx: CommandContext,
66
+ options: UpdateOptions = {}
67
+ ): Promise<CommandResult> {
68
+ // Get installation info
69
+ const info = await getInstallInfo(moduleName);
70
+
71
+ if (!info) {
72
+ return {
73
+ success: false,
74
+ error: `Module not found or not installed from GitHub: ${moduleName}. Only modules installed with 'cog add' can be updated.`,
75
+ };
76
+ }
77
+
78
+ if (!info.githubUrl) {
79
+ return {
80
+ success: false,
81
+ error: `Module was not installed from GitHub: ${moduleName}`,
82
+ };
83
+ }
84
+
85
+ // Get current version
86
+ const oldVersion = await getInstalledVersion(moduleName);
87
+
88
+ // Determine what ref to use
89
+ const tag = options.tag || info.tag;
90
+ const branch = info.branch || 'main';
91
+
92
+ // Re-install from source
93
+ const result = await add(info.githubUrl, ctx, {
94
+ module: info.modulePath,
95
+ name: moduleName,
96
+ tag,
97
+ branch: tag ? undefined : branch,
98
+ });
99
+
100
+ if (!result.success) {
101
+ return result;
102
+ }
103
+
104
+ const data = result.data as { version?: string };
105
+ const newVersion = data.version;
106
+
107
+ // Determine message
108
+ let message: string;
109
+ if (oldVersion && newVersion) {
110
+ if (oldVersion === newVersion) {
111
+ message = `Already up to date: ${moduleName} v${newVersion}`;
112
+ } else {
113
+ message = `Updated: ${moduleName} v${oldVersion} → v${newVersion}`;
114
+ }
115
+ } else if (newVersion) {
116
+ message = `Updated: ${moduleName} to v${newVersion}`;
117
+ } else {
118
+ message = `Updated: ${moduleName}`;
119
+ }
120
+
121
+ return {
122
+ success: true,
123
+ data: {
124
+ message,
125
+ name: moduleName,
126
+ oldVersion,
127
+ newVersion,
128
+ },
129
+ };
130
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Versions command - List available versions from GitHub
3
+ *
4
+ * cog versions ziel-io/cognitive-modules
5
+ */
6
+
7
+ import type { CommandContext, CommandResult } from '../types.js';
8
+
9
+ export interface VersionsOptions {
10
+ limit?: number;
11
+ }
12
+
13
+ /**
14
+ * Parse GitHub URL or shorthand
15
+ */
16
+ function parseGitHubUrl(url: string): { org: string; repo: string } {
17
+ if (!url.startsWith('http')) {
18
+ url = `https://github.com/${url}`;
19
+ }
20
+
21
+ const match = url.match(/https:\/\/github\.com\/([^\/]+)\/([^\/]+)\/?/);
22
+ if (!match) {
23
+ throw new Error(`Invalid GitHub URL: ${url}`);
24
+ }
25
+
26
+ return {
27
+ org: match[1],
28
+ repo: match[2].replace(/\.git$/, ''),
29
+ };
30
+ }
31
+
32
+ /**
33
+ * List available versions (tags) from GitHub
34
+ */
35
+ export async function versions(
36
+ url: string,
37
+ ctx: CommandContext,
38
+ options: VersionsOptions = {}
39
+ ): Promise<CommandResult> {
40
+ const { limit = 10 } = options;
41
+
42
+ try {
43
+ const { org, repo } = parseGitHubUrl(url);
44
+
45
+ // Fetch tags from GitHub API
46
+ const apiUrl = `https://api.github.com/repos/${org}/${repo}/tags?per_page=${limit}`;
47
+
48
+ const response = await fetch(apiUrl, {
49
+ headers: {
50
+ 'User-Agent': 'cognitive-runtime/1.0',
51
+ 'Accept': 'application/vnd.github.v3+json',
52
+ },
53
+ });
54
+
55
+ if (!response.ok) {
56
+ if (response.status === 404) {
57
+ throw new Error(`Repository not found: ${org}/${repo}`);
58
+ }
59
+ throw new Error(`GitHub API error: ${response.status}`);
60
+ }
61
+
62
+ const data = await response.json() as Array<{ name: string }>;
63
+ const tags = data.map(t => t.name);
64
+
65
+ return {
66
+ success: true,
67
+ data: {
68
+ repository: `${org}/${repo}`,
69
+ tags,
70
+ count: tags.length,
71
+ },
72
+ };
73
+ } catch (error) {
74
+ return {
75
+ success: false,
76
+ error: error instanceof Error ? error.message : String(error),
77
+ };
78
+ }
79
+ }
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
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
+ ModuleInput,
16
+ ModuleConstraints,
17
+ ToolsPolicy,
18
+ OutputContract,
19
+ FailureContract,
20
+ CommandContext,
21
+ CommandResult,
22
+ } from './types.js';
23
+
24
+ // Providers
25
+ export {
26
+ getProvider,
27
+ listProviders,
28
+ GeminiProvider,
29
+ OpenAIProvider,
30
+ AnthropicProvider,
31
+ BaseProvider,
32
+ } from './providers/index.js';
33
+
34
+ // Modules
35
+ export {
36
+ loadModule,
37
+ findModule,
38
+ listModules,
39
+ getDefaultSearchPaths,
40
+ runModule,
41
+ } from './modules/index.js';
42
+
43
+ // Commands
44
+ 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';