@sparkleideas/mcp 3.0.0-alpha.10

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 (279) hide show
  1. package/.claude/agents/analysis/analyze-code-quality.md +179 -0
  2. package/.claude/agents/analysis/code-analyzer.md +210 -0
  3. package/.claude/agents/analysis/code-review/analyze-code-quality.md +179 -0
  4. package/.claude/agents/architecture/arch-system-design.md +157 -0
  5. package/.claude/agents/architecture/system-design/arch-system-design.md +155 -0
  6. package/.claude/agents/consensus/byzantine-coordinator.md +63 -0
  7. package/.claude/agents/consensus/crdt-synchronizer.md +997 -0
  8. package/.claude/agents/consensus/gossip-coordinator.md +63 -0
  9. package/.claude/agents/consensus/performance-benchmarker.md +851 -0
  10. package/.claude/agents/consensus/quorum-manager.md +823 -0
  11. package/.claude/agents/consensus/raft-manager.md +63 -0
  12. package/.claude/agents/consensus/security-manager.md +622 -0
  13. package/.claude/agents/core/coder.md +453 -0
  14. package/.claude/agents/core/planner.md +375 -0
  15. package/.claude/agents/core/researcher.md +369 -0
  16. package/.claude/agents/core/reviewer.md +520 -0
  17. package/.claude/agents/core/tester.md +512 -0
  18. package/.claude/agents/custom/test-long-runner.md +44 -0
  19. package/.claude/agents/data/data-ml-model.md +445 -0
  20. package/.claude/agents/data/ml/data-ml-model.md +193 -0
  21. package/.claude/agents/development/backend/dev-backend-api.md +142 -0
  22. package/.claude/agents/development/dev-backend-api.md +345 -0
  23. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +164 -0
  24. package/.claude/agents/devops/ops-cicd-github.md +165 -0
  25. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +174 -0
  26. package/.claude/agents/documentation/docs-api-openapi.md +355 -0
  27. package/.claude/agents/flow-nexus/app-store.md +88 -0
  28. package/.claude/agents/flow-nexus/authentication.md +69 -0
  29. package/.claude/agents/flow-nexus/challenges.md +81 -0
  30. package/.claude/agents/flow-nexus/neural-network.md +88 -0
  31. package/.claude/agents/flow-nexus/payments.md +83 -0
  32. package/.claude/agents/flow-nexus/sandbox.md +76 -0
  33. package/.claude/agents/flow-nexus/swarm.md +76 -0
  34. package/.claude/agents/flow-nexus/user-tools.md +96 -0
  35. package/.claude/agents/flow-nexus/workflow.md +84 -0
  36. package/.claude/agents/github/code-review-swarm.md +377 -0
  37. package/.claude/agents/github/github-modes.md +173 -0
  38. package/.claude/agents/github/issue-tracker.md +576 -0
  39. package/.claude/agents/github/multi-repo-swarm.md +553 -0
  40. package/.claude/agents/github/pr-manager.md +438 -0
  41. package/.claude/agents/github/project-board-sync.md +509 -0
  42. package/.claude/agents/github/release-manager.md +605 -0
  43. package/.claude/agents/github/release-swarm.md +583 -0
  44. package/.claude/agents/github/repo-architect.md +398 -0
  45. package/.claude/agents/github/swarm-issue.md +573 -0
  46. package/.claude/agents/github/swarm-pr.md +428 -0
  47. package/.claude/agents/github/sync-coordinator.md +452 -0
  48. package/.claude/agents/github/workflow-automation.md +903 -0
  49. package/.claude/agents/goal/agent.md +816 -0
  50. package/.claude/agents/goal/goal-planner.md +73 -0
  51. package/.claude/agents/optimization/benchmark-suite.md +665 -0
  52. package/.claude/agents/optimization/load-balancer.md +431 -0
  53. package/.claude/agents/optimization/performance-monitor.md +672 -0
  54. package/.claude/agents/optimization/resource-allocator.md +674 -0
  55. package/.claude/agents/optimization/topology-optimizer.md +808 -0
  56. package/.claude/agents/payments/agentic-payments.md +126 -0
  57. package/.claude/agents/sona/sona-learning-optimizer.md +74 -0
  58. package/.claude/agents/sparc/architecture.md +699 -0
  59. package/.claude/agents/sparc/pseudocode.md +520 -0
  60. package/.claude/agents/sparc/refinement.md +802 -0
  61. package/.claude/agents/sparc/specification.md +478 -0
  62. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +225 -0
  63. package/.claude/agents/specialized/spec-mobile-react-native.md +227 -0
  64. package/.claude/agents/sublinear/consensus-coordinator.md +338 -0
  65. package/.claude/agents/sublinear/matrix-optimizer.md +185 -0
  66. package/.claude/agents/sublinear/pagerank-analyzer.md +299 -0
  67. package/.claude/agents/sublinear/performance-optimizer.md +368 -0
  68. package/.claude/agents/sublinear/trading-predictor.md +246 -0
  69. package/.claude/agents/swarm/adaptive-coordinator.md +1127 -0
  70. package/.claude/agents/swarm/hierarchical-coordinator.md +710 -0
  71. package/.claude/agents/swarm/mesh-coordinator.md +963 -0
  72. package/.claude/agents/templates/automation-smart-agent.md +205 -0
  73. package/.claude/agents/templates/base-template-generator.md +268 -0
  74. package/.claude/agents/templates/coordinator-swarm-init.md +90 -0
  75. package/.claude/agents/templates/github-pr-manager.md +177 -0
  76. package/.claude/agents/templates/implementer-sparc-coder.md +259 -0
  77. package/.claude/agents/templates/memory-coordinator.md +187 -0
  78. package/.claude/agents/templates/orchestrator-task.md +139 -0
  79. package/.claude/agents/templates/performance-analyzer.md +199 -0
  80. package/.claude/agents/templates/sparc-coordinator.md +514 -0
  81. package/.claude/agents/testing/production-validator.md +395 -0
  82. package/.claude/agents/testing/tdd-london-swarm.md +244 -0
  83. package/.claude/agents/v3/adr-architect.md +184 -0
  84. package/.claude/agents/v3/aidefence-guardian.md +282 -0
  85. package/.claude/agents/v3/claims-authorizer.md +208 -0
  86. package/.claude/agents/v3/collective-intelligence-coordinator.md +993 -0
  87. package/.claude/agents/v3/ddd-domain-expert.md +220 -0
  88. package/.claude/agents/v3/injection-analyst.md +236 -0
  89. package/.claude/agents/v3/memory-specialist.md +995 -0
  90. package/.claude/agents/v3/performance-engineer.md +1233 -0
  91. package/.claude/agents/v3/pii-detector.md +151 -0
  92. package/.claude/agents/v3/reasoningbank-learner.md +213 -0
  93. package/.claude/agents/v3/security-architect-aidefence.md +410 -0
  94. package/.claude/agents/v3/security-architect.md +867 -0
  95. package/.claude/agents/v3/security-auditor.md +771 -0
  96. package/.claude/agents/v3/sparc-orchestrator.md +182 -0
  97. package/.claude/agents/v3/swarm-memory-manager.md +157 -0
  98. package/.claude/agents/v3/v3-integration-architect.md +205 -0
  99. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +54 -0
  100. package/.claude/commands/analysis/README.md +9 -0
  101. package/.claude/commands/analysis/bottleneck-detect.md +162 -0
  102. package/.claude/commands/analysis/performance-bottlenecks.md +59 -0
  103. package/.claude/commands/analysis/performance-report.md +25 -0
  104. package/.claude/commands/analysis/token-efficiency.md +45 -0
  105. package/.claude/commands/analysis/token-usage.md +25 -0
  106. package/.claude/commands/automation/README.md +9 -0
  107. package/.claude/commands/automation/auto-agent.md +122 -0
  108. package/.claude/commands/automation/self-healing.md +106 -0
  109. package/.claude/commands/automation/session-memory.md +90 -0
  110. package/.claude/commands/automation/smart-agents.md +73 -0
  111. package/.claude/commands/automation/smart-spawn.md +25 -0
  112. package/.claude/commands/automation/workflow-select.md +25 -0
  113. package/.claude/commands/claude-flow-help.md +103 -0
  114. package/.claude/commands/claude-flow-memory.md +107 -0
  115. package/.claude/commands/claude-flow-swarm.md +205 -0
  116. package/.claude/commands/github/README.md +11 -0
  117. package/.claude/commands/github/code-review-swarm.md +514 -0
  118. package/.claude/commands/github/code-review.md +25 -0
  119. package/.claude/commands/github/github-modes.md +147 -0
  120. package/.claude/commands/github/github-swarm.md +121 -0
  121. package/.claude/commands/github/issue-tracker.md +292 -0
  122. package/.claude/commands/github/issue-triage.md +25 -0
  123. package/.claude/commands/github/multi-repo-swarm.md +519 -0
  124. package/.claude/commands/github/pr-enhance.md +26 -0
  125. package/.claude/commands/github/pr-manager.md +170 -0
  126. package/.claude/commands/github/project-board-sync.md +471 -0
  127. package/.claude/commands/github/release-manager.md +338 -0
  128. package/.claude/commands/github/release-swarm.md +544 -0
  129. package/.claude/commands/github/repo-analyze.md +25 -0
  130. package/.claude/commands/github/repo-architect.md +367 -0
  131. package/.claude/commands/github/swarm-issue.md +482 -0
  132. package/.claude/commands/github/swarm-pr.md +285 -0
  133. package/.claude/commands/github/sync-coordinator.md +301 -0
  134. package/.claude/commands/github/workflow-automation.md +442 -0
  135. package/.claude/commands/hooks/README.md +11 -0
  136. package/.claude/commands/hooks/overview.md +58 -0
  137. package/.claude/commands/hooks/post-edit.md +117 -0
  138. package/.claude/commands/hooks/post-task.md +112 -0
  139. package/.claude/commands/hooks/pre-edit.md +113 -0
  140. package/.claude/commands/hooks/pre-task.md +111 -0
  141. package/.claude/commands/hooks/session-end.md +118 -0
  142. package/.claude/commands/hooks/setup.md +103 -0
  143. package/.claude/commands/monitoring/README.md +9 -0
  144. package/.claude/commands/monitoring/agent-metrics.md +25 -0
  145. package/.claude/commands/monitoring/agents.md +44 -0
  146. package/.claude/commands/monitoring/real-time-view.md +25 -0
  147. package/.claude/commands/monitoring/status.md +46 -0
  148. package/.claude/commands/monitoring/swarm-monitor.md +25 -0
  149. package/.claude/commands/optimization/README.md +9 -0
  150. package/.claude/commands/optimization/auto-topology.md +62 -0
  151. package/.claude/commands/optimization/cache-manage.md +25 -0
  152. package/.claude/commands/optimization/parallel-execute.md +25 -0
  153. package/.claude/commands/optimization/parallel-execution.md +50 -0
  154. package/.claude/commands/optimization/topology-optimize.md +25 -0
  155. package/.claude/commands/sparc/analyzer.md +52 -0
  156. package/.claude/commands/sparc/architect.md +53 -0
  157. package/.claude/commands/sparc/ask.md +97 -0
  158. package/.claude/commands/sparc/batch-executor.md +54 -0
  159. package/.claude/commands/sparc/code.md +89 -0
  160. package/.claude/commands/sparc/coder.md +54 -0
  161. package/.claude/commands/sparc/debug.md +83 -0
  162. package/.claude/commands/sparc/debugger.md +54 -0
  163. package/.claude/commands/sparc/designer.md +53 -0
  164. package/.claude/commands/sparc/devops.md +109 -0
  165. package/.claude/commands/sparc/docs-writer.md +80 -0
  166. package/.claude/commands/sparc/documenter.md +54 -0
  167. package/.claude/commands/sparc/innovator.md +54 -0
  168. package/.claude/commands/sparc/integration.md +83 -0
  169. package/.claude/commands/sparc/mcp.md +117 -0
  170. package/.claude/commands/sparc/memory-manager.md +54 -0
  171. package/.claude/commands/sparc/optimizer.md +54 -0
  172. package/.claude/commands/sparc/orchestrator.md +132 -0
  173. package/.claude/commands/sparc/post-deployment-monitoring-mode.md +83 -0
  174. package/.claude/commands/sparc/refinement-optimization-mode.md +83 -0
  175. package/.claude/commands/sparc/researcher.md +54 -0
  176. package/.claude/commands/sparc/reviewer.md +54 -0
  177. package/.claude/commands/sparc/security-review.md +80 -0
  178. package/.claude/commands/sparc/sparc-modes.md +174 -0
  179. package/.claude/commands/sparc/sparc.md +111 -0
  180. package/.claude/commands/sparc/spec-pseudocode.md +80 -0
  181. package/.claude/commands/sparc/supabase-admin.md +348 -0
  182. package/.claude/commands/sparc/swarm-coordinator.md +54 -0
  183. package/.claude/commands/sparc/tdd.md +54 -0
  184. package/.claude/commands/sparc/tester.md +54 -0
  185. package/.claude/commands/sparc/tutorial.md +79 -0
  186. package/.claude/commands/sparc/workflow-manager.md +54 -0
  187. package/.claude/helpers/README.md +97 -0
  188. package/.claude/helpers/adr-compliance.sh +186 -0
  189. package/.claude/helpers/auto-commit.sh +178 -0
  190. package/.claude/helpers/checkpoint-manager.sh +251 -0
  191. package/.claude/helpers/daemon-manager.sh +252 -0
  192. package/.claude/helpers/ddd-tracker.sh +144 -0
  193. package/.claude/helpers/github-safe.js +106 -0
  194. package/.claude/helpers/github-setup.sh +28 -0
  195. package/.claude/helpers/guidance-hook.sh +13 -0
  196. package/.claude/helpers/guidance-hooks.sh +102 -0
  197. package/.claude/helpers/health-monitor.sh +108 -0
  198. package/.claude/helpers/learning-hooks.sh +329 -0
  199. package/.claude/helpers/learning-optimizer.sh +127 -0
  200. package/.claude/helpers/learning-service.mjs +1144 -0
  201. package/.claude/helpers/memory.js +83 -0
  202. package/.claude/helpers/metrics-db.mjs +488 -0
  203. package/.claude/helpers/pattern-consolidator.sh +86 -0
  204. package/.claude/helpers/perf-worker.sh +160 -0
  205. package/.claude/helpers/post-commit +16 -0
  206. package/.claude/helpers/pre-commit +26 -0
  207. package/.claude/helpers/quick-start.sh +19 -0
  208. package/.claude/helpers/router.js +66 -0
  209. package/.claude/helpers/security-scanner.sh +127 -0
  210. package/.claude/helpers/session.js +127 -0
  211. package/.claude/helpers/setup-mcp.sh +18 -0
  212. package/.claude/helpers/standard-checkpoint-hooks.sh +189 -0
  213. package/.claude/helpers/statusline-hook.sh +21 -0
  214. package/.claude/helpers/statusline.cjs +509 -0
  215. package/.claude/helpers/statusline.js +316 -0
  216. package/.claude/helpers/swarm-comms.sh +353 -0
  217. package/.claude/helpers/swarm-hooks.sh +761 -0
  218. package/.claude/helpers/swarm-monitor.sh +211 -0
  219. package/.claude/helpers/sync-v3-metrics.sh +245 -0
  220. package/.claude/helpers/update-v3-progress.sh +166 -0
  221. package/.claude/helpers/v3-quick-status.sh +58 -0
  222. package/.claude/helpers/v3.sh +111 -0
  223. package/.claude/helpers/validate-v3-config.sh +216 -0
  224. package/.claude/helpers/worker-manager.sh +170 -0
  225. package/.claude/settings.json +237 -0
  226. package/.claude/skills/agentdb-advanced/SKILL.md +550 -0
  227. package/.claude/skills/agentdb-learning/SKILL.md +545 -0
  228. package/.claude/skills/agentdb-memory-patterns/SKILL.md +339 -0
  229. package/.claude/skills/agentdb-optimization/SKILL.md +509 -0
  230. package/.claude/skills/agentdb-vector-search/SKILL.md +339 -0
  231. package/.claude/skills/github-code-review/SKILL.md +1140 -0
  232. package/.claude/skills/github-multi-repo/SKILL.md +874 -0
  233. package/.claude/skills/github-project-management/SKILL.md +1277 -0
  234. package/.claude/skills/github-release-management/SKILL.md +1081 -0
  235. package/.claude/skills/github-workflow-automation/SKILL.md +1065 -0
  236. package/.claude/skills/hooks-automation/SKILL.md +1201 -0
  237. package/.claude/skills/pair-programming/SKILL.md +1202 -0
  238. package/.claude/skills/reasoningbank-agentdb/SKILL.md +446 -0
  239. package/.claude/skills/reasoningbank-intelligence/SKILL.md +201 -0
  240. package/.claude/skills/skill-builder/SKILL.md +910 -0
  241. package/.claude/skills/sparc-methodology/SKILL.md +1115 -0
  242. package/.claude/skills/stream-chain/SKILL.md +563 -0
  243. package/.claude/skills/swarm-advanced/SKILL.md +973 -0
  244. package/.claude/skills/swarm-orchestration/SKILL.md +179 -0
  245. package/.claude/skills/v3-cli-modernization/SKILL.md +872 -0
  246. package/.claude/skills/v3-core-implementation/SKILL.md +797 -0
  247. package/.claude/skills/v3-ddd-architecture/SKILL.md +442 -0
  248. package/.claude/skills/v3-integration-deep/SKILL.md +241 -0
  249. package/.claude/skills/v3-mcp-optimization/SKILL.md +777 -0
  250. package/.claude/skills/v3-memory-unification/SKILL.md +174 -0
  251. package/.claude/skills/v3-performance-optimization/SKILL.md +390 -0
  252. package/.claude/skills/v3-security-overhaul/SKILL.md +82 -0
  253. package/.claude/skills/v3-swarm-coordination/SKILL.md +340 -0
  254. package/.claude/skills/verification-quality/SKILL.md +649 -0
  255. package/CLAUDE.md +711 -0
  256. package/README.md +428 -0
  257. package/__tests__/integration.test.ts +449 -0
  258. package/__tests__/mcp.test.ts +641 -0
  259. package/package.json +44 -0
  260. package/src/connection-pool.ts +344 -0
  261. package/src/index.ts +253 -0
  262. package/src/oauth.ts +447 -0
  263. package/src/prompt-registry.ts +296 -0
  264. package/src/rate-limiter.ts +266 -0
  265. package/src/resource-registry.ts +530 -0
  266. package/src/sampling.ts +363 -0
  267. package/src/schema-validator.ts +213 -0
  268. package/src/server.ts +1134 -0
  269. package/src/session-manager.ts +339 -0
  270. package/src/task-manager.ts +427 -0
  271. package/src/tool-registry.ts +475 -0
  272. package/src/transport/http.ts +532 -0
  273. package/src/transport/index.ts +233 -0
  274. package/src/transport/stdio.ts +252 -0
  275. package/src/transport/websocket.ts +396 -0
  276. package/src/types.ts +664 -0
  277. package/tmp.json +0 -0
  278. package/tsconfig.json +20 -0
  279. package/vitest.config.ts +13 -0
@@ -0,0 +1,427 @@
1
+ /**
2
+ * @sparkleideas/mcp - Task Manager
3
+ *
4
+ * MCP 2025-11-25 compliant async task management
5
+ * Supports: task tracking, progress reporting, cancellation
6
+ */
7
+
8
+ import { EventEmitter } from 'events';
9
+ import type {
10
+ MCPTask,
11
+ TaskState,
12
+ TaskProgress,
13
+ TaskResult,
14
+ MCPError,
15
+ ILogger,
16
+ } from './types.js';
17
+
18
+ export type TaskExecutor<T = unknown> = (
19
+ reportProgress: (progress: TaskProgress) => void,
20
+ signal: AbortSignal
21
+ ) => Promise<T>;
22
+
23
+ export interface TaskManagerOptions {
24
+ maxConcurrentTasks?: number;
25
+ taskTimeout?: number;
26
+ cleanupInterval?: number;
27
+ taskRetentionTime?: number;
28
+ }
29
+
30
+ interface ManagedTask extends MCPTask {
31
+ executor?: TaskExecutor;
32
+ abortController?: AbortController;
33
+ promise?: Promise<unknown>;
34
+ }
35
+
36
+ export class TaskManager extends EventEmitter {
37
+ private tasks: Map<string, ManagedTask> = new Map();
38
+ private runningCount = 0;
39
+ private taskCounter = 0;
40
+ private cleanupTimer?: NodeJS.Timeout;
41
+
42
+ private readonly options: Required<TaskManagerOptions>;
43
+
44
+ constructor(
45
+ private readonly logger: ILogger,
46
+ options: TaskManagerOptions = {}
47
+ ) {
48
+ super();
49
+ this.options = {
50
+ maxConcurrentTasks: options.maxConcurrentTasks ?? 10,
51
+ taskTimeout: options.taskTimeout ?? 300000, // 5 minutes
52
+ cleanupInterval: options.cleanupInterval ?? 60000, // 1 minute
53
+ taskRetentionTime: options.taskRetentionTime ?? 3600000, // 1 hour
54
+ };
55
+
56
+ this.startCleanupTimer();
57
+ }
58
+
59
+ /**
60
+ * Create a new task
61
+ */
62
+ createTask<T>(executor: TaskExecutor<T>, metadata?: Record<string, unknown>): string {
63
+ const taskId = `task-${++this.taskCounter}-${Date.now()}`;
64
+ const now = new Date();
65
+
66
+ const task: ManagedTask = {
67
+ id: taskId,
68
+ state: 'pending',
69
+ createdAt: now,
70
+ updatedAt: now,
71
+ metadata,
72
+ executor: executor as TaskExecutor,
73
+ };
74
+
75
+ this.tasks.set(taskId, task);
76
+
77
+ this.logger.debug('Task created', { taskId });
78
+ this.emit('task:created', { taskId });
79
+
80
+ // Auto-start if we have capacity
81
+ if (this.runningCount < this.options.maxConcurrentTasks) {
82
+ this.startTask(taskId);
83
+ }
84
+
85
+ return taskId;
86
+ }
87
+
88
+ /**
89
+ * Start a pending task
90
+ */
91
+ private async startTask(taskId: string): Promise<void> {
92
+ const task = this.tasks.get(taskId);
93
+ if (!task || task.state !== 'pending') {
94
+ return;
95
+ }
96
+
97
+ if (this.runningCount >= this.options.maxConcurrentTasks) {
98
+ return;
99
+ }
100
+
101
+ task.state = 'running';
102
+ task.updatedAt = new Date();
103
+ task.abortController = new AbortController();
104
+ this.runningCount++;
105
+
106
+ this.logger.debug('Task started', { taskId });
107
+ this.emit('task:started', { taskId });
108
+
109
+ // Set up timeout
110
+ const timeoutId = setTimeout(() => {
111
+ this.cancelTask(taskId, 'Task timeout');
112
+ }, this.options.taskTimeout);
113
+
114
+ // Progress reporter
115
+ const reportProgress = (progress: TaskProgress) => {
116
+ task.progress = progress;
117
+ task.updatedAt = new Date();
118
+ this.emit('task:progress', { taskId, progress });
119
+ };
120
+
121
+ try {
122
+ const result = await task.executor!(reportProgress, task.abortController.signal);
123
+
124
+ clearTimeout(timeoutId);
125
+
126
+ if (task.state === 'running') {
127
+ task.state = 'completed';
128
+ task.result = result;
129
+ task.updatedAt = new Date();
130
+ task.progress = { progress: 100, total: 100 };
131
+
132
+ this.logger.debug('Task completed', { taskId });
133
+ this.emit('task:completed', { taskId, result });
134
+ }
135
+ } catch (error) {
136
+ clearTimeout(timeoutId);
137
+
138
+ if (task.state === 'running') {
139
+ if (task.abortController.signal.aborted) {
140
+ task.state = 'cancelled';
141
+ this.logger.debug('Task cancelled', { taskId });
142
+ this.emit('task:cancelled', { taskId });
143
+ } else {
144
+ task.state = 'failed';
145
+ task.error = {
146
+ code: -32603,
147
+ message: error instanceof Error ? error.message : 'Task failed',
148
+ };
149
+ this.logger.error('Task failed', { taskId, error });
150
+ this.emit('task:failed', { taskId, error: task.error });
151
+ }
152
+ task.updatedAt = new Date();
153
+ }
154
+ } finally {
155
+ this.runningCount--;
156
+ task.abortController = undefined;
157
+
158
+ // Start next pending task
159
+ this.startNextPendingTask();
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Start next pending task if available
165
+ */
166
+ private startNextPendingTask(): void {
167
+ for (const [taskId, task] of this.tasks) {
168
+ if (task.state === 'pending') {
169
+ this.startTask(taskId);
170
+ break;
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Cancel a task
177
+ */
178
+ cancelTask(taskId: string, reason?: string): boolean {
179
+ const task = this.tasks.get(taskId);
180
+ if (!task) {
181
+ return false;
182
+ }
183
+
184
+ if (task.state !== 'pending' && task.state !== 'running') {
185
+ return false;
186
+ }
187
+
188
+ if (task.abortController) {
189
+ task.abortController.abort(reason);
190
+ }
191
+
192
+ if (task.state === 'pending') {
193
+ task.state = 'cancelled';
194
+ task.updatedAt = new Date();
195
+ task.error = { code: -32800, message: reason || 'Cancelled' };
196
+ this.emit('task:cancelled', { taskId, reason });
197
+ }
198
+
199
+ this.logger.debug('Task cancel requested', { taskId, reason });
200
+ return true;
201
+ }
202
+
203
+ /**
204
+ * Get task status
205
+ */
206
+ getTask(taskId: string): TaskResult | undefined {
207
+ const task = this.tasks.get(taskId);
208
+ if (!task) {
209
+ return undefined;
210
+ }
211
+
212
+ return {
213
+ taskId: task.id,
214
+ state: task.state,
215
+ progress: task.progress,
216
+ result: task.result,
217
+ error: task.error,
218
+ };
219
+ }
220
+
221
+ /**
222
+ * Get all tasks
223
+ */
224
+ getAllTasks(): TaskResult[] {
225
+ return Array.from(this.tasks.values()).map((task) => ({
226
+ taskId: task.id,
227
+ state: task.state,
228
+ progress: task.progress,
229
+ result: task.result,
230
+ error: task.error,
231
+ }));
232
+ }
233
+
234
+ /**
235
+ * Get tasks by state
236
+ */
237
+ getTasksByState(state: TaskState): TaskResult[] {
238
+ return Array.from(this.tasks.values())
239
+ .filter((task) => task.state === state)
240
+ .map((task) => ({
241
+ taskId: task.id,
242
+ state: task.state,
243
+ progress: task.progress,
244
+ result: task.result,
245
+ error: task.error,
246
+ }));
247
+ }
248
+
249
+ /**
250
+ * Wait for task completion
251
+ */
252
+ async waitForTask(taskId: string, timeout?: number): Promise<TaskResult> {
253
+ const task = this.tasks.get(taskId);
254
+ if (!task) {
255
+ throw new Error(`Task not found: ${taskId}`);
256
+ }
257
+
258
+ const effectiveTimeout = timeout ?? this.options.taskTimeout;
259
+
260
+ return new Promise((resolve, reject) => {
261
+ const checkState = () => {
262
+ const result = this.getTask(taskId);
263
+ if (!result) {
264
+ reject(new Error(`Task not found: ${taskId}`));
265
+ return true;
266
+ }
267
+ if (result.state === 'completed' || result.state === 'failed' || result.state === 'cancelled') {
268
+ resolve(result);
269
+ return true;
270
+ }
271
+ return false;
272
+ };
273
+
274
+ if (checkState()) return;
275
+
276
+ const timeoutId = setTimeout(() => {
277
+ this.off('task:completed', onComplete);
278
+ this.off('task:failed', onFail);
279
+ this.off('task:cancelled', onCancel);
280
+ reject(new Error(`Wait timeout for task: ${taskId}`));
281
+ }, effectiveTimeout);
282
+
283
+ const cleanup = () => {
284
+ clearTimeout(timeoutId);
285
+ this.off('task:completed', onComplete);
286
+ this.off('task:failed', onFail);
287
+ this.off('task:cancelled', onCancel);
288
+ };
289
+
290
+ const onComplete = (event: { taskId: string }) => {
291
+ if (event.taskId === taskId) {
292
+ cleanup();
293
+ resolve(this.getTask(taskId)!);
294
+ }
295
+ };
296
+
297
+ const onFail = (event: { taskId: string }) => {
298
+ if (event.taskId === taskId) {
299
+ cleanup();
300
+ resolve(this.getTask(taskId)!);
301
+ }
302
+ };
303
+
304
+ const onCancel = (event: { taskId: string }) => {
305
+ if (event.taskId === taskId) {
306
+ cleanup();
307
+ resolve(this.getTask(taskId)!);
308
+ }
309
+ };
310
+
311
+ this.on('task:completed', onComplete);
312
+ this.on('task:failed', onFail);
313
+ this.on('task:cancelled', onCancel);
314
+ });
315
+ }
316
+
317
+ /**
318
+ * Get stats
319
+ */
320
+ getStats(): {
321
+ totalTasks: number;
322
+ pendingTasks: number;
323
+ runningTasks: number;
324
+ completedTasks: number;
325
+ failedTasks: number;
326
+ cancelledTasks: number;
327
+ } {
328
+ let pending = 0;
329
+ let running = 0;
330
+ let completed = 0;
331
+ let failed = 0;
332
+ let cancelled = 0;
333
+
334
+ for (const task of this.tasks.values()) {
335
+ switch (task.state) {
336
+ case 'pending':
337
+ pending++;
338
+ break;
339
+ case 'running':
340
+ running++;
341
+ break;
342
+ case 'completed':
343
+ completed++;
344
+ break;
345
+ case 'failed':
346
+ failed++;
347
+ break;
348
+ case 'cancelled':
349
+ cancelled++;
350
+ break;
351
+ }
352
+ }
353
+
354
+ return {
355
+ totalTasks: this.tasks.size,
356
+ pendingTasks: pending,
357
+ runningTasks: running,
358
+ completedTasks: completed,
359
+ failedTasks: failed,
360
+ cancelledTasks: cancelled,
361
+ };
362
+ }
363
+
364
+ /**
365
+ * Start cleanup timer
366
+ */
367
+ private startCleanupTimer(): void {
368
+ this.cleanupTimer = setInterval(() => {
369
+ this.cleanupOldTasks();
370
+ }, this.options.cleanupInterval);
371
+ }
372
+
373
+ /**
374
+ * Cleanup old completed/failed/cancelled tasks
375
+ */
376
+ private cleanupOldTasks(): void {
377
+ const now = Date.now();
378
+ const toDelete: string[] = [];
379
+
380
+ for (const [taskId, task] of this.tasks) {
381
+ if (
382
+ (task.state === 'completed' || task.state === 'failed' || task.state === 'cancelled') &&
383
+ now - task.updatedAt.getTime() > this.options.taskRetentionTime
384
+ ) {
385
+ toDelete.push(taskId);
386
+ }
387
+ }
388
+
389
+ for (const taskId of toDelete) {
390
+ this.tasks.delete(taskId);
391
+ this.logger.debug('Task cleaned up', { taskId });
392
+ }
393
+
394
+ if (toDelete.length > 0) {
395
+ this.emit('tasks:cleaned', { count: toDelete.length });
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Destroy the task manager
401
+ */
402
+ destroy(): void {
403
+ if (this.cleanupTimer) {
404
+ clearInterval(this.cleanupTimer);
405
+ this.cleanupTimer = undefined;
406
+ }
407
+
408
+ // Cancel all running tasks
409
+ for (const task of this.tasks.values()) {
410
+ if (task.abortController) {
411
+ task.abortController.abort('Task manager destroyed');
412
+ }
413
+ }
414
+
415
+ this.tasks.clear();
416
+ this.removeAllListeners();
417
+
418
+ this.logger.debug('Task manager destroyed');
419
+ }
420
+ }
421
+
422
+ export function createTaskManager(
423
+ logger: ILogger,
424
+ options?: TaskManagerOptions
425
+ ): TaskManager {
426
+ return new TaskManager(logger, options);
427
+ }