confused-ai-core 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 (114) hide show
  1. package/FEATURES.md +169 -0
  2. package/package.json +119 -0
  3. package/src/agent.ts +187 -0
  4. package/src/agentic/index.ts +87 -0
  5. package/src/agentic/runner.ts +386 -0
  6. package/src/agentic/types.ts +91 -0
  7. package/src/artifacts/artifact.ts +417 -0
  8. package/src/artifacts/index.ts +42 -0
  9. package/src/artifacts/media.ts +304 -0
  10. package/src/cli/index.ts +122 -0
  11. package/src/core/base-agent.ts +151 -0
  12. package/src/core/context-builder.ts +106 -0
  13. package/src/core/index.ts +8 -0
  14. package/src/core/schemas.ts +17 -0
  15. package/src/core/types.ts +158 -0
  16. package/src/create-agent.ts +309 -0
  17. package/src/debug-logger.ts +188 -0
  18. package/src/dx/agent.ts +88 -0
  19. package/src/dx/define-agent.ts +183 -0
  20. package/src/dx/dev-logger.ts +57 -0
  21. package/src/dx/index.ts +11 -0
  22. package/src/errors.ts +175 -0
  23. package/src/execution/engine.ts +522 -0
  24. package/src/execution/graph-builder.ts +362 -0
  25. package/src/execution/index.ts +8 -0
  26. package/src/execution/types.ts +257 -0
  27. package/src/execution/worker-pool.ts +308 -0
  28. package/src/extensions/index.ts +123 -0
  29. package/src/guardrails/allowlist.ts +155 -0
  30. package/src/guardrails/index.ts +17 -0
  31. package/src/guardrails/types.ts +159 -0
  32. package/src/guardrails/validator.ts +265 -0
  33. package/src/index.ts +74 -0
  34. package/src/knowledge/index.ts +5 -0
  35. package/src/knowledge/types.ts +52 -0
  36. package/src/learning/in-memory-store.ts +72 -0
  37. package/src/learning/index.ts +6 -0
  38. package/src/learning/types.ts +42 -0
  39. package/src/llm/cache.ts +300 -0
  40. package/src/llm/index.ts +22 -0
  41. package/src/llm/model-resolver.ts +81 -0
  42. package/src/llm/openai-provider.ts +313 -0
  43. package/src/llm/openrouter-provider.ts +29 -0
  44. package/src/llm/types.ts +131 -0
  45. package/src/memory/in-memory-store.ts +255 -0
  46. package/src/memory/index.ts +7 -0
  47. package/src/memory/types.ts +193 -0
  48. package/src/memory/vector-store.ts +251 -0
  49. package/src/observability/console-logger.ts +123 -0
  50. package/src/observability/index.ts +12 -0
  51. package/src/observability/metrics.ts +85 -0
  52. package/src/observability/otlp-exporter.ts +417 -0
  53. package/src/observability/tracer.ts +105 -0
  54. package/src/observability/types.ts +341 -0
  55. package/src/orchestration/agent-adapter.ts +33 -0
  56. package/src/orchestration/index.ts +34 -0
  57. package/src/orchestration/load-balancer.ts +151 -0
  58. package/src/orchestration/mcp-types.ts +59 -0
  59. package/src/orchestration/message-bus.ts +192 -0
  60. package/src/orchestration/orchestrator.ts +349 -0
  61. package/src/orchestration/pipeline.ts +66 -0
  62. package/src/orchestration/supervisor.ts +107 -0
  63. package/src/orchestration/swarm.ts +1099 -0
  64. package/src/orchestration/toolkit.ts +47 -0
  65. package/src/orchestration/types.ts +339 -0
  66. package/src/planner/classical-planner.ts +383 -0
  67. package/src/planner/index.ts +8 -0
  68. package/src/planner/llm-planner.ts +353 -0
  69. package/src/planner/types.ts +227 -0
  70. package/src/planner/validator.ts +297 -0
  71. package/src/production/circuit-breaker.ts +290 -0
  72. package/src/production/graceful-shutdown.ts +251 -0
  73. package/src/production/health.ts +333 -0
  74. package/src/production/index.ts +57 -0
  75. package/src/production/latency-eval.ts +62 -0
  76. package/src/production/rate-limiter.ts +287 -0
  77. package/src/production/resumable-stream.ts +289 -0
  78. package/src/production/types.ts +81 -0
  79. package/src/sdk/index.ts +374 -0
  80. package/src/session/db-driver.ts +50 -0
  81. package/src/session/in-memory-store.ts +235 -0
  82. package/src/session/index.ts +12 -0
  83. package/src/session/sql-store.ts +315 -0
  84. package/src/session/sqlite-store.ts +61 -0
  85. package/src/session/types.ts +153 -0
  86. package/src/tools/base-tool.ts +223 -0
  87. package/src/tools/browser-tool.ts +123 -0
  88. package/src/tools/calculator-tool.ts +265 -0
  89. package/src/tools/file-tools.ts +394 -0
  90. package/src/tools/github-tool.ts +432 -0
  91. package/src/tools/hackernews-tool.ts +187 -0
  92. package/src/tools/http-tool.ts +118 -0
  93. package/src/tools/index.ts +99 -0
  94. package/src/tools/jira-tool.ts +373 -0
  95. package/src/tools/notion-tool.ts +322 -0
  96. package/src/tools/openai-tool.ts +236 -0
  97. package/src/tools/registry.ts +131 -0
  98. package/src/tools/serpapi-tool.ts +234 -0
  99. package/src/tools/shell-tool.ts +118 -0
  100. package/src/tools/slack-tool.ts +327 -0
  101. package/src/tools/telegram-tool.ts +127 -0
  102. package/src/tools/types.ts +229 -0
  103. package/src/tools/websearch-tool.ts +335 -0
  104. package/src/tools/wikipedia-tool.ts +177 -0
  105. package/src/tools/yfinance-tool.ts +33 -0
  106. package/src/voice/index.ts +17 -0
  107. package/src/voice/voice-provider.ts +228 -0
  108. package/tests/artifact.test.ts +241 -0
  109. package/tests/circuit-breaker.test.ts +171 -0
  110. package/tests/health.test.ts +192 -0
  111. package/tests/llm-cache.test.ts +186 -0
  112. package/tests/rate-limiter.test.ts +161 -0
  113. package/tsconfig.json +29 -0
  114. package/vitest.config.ts +47 -0
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Classical planner implementation using task decomposition
3
+ */
4
+
5
+ import {
6
+ Planner,
7
+ Plan,
8
+ PlanContext,
9
+ PlanFeedback,
10
+ ValidationResult,
11
+ Task,
12
+ TaskPriority,
13
+ ClassicalPlannerConfig,
14
+ PlanningAlgorithm,
15
+ } from './types.js';
16
+ import type { EntityId } from '../core/types.js';
17
+
18
+ /**
19
+ * Classical planner using rule-based task decomposition
20
+ */
21
+ export class ClassicalPlanner implements Planner {
22
+ private plannerConfig: Required<ClassicalPlannerConfig>;
23
+ private taskPatterns: Map<string, TaskPattern> = new Map();
24
+
25
+ constructor(config: ClassicalPlannerConfig) {
26
+ this.plannerConfig = {
27
+ maxIterations: config.maxIterations ?? 10,
28
+ timeoutMs: config.timeoutMs ?? 30000,
29
+ allowParallelExecution: config.allowParallelExecution ?? true,
30
+ retryPolicy: config.retryPolicy ?? {
31
+ maxRetries: 3,
32
+ backoffMs: 1000,
33
+ maxBackoffMs: 30000,
34
+ exponentialBase: 2,
35
+ },
36
+ algorithm: config.algorithm ?? PlanningAlgorithm.HIERARCHICAL,
37
+ heuristic: config.heuristic ?? 'default',
38
+ };
39
+
40
+ this.registerDefaultPatterns();
41
+ }
42
+
43
+ /**
44
+ * Get planner configuration
45
+ */
46
+ getConfig(): Required<ClassicalPlannerConfig> {
47
+ return this.plannerConfig;
48
+ }
49
+
50
+ async plan(goal: string, context?: PlanContext): Promise<Plan> {
51
+ const planId = this.generateId();
52
+ const tasks: Task[] = [];
53
+
54
+ // Analyze goal and match against patterns
55
+ const matchedPattern = this.findMatchingPattern(goal, context);
56
+
57
+ if (matchedPattern) {
58
+ // Use pattern to generate tasks
59
+ const patternTasks = matchedPattern.generateTasks(goal, context);
60
+ tasks.push(...patternTasks);
61
+ } else {
62
+ // Fallback: create a single task for the goal
63
+ tasks.push(this.createSimpleTask(goal));
64
+ }
65
+
66
+ // Build dependency graph
67
+ this.buildDependencies(tasks);
68
+
69
+ // Estimate durations
70
+ this.estimateDurations(tasks);
71
+
72
+ const plan: Plan = {
73
+ id: planId,
74
+ goal,
75
+ tasks,
76
+ createdAt: new Date(),
77
+ metadata: {
78
+ plannerType: 'classical',
79
+ estimatedTotalDurationMs: this.calculateTotalDuration(tasks),
80
+ confidence: matchedPattern ? 0.8 : 0.5,
81
+ context: context?.metadata,
82
+ },
83
+ };
84
+
85
+ return plan;
86
+ }
87
+
88
+ async refine(plan: Plan, feedback: PlanFeedback): Promise<Plan> {
89
+ const refinedTasks: Task[] = [];
90
+
91
+ for (const task of plan.tasks) {
92
+ if (task.id === feedback.failedTaskId) {
93
+ // Add retry or alternative task
94
+ refinedTasks.push({
95
+ ...task,
96
+ metadata: {
97
+ ...task.metadata,
98
+ maxRetries: (task.metadata.maxRetries ?? 0) + 1,
99
+ },
100
+ });
101
+
102
+ // Add alternative task if suggested
103
+ if (feedback.suggestions && feedback.suggestions.length > 0) {
104
+ refinedTasks.push(
105
+ this.createAlternativeTask(task, feedback.suggestions[0])
106
+ );
107
+ }
108
+ } else {
109
+ refinedTasks.push(task);
110
+ }
111
+ }
112
+
113
+ // Rebuild dependencies
114
+ this.buildDependencies(refinedTasks);
115
+
116
+ return {
117
+ ...plan,
118
+ tasks: refinedTasks,
119
+ metadata: {
120
+ ...plan.metadata,
121
+ confidence: (plan.metadata.confidence ?? 0.5) * 0.9, // Reduce confidence on refinement
122
+ },
123
+ };
124
+ }
125
+
126
+ validate(plan: Plan): ValidationResult {
127
+ const errors: ValidationResult['errors'] = [];
128
+
129
+ // Check for circular dependencies
130
+ const visited = new Set<EntityId>();
131
+ const recursionStack = new Set<EntityId>();
132
+
133
+ const hasCycle = (taskId: EntityId, taskMap: Map<EntityId, Task>): boolean => {
134
+ visited.add(taskId);
135
+ recursionStack.add(taskId);
136
+
137
+ const task = taskMap.get(taskId);
138
+ if (task) {
139
+ for (const depId of task.dependencies) {
140
+ if (!visited.has(depId)) {
141
+ if (hasCycle(depId, taskMap)) {
142
+ return true;
143
+ }
144
+ } else if (recursionStack.has(depId)) {
145
+ return true;
146
+ }
147
+ }
148
+ }
149
+
150
+ recursionStack.delete(taskId);
151
+ return false;
152
+ };
153
+
154
+ const taskMap = new Map(plan.tasks.map(t => [t.id, t]));
155
+
156
+ for (const task of plan.tasks) {
157
+ if (!visited.has(task.id)) {
158
+ if (hasCycle(task.id, taskMap)) {
159
+ errors.push({
160
+ taskId: task.id,
161
+ message: 'Circular dependency detected',
162
+ severity: 'error',
163
+ });
164
+ }
165
+ }
166
+
167
+ // Check for missing dependencies
168
+ for (const depId of task.dependencies) {
169
+ if (!taskMap.has(depId)) {
170
+ errors.push({
171
+ taskId: task.id,
172
+ message: `Missing dependency: ${depId}`,
173
+ severity: 'error',
174
+ });
175
+ }
176
+ }
177
+ }
178
+
179
+ return {
180
+ valid: errors.length === 0,
181
+ errors,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Register a task pattern
187
+ */
188
+ registerPattern(pattern: TaskPattern): void {
189
+ this.taskPatterns.set(pattern.name, pattern);
190
+ }
191
+
192
+ /**
193
+ * Find a matching pattern for the goal
194
+ */
195
+ private findMatchingPattern(goal: string, context?: PlanContext): TaskPattern | undefined {
196
+ for (const pattern of this.taskPatterns.values()) {
197
+ if (pattern.matches(goal, context)) {
198
+ return pattern;
199
+ }
200
+ }
201
+ return undefined;
202
+ }
203
+
204
+ /**
205
+ * Create a simple task for a goal
206
+ */
207
+ private createSimpleTask(goal: string): Task {
208
+ return {
209
+ id: this.generateId(),
210
+ name: 'Execute Goal',
211
+ description: goal,
212
+ dependencies: [],
213
+ priority: TaskPriority.MEDIUM,
214
+ metadata: {},
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Create an alternative task based on feedback
220
+ */
221
+ private createAlternativeTask(originalTask: Task, suggestion: string): Task {
222
+ return {
223
+ id: this.generateId(),
224
+ name: `${originalTask.name} (Alternative)`,
225
+ description: suggestion,
226
+ dependencies: originalTask.dependencies,
227
+ priority: originalTask.priority,
228
+ metadata: {
229
+ ...originalTask.metadata,
230
+ custom: {
231
+ ...originalTask.metadata.custom,
232
+ isAlternative: true,
233
+ originalTaskId: originalTask.id,
234
+ },
235
+ },
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Build task dependencies based on patterns and context
241
+ */
242
+ private buildDependencies(tasks: Task[]): void {
243
+ // Simple sequential dependency for now
244
+ // In a real implementation, this would analyze task relationships
245
+ for (let i = 1; i < tasks.length; i++) {
246
+ const task = tasks[i];
247
+ if (task.dependencies.length === 0) {
248
+ // Add dependency on previous task
249
+ Object.assign(task, {
250
+ dependencies: [tasks[i - 1].id],
251
+ });
252
+ }
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Estimate task durations
258
+ */
259
+ private estimateDurations(tasks: Task[]): void {
260
+ for (const task of tasks) {
261
+ if (!task.estimatedDurationMs) {
262
+ // Simple heuristic based on description length
263
+ const baseDuration = 5000;
264
+ const complexityFactor = Math.min(task.description.length / 100, 5);
265
+ Object.assign(task, {
266
+ estimatedDurationMs: baseDuration * complexityFactor,
267
+ });
268
+ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Calculate total plan duration
274
+ */
275
+ private calculateTotalDuration(tasks: Task[]): number {
276
+ return tasks.reduce((sum, task) => sum + (task.estimatedDurationMs ?? 5000), 0);
277
+ }
278
+
279
+ /**
280
+ * Generate a unique ID
281
+ */
282
+ private generateId(): EntityId {
283
+ return `task-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
284
+ }
285
+
286
+ /**
287
+ * Register default task patterns
288
+ */
289
+ private registerDefaultPatterns(): void {
290
+ // Research pattern
291
+ this.registerPattern({
292
+ name: 'research',
293
+ matches: (goal) => /research|investigate|find|search/i.test(goal),
294
+ generateTasks: (goal, context) => [
295
+ {
296
+ id: this.generateId(),
297
+ name: 'Gather Information',
298
+ description: `Search for information about: ${goal}`,
299
+ dependencies: [],
300
+ priority: TaskPriority.HIGH,
301
+ metadata: {
302
+ toolIds: context?.availableTools?.filter(t =>
303
+ t.includes('search') || t.includes('web')
304
+ ),
305
+ },
306
+ },
307
+ {
308
+ id: this.generateId(),
309
+ name: 'Analyze Findings',
310
+ description: 'Analyze and synthesize gathered information',
311
+ dependencies: [], // Will be set by buildDependencies
312
+ priority: TaskPriority.HIGH,
313
+ metadata: {},
314
+ },
315
+ {
316
+ id: this.generateId(),
317
+ name: 'Generate Report',
318
+ description: 'Create a comprehensive report from the analysis',
319
+ dependencies: [],
320
+ priority: TaskPriority.MEDIUM,
321
+ metadata: {
322
+ outputKey: 'report',
323
+ },
324
+ },
325
+ ],
326
+ });
327
+
328
+ // Data processing pattern
329
+ this.registerPattern({
330
+ name: 'data-processing',
331
+ matches: (goal) => /process|analyze|transform|convert/i.test(goal),
332
+ generateTasks: (goal, context) => [
333
+ {
334
+ id: this.generateId(),
335
+ name: 'Fetch Data',
336
+ description: `Retrieve data for: ${goal}`,
337
+ dependencies: [],
338
+ priority: TaskPriority.HIGH,
339
+ metadata: {
340
+ toolIds: context?.availableTools?.filter(t =>
341
+ t.includes('db') || t.includes('api') || t.includes('file')
342
+ ),
343
+ },
344
+ },
345
+ {
346
+ id: this.generateId(),
347
+ name: 'Validate Data',
348
+ description: 'Validate data integrity and format',
349
+ dependencies: [],
350
+ priority: TaskPriority.HIGH,
351
+ metadata: {},
352
+ },
353
+ {
354
+ id: this.generateId(),
355
+ name: 'Process Data',
356
+ description: 'Apply transformations and processing logic',
357
+ dependencies: [],
358
+ priority: TaskPriority.HIGH,
359
+ metadata: {},
360
+ },
361
+ {
362
+ id: this.generateId(),
363
+ name: 'Store Results',
364
+ description: 'Save processed results',
365
+ dependencies: [],
366
+ priority: TaskPriority.MEDIUM,
367
+ metadata: {
368
+ outputKey: 'results',
369
+ },
370
+ },
371
+ ],
372
+ });
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Task pattern interface for rule-based planning
378
+ */
379
+ interface TaskPattern {
380
+ name: string;
381
+ matches(goal: string, context?: PlanContext): boolean;
382
+ generateTasks(goal: string, context?: PlanContext): Task[];
383
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Planner module exports
3
+ */
4
+
5
+ export * from './types.js';
6
+ export { LLMPlanner } from './llm-planner.js';
7
+ export { ClassicalPlanner } from './classical-planner.js';
8
+ export { PlanValidator } from './validator.js';