@kb-labs/shared-command-kit 1.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.
@@ -0,0 +1,650 @@
1
+ import { platform } from '@kb-labs/core-runtime';
2
+ export { PluginContextV3 } from '@kb-labs/plugin-contracts';
3
+ import { ILogger, UseLLMOptions, ILLM, LLMTier, IEmbeddings, IVectorStore, IAnalytics, IStorage, ICache } from '@kb-labs/core-platform';
4
+ export { LLMTier, UseLLMOptions } from '@kb-labs/core-platform';
5
+
6
+ /**
7
+ * @module @kb-labs/shared-command-kit/helpers/use-platform
8
+ * Global platform singleton access helper
9
+ *
10
+ * Provides clean access to platform services without context drilling.
11
+ * Similar to React hooks pattern, but for KB Labs platform.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { usePlatform } from '@kb-labs/shared-command-kit';
16
+ *
17
+ * // In any command handler
18
+ * async handler(ctx, argv, flags) {
19
+ * const platform = usePlatform();
20
+ *
21
+ * if (platform.llm) {
22
+ * const result = await platform.llm.complete('prompt');
23
+ * }
24
+ *
25
+ * await platform.logger.info('Task completed');
26
+ * }
27
+ * ```
28
+ */
29
+
30
+ /**
31
+ * Access global platform singleton
32
+ *
33
+ * Returns the initialized platform object with all registered adapters.
34
+ * This is the single source of truth for platform services.
35
+ *
36
+ * **What's available:**
37
+ * - `platform.llm` - LLM adapter (OpenAI, Anthropic, etc.)
38
+ * - `platform.embeddings` - Embeddings adapter
39
+ * - `platform.vectorStore` - Vector storage (Qdrant, local, etc.)
40
+ * - `platform.storage` - File/blob storage
41
+ * - `platform.cache` - Caching layer
42
+ * - `platform.analytics` - Analytics/telemetry
43
+ * - `platform.logger` - Structured logging
44
+ * - `platform.eventBus` - Event system
45
+ * - `platform.workflows` - Workflow engine
46
+ * - `platform.jobs` - Background jobs
47
+ * - `platform.cron` - Scheduled tasks
48
+ * - `platform.resources` - Resource management
49
+ * - `platform.invoke` - Plugin invocation
50
+ * - `platform.artifacts` - Build artifacts
51
+ *
52
+ * **Graceful degradation:**
53
+ * Always check if adapter is available before using:
54
+ * ```typescript
55
+ * const platform = usePlatform();
56
+ * if (platform.llm) {
57
+ * // Use LLM
58
+ * } else {
59
+ * // Fallback logic
60
+ * }
61
+ * ```
62
+ *
63
+ * **Multi-tenancy:**
64
+ * Currently returns global singleton (single-tenant).
65
+ * Future: Will support tenant-scoped platform via AsyncLocalStorage.
66
+ *
67
+ * @returns Global platform singleton
68
+ */
69
+ declare function usePlatform(): typeof platform;
70
+ /**
71
+ * Check if specific platform adapter is configured
72
+ *
73
+ * Useful for conditional logic based on available services.
74
+ *
75
+ * @param adapterName - Name of the adapter to check
76
+ * @returns true if adapter is configured and available
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * if (isPlatformConfigured('llm')) {
81
+ * // Use LLM-powered feature
82
+ * } else {
83
+ * // Use deterministic fallback
84
+ * }
85
+ * ```
86
+ */
87
+ declare function isPlatformConfigured(adapterName: keyof typeof platform): boolean;
88
+
89
+ /**
90
+ * @module @kb-labs/shared-command-kit/helpers/use-config
91
+ * Global config access helper
92
+ *
93
+ * Provides clean access to product-specific configuration without context drilling.
94
+ * Similar to React hooks pattern, but for KB Labs config.
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * import { useConfig } from '@kb-labs/shared-command-kit';
99
+ *
100
+ * // In any command handler
101
+ * async handler(ctx, argv, flags) {
102
+ * const config = await useConfig('mind');
103
+ *
104
+ * if (config) {
105
+ * const scopes = config.scopes;
106
+ * // Use config...
107
+ * }
108
+ * }
109
+ * ```
110
+ */
111
+ /**
112
+ * Access product-specific configuration from kb.config.json
113
+ *
114
+ * Returns ONLY the config for the specified product and profile.
115
+ * Uses platform.config adapter (works across parent/child processes via IPC).
116
+ * Supports both Profiles v2 and legacy config structures.
117
+ *
118
+ * **Security:** This function returns ONLY the product-specific config,
119
+ * not the entire kb.config.json. This prevents cross-product config access.
120
+ *
121
+ * **Auto-detection:** If productId is not provided, it's automatically inferred
122
+ * from the plugin's manifest.configSection field (passed via execution context).
123
+ *
124
+ * **Profiles v2 structure:**
125
+ * ```json
126
+ * {
127
+ * "profiles": [
128
+ * {
129
+ * "id": "default",
130
+ * "products": {
131
+ * "mind": { "scopes": [...] },
132
+ * "workflow": { "maxConcurrency": 10 }
133
+ * }
134
+ * }
135
+ * ]
136
+ * }
137
+ * ```
138
+ *
139
+ * **Legacy structure:**
140
+ * ```json
141
+ * {
142
+ * "knowledge": { "scopes": [...] }, // for "mind" product
143
+ * "workflow": { "maxConcurrency": 10 }
144
+ * }
145
+ * ```
146
+ *
147
+ * @param productId - Product identifier (e.g., 'mind', 'workflow', 'plugins'). Optional - auto-detected from context.
148
+ * @param profileId - Profile identifier (defaults to 'default' or KB_PROFILE env var)
149
+ * @returns Promise resolving to product-specific config or undefined
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * // Auto-detect from context (recommended)
154
+ * const config = await useConfig();
155
+ *
156
+ * // Explicit product ID
157
+ * const mindConfig = await useConfig('mind');
158
+ * if (mindConfig?.scopes) {
159
+ * // Use scopes
160
+ * }
161
+ *
162
+ * // With explicit profile
163
+ * const workflowConfig = await useConfig('workflow', 'production');
164
+ * ```
165
+ */
166
+ declare function useConfig<T = any>(productId?: string, profileId?: string): Promise<T | undefined>;
167
+
168
+ /**
169
+ * @module @kb-labs/shared-command-kit/helpers/use-logger
170
+ * Global logger access helper
171
+ *
172
+ * Provides clean access to structured logging without context drilling.
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * import { useLogger } from '@kb-labs/shared-command-kit';
177
+ *
178
+ * async handler(ctx, argv, flags) {
179
+ * const logger = useLogger();
180
+ *
181
+ * await logger.info('Processing started');
182
+ * await logger.debug('Details', { userId: 123 });
183
+ * await logger.error('Failed', { error: err });
184
+ * }
185
+ * ```
186
+ */
187
+
188
+ /**
189
+ * Access global logger
190
+ *
191
+ * Returns the platform logger with structured logging capabilities.
192
+ * Supports child loggers with additional context.
193
+ *
194
+ * **Methods:**
195
+ * - `logger.trace(message, meta?)` - Trace-level logs (most verbose)
196
+ * - `logger.debug(message, meta?)` - Debug-level logs
197
+ * - `logger.info(message, meta?)` - Info-level logs
198
+ * - `logger.warn(message, meta?)` - Warning-level logs
199
+ * - `logger.error(message, meta?)` - Error-level logs
200
+ * - `logger.child(meta)` - Create child logger with additional context
201
+ *
202
+ * @returns Platform logger instance
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * const logger = useLogger();
207
+ *
208
+ * await logger.info('Task started', { taskId: '123' });
209
+ * await logger.error('Task failed', { taskId: '123', error: err.message });
210
+ *
211
+ * // Child logger with persistent context
212
+ * const taskLogger = logger.child({ taskId: '123', userId: 'user-1' });
213
+ * await taskLogger.info('Step 1 completed');
214
+ * await taskLogger.info('Step 2 completed');
215
+ * ```
216
+ */
217
+ declare function useLogger(): ILogger;
218
+ /**
219
+ * Create child logger with additional context
220
+ *
221
+ * Useful for scoped logging within a specific operation.
222
+ *
223
+ * @param context - Additional context to attach to all log entries
224
+ * @returns Child logger with persistent context
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * const logger = useLoggerWithContext({ operation: 'release', version: '1.0.0' });
229
+ *
230
+ * await logger.info('Started'); // Automatically includes operation + version
231
+ * await logger.info('Completed');
232
+ * ```
233
+ */
234
+ declare function useLoggerWithContext(context: Record<string, unknown>): ILogger;
235
+
236
+ /**
237
+ * @module @kb-labs/shared-command-kit/helpers/use-llm
238
+ * Global LLM access helper with tier-based model selection.
239
+ *
240
+ * Provides clean access to LLM with adaptive tier routing.
241
+ * Plugins specify tiers (small/medium/large), platform resolves to actual models.
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * import { useLLM } from '@kb-labs/shared-command-kit';
246
+ *
247
+ * async handler(ctx, argv, flags) {
248
+ * // Simple usage (uses configured default tier)
249
+ * const llm = useLLM();
250
+ *
251
+ * // Request specific tier (platform adapts if needed)
252
+ * const llm = useLLM({ tier: 'small' }); // Simple tasks
253
+ * const llm = useLLM({ tier: 'large' }); // Complex tasks
254
+ *
255
+ * // Request capabilities
256
+ * const llm = useLLM({ tier: 'medium', capabilities: ['coding'] });
257
+ *
258
+ * if (llm) {
259
+ * const result = await llm.complete('Explain this code');
260
+ * console.log(result.content);
261
+ * }
262
+ * }
263
+ * ```
264
+ */
265
+
266
+ /**
267
+ * Access global LLM adapter with tier-based selection.
268
+ *
269
+ * Platform automatically adapts to available models:
270
+ * - If plugin requests 'small' but 'medium' configured → uses 'medium' (escalation)
271
+ * - If plugin requests 'large' but 'medium' configured → uses 'medium' with warning (degradation)
272
+ *
273
+ * **Tiers are user-defined slots:**
274
+ * - `small` - Plugin says: "This task is simple"
275
+ * - `medium` - Plugin says: "Standard task"
276
+ * - `large` - Plugin says: "Complex task, need maximum quality"
277
+ *
278
+ * User decides what model maps to each tier in their config.
279
+ *
280
+ * @param options - Optional tier and capability requirements
281
+ * @returns LLM adapter or undefined if not configured
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * // Simple usage (uses configured default)
286
+ * const llm = useLLM();
287
+ *
288
+ * // Request specific tier
289
+ * const llm = useLLM({ tier: 'small' }); // Simple tasks
290
+ * const llm = useLLM({ tier: 'large' }); // Complex tasks
291
+ *
292
+ * // Request capabilities
293
+ * const llm = useLLM({ tier: 'medium', capabilities: ['coding'] });
294
+ * const llm = useLLM({ capabilities: ['vision'] });
295
+ *
296
+ * if (llm) {
297
+ * const result = await llm.complete('Generate commit message');
298
+ * console.log(result.content);
299
+ * }
300
+ * ```
301
+ */
302
+ declare function useLLM(options?: UseLLMOptions): ILLM | undefined;
303
+ /**
304
+ * Check if LLM is available.
305
+ *
306
+ * Useful for conditional logic (LLM-powered vs deterministic fallback).
307
+ *
308
+ * @returns true if LLM is configured and ready
309
+ *
310
+ * @example
311
+ * ```typescript
312
+ * if (isLLMAvailable()) {
313
+ * const summary = await generateWithLLM(data);
314
+ * } else {
315
+ * const summary = generateDeterministic(data);
316
+ * }
317
+ * ```
318
+ */
319
+ declare function isLLMAvailable(): boolean;
320
+ /**
321
+ * Get configured LLM tier.
322
+ *
323
+ * Useful for diagnostics and logging.
324
+ *
325
+ * @returns Configured tier or undefined if LLM not available/not a router
326
+ *
327
+ * @example
328
+ * ```typescript
329
+ * const tier = getLLMTier();
330
+ * console.log(`Using LLM tier: ${tier ?? 'default'}`);
331
+ * ```
332
+ */
333
+ declare function getLLMTier(): LLMTier | undefined;
334
+
335
+ /**
336
+ * @module @kb-labs/shared-command-kit/helpers/use-embeddings
337
+ * Global Embeddings access helper
338
+ */
339
+
340
+ /**
341
+ * Access global Embeddings adapter
342
+ *
343
+ * Returns the platform embeddings adapter (OpenAI, etc.).
344
+ * Returns undefined if embeddings is not configured (graceful degradation).
345
+ *
346
+ * @returns Embeddings adapter or undefined if not configured
347
+ *
348
+ * @example
349
+ * ```typescript
350
+ * const embeddings = useEmbeddings();
351
+ *
352
+ * if (embeddings) {
353
+ * const vector = await embeddings.embed('Hello, world!');
354
+ * console.log(vector.length); // e.g., 1536 for OpenAI
355
+ * }
356
+ * ```
357
+ */
358
+ declare function useEmbeddings(): IEmbeddings | undefined;
359
+ /**
360
+ * Check if Embeddings is available
361
+ *
362
+ * @returns true if embeddings is configured and ready
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * if (isEmbeddingsAvailable()) {
367
+ * const vector = await embeddings.embed(text);
368
+ * } else {
369
+ * // Use deterministic fallback
370
+ * }
371
+ * ```
372
+ */
373
+ declare function isEmbeddingsAvailable(): boolean;
374
+
375
+ /**
376
+ * @module @kb-labs/shared-command-kit/helpers/use-vector-store
377
+ * Global VectorStore access helper
378
+ */
379
+
380
+ /**
381
+ * Access global VectorStore adapter
382
+ *
383
+ * Returns the platform vector store adapter (Qdrant, local, etc.).
384
+ * Returns undefined if vectorStore is not configured (graceful degradation).
385
+ *
386
+ * @returns VectorStore adapter or undefined if not configured
387
+ *
388
+ * @example
389
+ * ```typescript
390
+ * const vectorStore = useVectorStore();
391
+ *
392
+ * if (vectorStore) {
393
+ * await vectorStore.upsert([{ id: '1', vector: [0.1, 0.2], metadata: {} }]);
394
+ * const results = await vectorStore.search([0.1, 0.2], 10);
395
+ * }
396
+ * ```
397
+ */
398
+ declare function useVectorStore(): IVectorStore | undefined;
399
+ /**
400
+ * Check if VectorStore is available
401
+ *
402
+ * @returns true if vectorStore is configured and ready
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * if (isVectorStoreAvailable()) {
407
+ * await vectorStore.upsert(records);
408
+ * } else {
409
+ * // Use local fallback
410
+ * }
411
+ * ```
412
+ */
413
+ declare function isVectorStoreAvailable(): boolean;
414
+
415
+ /**
416
+ * @module @kb-labs/shared-command-kit/helpers/use-analytics
417
+ * Global analytics access helper
418
+ *
419
+ * Provides clean access to analytics/telemetry without context drilling.
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * import { useAnalytics } from '@kb-labs/shared-command-kit';
424
+ *
425
+ * async handler(ctx, argv, flags) {
426
+ * const analytics = useAnalytics();
427
+ *
428
+ * if (analytics) {
429
+ * await analytics.track('release_started', { version: '1.0.0' });
430
+ * analytics.metric('release_duration_ms', 1234);
431
+ * }
432
+ * }
433
+ * ```
434
+ */
435
+
436
+ /**
437
+ * Access global analytics adapter
438
+ *
439
+ * Returns the platform analytics adapter for tracking events and metrics.
440
+ * Returns undefined if analytics is not configured (graceful degradation).
441
+ *
442
+ * **Methods:**
443
+ * - `analytics.track(event, properties?)` - Track events
444
+ * - `analytics.metric(name, value, tags?)` - Record metrics
445
+ *
446
+ * **Always check availability:**
447
+ * ```typescript
448
+ * const analytics = useAnalytics();
449
+ * if (analytics) {
450
+ * await analytics.track('event');
451
+ * }
452
+ * ```
453
+ *
454
+ * @returns Analytics adapter or undefined if not configured
455
+ *
456
+ * @example
457
+ * ```typescript
458
+ * const analytics = useAnalytics();
459
+ *
460
+ * if (analytics) {
461
+ * await analytics.track('command_executed', {
462
+ * command: 'release:run',
463
+ * duration_ms: 1234,
464
+ * success: true,
465
+ * });
466
+ *
467
+ * analytics.metric('release_packages_count', 5, {
468
+ * project: 'kb-labs',
469
+ * });
470
+ * }
471
+ * ```
472
+ */
473
+ declare function useAnalytics(): IAnalytics | undefined;
474
+ /**
475
+ * Track event with analytics (safe, global singleton)
476
+ *
477
+ * Convenience wrapper that uses global platform analytics.
478
+ * Does nothing if analytics is not configured.
479
+ *
480
+ * NOTE: For context-based analytics, use trackEvent() from '../analytics/with-analytics'.
481
+ * This helper uses global singleton, not request-scoped context.
482
+ *
483
+ * @param event - Event name
484
+ * @param properties - Event properties
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * import { trackAnalyticsEvent } from '@kb-labs/shared-command-kit/helpers';
489
+ *
490
+ * // No need to check if analytics exists
491
+ * await trackAnalyticsEvent('release_completed', { version: '1.0.0', packages: 5 });
492
+ * ```
493
+ */
494
+ declare function trackAnalyticsEvent(event: string, properties?: Record<string, unknown>): Promise<void>;
495
+
496
+ /**
497
+ * @module @kb-labs/shared-command-kit/helpers/use-storage
498
+ * Global storage access helper
499
+ *
500
+ * Provides clean access to file/blob storage adapter.
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * import { useStorage } from '@kb-labs/shared-command-kit';
505
+ *
506
+ * async handler(ctx, argv, flags) {
507
+ * const storage = useStorage();
508
+ *
509
+ * if (storage) {
510
+ * await storage.write('path/to/file.txt', 'content');
511
+ * const content = await storage.read('path/to/file.txt');
512
+ * }
513
+ * }
514
+ * ```
515
+ */
516
+
517
+ /**
518
+ * Access global storage adapter
519
+ *
520
+ * Returns the platform storage adapter for file/blob operations.
521
+ * Returns undefined if storage is not configured (graceful degradation).
522
+ *
523
+ * **Methods:**
524
+ * - `storage.read(path)` - Read file content
525
+ * - `storage.write(path, content)` - Write file content
526
+ * - `storage.exists(path)` - Check if file exists
527
+ * - `storage.delete(path)` - Delete file
528
+ * - `storage.list(prefix?)` - List files
529
+ *
530
+ * **Always check availability:**
531
+ * ```typescript
532
+ * const storage = useStorage();
533
+ * if (storage) {
534
+ * await storage.write('file.txt', 'content');
535
+ * }
536
+ * ```
537
+ *
538
+ * @returns Storage adapter or undefined if not configured
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * const storage = useStorage();
543
+ *
544
+ * if (storage) {
545
+ * // Write file
546
+ * await storage.write('releases/v1.0.0.json', JSON.stringify(data));
547
+ *
548
+ * // Read file
549
+ * const content = await storage.read('releases/v1.0.0.json');
550
+ * const data = JSON.parse(content);
551
+ *
552
+ * // Check existence
553
+ * const exists = await storage.exists('releases/v1.0.0.json');
554
+ *
555
+ * // List files
556
+ * const files = await storage.list('releases/');
557
+ * }
558
+ * ```
559
+ */
560
+ declare function useStorage(): IStorage | undefined;
561
+
562
+ /**
563
+ * @module @kb-labs/shared-command-kit/helpers/use-cache
564
+ * Global Cache access helper
565
+ *
566
+ * Provides clean access to platform cache (Redis, InMemory, or custom adapter).
567
+ *
568
+ * @example
569
+ * ```typescript
570
+ * import { useCache } from '@kb-labs/shared-command-kit';
571
+ *
572
+ * async handler(ctx, argv, flags) {
573
+ * const cache = useCache();
574
+ *
575
+ * if (cache) {
576
+ * await cache.set('key', { data: 'value' }, 60000); // TTL: 60s
577
+ * const value = await cache.get('key');
578
+ * console.log(value);
579
+ * }
580
+ * }
581
+ * ```
582
+ */
583
+
584
+ /**
585
+ * Access global cache adapter
586
+ *
587
+ * Returns the platform cache adapter (Redis, InMemory, or custom).
588
+ * Returns undefined if cache is not configured (graceful degradation).
589
+ *
590
+ * **Methods:**
591
+ * - `cache.set(key, value, ttlMs?)` - Store value with optional TTL
592
+ * - `cache.get<T>(key)` - Retrieve value by key
593
+ * - `cache.delete(key)` - Remove value
594
+ * - `cache.clear()` - Clear all cached values
595
+ *
596
+ * **Always check availability:**
597
+ * ```typescript
598
+ * const cache = useCache();
599
+ * if (cache) {
600
+ * await cache.set('query-123', result, 60000);
601
+ * } else {
602
+ * // No caching, compute every time
603
+ * }
604
+ * ```
605
+ *
606
+ * @returns Cache adapter or undefined if not configured
607
+ *
608
+ * @example
609
+ * ```typescript
610
+ * const cache = useCache();
611
+ *
612
+ * if (cache) {
613
+ * // Check cache first
614
+ * const cached = await cache.get<QueryResult>('query-123');
615
+ * if (cached) {
616
+ * return cached;
617
+ * }
618
+ *
619
+ * // Compute result
620
+ * const result = await expensiveQuery();
621
+ *
622
+ * // Cache for 5 minutes
623
+ * await cache.set('query-123', result, 5 * 60 * 1000);
624
+ *
625
+ * return result;
626
+ * }
627
+ * ```
628
+ */
629
+ declare function useCache(): ICache | undefined;
630
+ /**
631
+ * Check if cache is available
632
+ *
633
+ * Useful for conditional logic (cached vs non-cached execution).
634
+ *
635
+ * @returns true if cache is configured and ready
636
+ *
637
+ * @example
638
+ * ```typescript
639
+ * if (isCacheAvailable()) {
640
+ * // Use cached results
641
+ * const result = await getCachedOrCompute(key);
642
+ * } else {
643
+ * // Compute every time
644
+ * const result = await compute();
645
+ * }
646
+ * ```
647
+ */
648
+ declare function isCacheAvailable(): boolean;
649
+
650
+ export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };