@sparkleideas/integration 3.5.2-patch.1

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.
@@ -0,0 +1,435 @@
1
+ /**
2
+ * SDK Bridge for @sparkleideas/agentic-flow API Compatibility
3
+ *
4
+ * Provides API compatibility layer between @sparkleideas/claude-flow v3 and
5
+ * @sparkleideas/agentic-flow@alpha, handling version negotiation, feature
6
+ * detection, and fallback behavior.
7
+ *
8
+ * Key Responsibilities:
9
+ * - Version negotiation and compatibility checking
10
+ * - API translation for v2 -> v3 migration
11
+ * - Feature detection and graceful degradation
12
+ * - Deprecated API support with warnings
13
+ *
14
+ * @module v3/integration/sdk-bridge
15
+ * @version 3.0.0-alpha.1
16
+ */
17
+
18
+ import { EventEmitter } from 'events';
19
+ import type {
20
+ SDKBridgeConfig,
21
+ SDKVersion,
22
+ SDKCompatibility,
23
+ } from './types.js';
24
+
25
+ /**
26
+ * Feature availability by SDK version
27
+ */
28
+ const FEATURE_MATRIX: Record<string, { minVersion: string; optional: boolean }> = {
29
+ 'sona-learning': { minVersion: '2.0.0', optional: false },
30
+ 'flash-attention': { minVersion: '2.0.0', optional: false },
31
+ 'agentdb-hnsw': { minVersion: '2.0.0', optional: false },
32
+ 'gnn-refinement': { minVersion: '2.0.0', optional: true },
33
+ 'trajectory-tracking': { minVersion: '2.0.0', optional: false },
34
+ 'intelligence-bridge': { minVersion: '2.0.1', optional: false },
35
+ 'quic-transport': { minVersion: '2.0.1', optional: true },
36
+ 'nightly-learning': { minVersion: '2.0.1', optional: true },
37
+ 'micro-lora': { minVersion: '2.0.1', optional: true },
38
+ };
39
+
40
+ /**
41
+ * Deprecated API mappings (old -> new)
42
+ */
43
+ const DEPRECATED_API_MAP: Record<string, {
44
+ replacement: string;
45
+ since: string;
46
+ removed?: string;
47
+ transformer?: (args: unknown[]) => unknown[];
48
+ }> = {
49
+ 'ReasoningBank.initialize': {
50
+ replacement: 'HybridReasoningBank.initialize',
51
+ since: '2.0.0',
52
+ },
53
+ 'AgentDB.store': {
54
+ replacement: 'AgentDBFast.store',
55
+ since: '2.0.0',
56
+ transformer: (args) => args, // Same signature
57
+ },
58
+ 'computeEmbedding': {
59
+ replacement: 'EmbeddingService.compute',
60
+ since: '2.0.0',
61
+ },
62
+ };
63
+
64
+ /**
65
+ * SDKBridge - API Compatibility Layer
66
+ *
67
+ * This bridge handles version compatibility, feature detection,
68
+ * and API translation between @sparkleideas/claude-flow and @sparkleideas/agentic-flow.
69
+ */
70
+ export class SDKBridge extends EventEmitter {
71
+ private config: SDKBridgeConfig;
72
+ private initialized: boolean = false;
73
+ private currentVersion: SDKVersion | null = null;
74
+ private availableFeatures: Set<string> = new Set();
75
+ private deprecationWarnings: Set<string> = new Set();
76
+
77
+ constructor(config: Partial<SDKBridgeConfig> = {}) {
78
+ super();
79
+ this.config = this.mergeConfig(config);
80
+ }
81
+
82
+ /**
83
+ * Initialize the SDK bridge
84
+ */
85
+ async initialize(): Promise<void> {
86
+ if (this.initialized) {
87
+ return;
88
+ }
89
+
90
+ this.emit('initializing');
91
+
92
+ try {
93
+ // Detect SDK version
94
+ this.currentVersion = await this.detectVersion();
95
+
96
+ // Check compatibility
97
+ const compatibility = await this.checkCompatibility();
98
+ if (!compatibility.compatible) {
99
+ throw new Error(
100
+ `SDK version ${this.currentVersion.full} is not compatible. ` +
101
+ `Required: ${compatibility.minVersion.full} - ${compatibility.maxVersion.full}`
102
+ );
103
+ }
104
+
105
+ // Detect available features
106
+ await this.detectFeatures();
107
+
108
+ this.initialized = true;
109
+ this.emit('initialized', {
110
+ version: this.currentVersion,
111
+ features: Array.from(this.availableFeatures)
112
+ });
113
+ } catch (error) {
114
+ this.emit('initialization-failed', { error });
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Ping to check if SDK is available
121
+ */
122
+ async ping(): Promise<boolean> {
123
+ // Simple health check
124
+ return this.initialized;
125
+ }
126
+
127
+ /**
128
+ * Get current SDK version
129
+ */
130
+ getVersion(): SDKVersion | null {
131
+ return this.currentVersion;
132
+ }
133
+
134
+ /**
135
+ * Check if a feature is available
136
+ */
137
+ isFeatureAvailable(feature: string): boolean {
138
+ return this.availableFeatures.has(feature);
139
+ }
140
+
141
+ /**
142
+ * Get all available features
143
+ */
144
+ getAvailableFeatures(): string[] {
145
+ return Array.from(this.availableFeatures);
146
+ }
147
+
148
+ /**
149
+ * Get compatibility information
150
+ */
151
+ async checkCompatibility(): Promise<SDKCompatibility> {
152
+ const current = this.currentVersion || await this.detectVersion();
153
+
154
+ const minVersion = this.parseVersion('2.0.0-alpha.0');
155
+ const maxVersion = this.parseVersion('3.0.0');
156
+
157
+ const compatible =
158
+ this.compareVersions(current, minVersion) >= 0 &&
159
+ this.compareVersions(current, maxVersion) < 0;
160
+
161
+ const requiredFeatures = Object.entries(FEATURE_MATRIX)
162
+ .filter(([_, info]) => !info.optional)
163
+ .map(([name]) => name);
164
+
165
+ const optionalFeatures = Object.entries(FEATURE_MATRIX)
166
+ .filter(([_, info]) => info.optional)
167
+ .map(([name]) => name);
168
+
169
+ return {
170
+ minVersion,
171
+ maxVersion,
172
+ currentVersion: current,
173
+ compatible,
174
+ requiredFeatures,
175
+ optionalFeatures,
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Translate deprecated API call to new API
181
+ */
182
+ translateDeprecatedAPI(
183
+ oldAPI: string,
184
+ args: unknown[]
185
+ ): { newAPI: string; args: unknown[] } | null {
186
+ const mapping = DEPRECATED_API_MAP[oldAPI];
187
+ if (!mapping) {
188
+ return null;
189
+ }
190
+
191
+ // Emit deprecation warning (once per API)
192
+ if (!this.deprecationWarnings.has(oldAPI)) {
193
+ this.deprecationWarnings.add(oldAPI);
194
+ const message = `'${oldAPI}' is deprecated since ${mapping.since}. ` +
195
+ `Use '${mapping.replacement}' instead.`;
196
+
197
+ switch (this.config.fallbackBehavior) {
198
+ case 'error':
199
+ throw new Error(message);
200
+ case 'warn':
201
+ console.warn(`[DEPRECATED] ${message}`);
202
+ this.emit('deprecation-warning', { oldAPI, mapping });
203
+ break;
204
+ case 'silent':
205
+ // Log but don't warn
206
+ break;
207
+ }
208
+ }
209
+
210
+ const newArgs = mapping.transformer ? mapping.transformer(args) : args;
211
+ return { newAPI: mapping.replacement, args: newArgs };
212
+ }
213
+
214
+ /**
215
+ * Wrap an API call with compatibility handling
216
+ */
217
+ async wrapAPICall<T>(
218
+ apiName: string,
219
+ apiCall: () => Promise<T>,
220
+ fallback?: () => Promise<T>
221
+ ): Promise<T> {
222
+ this.ensureInitialized();
223
+
224
+ try {
225
+ return await apiCall();
226
+ } catch (error) {
227
+ // Check if this is a version-related error
228
+ if (this.isVersionError(error)) {
229
+ if (fallback) {
230
+ this.emit('fallback-used', { apiName, error });
231
+ return await fallback();
232
+ }
233
+ }
234
+ throw error;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Get feature requirements for a capability
240
+ */
241
+ getFeatureRequirements(capability: string): {
242
+ required: string[];
243
+ optional: string[];
244
+ satisfied: boolean;
245
+ } {
246
+ const capabilityFeatures: Record<string, { required: string[]; optional: string[] }> = {
247
+ 'learning': {
248
+ required: ['sona-learning', 'trajectory-tracking'],
249
+ optional: ['nightly-learning', 'micro-lora'],
250
+ },
251
+ 'attention': {
252
+ required: ['flash-attention'],
253
+ optional: [],
254
+ },
255
+ 'search': {
256
+ required: ['agentdb-hnsw'],
257
+ optional: ['gnn-refinement'],
258
+ },
259
+ 'coordination': {
260
+ required: ['sona-learning', 'flash-attention'],
261
+ optional: ['quic-transport'],
262
+ },
263
+ };
264
+
265
+ const features = capabilityFeatures[capability] || { required: [], optional: [] };
266
+ const satisfied = features.required.every(f => this.availableFeatures.has(f));
267
+
268
+ return {
269
+ ...features,
270
+ satisfied,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Negotiate version with remote SDK
276
+ */
277
+ async negotiateVersion(preferredVersion?: string): Promise<SDKVersion> {
278
+ // In a real implementation, this would communicate with the SDK
279
+ // to determine the best compatible version to use
280
+
281
+ const preferred = preferredVersion
282
+ ? this.parseVersion(preferredVersion)
283
+ : this.currentVersion;
284
+
285
+ if (!preferred) {
286
+ return this.currentVersion || this.parseVersion('2.0.1-alpha.50');
287
+ }
288
+
289
+ // Return the negotiated version
290
+ return preferred;
291
+ }
292
+
293
+ /**
294
+ * Get migration guide for deprecated APIs
295
+ */
296
+ getMigrationGuide(): Record<string, {
297
+ old: string;
298
+ new: string;
299
+ example: string;
300
+ }> {
301
+ const guide: Record<string, { old: string; new: string; example: string }> = {};
302
+
303
+ for (const [oldAPI, mapping] of Object.entries(DEPRECATED_API_MAP)) {
304
+ guide[oldAPI] = {
305
+ old: oldAPI,
306
+ new: mapping.replacement,
307
+ example: this.generateMigrationExample(oldAPI, mapping.replacement),
308
+ };
309
+ }
310
+
311
+ return guide;
312
+ }
313
+
314
+ /**
315
+ * Shutdown the bridge
316
+ */
317
+ async shutdown(): Promise<void> {
318
+ this.initialized = false;
319
+ this.availableFeatures.clear();
320
+ this.deprecationWarnings.clear();
321
+ this.emit('shutdown');
322
+ }
323
+
324
+ // ===== Private Methods =====
325
+
326
+ private mergeConfig(config: Partial<SDKBridgeConfig>): SDKBridgeConfig {
327
+ return {
328
+ targetVersion: config.targetVersion || 'alpha',
329
+ enableVersionNegotiation: config.enableVersionNegotiation ?? true,
330
+ fallbackBehavior: config.fallbackBehavior || 'warn',
331
+ enableCompatibilityLayer: config.enableCompatibilityLayer ?? true,
332
+ supportDeprecatedAPIs: config.supportDeprecatedAPIs ?? true,
333
+ };
334
+ }
335
+
336
+ private async detectVersion(): Promise<SDKVersion> {
337
+ // Detect @sparkleideas/agentic-flow version dynamically
338
+ try {
339
+ const af = await import('@sparkleideas/agentic-flow');
340
+ if (af.VERSION) {
341
+ return this.parseVersion(af.VERSION);
342
+ }
343
+ } catch {
344
+ // @sparkleideas/agentic-flow not available, use fallback version
345
+ }
346
+ return this.parseVersion('2.0.1-alpha.50');
347
+ }
348
+
349
+ private async detectFeatures(): Promise<void> {
350
+ if (!this.currentVersion) {
351
+ return;
352
+ }
353
+
354
+ for (const [feature, info] of Object.entries(FEATURE_MATRIX)) {
355
+ const minVersion = this.parseVersion(info.minVersion);
356
+ if (this.compareVersions(this.currentVersion, minVersion) >= 0) {
357
+ this.availableFeatures.add(feature);
358
+ }
359
+ }
360
+
361
+ this.emit('features-detected', {
362
+ features: Array.from(this.availableFeatures)
363
+ });
364
+ }
365
+
366
+ private parseVersion(version: string): SDKVersion {
367
+ // Handle versions like "2.0.1-alpha.50" or "2.0.0"
368
+ const parts = version.split('-');
369
+ const core = parts[0].split('.');
370
+ const prerelease = parts[1] || undefined;
371
+
372
+ return {
373
+ major: parseInt(core[0] || '0', 10),
374
+ minor: parseInt(core[1] || '0', 10),
375
+ patch: parseInt(core[2] || '0', 10),
376
+ prerelease,
377
+ full: version,
378
+ };
379
+ }
380
+
381
+ private compareVersions(a: SDKVersion, b: SDKVersion): number {
382
+ // Compare major, minor, patch
383
+ if (a.major !== b.major) return a.major - b.major;
384
+ if (a.minor !== b.minor) return a.minor - b.minor;
385
+ if (a.patch !== b.patch) return a.patch - b.patch;
386
+
387
+ // Compare prerelease (alpha < beta < rc < release)
388
+ if (!a.prerelease && b.prerelease) return 1;
389
+ if (a.prerelease && !b.prerelease) return -1;
390
+ if (!a.prerelease && !b.prerelease) return 0;
391
+
392
+ // Both have prerelease
393
+ return (a.prerelease || '').localeCompare(b.prerelease || '');
394
+ }
395
+
396
+ private isVersionError(error: unknown): boolean {
397
+ const message = (error as Error)?.message || '';
398
+ return message.includes('version') ||
399
+ message.includes('not supported') ||
400
+ message.includes('deprecated');
401
+ }
402
+
403
+ private generateMigrationExample(oldAPI: string, newAPI: string): string {
404
+ // Generate a simple migration example
405
+ const oldParts = oldAPI.split('.');
406
+ const newParts = newAPI.split('.');
407
+
408
+ const oldCall = oldParts.length > 1
409
+ ? `${oldParts[0]}.${oldParts[1]}(args)`
410
+ : `${oldAPI}(args)`;
411
+
412
+ const newCall = newParts.length > 1
413
+ ? `new ${newParts[0]}().${newParts[1]}(args)`
414
+ : `${newAPI}(args)`;
415
+
416
+ return `// Before:\n${oldCall}\n\n// After:\n${newCall}`;
417
+ }
418
+
419
+ private ensureInitialized(): void {
420
+ if (!this.initialized) {
421
+ throw new Error('SDKBridge not initialized. Call initialize() first.');
422
+ }
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Create and initialize an SDK bridge
428
+ */
429
+ export async function createSDKBridge(
430
+ config?: Partial<SDKBridgeConfig>
431
+ ): Promise<SDKBridge> {
432
+ const bridge = new SDKBridge(config);
433
+ await bridge.initialize();
434
+ return bridge;
435
+ }