@soleri/core 0.0.1 → 2.0.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 (74) hide show
  1. package/dist/brain/brain.d.ts +85 -0
  2. package/dist/brain/brain.d.ts.map +1 -0
  3. package/dist/brain/brain.js +506 -0
  4. package/dist/brain/brain.js.map +1 -0
  5. package/dist/cognee/client.d.ts +35 -0
  6. package/dist/cognee/client.d.ts.map +1 -0
  7. package/dist/cognee/client.js +289 -0
  8. package/dist/cognee/client.js.map +1 -0
  9. package/dist/cognee/types.d.ts +46 -0
  10. package/dist/cognee/types.d.ts.map +1 -0
  11. package/dist/cognee/types.js +3 -0
  12. package/dist/cognee/types.js.map +1 -0
  13. package/dist/facades/facade-factory.d.ts +5 -0
  14. package/dist/facades/facade-factory.d.ts.map +1 -0
  15. package/dist/facades/facade-factory.js +49 -0
  16. package/dist/facades/facade-factory.js.map +1 -0
  17. package/dist/facades/types.d.ts +42 -0
  18. package/dist/facades/types.d.ts.map +1 -0
  19. package/dist/facades/types.js +6 -0
  20. package/dist/facades/types.js.map +1 -0
  21. package/dist/index.d.ts +19 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +19 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/intelligence/loader.d.ts +3 -0
  26. package/dist/intelligence/loader.d.ts.map +1 -0
  27. package/dist/intelligence/loader.js +41 -0
  28. package/dist/intelligence/loader.js.map +1 -0
  29. package/dist/intelligence/types.d.ts +20 -0
  30. package/dist/intelligence/types.d.ts.map +1 -0
  31. package/dist/intelligence/types.js +2 -0
  32. package/dist/intelligence/types.js.map +1 -0
  33. package/dist/llm/key-pool.d.ts +38 -0
  34. package/dist/llm/key-pool.d.ts.map +1 -0
  35. package/dist/llm/key-pool.js +154 -0
  36. package/dist/llm/key-pool.js.map +1 -0
  37. package/dist/llm/types.d.ts +80 -0
  38. package/dist/llm/types.d.ts.map +1 -0
  39. package/dist/llm/types.js +37 -0
  40. package/dist/llm/types.js.map +1 -0
  41. package/dist/llm/utils.d.ts +26 -0
  42. package/dist/llm/utils.d.ts.map +1 -0
  43. package/dist/llm/utils.js +197 -0
  44. package/dist/llm/utils.js.map +1 -0
  45. package/dist/planning/planner.d.ts +48 -0
  46. package/dist/planning/planner.d.ts.map +1 -0
  47. package/dist/planning/planner.js +109 -0
  48. package/dist/planning/planner.js.map +1 -0
  49. package/dist/vault/vault.d.ts +80 -0
  50. package/dist/vault/vault.d.ts.map +1 -0
  51. package/dist/vault/vault.js +353 -0
  52. package/dist/vault/vault.js.map +1 -0
  53. package/package.json +56 -4
  54. package/src/__tests__/brain.test.ts +740 -0
  55. package/src/__tests__/cognee-client.test.ts +524 -0
  56. package/src/__tests__/llm.test.ts +556 -0
  57. package/src/__tests__/loader.test.ts +176 -0
  58. package/src/__tests__/planner.test.ts +261 -0
  59. package/src/__tests__/vault.test.ts +494 -0
  60. package/src/brain/brain.ts +678 -0
  61. package/src/cognee/client.ts +350 -0
  62. package/src/cognee/types.ts +62 -0
  63. package/src/facades/facade-factory.ts +64 -0
  64. package/src/facades/types.ts +42 -0
  65. package/src/index.ts +75 -0
  66. package/src/intelligence/loader.ts +42 -0
  67. package/src/intelligence/types.ts +20 -0
  68. package/src/llm/key-pool.ts +190 -0
  69. package/src/llm/types.ts +116 -0
  70. package/src/llm/utils.ts +248 -0
  71. package/src/planning/planner.ts +151 -0
  72. package/src/vault/vault.ts +455 -0
  73. package/tsconfig.json +22 -0
  74. package/vitest.config.ts +15 -0
@@ -0,0 +1,190 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { SecretString } from './types.js';
5
+ import type { KeyPoolConfig, KeyStatus } from './types.js';
6
+ import { CircuitBreaker } from './utils.js';
7
+
8
+ // =============================================================================
9
+ // CONSTANTS
10
+ // =============================================================================
11
+
12
+ const DEFAULT_PREEMPTIVE_THRESHOLD = 50;
13
+
14
+ // =============================================================================
15
+ // KEY POOL
16
+ // =============================================================================
17
+
18
+ export class KeyPool {
19
+ private keys: SecretString[];
20
+ private activeIndex: number = 0;
21
+ private keyBreakers: Map<number, CircuitBreaker> = new Map();
22
+ private remainingQuota: Map<number, number> = new Map();
23
+ private readonly preemptiveThreshold: number;
24
+
25
+ constructor(config: KeyPoolConfig) {
26
+ this.keys = config.keys.filter((k) => k.length > 0).map((k) => new SecretString(k));
27
+ this.preemptiveThreshold = config.preemptiveThreshold ?? DEFAULT_PREEMPTIVE_THRESHOLD;
28
+
29
+ for (let i = 0; i < this.keys.length; i++) {
30
+ this.keyBreakers.set(
31
+ i,
32
+ new CircuitBreaker({
33
+ name: `key-pool-${i}`,
34
+ failureThreshold: 3,
35
+ resetTimeoutMs: 30_000,
36
+ }),
37
+ );
38
+ }
39
+
40
+ if (this.keys.length > 1) {
41
+ console.error(`[LLM] KeyPool initialized with ${this.keys.length} keys`);
42
+ }
43
+ }
44
+
45
+ get hasKeys(): boolean {
46
+ return this.keys.length > 0;
47
+ }
48
+
49
+ getActiveKey(): SecretString {
50
+ if (this.keys.length === 0) {
51
+ throw new Error('KeyPool has no keys — cannot get active key');
52
+ }
53
+ return this.keys[this.activeIndex];
54
+ }
55
+
56
+ get activeKeyIndex(): number {
57
+ return this.activeIndex;
58
+ }
59
+
60
+ get poolSize(): number {
61
+ return this.keys.length;
62
+ }
63
+
64
+ get exhausted(): boolean {
65
+ if (this.keys.length === 0) return true;
66
+ for (let i = 0; i < this.keys.length; i++) {
67
+ const breaker = this.keyBreakers.get(i)!;
68
+ if (!breaker.isOpen()) return false;
69
+ }
70
+ return true;
71
+ }
72
+
73
+ rotateOnError(): SecretString | null {
74
+ const breaker = this.keyBreakers.get(this.activeIndex);
75
+ if (breaker) {
76
+ breaker.recordFailure();
77
+ }
78
+ return this.findNextHealthyKey();
79
+ }
80
+
81
+ rotatePreemptive(): boolean {
82
+ const previousIndex = this.activeIndex;
83
+ const remaining = this.remainingQuota.get(previousIndex);
84
+ if (remaining !== undefined && remaining < this.preemptiveThreshold) {
85
+ const next = this.findNextHealthyKey();
86
+ if (next) {
87
+ console.error(
88
+ `[LLM] KeyPool preemptive rotation: key ${previousIndex} remaining=${remaining} < threshold=${this.preemptiveThreshold}`,
89
+ );
90
+ return true;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+
96
+ updateQuota(keyIndex: number, remaining: number): void {
97
+ this.remainingQuota.set(keyIndex, remaining);
98
+ }
99
+
100
+ getStatus(): {
101
+ poolSize: number;
102
+ activeKeyIndex: number;
103
+ exhausted: boolean;
104
+ perKeyStatus: KeyStatus[];
105
+ } {
106
+ const perKeyStatus: KeyStatus[] = [];
107
+ for (let i = 0; i < this.keys.length; i++) {
108
+ perKeyStatus.push({
109
+ index: i,
110
+ circuitState: this.keyBreakers.get(i)!.getState(),
111
+ remainingQuota: this.remainingQuota.get(i) ?? null,
112
+ });
113
+ }
114
+ return {
115
+ poolSize: this.poolSize,
116
+ activeKeyIndex: this.activeIndex,
117
+ exhausted: this.exhausted,
118
+ perKeyStatus,
119
+ };
120
+ }
121
+
122
+ private findNextHealthyKey(): SecretString | null {
123
+ const startIndex = this.activeIndex;
124
+ for (let offset = 1; offset <= this.keys.length; offset++) {
125
+ const candidateIndex = (startIndex + offset) % this.keys.length;
126
+ const breaker = this.keyBreakers.get(candidateIndex)!;
127
+ if (!breaker.isOpen()) {
128
+ this.activeIndex = candidateIndex;
129
+ return this.keys[candidateIndex];
130
+ }
131
+ }
132
+ console.error('[LLM] KeyPool: all keys exhausted — no healthy key available');
133
+ return null;
134
+ }
135
+ }
136
+
137
+ // =============================================================================
138
+ // KEY LOADING
139
+ // =============================================================================
140
+
141
+ export interface KeyPoolFiles {
142
+ openai: KeyPoolConfig;
143
+ anthropic: KeyPoolConfig;
144
+ }
145
+
146
+ /**
147
+ * Load key pool configuration for an agent.
148
+ * Key loading priority:
149
+ * 1. ~/.{agentId}/keys.json
150
+ * 2. Fallback: OPENAI_API_KEY / ANTHROPIC_API_KEY env vars
151
+ * 3. Empty pool
152
+ */
153
+ export function loadKeyPoolConfig(agentId: string): KeyPoolFiles {
154
+ if (!agentId || /[/\\]/.test(agentId) || agentId.includes('..')) {
155
+ throw new Error(`Invalid agentId: ${agentId}`);
156
+ }
157
+ const keysFilePath = path.join(homedir(), `.${agentId}`, 'keys.json');
158
+
159
+ let openaiKeys: string[] = [];
160
+ let anthropicKeys: string[] = [];
161
+
162
+ try {
163
+ if (fs.existsSync(keysFilePath)) {
164
+ const data = JSON.parse(fs.readFileSync(keysFilePath, 'utf-8'));
165
+ if (data?.openai && Array.isArray(data.openai)) {
166
+ openaiKeys = data.openai;
167
+ }
168
+ if (data?.anthropic && Array.isArray(data.anthropic)) {
169
+ anthropicKeys = data.anthropic;
170
+ }
171
+ }
172
+ } catch {
173
+ console.error('[LLM] Could not read keys.json, falling back to env vars');
174
+ }
175
+
176
+ // Fallback: environment variables
177
+ if (openaiKeys.length === 0) {
178
+ const envKey = process.env.OPENAI_API_KEY || '';
179
+ if (envKey) openaiKeys = [envKey];
180
+ }
181
+ if (anthropicKeys.length === 0) {
182
+ const envKey = process.env.ANTHROPIC_API_KEY || '';
183
+ if (envKey) anthropicKeys = [envKey];
184
+ }
185
+
186
+ return {
187
+ openai: { keys: openaiKeys },
188
+ anthropic: { keys: anthropicKeys },
189
+ };
190
+ }
@@ -0,0 +1,116 @@
1
+ const REDACTED = '[REDACTED]';
2
+
3
+ export class SecretString {
4
+ #value: string;
5
+
6
+ constructor(value: string) {
7
+ this.#value = value;
8
+ }
9
+
10
+ expose(): string {
11
+ return this.#value;
12
+ }
13
+
14
+ get isSet(): boolean {
15
+ return this.#value.length > 0;
16
+ }
17
+
18
+ toString(): string {
19
+ return REDACTED;
20
+ }
21
+ toJSON(): string {
22
+ return REDACTED;
23
+ }
24
+ [Symbol.toPrimitive](): string {
25
+ return REDACTED;
26
+ }
27
+ [Symbol.for('nodejs.util.inspect.custom')](): string {
28
+ return REDACTED;
29
+ }
30
+ }
31
+
32
+ export class LLMError extends Error {
33
+ retryable: boolean;
34
+ statusCode?: number;
35
+
36
+ constructor(message: string, options?: { retryable?: boolean; statusCode?: number }) {
37
+ super(message);
38
+ this.name = 'LLMError';
39
+ this.retryable = options?.retryable ?? false;
40
+ this.statusCode = options?.statusCode;
41
+ Object.setPrototypeOf(this, LLMError.prototype);
42
+ }
43
+ }
44
+
45
+ export interface LLMCallOptions {
46
+ provider: 'openai' | 'anthropic';
47
+ model: string;
48
+ systemPrompt: string;
49
+ userPrompt: string;
50
+ temperature?: number;
51
+ maxTokens?: number;
52
+ caller: string;
53
+ task?: string;
54
+ }
55
+
56
+ export interface LLMCallResult {
57
+ text: string;
58
+ model: string;
59
+ provider: 'openai' | 'anthropic';
60
+ inputTokens?: number;
61
+ outputTokens?: number;
62
+ durationMs: number;
63
+ }
64
+
65
+ export type CircuitState = 'closed' | 'open' | 'half-open';
66
+
67
+ export interface CircuitBreakerConfig {
68
+ failureThreshold: number;
69
+ resetTimeoutMs: number;
70
+ name: string;
71
+ }
72
+
73
+ export interface CircuitBreakerSnapshot {
74
+ state: CircuitState;
75
+ failureCount: number;
76
+ lastFailureAt: number | null;
77
+ }
78
+
79
+ export interface KeyPoolConfig {
80
+ keys: string[];
81
+ preemptiveThreshold?: number;
82
+ }
83
+
84
+ export interface KeyStatus {
85
+ index: number;
86
+ circuitState: CircuitBreakerSnapshot;
87
+ remainingQuota: number | null;
88
+ }
89
+
90
+ export interface RouteEntry {
91
+ caller: string;
92
+ task?: string;
93
+ model: string;
94
+ provider: 'openai' | 'anthropic';
95
+ }
96
+
97
+ export interface RoutingConfig {
98
+ routes: RouteEntry[];
99
+ defaultOpenAIModel: string;
100
+ defaultAnthropicModel: string;
101
+ }
102
+
103
+ export interface RateLimitInfo {
104
+ remaining: number | null;
105
+ resetMs: number | null;
106
+ retryAfterMs: number | null;
107
+ }
108
+
109
+ export interface RetryConfig {
110
+ maxAttempts: number;
111
+ baseDelayMs: number;
112
+ maxDelayMs: number;
113
+ jitter: number;
114
+ shouldRetry?: (error: unknown) => boolean;
115
+ onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
116
+ }
@@ -0,0 +1,248 @@
1
+ import type {
2
+ CircuitBreakerConfig,
3
+ CircuitBreakerSnapshot,
4
+ CircuitState,
5
+ LLMError,
6
+ RateLimitInfo,
7
+ RetryConfig,
8
+ } from './types.js';
9
+
10
+ // =============================================================================
11
+ // HELPERS
12
+ // =============================================================================
13
+
14
+ function isRetryable(error: unknown): boolean {
15
+ if (error && typeof error === 'object' && 'retryable' in error) {
16
+ return (error as { retryable: boolean }).retryable === true;
17
+ }
18
+ return false;
19
+ }
20
+
21
+ function sleep(ms: number): Promise<void> {
22
+ return new Promise((resolve) => setTimeout(resolve, ms));
23
+ }
24
+
25
+ // =============================================================================
26
+ // CIRCUIT BREAKER
27
+ // =============================================================================
28
+
29
+ const DEFAULT_CB_CONFIG: CircuitBreakerConfig = {
30
+ failureThreshold: 5,
31
+ resetTimeoutMs: 60_000,
32
+ name: 'default',
33
+ };
34
+
35
+ export class CircuitOpenError extends Error {
36
+ retryable = false;
37
+ constructor(name: string) {
38
+ super(`${name} circuit breaker is open — calls are being rejected`);
39
+ this.name = 'CircuitOpenError';
40
+ Object.setPrototypeOf(this, CircuitOpenError.prototype);
41
+ }
42
+ }
43
+
44
+ export class CircuitBreaker {
45
+ private state: CircuitState = 'closed';
46
+ private failureCount = 0;
47
+ private lastFailureAt: number | null = null;
48
+ private readonly config: CircuitBreakerConfig;
49
+
50
+ constructor(config?: Partial<CircuitBreakerConfig>) {
51
+ this.config = { ...DEFAULT_CB_CONFIG, ...config };
52
+ }
53
+
54
+ async call<T>(fn: () => Promise<T>): Promise<T> {
55
+ if (this.state === 'open') {
56
+ if (this.shouldProbe()) {
57
+ this.transitionTo('half-open');
58
+ } else {
59
+ throw new CircuitOpenError(this.config.name);
60
+ }
61
+ }
62
+
63
+ try {
64
+ const result = await fn();
65
+ this.onSuccess();
66
+ return result;
67
+ } catch (error) {
68
+ this.onFailure(error);
69
+ throw error;
70
+ }
71
+ }
72
+
73
+ getState(): CircuitBreakerSnapshot {
74
+ if (this.state === 'open' && this.shouldProbe()) {
75
+ this.transitionTo('half-open');
76
+ }
77
+ return {
78
+ state: this.state,
79
+ failureCount: this.failureCount,
80
+ lastFailureAt: this.lastFailureAt,
81
+ };
82
+ }
83
+
84
+ isOpen(): boolean {
85
+ return this.state === 'open' && !this.shouldProbe();
86
+ }
87
+
88
+ reset(): void {
89
+ this.transitionTo('closed');
90
+ this.failureCount = 0;
91
+ this.lastFailureAt = null;
92
+ }
93
+
94
+ /** Synchronously record a failure (used by KeyPool to trip breaker without async) */
95
+ recordFailure(): void {
96
+ this.failureCount++;
97
+ this.lastFailureAt = Date.now();
98
+ if (this.state === 'half-open') {
99
+ this.transitionTo('open');
100
+ return;
101
+ }
102
+ if (this.failureCount >= this.config.failureThreshold) {
103
+ console.error(
104
+ `[LLM] CircuitBreaker:${this.config.name} threshold reached (${this.failureCount}/${this.config.failureThreshold}) — opening`,
105
+ );
106
+ this.transitionTo('open');
107
+ }
108
+ }
109
+
110
+ private onSuccess(): void {
111
+ this.failureCount = 0;
112
+ this.transitionTo('closed');
113
+ }
114
+
115
+ private onFailure(error: unknown): void {
116
+ if (!isRetryable(error)) {
117
+ return;
118
+ }
119
+
120
+ this.failureCount++;
121
+ this.lastFailureAt = Date.now();
122
+
123
+ if (this.state === 'half-open') {
124
+ this.transitionTo('open');
125
+ return;
126
+ }
127
+
128
+ if (this.failureCount >= this.config.failureThreshold) {
129
+ console.error(
130
+ `[LLM] CircuitBreaker:${this.config.name} threshold reached (${this.failureCount}/${this.config.failureThreshold}) — opening`,
131
+ );
132
+ this.transitionTo('open');
133
+ }
134
+ }
135
+
136
+ private shouldProbe(): boolean {
137
+ if (this.lastFailureAt === null) return false;
138
+ return Date.now() - this.lastFailureAt >= this.config.resetTimeoutMs;
139
+ }
140
+
141
+ private transitionTo(newState: CircuitState): void {
142
+ if (this.state !== newState) {
143
+ this.state = newState;
144
+ }
145
+ }
146
+ }
147
+
148
+ // =============================================================================
149
+ // RETRY
150
+ // =============================================================================
151
+
152
+ const DEFAULT_RETRY_CONFIG: RetryConfig = {
153
+ maxAttempts: 3,
154
+ baseDelayMs: 1000,
155
+ maxDelayMs: 30000,
156
+ jitter: 0.1,
157
+ };
158
+
159
+ export function computeDelay(error: unknown, attempt: number, config: RetryConfig): number {
160
+ const retryAfterMs = (error as Partial<LLMError> & { retryAfterMs?: number })?.retryAfterMs;
161
+ if (retryAfterMs !== undefined && retryAfterMs > 0) {
162
+ return Math.min(retryAfterMs, config.maxDelayMs);
163
+ }
164
+
165
+ const exponential = config.baseDelayMs * Math.pow(2, attempt);
166
+ const capped = Math.min(exponential, config.maxDelayMs);
167
+
168
+ const jitterRange = capped * config.jitter;
169
+ const jitterOffset = (Math.random() * 2 - 1) * jitterRange;
170
+
171
+ return Math.max(0, Math.round(capped + jitterOffset));
172
+ }
173
+
174
+ export async function retry<T>(fn: () => Promise<T>, config?: Partial<RetryConfig>): Promise<T> {
175
+ const resolved: RetryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
176
+ if (resolved.maxAttempts < 1) {
177
+ throw new Error(`retry maxAttempts must be >= 1, got ${resolved.maxAttempts}`);
178
+ }
179
+ const shouldRetry = resolved.shouldRetry ?? isRetryable;
180
+
181
+ let lastError: unknown;
182
+
183
+ for (let attempt = 0; attempt < resolved.maxAttempts; attempt++) {
184
+ try {
185
+ return await fn();
186
+ } catch (error) {
187
+ lastError = error;
188
+
189
+ if (attempt >= resolved.maxAttempts - 1 || !shouldRetry(error)) {
190
+ throw error;
191
+ }
192
+
193
+ const delay = computeDelay(error, attempt, resolved);
194
+ resolved.onRetry?.(error, attempt + 1, delay);
195
+
196
+ await sleep(delay);
197
+ }
198
+ }
199
+
200
+ throw lastError;
201
+ }
202
+
203
+ // =============================================================================
204
+ // RATE LIMIT HEADER PARSER
205
+ // =============================================================================
206
+
207
+ export function parseRateLimitHeaders(headers: Headers): RateLimitInfo {
208
+ const remaining = headers.get('x-ratelimit-remaining-requests');
209
+ const reset = headers.get('x-ratelimit-reset-requests');
210
+ const retryAfter = headers.get('retry-after');
211
+
212
+ return {
213
+ remaining:
214
+ remaining !== null ? (isNaN(parseInt(remaining, 10)) ? null : parseInt(remaining, 10)) : null,
215
+ resetMs: reset !== null ? parseResetDuration(reset) : null,
216
+ retryAfterMs: retryAfter !== null ? parseRetryAfter(retryAfter) : null,
217
+ };
218
+ }
219
+
220
+ function parseResetDuration(value: string): number | null {
221
+ let totalMs = 0;
222
+ let matched = false;
223
+
224
+ const minMatch = value.match(/(\d+)m(?!\s*s)/);
225
+ if (minMatch) {
226
+ totalMs += parseInt(minMatch[1], 10) * 60_000;
227
+ matched = true;
228
+ }
229
+
230
+ const msMatch = value.match(/(\d+)ms/);
231
+ if (msMatch) {
232
+ totalMs += parseInt(msMatch[1], 10);
233
+ matched = true;
234
+ }
235
+
236
+ const secMatch = value.match(/(\d+)(?<!m)s/);
237
+ if (secMatch) {
238
+ totalMs += parseInt(secMatch[1], 10) * 1000;
239
+ matched = true;
240
+ }
241
+
242
+ return matched ? totalMs : null;
243
+ }
244
+
245
+ function parseRetryAfter(value: string): number | null {
246
+ const seconds = parseFloat(value);
247
+ return isNaN(seconds) ? null : Math.ceil(seconds * 1000);
248
+ }
@@ -0,0 +1,151 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+
4
+ export type PlanStatus = 'draft' | 'approved' | 'executing' | 'completed';
5
+ export type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'skipped' | 'failed';
6
+
7
+ export interface PlanTask {
8
+ id: string;
9
+ title: string;
10
+ description: string;
11
+ status: TaskStatus;
12
+ updatedAt: number;
13
+ }
14
+
15
+ export interface Plan {
16
+ id: string;
17
+ objective: string;
18
+ scope: string;
19
+ status: PlanStatus;
20
+ decisions: string[];
21
+ tasks: PlanTask[];
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ }
25
+
26
+ export interface PlanStore {
27
+ version: string;
28
+ plans: Plan[];
29
+ }
30
+
31
+ export class Planner {
32
+ private filePath: string;
33
+ private store: PlanStore;
34
+
35
+ constructor(filePath: string) {
36
+ this.filePath = filePath;
37
+ this.store = this.load();
38
+ }
39
+
40
+ private load(): PlanStore {
41
+ if (!existsSync(this.filePath)) {
42
+ return { version: '1.0', plans: [] };
43
+ }
44
+ try {
45
+ const data = readFileSync(this.filePath, 'utf-8');
46
+ return JSON.parse(data) as PlanStore;
47
+ } catch {
48
+ return { version: '1.0', plans: [] };
49
+ }
50
+ }
51
+
52
+ private save(): void {
53
+ mkdirSync(dirname(this.filePath), { recursive: true });
54
+ writeFileSync(this.filePath, JSON.stringify(this.store, null, 2), 'utf-8');
55
+ }
56
+
57
+ create(params: {
58
+ objective: string;
59
+ scope: string;
60
+ decisions?: string[];
61
+ tasks?: Array<{ title: string; description: string }>;
62
+ }): Plan {
63
+ const now = Date.now();
64
+ const plan: Plan = {
65
+ id: `plan-${now}-${Math.random().toString(36).slice(2, 8)}`,
66
+ objective: params.objective,
67
+ scope: params.scope,
68
+ status: 'draft',
69
+ decisions: params.decisions ?? [],
70
+ tasks: (params.tasks ?? []).map((t, i) => ({
71
+ id: `task-${i + 1}`,
72
+ title: t.title,
73
+ description: t.description,
74
+ status: 'pending' as TaskStatus,
75
+ updatedAt: now,
76
+ })),
77
+ createdAt: now,
78
+ updatedAt: now,
79
+ };
80
+ this.store.plans.push(plan);
81
+ this.save();
82
+ return plan;
83
+ }
84
+
85
+ get(planId: string): Plan | null {
86
+ return this.store.plans.find((p) => p.id === planId) ?? null;
87
+ }
88
+
89
+ list(): Plan[] {
90
+ return [...this.store.plans];
91
+ }
92
+
93
+ approve(planId: string): Plan {
94
+ const plan = this.get(planId);
95
+ if (!plan) throw new Error(`Plan not found: ${planId}`);
96
+ if (plan.status !== 'draft')
97
+ throw new Error(`Cannot approve plan in '${plan.status}' status — must be 'draft'`);
98
+ plan.status = 'approved';
99
+ plan.updatedAt = Date.now();
100
+ this.save();
101
+ return plan;
102
+ }
103
+
104
+ startExecution(planId: string): Plan {
105
+ const plan = this.get(planId);
106
+ if (!plan) throw new Error(`Plan not found: ${planId}`);
107
+ if (plan.status !== 'approved')
108
+ throw new Error(`Cannot execute plan in '${plan.status}' status — must be 'approved'`);
109
+ plan.status = 'executing';
110
+ plan.updatedAt = Date.now();
111
+ this.save();
112
+ return plan;
113
+ }
114
+
115
+ updateTask(planId: string, taskId: string, status: TaskStatus): Plan {
116
+ const plan = this.get(planId);
117
+ if (!plan) throw new Error(`Plan not found: ${planId}`);
118
+ if (plan.status !== 'executing')
119
+ throw new Error(
120
+ `Cannot update tasks on plan in '${plan.status}' status — must be 'executing'`,
121
+ );
122
+ const task = plan.tasks.find((t) => t.id === taskId);
123
+ if (!task) throw new Error(`Task not found: ${taskId}`);
124
+ task.status = status;
125
+ task.updatedAt = Date.now();
126
+ plan.updatedAt = Date.now();
127
+ this.save();
128
+ return plan;
129
+ }
130
+
131
+ complete(planId: string): Plan {
132
+ const plan = this.get(planId);
133
+ if (!plan) throw new Error(`Plan not found: ${planId}`);
134
+ if (plan.status !== 'executing')
135
+ throw new Error(`Cannot complete plan in '${plan.status}' status — must be 'executing'`);
136
+ plan.status = 'completed';
137
+ plan.updatedAt = Date.now();
138
+ this.save();
139
+ return plan;
140
+ }
141
+
142
+ getExecuting(): Plan[] {
143
+ return this.store.plans.filter((p) => p.status === 'executing');
144
+ }
145
+
146
+ getActive(): Plan[] {
147
+ return this.store.plans.filter(
148
+ (p) => p.status === 'draft' || p.status === 'approved' || p.status === 'executing',
149
+ );
150
+ }
151
+ }