cognitive-core 0.0.1 → 0.0.2

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.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
1
  # cognitive-core
2
2
 
3
- > Coming soon
3
+ TypeScript client for [Cognitive Core](https://github.com/alexngai/meta-learning-engine) - A meta-learning framework for learning from agent trajectories.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install cognitive-core
9
+ ```
10
+
11
+ **Prerequisites:** Python 3.10+
12
+
13
+ ## Setup
14
+
15
+ The package can automatically set up a Python virtual environment and install dependencies:
16
+
17
+ ```typescript
18
+ import { setup, CognitiveCore } from "cognitive-core";
19
+
20
+ // One-time setup (creates .cognitive-core/ venv)
21
+ const { pythonPath, version } = await setup();
22
+ console.log(`Installed cognitive-core ${version}`);
23
+
24
+ // CognitiveCore automatically uses the venv
25
+ const core = new CognitiveCore();
26
+ await core.start();
27
+ ```
28
+
29
+ ### Setup Options
30
+
31
+ ```typescript
32
+ await setup({
33
+ // Custom venv location (default: ".cognitive-core")
34
+ venvDir: "./my-venv",
35
+
36
+ // Install optional features
37
+ extras: ["arc", "embeddings", "llm"],
38
+
39
+ // Specific version
40
+ version: "0.1.0",
41
+
42
+ // Quiet mode
43
+ verbose: false,
44
+ });
45
+ ```
46
+
47
+ ### Manual Installation
48
+
49
+ If you prefer to manage Python yourself:
50
+
51
+ ```bash
52
+ pip install cognitive-core
53
+ ```
54
+
55
+ Then use the system Python:
56
+
57
+ ```typescript
58
+ const core = new CognitiveCore({ pythonPath: "python3" });
59
+ ```
60
+
61
+ ## Quick Start
62
+
63
+ ```typescript
64
+ import { CognitiveCore } from "cognitive-core";
65
+
66
+ const core = new CognitiveCore();
67
+
68
+ // Start the Python subprocess
69
+ await core.start();
70
+
71
+ // Get version
72
+ const version = await core.version();
73
+ console.log(`Running cognitive-core v${version}`);
74
+
75
+ // Create an environment
76
+ const env = await core.env.create("arc");
77
+
78
+ // Reset with a task
79
+ const { observation } = await core.env.reset(env.envId, {
80
+ id: "task-1",
81
+ domain: "arc",
82
+ description: "Transform the input grid",
83
+ context: {
84
+ grids: {
85
+ train: [
86
+ [[[0, 1], [1, 0]], [[1, 0], [0, 1]]],
87
+ ],
88
+ test: [
89
+ [[[0, 0], [1, 1]], [[1, 1], [0, 0]]],
90
+ ],
91
+ },
92
+ },
93
+ });
94
+
95
+ // Verify a solution
96
+ const outcome = await core.env.verify(env.envId, [[1, 1], [0, 0]]);
97
+ console.log(`Success: ${outcome.success}, Score: ${outcome.partialScore}`);
98
+
99
+ // Stop the subprocess
100
+ await core.stop();
101
+ ```
102
+
103
+ ## API
104
+
105
+ ### CognitiveCore
106
+
107
+ Main client class.
108
+
109
+ ```typescript
110
+ const core = new CognitiveCore(options?: CognitiveCoreOptions);
111
+ ```
112
+
113
+ **Options:**
114
+ - `pythonPath`: Path to Python executable (default: `"python"`)
115
+ - `cwd`: Working directory for Python process
116
+ - `env`: Environment variables for Python process
117
+ - `timeout`: Command timeout in milliseconds (default: `30000`)
118
+
119
+ **Methods:**
120
+ - `start()`: Start the Python subprocess
121
+ - `stop()`: Stop the Python subprocess
122
+ - `version()`: Get Python package version
123
+ - `isRunning`: Check if client is running
124
+
125
+ ### Environment API (`core.env`)
126
+
127
+ - `create(domain)`: Create a new environment
128
+ - `reset(envId, task)`: Reset environment with a task
129
+ - `step(envId, action)`: Execute an action
130
+ - `verify(envId, solution)`: Verify a solution
131
+
132
+ ### Memory API (`core.memory`)
133
+
134
+ - `searchExperiences(query, k)`: Search for similar experiences
135
+ - `searchStrategies(query, k)`: Search for relevant strategies
136
+ - `searchConcepts(query, k)`: Search for code concepts
137
+ - `store(trajectory)`: Store a trajectory
138
+
139
+ ### Search API (`core.search`)
140
+
141
+ - `solve(task)`: Solve a task using configured search strategy
142
+
143
+ ## Low-Level Client
144
+
145
+ For advanced usage, access the raw subprocess client:
146
+
147
+ ```typescript
148
+ import { CognitiveCoreClient } from "cognitive-core";
149
+
150
+ const client = new CognitiveCoreClient();
151
+ await client.start();
152
+
153
+ // Execute arbitrary commands
154
+ const result = await client.execute("custom.command", { arg: "value" });
155
+
156
+ await client.stop();
157
+ ```
158
+
159
+ ## Types
160
+
161
+ Full TypeScript types are included for all data structures:
162
+
163
+ ```typescript
164
+ import type {
165
+ Task,
166
+ Trajectory,
167
+ Outcome,
168
+ Experience,
169
+ Strategy,
170
+ CodeConcept,
171
+ Grid,
172
+ ARCTask,
173
+ } from "cognitive-core";
174
+ ```
175
+
176
+ ## License
177
+
178
+ MIT
@@ -0,0 +1,466 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * TypeScript type definitions for Cognitive Core.
5
+ *
6
+ * These types mirror the Python dataclasses in cognitive_core.core.types
7
+ */
8
+ /**
9
+ * Verification specification for tasks
10
+ */
11
+ interface VerificationSpec {
12
+ method: string;
13
+ expectedOutput?: unknown;
14
+ testCommand?: string;
15
+ timeout?: number;
16
+ }
17
+ /**
18
+ * Domain-agnostic task representation
19
+ */
20
+ interface Task {
21
+ id: string;
22
+ domain: string;
23
+ description: string;
24
+ context: Record<string, unknown>;
25
+ verification: VerificationSpec;
26
+ }
27
+ /**
28
+ * Single step in a trajectory
29
+ */
30
+ interface Step {
31
+ thought?: string;
32
+ action: string;
33
+ observation: string;
34
+ metadata?: Record<string, unknown>;
35
+ }
36
+ /**
37
+ * Result of a trajectory
38
+ */
39
+ interface Outcome {
40
+ success: boolean;
41
+ partialScore?: number;
42
+ errorInfo?: string;
43
+ verificationDetails?: Record<string, unknown>;
44
+ }
45
+ /**
46
+ * Complete trajectory for a task attempt
47
+ */
48
+ interface Trajectory {
49
+ task: Task;
50
+ steps: Step[];
51
+ outcome: Outcome;
52
+ agentId: string;
53
+ timestamp: string;
54
+ llmCalls?: number;
55
+ totalTokens?: number;
56
+ wallTimeSeconds?: number;
57
+ }
58
+ /**
59
+ * Reusable code pattern
60
+ */
61
+ interface CodeConcept {
62
+ id: string;
63
+ name: string;
64
+ description: string;
65
+ code: string;
66
+ signature: string;
67
+ examples: Array<[string, string]>;
68
+ usageCount?: number;
69
+ successRate?: number;
70
+ }
71
+ /**
72
+ * Stored experience for retrieval
73
+ */
74
+ interface Experience {
75
+ id: string;
76
+ taskInput: string;
77
+ solutionOutput: string;
78
+ feedback: string;
79
+ success: boolean;
80
+ trajectoryId: string;
81
+ timestamp: string;
82
+ }
83
+ /**
84
+ * Abstract reasoning pattern
85
+ */
86
+ interface Strategy {
87
+ id: string;
88
+ situation: string;
89
+ suggestion: string;
90
+ parameters: Array<Record<string, string>>;
91
+ usageCount?: number;
92
+ successRate?: number;
93
+ }
94
+ /**
95
+ * A candidate solution
96
+ */
97
+ interface Candidate {
98
+ solution: unknown;
99
+ confidence: number;
100
+ reasoning: string;
101
+ source: "generated" | "adapted" | "retrieved";
102
+ fitness?: number;
103
+ parentIds?: string[];
104
+ trajectory?: Trajectory;
105
+ }
106
+ /**
107
+ * Output of task router
108
+ */
109
+ interface RoutingDecision {
110
+ strategy: "direct" | "evolutionary" | "mcts" | "adapt";
111
+ relevantConcepts: CodeConcept[];
112
+ similarExperiences: Experience[];
113
+ suggestedStrategies: Strategy[];
114
+ estimatedDifficulty: number;
115
+ searchBudget: number;
116
+ }
117
+ /**
118
+ * Step result from environment
119
+ */
120
+ interface StepResult {
121
+ observation: string;
122
+ reward: number;
123
+ done: boolean;
124
+ info: Record<string, unknown>;
125
+ }
126
+ /**
127
+ * ARC grid type (2D array of integers 0-9)
128
+ */
129
+ type Grid = number[][];
130
+ /**
131
+ * ARC task structure
132
+ */
133
+ interface ARCTask {
134
+ id: string;
135
+ train: Array<[Grid, Grid]>;
136
+ test: Array<[Grid, Grid]>;
137
+ }
138
+ /**
139
+ * Command request to Python subprocess
140
+ */
141
+ interface CommandRequest {
142
+ command: string;
143
+ args?: Record<string, unknown>;
144
+ }
145
+ /**
146
+ * Response from Python subprocess
147
+ */
148
+ interface CommandResponse<T = unknown> {
149
+ success: boolean;
150
+ result?: T;
151
+ error?: string;
152
+ }
153
+ /**
154
+ * Options for CognitiveCore client
155
+ */
156
+ interface CognitiveCoreOptions {
157
+ /**
158
+ * Path to Python executable (default: "python")
159
+ */
160
+ pythonPath?: string;
161
+ /**
162
+ * Working directory for Python process
163
+ */
164
+ cwd?: string;
165
+ /**
166
+ * Environment variables for Python process
167
+ */
168
+ env?: Record<string, string>;
169
+ /**
170
+ * Timeout for commands in milliseconds (default: 30000)
171
+ */
172
+ timeout?: number;
173
+ }
174
+
175
+ /**
176
+ * Python subprocess client for Cognitive Core.
177
+ *
178
+ * Manages communication with the Python cognitive-core package via JSON
179
+ * over stdin/stdout.
180
+ */
181
+
182
+ /**
183
+ * Client that communicates with the Python cognitive-core package.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * const client = new CognitiveCoreClient();
188
+ * await client.start();
189
+ *
190
+ * const result = await client.execute("version");
191
+ * console.log(result); // { version: "0.1.0" }
192
+ *
193
+ * await client.stop();
194
+ * ```
195
+ */
196
+ declare class CognitiveCoreClient extends EventEmitter {
197
+ private process;
198
+ private buffer;
199
+ private pendingRequests;
200
+ private requestId;
201
+ private options;
202
+ constructor(options?: CognitiveCoreOptions);
203
+ /**
204
+ * Start the Python subprocess.
205
+ */
206
+ start(): Promise<void>;
207
+ /**
208
+ * Stop the Python subprocess.
209
+ */
210
+ stop(): Promise<void>;
211
+ /**
212
+ * Execute a command on the Python process.
213
+ *
214
+ * @param command - Command to execute (e.g., "memory.search", "env.reset")
215
+ * @param args - Command arguments
216
+ * @returns Command result
217
+ */
218
+ execute<T = unknown>(command: string, args?: Record<string, unknown>): Promise<T>;
219
+ /**
220
+ * Check if the client is running.
221
+ */
222
+ get isRunning(): boolean;
223
+ private sendRequest;
224
+ private handleData;
225
+ private handleResponse;
226
+ private cleanup;
227
+ }
228
+
229
+ /**
230
+ * Setup utilities for managing Python virtual environment and dependencies.
231
+ */
232
+ interface SetupOptions {
233
+ /**
234
+ * Directory where the virtual environment will be created.
235
+ * Defaults to ".cognitive-core" in current working directory.
236
+ */
237
+ venvDir?: string;
238
+ /**
239
+ * Python executable to use for creating the venv.
240
+ * Defaults to "python3" on Unix, "python" on Windows.
241
+ */
242
+ pythonPath?: string;
243
+ /**
244
+ * Version of cognitive-core to install.
245
+ * Defaults to latest.
246
+ */
247
+ version?: string;
248
+ /**
249
+ * Extra pip packages to install.
250
+ */
251
+ extras?: string[];
252
+ /**
253
+ * Whether to show installation progress.
254
+ * Defaults to true.
255
+ */
256
+ verbose?: boolean;
257
+ }
258
+ interface SetupResult {
259
+ /**
260
+ * Path to the virtual environment directory.
261
+ */
262
+ venvPath: string;
263
+ /**
264
+ * Path to the Python executable in the venv.
265
+ */
266
+ pythonPath: string;
267
+ /**
268
+ * Path to pip in the venv.
269
+ */
270
+ pipPath: string;
271
+ /**
272
+ * Whether the venv was newly created (vs already existed).
273
+ */
274
+ created: boolean;
275
+ /**
276
+ * Installed version of cognitive-core.
277
+ */
278
+ version: string;
279
+ }
280
+ /**
281
+ * Setup the Python environment for cognitive-core.
282
+ *
283
+ * Creates a virtual environment and installs the cognitive-core package.
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * import { setup } from "cognitive-core";
288
+ *
289
+ * // Basic setup
290
+ * const result = await setup();
291
+ * console.log(`Installed cognitive-core ${result.version}`);
292
+ *
293
+ * // Custom options
294
+ * const result = await setup({
295
+ * venvDir: "./my-venv",
296
+ * extras: ["arc", "embeddings"],
297
+ * verbose: true,
298
+ * });
299
+ * ```
300
+ */
301
+ declare function setup(options?: SetupOptions): Promise<SetupResult>;
302
+ /**
303
+ * Check if cognitive-core is set up in the given directory.
304
+ */
305
+ declare function isSetUp(venvDir?: string): boolean;
306
+ /**
307
+ * Get the Python path for an existing setup.
308
+ * Returns null if not set up.
309
+ */
310
+ declare function getPythonPath(venvDir?: string): string | null;
311
+
312
+ /**
313
+ * Cognitive Core - TypeScript client for the meta-learning framework.
314
+ *
315
+ * This package provides a TypeScript API for interacting with the Python
316
+ * cognitive-core package via subprocess communication.
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * import { CognitiveCore } from "cognitive-core";
321
+ *
322
+ * const core = new CognitiveCore();
323
+ * await core.start();
324
+ *
325
+ * // Create an environment
326
+ * const env = await core.env.create("arc");
327
+ *
328
+ * // Reset with a task
329
+ * const observation = await core.env.reset(env.envId, {
330
+ * id: "task-1",
331
+ * domain: "arc",
332
+ * description: "Solve this puzzle",
333
+ * context: { grids: { train: [...], test: [...] } },
334
+ * });
335
+ *
336
+ * // Verify a solution
337
+ * const outcome = await core.env.verify(env.envId, solution);
338
+ *
339
+ * await core.stop();
340
+ * ```
341
+ *
342
+ * @packageDocumentation
343
+ */
344
+
345
+ /**
346
+ * Environment operations
347
+ */
348
+ declare class EnvironmentAPI {
349
+ private client;
350
+ constructor(client: CognitiveCoreClient);
351
+ /**
352
+ * Create a new environment.
353
+ */
354
+ create(domain?: string): Promise<{
355
+ envId: string;
356
+ domain: string;
357
+ }>;
358
+ /**
359
+ * Reset an environment with a task.
360
+ */
361
+ reset(envId: string, task: Partial<Task>): Promise<{
362
+ envId: string;
363
+ observation: string;
364
+ }>;
365
+ /**
366
+ * Execute an action in the environment.
367
+ */
368
+ step(envId: string, action: string): Promise<StepResult>;
369
+ /**
370
+ * Verify a solution.
371
+ */
372
+ verify(envId: string, solution: unknown): Promise<Outcome>;
373
+ }
374
+ /**
375
+ * Memory operations
376
+ */
377
+ declare class MemoryAPI {
378
+ private client;
379
+ constructor(client: CognitiveCoreClient);
380
+ /**
381
+ * Search for similar experiences.
382
+ */
383
+ searchExperiences(query: string, k?: number): Promise<Experience[]>;
384
+ /**
385
+ * Search for relevant strategies.
386
+ */
387
+ searchStrategies(query: string, k?: number): Promise<Strategy[]>;
388
+ /**
389
+ * Search for relevant concepts.
390
+ */
391
+ searchConcepts(query: string, k?: number): Promise<CodeConcept[]>;
392
+ /**
393
+ * Store a trajectory in memory.
394
+ */
395
+ store(trajectory: unknown): Promise<{
396
+ id: string;
397
+ }>;
398
+ }
399
+ /**
400
+ * Search operations
401
+ */
402
+ declare class SearchAPI {
403
+ private client;
404
+ constructor(client: CognitiveCoreClient);
405
+ /**
406
+ * Solve a task using the configured search strategy.
407
+ */
408
+ solve(task: Partial<Task>): Promise<{
409
+ trajectory: unknown;
410
+ outcome: Outcome;
411
+ }>;
412
+ }
413
+ /**
414
+ * Main Cognitive Core client with high-level API.
415
+ *
416
+ * @example
417
+ * ```typescript
418
+ * // Quick start (uses system Python or auto-detects venv)
419
+ * const core = new CognitiveCore();
420
+ * await core.start();
421
+ *
422
+ * // With explicit setup first
423
+ * import { setup, CognitiveCore } from "cognitive-core";
424
+ * const { pythonPath } = await setup();
425
+ * const core = new CognitiveCore({ pythonPath });
426
+ * await core.start();
427
+ * ```
428
+ */
429
+ declare class CognitiveCore {
430
+ private client;
431
+ /**
432
+ * Environment operations (create, reset, step, verify)
433
+ */
434
+ readonly env: EnvironmentAPI;
435
+ /**
436
+ * Memory operations (search, store)
437
+ */
438
+ readonly memory: MemoryAPI;
439
+ /**
440
+ * Search operations (solve)
441
+ */
442
+ readonly search: SearchAPI;
443
+ constructor(options?: CognitiveCoreOptions);
444
+ /**
445
+ * Start the Python subprocess.
446
+ */
447
+ start(): Promise<void>;
448
+ /**
449
+ * Stop the Python subprocess.
450
+ */
451
+ stop(): Promise<void>;
452
+ /**
453
+ * Get the version of the Python cognitive-core package.
454
+ */
455
+ version(): Promise<string>;
456
+ /**
457
+ * Check if the client is running.
458
+ */
459
+ get isRunning(): boolean;
460
+ /**
461
+ * Access the underlying client for advanced usage.
462
+ */
463
+ get rawClient(): CognitiveCoreClient;
464
+ }
465
+
466
+ export { type ARCTask, type Candidate, type CodeConcept, CognitiveCore, CognitiveCoreClient, type CognitiveCoreOptions, type CommandRequest, type CommandResponse, type Experience, type Grid, type Outcome, type RoutingDecision, type SetupOptions, type SetupResult, type Step, type StepResult, type Strategy, type Task, type Trajectory, type VerificationSpec, CognitiveCore as default, getPythonPath, isSetUp, setup };