@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,274 @@
1
+ import { platform } from '@kb-labs/core-runtime';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/helpers/use-platform.ts
14
+ var use_platform_exports = {};
15
+ __export(use_platform_exports, {
16
+ isPlatformConfigured: () => isPlatformConfigured,
17
+ usePlatform: () => usePlatform
18
+ });
19
+ function usePlatform() {
20
+ return platform;
21
+ }
22
+ function isPlatformConfigured(adapterName) {
23
+ const platform = usePlatform();
24
+ const adapter = platform[adapterName];
25
+ if (!adapter) {
26
+ return false;
27
+ }
28
+ if ("hasAdapter" in platform && typeof platform.hasAdapter === "function") {
29
+ return platform.hasAdapter(adapterName);
30
+ }
31
+ if (typeof adapter === "object" && adapter.constructor) {
32
+ const constructorName = adapter.constructor.name;
33
+ return !constructorName.toLowerCase().includes("noop") && !constructorName.toLowerCase().includes("fallback");
34
+ }
35
+ return true;
36
+ }
37
+ var init_use_platform = __esm({
38
+ "src/helpers/use-platform.ts"() {
39
+ }
40
+ });
41
+
42
+ // src/helpers/index.ts
43
+ init_use_platform();
44
+
45
+ // src/helpers/use-config.ts
46
+ async function useConfig(productId, profileId) {
47
+ let effectiveProductId = productId;
48
+ if (!effectiveProductId) {
49
+ effectiveProductId = globalThis.__KB_CONFIG_SECTION__;
50
+ }
51
+ if (!effectiveProductId) {
52
+ return void 0;
53
+ }
54
+ const { usePlatform: usePlatform2 } = await Promise.resolve().then(() => (init_use_platform(), use_platform_exports));
55
+ const platform = usePlatform2();
56
+ if (!platform) {
57
+ return void 0;
58
+ }
59
+ return await platform.config.getConfig(effectiveProductId, profileId);
60
+ }
61
+
62
+ // src/helpers/use-logger.ts
63
+ init_use_platform();
64
+ function useLogger() {
65
+ const platform = usePlatform();
66
+ return platform.logger;
67
+ }
68
+ function useLoggerWithContext(context) {
69
+ const logger = useLogger();
70
+ return logger.child(context);
71
+ }
72
+
73
+ // src/helpers/use-llm.ts
74
+ init_use_platform();
75
+ function useLLM(options) {
76
+ const platform = usePlatform();
77
+ const llm = platform.llm;
78
+ if (!llm) {
79
+ return void 0;
80
+ }
81
+ if (options && isLLMRouter(llm)) {
82
+ return new LazyBoundLLM(llm, options);
83
+ }
84
+ return llm;
85
+ }
86
+ var LazyBoundLLM = class {
87
+ constructor(router, options) {
88
+ this.router = router;
89
+ this.options = options;
90
+ }
91
+ _resolved = null;
92
+ resolve() {
93
+ if (!this._resolved) {
94
+ this._resolved = this.router.resolveAdapter(this.options);
95
+ }
96
+ return this._resolved;
97
+ }
98
+ mergeExecutionPolicy(callOptions) {
99
+ const globalPolicy = this.options.execution;
100
+ const localPolicy = callOptions?.execution;
101
+ if (!globalPolicy && !localPolicy) {
102
+ return void 0;
103
+ }
104
+ return {
105
+ ...globalPolicy,
106
+ ...localPolicy,
107
+ cache: { ...globalPolicy?.cache, ...localPolicy?.cache },
108
+ stream: { ...globalPolicy?.stream, ...localPolicy?.stream }
109
+ };
110
+ }
111
+ async resolveProtocolCapabilities(adapter) {
112
+ if (!adapter.getProtocolCapabilities) {
113
+ return {
114
+ cache: { supported: false },
115
+ stream: { supported: true }
116
+ };
117
+ }
118
+ return adapter.getProtocolCapabilities();
119
+ }
120
+ enforceCachePolicy(caps, execution) {
121
+ if (execution?.cache?.mode === "require" && !caps.cache.supported) {
122
+ throw new Error("CACHE_NOT_SUPPORTED: adapter does not support required cache policy");
123
+ }
124
+ }
125
+ buildDecisionTrace(caps, execution, streamAppliedMode, streamFallback, reason) {
126
+ const requestedCacheMode = execution?.cache?.mode ?? "prefer";
127
+ const requestedStreamMode = execution?.stream?.mode ?? "prefer";
128
+ return {
129
+ cacheRequestedMode: requestedCacheMode,
130
+ cacheSupported: caps.cache.supported,
131
+ cacheAppliedMode: requestedCacheMode === "require" || requestedCacheMode === "bypass" ? requestedCacheMode : caps.cache.supported ? "prefer" : "bypass",
132
+ streamRequestedMode: requestedStreamMode,
133
+ streamSupported: caps.stream.supported,
134
+ streamAppliedMode,
135
+ streamFallback,
136
+ reason
137
+ };
138
+ }
139
+ withDecisionMetadata(options, trace) {
140
+ if (!options) {
141
+ return { metadata: { cacheDecisionTrace: trace } };
142
+ }
143
+ return {
144
+ ...options,
145
+ metadata: {
146
+ ...options.metadata,
147
+ cacheDecisionTrace: trace
148
+ }
149
+ };
150
+ }
151
+ async complete(prompt, options) {
152
+ const { adapter, model } = await this.resolve();
153
+ const execution = this.mergeExecutionPolicy(options);
154
+ const caps = await this.resolveProtocolCapabilities(adapter);
155
+ this.enforceCachePolicy(caps, execution);
156
+ const trace = this.buildDecisionTrace(caps, execution, "off");
157
+ const optionsWithTrace = this.withDecisionMetadata(options, trace);
158
+ return adapter.complete(prompt, { ...optionsWithTrace, model, execution });
159
+ }
160
+ async *stream(prompt, options) {
161
+ const { adapter, model } = await this.resolve();
162
+ const execution = this.mergeExecutionPolicy(options);
163
+ const caps = await this.resolveProtocolCapabilities(adapter);
164
+ this.enforceCachePolicy(caps, execution);
165
+ const streamMode = execution?.stream?.mode ?? "prefer";
166
+ const canStream = caps.stream.supported;
167
+ const allowFallback = execution?.stream?.fallbackToComplete ?? true;
168
+ if (streamMode === "off" || !canStream && streamMode === "prefer" && allowFallback) {
169
+ const fallbackReason = streamMode === "off" ? "STREAM_OFF" : "STREAM_UNSUPPORTED_FALLBACK_TO_COMPLETE";
170
+ const trace2 = this.buildDecisionTrace(caps, execution, "off", "complete", fallbackReason);
171
+ const optionsWithTrace2 = this.withDecisionMetadata(options, trace2);
172
+ const response = await adapter.complete(prompt, { ...optionsWithTrace2, model, execution });
173
+ if (response.content) {
174
+ yield response.content;
175
+ }
176
+ return;
177
+ }
178
+ if (!canStream && streamMode === "require") {
179
+ throw new Error("STREAM_NOT_SUPPORTED: adapter does not support required streaming");
180
+ }
181
+ const trace = this.buildDecisionTrace(caps, execution, streamMode);
182
+ const optionsWithTrace = this.withDecisionMetadata(options, trace);
183
+ yield* adapter.stream(prompt, { ...optionsWithTrace, model, execution });
184
+ }
185
+ async chatWithTools(messages, options) {
186
+ const { adapter, model, tier } = await this.resolve();
187
+ const execution = this.mergeExecutionPolicy(options);
188
+ const caps = await this.resolveProtocolCapabilities(adapter);
189
+ this.enforceCachePolicy(caps, execution);
190
+ if (!adapter.chatWithTools) {
191
+ throw new Error("Current adapter does not support chatWithTools");
192
+ }
193
+ const trace = this.buildDecisionTrace(caps, execution, "off");
194
+ const optionsWithTrace = this.withDecisionMetadata(options, trace);
195
+ return adapter.chatWithTools(messages, {
196
+ ...optionsWithTrace,
197
+ model,
198
+ execution,
199
+ metadata: { ...optionsWithTrace.metadata, tier }
200
+ });
201
+ }
202
+ };
203
+ function isLLMAvailable() {
204
+ const llm = useLLM();
205
+ return !!llm;
206
+ }
207
+ function getLLMTier() {
208
+ const platform = usePlatform();
209
+ const llm = platform.llm;
210
+ if (llm && isLLMRouter(llm)) {
211
+ return llm.getConfiguredTier();
212
+ }
213
+ return void 0;
214
+ }
215
+ function isLLMRouter(llm) {
216
+ return typeof llm.getConfiguredTier === "function" && typeof llm.resolve === "function";
217
+ }
218
+
219
+ // src/helpers/use-embeddings.ts
220
+ init_use_platform();
221
+ function useEmbeddings() {
222
+ const platform = usePlatform();
223
+ return platform.embeddings;
224
+ }
225
+ function isEmbeddingsAvailable() {
226
+ const embeddings = useEmbeddings();
227
+ return !!embeddings;
228
+ }
229
+
230
+ // src/helpers/use-vector-store.ts
231
+ init_use_platform();
232
+ function useVectorStore() {
233
+ const platform = usePlatform();
234
+ return platform.vectorStore;
235
+ }
236
+ function isVectorStoreAvailable() {
237
+ const vectorStore = useVectorStore();
238
+ return !!vectorStore;
239
+ }
240
+
241
+ // src/helpers/use-analytics.ts
242
+ init_use_platform();
243
+ function useAnalytics() {
244
+ const platform = usePlatform();
245
+ return platform.analytics;
246
+ }
247
+ async function trackAnalyticsEvent(event, properties) {
248
+ const analytics = useAnalytics();
249
+ if (analytics) {
250
+ await analytics.track(event, properties);
251
+ }
252
+ }
253
+
254
+ // src/helpers/use-storage.ts
255
+ init_use_platform();
256
+ function useStorage() {
257
+ const platform = usePlatform();
258
+ return platform.storage;
259
+ }
260
+
261
+ // src/helpers/use-cache.ts
262
+ init_use_platform();
263
+ function useCache() {
264
+ const platform = usePlatform();
265
+ return platform.cache;
266
+ }
267
+ function isCacheAvailable() {
268
+ const cache = useCache();
269
+ return !!cache;
270
+ }
271
+
272
+ export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
273
+ //# sourceMappingURL=index.js.map
274
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/helpers/use-platform.ts","../../src/helpers/index.ts","../../src/helpers/use-config.ts","../../src/helpers/use-logger.ts","../../src/helpers/use-llm.ts","../../src/helpers/use-embeddings.ts","../../src/helpers/use-vector-store.ts","../../src/helpers/use-analytics.ts","../../src/helpers/use-storage.ts","../../src/helpers/use-cache.ts"],"names":["globalPlatform","usePlatform","trace","optionsWithTrace"],"mappings":";;;;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,oBAAA,EAAA,MAAA,oBAAA;AAAA,EAAA,WAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAiEO,SAAS,WAAA,GAAqC;AACnD,EAAA,OAAOA,QAAA;AACT;AAmBO,SAAS,qBAAqB,WAAA,EAAmD;AAC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;AChDA,iBAAA,EAAA;AAgDO,SAAS,QAAA,GAA+B;AAC7C,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,OAAO,QAAA,CAAS,KAAA;AAClB;AAoBO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,QAAQ,QAAA,EAAS;AACvB,EAAA,OAAO,CAAC,CAAC,KAAA;AACX","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/shared-command-kit/helpers/use-platform\n * Global platform singleton access helper\n *\n * Provides clean access to platform services without context drilling.\n * Similar to React hooks pattern, but for KB Labs platform.\n *\n * @example\n * ```typescript\n * import { usePlatform } from '@kb-labs/shared-command-kit';\n *\n * // In any command handler\n * async handler(ctx, argv, flags) {\n * const platform = usePlatform();\n *\n * if (platform.llm) {\n * const result = await platform.llm.complete('prompt');\n * }\n *\n * await platform.logger.info('Task completed');\n * }\n * ```\n */\n\nimport { platform as globalPlatform } from '@kb-labs/core-runtime';\n\n/**\n * Access global platform singleton\n *\n * Returns the initialized platform object with all registered adapters.\n * This is the single source of truth for platform services.\n *\n * **What's available:**\n * - `platform.llm` - LLM adapter (OpenAI, Anthropic, etc.)\n * - `platform.embeddings` - Embeddings adapter\n * - `platform.vectorStore` - Vector storage (Qdrant, local, etc.)\n * - `platform.storage` - File/blob storage\n * - `platform.cache` - Caching layer\n * - `platform.analytics` - Analytics/telemetry\n * - `platform.logger` - Structured logging\n * - `platform.eventBus` - Event system\n * - `platform.workflows` - Workflow engine\n * - `platform.jobs` - Background jobs\n * - `platform.cron` - Scheduled tasks\n * - `platform.resources` - Resource management\n * - `platform.invoke` - Plugin invocation\n * - `platform.artifacts` - Build artifacts\n *\n * **Graceful degradation:**\n * Always check if adapter is available before using:\n * ```typescript\n * const platform = usePlatform();\n * if (platform.llm) {\n * // Use LLM\n * } else {\n * // Fallback logic\n * }\n * ```\n *\n * **Multi-tenancy:**\n * Currently returns global singleton (single-tenant).\n * Future: Will support tenant-scoped platform via AsyncLocalStorage.\n *\n * @returns Global platform singleton\n */\nexport function usePlatform(): typeof globalPlatform {\n return globalPlatform;\n}\n\n/**\n * Check if specific platform adapter is configured\n *\n * Useful for conditional logic based on available services.\n *\n * @param adapterName - Name of the adapter to check\n * @returns true if adapter is configured and available\n *\n * @example\n * ```typescript\n * if (isPlatformConfigured('llm')) {\n * // Use LLM-powered feature\n * } else {\n * // Use deterministic fallback\n * }\n * ```\n */\nexport function isPlatformConfigured(adapterName: keyof typeof globalPlatform): boolean {\n const platform = usePlatform();\n\n // Check if adapter exists and is not a noop/fallback\n const adapter = platform[adapterName];\n\n if (!adapter) {\n return false;\n }\n\n // For adapters with hasAdapter method (like platform itself)\n if ('hasAdapter' in platform && typeof platform.hasAdapter === 'function') {\n return platform.hasAdapter(adapterName as any);\n }\n\n // Fallback: check if adapter is not noop\n // Noop adapters usually have a specific constructor name or are simple objects\n if (typeof adapter === 'object' && adapter.constructor) {\n const constructorName = adapter.constructor.name;\n return !constructorName.toLowerCase().includes('noop') &&\n !constructorName.toLowerCase().includes('fallback');\n }\n\n return true;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers\n * Global platform access helpers\n *\n * Provides clean, type-safe access to platform services without context drilling.\n * Similar to React hooks pattern, but for KB Labs platform.\n *\n * @example\n * ```typescript\n * import { useLLM, useLogger, useAnalytics } from '@kb-labs/shared-command-kit/helpers';\n *\n * async handler(ctx, argv, flags) {\n * const logger = useLogger();\n * const llm = useLLM();\n *\n * await logger.info('Processing started');\n *\n * if (llm) {\n * const result = await llm.complete('prompt');\n * await logger.info('LLM result', { length: result.content.length });\n * }\n * }\n * ```\n */\n\n// Platform singleton\nexport { usePlatform, isPlatformConfigured } from './use-platform';\n\n// Context types and helpers\nexport type { PluginContextV3 } from './context';\n\n// Config access\nexport { useConfig } from './use-config';\n\n// Core services\nexport { useLogger, useLoggerWithContext } from './use-logger.js';\nexport { useLLM, isLLMAvailable, getLLMTier, type LLMTier, type UseLLMOptions } from './use-llm.js';\nexport { useEmbeddings, isEmbeddingsAvailable } from './use-embeddings.js';\nexport { useVectorStore, isVectorStoreAvailable } from './use-vector-store.js';\nexport { useAnalytics, trackAnalyticsEvent } from './use-analytics.js';\nexport { useStorage } from './use-storage.js';\nexport { useCache, isCacheAvailable } from './use-cache.js';\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-config\n * Global config access helper\n *\n * Provides clean access to product-specific configuration without context drilling.\n * Similar to React hooks pattern, but for KB Labs config.\n *\n * @example\n * ```typescript\n * import { useConfig } from '@kb-labs/shared-command-kit';\n *\n * // In any command handler\n * async handler(ctx, argv, flags) {\n * const config = await useConfig('mind');\n *\n * if (config) {\n * const scopes = config.scopes;\n * // Use config...\n * }\n * }\n * ```\n */\n\n/**\n * Access product-specific configuration from kb.config.json\n *\n * Returns ONLY the config for the specified product and profile.\n * Uses platform.config adapter (works across parent/child processes via IPC).\n * Supports both Profiles v2 and legacy config structures.\n *\n * **Security:** This function returns ONLY the product-specific config,\n * not the entire kb.config.json. This prevents cross-product config access.\n *\n * **Auto-detection:** If productId is not provided, it's automatically inferred\n * from the plugin's manifest.configSection field (passed via execution context).\n *\n * **Profiles v2 structure:**\n * ```json\n * {\n * \"profiles\": [\n * {\n * \"id\": \"default\",\n * \"products\": {\n * \"mind\": { \"scopes\": [...] },\n * \"workflow\": { \"maxConcurrency\": 10 }\n * }\n * }\n * ]\n * }\n * ```\n *\n * **Legacy structure:**\n * ```json\n * {\n * \"knowledge\": { \"scopes\": [...] }, // for \"mind\" product\n * \"workflow\": { \"maxConcurrency\": 10 }\n * }\n * ```\n *\n * @param productId - Product identifier (e.g., 'mind', 'workflow', 'plugins'). Optional - auto-detected from context.\n * @param profileId - Profile identifier (defaults to 'default' or KB_PROFILE env var)\n * @returns Promise resolving to product-specific config or undefined\n *\n * @example\n * ```typescript\n * // Auto-detect from context (recommended)\n * const config = await useConfig();\n *\n * // Explicit product ID\n * const mindConfig = await useConfig('mind');\n * if (mindConfig?.scopes) {\n * // Use scopes\n * }\n *\n * // With explicit profile\n * const workflowConfig = await useConfig('workflow', 'production');\n * ```\n */\nexport async function useConfig<T = any>(productId?: string, profileId?: string): Promise<T | undefined> {\n // Auto-detect productId from manifest.configSection if not provided\n let effectiveProductId = productId;\n if (!effectiveProductId) {\n effectiveProductId = (globalThis as any).__KB_CONFIG_SECTION__;\n }\n\n if (!effectiveProductId) {\n return undefined;\n }\n\n const { usePlatform } = await import('./use-platform.js');\n const platform = usePlatform();\n\n if (!platform) {\n return undefined;\n }\n\n // Returns ONLY the product-specific config, not the entire kb.config.json\n return await platform.config.getConfig(effectiveProductId, profileId) as T | undefined;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-logger\n * Global logger access helper\n *\n * Provides clean access to structured logging without context drilling.\n *\n * @example\n * ```typescript\n * import { useLogger } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * const logger = useLogger();\n *\n * await logger.info('Processing started');\n * await logger.debug('Details', { userId: 123 });\n * await logger.error('Failed', { error: err });\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform';\nimport type { ILogger } from '@kb-labs/core-platform';\n\n/**\n * Access global logger\n *\n * Returns the platform logger with structured logging capabilities.\n * Supports child loggers with additional context.\n *\n * **Methods:**\n * - `logger.trace(message, meta?)` - Trace-level logs (most verbose)\n * - `logger.debug(message, meta?)` - Debug-level logs\n * - `logger.info(message, meta?)` - Info-level logs\n * - `logger.warn(message, meta?)` - Warning-level logs\n * - `logger.error(message, meta?)` - Error-level logs\n * - `logger.child(meta)` - Create child logger with additional context\n *\n * @returns Platform logger instance\n *\n * @example\n * ```typescript\n * const logger = useLogger();\n *\n * await logger.info('Task started', { taskId: '123' });\n * await logger.error('Task failed', { taskId: '123', error: err.message });\n *\n * // Child logger with persistent context\n * const taskLogger = logger.child({ taskId: '123', userId: 'user-1' });\n * await taskLogger.info('Step 1 completed');\n * await taskLogger.info('Step 2 completed');\n * ```\n */\nexport function useLogger(): ILogger {\n const platform = usePlatform();\n return platform.logger;\n}\n\n/**\n * Create child logger with additional context\n *\n * Useful for scoped logging within a specific operation.\n *\n * @param context - Additional context to attach to all log entries\n * @returns Child logger with persistent context\n *\n * @example\n * ```typescript\n * const logger = useLoggerWithContext({ operation: 'release', version: '1.0.0' });\n *\n * await logger.info('Started'); // Automatically includes operation + version\n * await logger.info('Completed');\n * ```\n */\nexport function useLoggerWithContext(context: Record<string, unknown>): ILogger {\n const logger = useLogger();\n return logger.child(context);\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-llm\n * Global LLM access helper with tier-based model selection.\n *\n * Provides clean access to LLM with adaptive tier routing.\n * Plugins specify tiers (small/medium/large), platform resolves to actual models.\n *\n * @example\n * ```typescript\n * import { useLLM } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * // Simple usage (uses configured default tier)\n * const llm = useLLM();\n *\n * // Request specific tier (platform adapts if needed)\n * const llm = useLLM({ tier: 'small' }); // Simple tasks\n * const llm = useLLM({ tier: 'large' }); // Complex tasks\n *\n * // Request capabilities\n * const llm = useLLM({ tier: 'medium', capabilities: ['coding'] });\n *\n * if (llm) {\n * const result = await llm.complete('Explain this code');\n * console.log(result.content);\n * }\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform.js';\nimport type {\n ILLM,\n LLMTier,\n LLMOptions,\n LLMResponse,\n LLMMessage,\n LLMToolCallOptions,\n LLMToolCallResponse,\n UseLLMOptions,\n ILLMRouter,\n LLMAdapterBinding,\n LLMExecutionPolicy,\n LLMProtocolCapabilities,\n LLMCacheDecisionTrace,\n} from '@kb-labs/core-platform';\n\n/**\n * Access global LLM adapter with tier-based selection.\n *\n * Platform automatically adapts to available models:\n * - If plugin requests 'small' but 'medium' configured → uses 'medium' (escalation)\n * - If plugin requests 'large' but 'medium' configured → uses 'medium' with warning (degradation)\n *\n * **Tiers are user-defined slots:**\n * - `small` - Plugin says: \"This task is simple\"\n * - `medium` - Plugin says: \"Standard task\"\n * - `large` - Plugin says: \"Complex task, need maximum quality\"\n *\n * User decides what model maps to each tier in their config.\n *\n * @param options - Optional tier and capability requirements\n * @returns LLM adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * // Simple usage (uses configured default)\n * const llm = useLLM();\n *\n * // Request specific tier\n * const llm = useLLM({ tier: 'small' }); // Simple tasks\n * const llm = useLLM({ tier: 'large' }); // Complex tasks\n *\n * // Request capabilities\n * const llm = useLLM({ tier: 'medium', capabilities: ['coding'] });\n * const llm = useLLM({ capabilities: ['vision'] });\n *\n * if (llm) {\n * const result = await llm.complete('Generate commit message');\n * console.log(result.content);\n * }\n * ```\n */\nexport function useLLM(options?: UseLLMOptions): ILLM | undefined {\n const platform = usePlatform();\n const llm = platform.llm;\n\n if (!llm) {\n return undefined;\n }\n\n // If router and options given → return immutable LazyBoundLLM (no state mutation)\n if (options && isLLMRouter(llm)) {\n return new LazyBoundLLM(llm, options);\n }\n\n return llm;\n}\n\n/**\n * Lazy adapter binding that resolves tier on first use.\n * Immutable — does NOT mutate the global LLMRouter state.\n * This fixes the race condition where useLLM({ tier: 'large' }) was immediately\n * overwritten by useLLM({ tier: 'small' }) from SmartSummarizer.\n */\nclass LazyBoundLLM implements ILLM {\n private _resolved: Promise<LLMAdapterBinding> | null = null;\n\n constructor(\n private readonly router: ILLM & ILLMRouter,\n private readonly options: UseLLMOptions,\n ) {}\n\n private resolve(): Promise<LLMAdapterBinding> {\n if (!this._resolved) {\n this._resolved = this.router.resolveAdapter(this.options);\n }\n return this._resolved;\n }\n\n private mergeExecutionPolicy(callOptions?: LLMOptions): LLMExecutionPolicy | undefined {\n const globalPolicy = this.options.execution;\n const localPolicy = callOptions?.execution;\n if (!globalPolicy && !localPolicy) {\n return undefined;\n }\n return {\n ...globalPolicy,\n ...localPolicy,\n cache: { ...globalPolicy?.cache, ...localPolicy?.cache },\n stream: { ...globalPolicy?.stream, ...localPolicy?.stream },\n };\n }\n\n private async resolveProtocolCapabilities(adapter: ILLM): Promise<LLMProtocolCapabilities> {\n if (!adapter.getProtocolCapabilities) {\n return {\n cache: { supported: false },\n stream: { supported: true },\n };\n }\n return adapter.getProtocolCapabilities();\n }\n\n private enforceCachePolicy(caps: LLMProtocolCapabilities, execution?: LLMExecutionPolicy): void {\n if (execution?.cache?.mode === 'require' && !caps.cache.supported) {\n throw new Error('CACHE_NOT_SUPPORTED: adapter does not support required cache policy');\n }\n }\n\n private buildDecisionTrace(\n caps: LLMProtocolCapabilities,\n execution: LLMExecutionPolicy | undefined,\n streamAppliedMode: 'prefer' | 'require' | 'off',\n streamFallback?: 'complete',\n reason?: string,\n ): LLMCacheDecisionTrace {\n const requestedCacheMode = execution?.cache?.mode ?? 'prefer';\n const requestedStreamMode = execution?.stream?.mode ?? 'prefer';\n\n return {\n cacheRequestedMode: requestedCacheMode,\n cacheSupported: caps.cache.supported,\n cacheAppliedMode:\n requestedCacheMode === 'require' || requestedCacheMode === 'bypass'\n ? requestedCacheMode\n : caps.cache.supported\n ? 'prefer'\n : 'bypass',\n streamRequestedMode: requestedStreamMode,\n streamSupported: caps.stream.supported,\n streamAppliedMode,\n streamFallback,\n reason,\n };\n }\n\n private withDecisionMetadata(\n options: LLMOptions | undefined,\n trace: LLMCacheDecisionTrace,\n ): LLMOptions | undefined {\n if (!options) {\n return { metadata: { cacheDecisionTrace: trace } };\n }\n\n return {\n ...options,\n metadata: {\n ...options.metadata,\n cacheDecisionTrace: trace,\n },\n };\n }\n\n async complete(prompt: string, options?: LLMOptions): Promise<LLMResponse> {\n const { adapter, model } = await this.resolve();\n const execution = this.mergeExecutionPolicy(options);\n const caps = await this.resolveProtocolCapabilities(adapter);\n this.enforceCachePolicy(caps, execution);\n const trace = this.buildDecisionTrace(caps, execution, 'off');\n const optionsWithTrace = this.withDecisionMetadata(options, trace);\n return adapter.complete(prompt, { ...optionsWithTrace, model, execution });\n }\n\n async *stream(prompt: string, options?: LLMOptions): AsyncIterable<string> {\n const { adapter, model } = await this.resolve();\n const execution = this.mergeExecutionPolicy(options);\n const caps = await this.resolveProtocolCapabilities(adapter);\n this.enforceCachePolicy(caps, execution);\n\n const streamMode = execution?.stream?.mode ?? 'prefer';\n const canStream = caps.stream.supported;\n const allowFallback = execution?.stream?.fallbackToComplete ?? true;\n\n if (streamMode === 'off' || (!canStream && streamMode === 'prefer' && allowFallback)) {\n const fallbackReason =\n streamMode === 'off'\n ? 'STREAM_OFF'\n : 'STREAM_UNSUPPORTED_FALLBACK_TO_COMPLETE';\n const trace = this.buildDecisionTrace(caps, execution, 'off', 'complete', fallbackReason);\n const optionsWithTrace = this.withDecisionMetadata(options, trace);\n const response = await adapter.complete(prompt, { ...optionsWithTrace, model, execution });\n if (response.content) {\n yield response.content;\n }\n return;\n }\n\n if (!canStream && streamMode === 'require') {\n throw new Error('STREAM_NOT_SUPPORTED: adapter does not support required streaming');\n }\n\n const trace = this.buildDecisionTrace(caps, execution, streamMode);\n const optionsWithTrace = this.withDecisionMetadata(options, trace);\n yield* adapter.stream(prompt, { ...optionsWithTrace, model, execution });\n }\n\n async chatWithTools(\n messages: LLMMessage[],\n options: LLMToolCallOptions,\n ): Promise<LLMToolCallResponse> {\n const { adapter, model, tier } = await this.resolve();\n const execution = this.mergeExecutionPolicy(options);\n const caps = await this.resolveProtocolCapabilities(adapter);\n this.enforceCachePolicy(caps, execution);\n if (!adapter.chatWithTools) {\n throw new Error('Current adapter does not support chatWithTools');\n }\n const trace = this.buildDecisionTrace(caps, execution, 'off');\n const optionsWithTrace = this.withDecisionMetadata(options, trace) as LLMToolCallOptions;\n return adapter.chatWithTools(messages, {\n ...optionsWithTrace,\n model,\n execution,\n metadata: { ...optionsWithTrace.metadata, tier },\n });\n }\n}\n\n/**\n * Check if LLM is available.\n *\n * Useful for conditional logic (LLM-powered vs deterministic fallback).\n *\n * @returns true if LLM is configured and ready\n *\n * @example\n * ```typescript\n * if (isLLMAvailable()) {\n * const summary = await generateWithLLM(data);\n * } else {\n * const summary = generateDeterministic(data);\n * }\n * ```\n */\nexport function isLLMAvailable(): boolean {\n const llm = useLLM();\n return !!llm;\n}\n\n/**\n * Get configured LLM tier.\n *\n * Useful for diagnostics and logging.\n *\n * @returns Configured tier or undefined if LLM not available/not a router\n *\n * @example\n * ```typescript\n * const tier = getLLMTier();\n * console.log(`Using LLM tier: ${tier ?? 'default'}`);\n * ```\n */\nexport function getLLMTier(): LLMTier | undefined {\n const platform = usePlatform();\n const llm = platform.llm;\n\n if (llm && isLLMRouter(llm)) {\n return llm.getConfiguredTier();\n }\n\n return undefined;\n}\n\n/**\n * Type guard for ILLMRouter.\n */\nfunction isLLMRouter(llm: ILLM): llm is ILLM & ILLMRouter {\n return (\n typeof (llm as unknown as ILLMRouter).getConfiguredTier === 'function' &&\n typeof (llm as unknown as ILLMRouter).resolve === 'function'\n );\n}\n\n// Re-export types for convenience\nexport type { LLMTier, UseLLMOptions } from '@kb-labs/core-platform';\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-embeddings\n * Global Embeddings access helper\n */\n\nimport { usePlatform } from './use-platform';\nimport type { IEmbeddings } from '@kb-labs/core-platform';\n\n/**\n * Access global Embeddings adapter\n *\n * Returns the platform embeddings adapter (OpenAI, etc.).\n * Returns undefined if embeddings is not configured (graceful degradation).\n *\n * @returns Embeddings adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * const embeddings = useEmbeddings();\n *\n * if (embeddings) {\n * const vector = await embeddings.embed('Hello, world!');\n * console.log(vector.length); // e.g., 1536 for OpenAI\n * }\n * ```\n */\nexport function useEmbeddings(): IEmbeddings | undefined {\n const platform = usePlatform();\n return platform.embeddings;\n}\n\n/**\n * Check if Embeddings is available\n *\n * @returns true if embeddings is configured and ready\n *\n * @example\n * ```typescript\n * if (isEmbeddingsAvailable()) {\n * const vector = await embeddings.embed(text);\n * } else {\n * // Use deterministic fallback\n * }\n * ```\n */\nexport function isEmbeddingsAvailable(): boolean {\n const embeddings = useEmbeddings();\n return !!embeddings;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-vector-store\n * Global VectorStore access helper\n */\n\nimport { usePlatform } from './use-platform';\nimport type { IVectorStore } from '@kb-labs/core-platform';\n\n/**\n * Access global VectorStore adapter\n *\n * Returns the platform vector store adapter (Qdrant, local, etc.).\n * Returns undefined if vectorStore is not configured (graceful degradation).\n *\n * @returns VectorStore adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * const vectorStore = useVectorStore();\n *\n * if (vectorStore) {\n * await vectorStore.upsert([{ id: '1', vector: [0.1, 0.2], metadata: {} }]);\n * const results = await vectorStore.search([0.1, 0.2], 10);\n * }\n * ```\n */\nexport function useVectorStore(): IVectorStore | undefined {\n const platform = usePlatform();\n return platform.vectorStore;\n}\n\n/**\n * Check if VectorStore is available\n *\n * @returns true if vectorStore is configured and ready\n *\n * @example\n * ```typescript\n * if (isVectorStoreAvailable()) {\n * await vectorStore.upsert(records);\n * } else {\n * // Use local fallback\n * }\n * ```\n */\nexport function isVectorStoreAvailable(): boolean {\n const vectorStore = useVectorStore();\n return !!vectorStore;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-analytics\n * Global analytics access helper\n *\n * Provides clean access to analytics/telemetry without context drilling.\n *\n * @example\n * ```typescript\n * import { useAnalytics } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * const analytics = useAnalytics();\n *\n * if (analytics) {\n * await analytics.track('release_started', { version: '1.0.0' });\n * analytics.metric('release_duration_ms', 1234);\n * }\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform';\nimport type { IAnalytics } from '@kb-labs/core-platform';\n\n/**\n * Access global analytics adapter\n *\n * Returns the platform analytics adapter for tracking events and metrics.\n * Returns undefined if analytics is not configured (graceful degradation).\n *\n * **Methods:**\n * - `analytics.track(event, properties?)` - Track events\n * - `analytics.metric(name, value, tags?)` - Record metrics\n *\n * **Always check availability:**\n * ```typescript\n * const analytics = useAnalytics();\n * if (analytics) {\n * await analytics.track('event');\n * }\n * ```\n *\n * @returns Analytics adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * const analytics = useAnalytics();\n *\n * if (analytics) {\n * await analytics.track('command_executed', {\n * command: 'release:run',\n * duration_ms: 1234,\n * success: true,\n * });\n *\n * analytics.metric('release_packages_count', 5, {\n * project: 'kb-labs',\n * });\n * }\n * ```\n */\nexport function useAnalytics(): IAnalytics | undefined {\n const platform = usePlatform();\n return platform.analytics;\n}\n\n/**\n * Track event with analytics (safe, global singleton)\n *\n * Convenience wrapper that uses global platform analytics.\n * Does nothing if analytics is not configured.\n *\n * NOTE: For context-based analytics, use trackEvent() from '../analytics/with-analytics'.\n * This helper uses global singleton, not request-scoped context.\n *\n * @param event - Event name\n * @param properties - Event properties\n *\n * @example\n * ```typescript\n * import { trackAnalyticsEvent } from '@kb-labs/shared-command-kit/helpers';\n *\n * // No need to check if analytics exists\n * await trackAnalyticsEvent('release_completed', { version: '1.0.0', packages: 5 });\n * ```\n */\nexport async function trackAnalyticsEvent(\n event: string,\n properties?: Record<string, unknown>\n): Promise<void> {\n const analytics = useAnalytics();\n if (analytics) {\n await analytics.track(event, properties);\n }\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-storage\n * Global storage access helper\n *\n * Provides clean access to file/blob storage adapter.\n *\n * @example\n * ```typescript\n * import { useStorage } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * const storage = useStorage();\n *\n * if (storage) {\n * await storage.write('path/to/file.txt', 'content');\n * const content = await storage.read('path/to/file.txt');\n * }\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform';\nimport type { IStorage } from '@kb-labs/core-platform';\n\n/**\n * Access global storage adapter\n *\n * Returns the platform storage adapter for file/blob operations.\n * Returns undefined if storage is not configured (graceful degradation).\n *\n * **Methods:**\n * - `storage.read(path)` - Read file content\n * - `storage.write(path, content)` - Write file content\n * - `storage.exists(path)` - Check if file exists\n * - `storage.delete(path)` - Delete file\n * - `storage.list(prefix?)` - List files\n *\n * **Always check availability:**\n * ```typescript\n * const storage = useStorage();\n * if (storage) {\n * await storage.write('file.txt', 'content');\n * }\n * ```\n *\n * @returns Storage adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * const storage = useStorage();\n *\n * if (storage) {\n * // Write file\n * await storage.write('releases/v1.0.0.json', JSON.stringify(data));\n *\n * // Read file\n * const content = await storage.read('releases/v1.0.0.json');\n * const data = JSON.parse(content);\n *\n * // Check existence\n * const exists = await storage.exists('releases/v1.0.0.json');\n *\n * // List files\n * const files = await storage.list('releases/');\n * }\n * ```\n */\nexport function useStorage(): IStorage | undefined {\n const platform = usePlatform();\n return platform.storage;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-cache\n * Global Cache access helper\n *\n * Provides clean access to platform cache (Redis, InMemory, or custom adapter).\n *\n * @example\n * ```typescript\n * import { useCache } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * const cache = useCache();\n *\n * if (cache) {\n * await cache.set('key', { data: 'value' }, 60000); // TTL: 60s\n * const value = await cache.get('key');\n * console.log(value);\n * }\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform.js';\nimport type { ICache } from '@kb-labs/core-platform';\n\n/**\n * Access global cache adapter\n *\n * Returns the platform cache adapter (Redis, InMemory, or custom).\n * Returns undefined if cache is not configured (graceful degradation).\n *\n * **Methods:**\n * - `cache.set(key, value, ttlMs?)` - Store value with optional TTL\n * - `cache.get<T>(key)` - Retrieve value by key\n * - `cache.delete(key)` - Remove value\n * - `cache.clear()` - Clear all cached values\n *\n * **Always check availability:**\n * ```typescript\n * const cache = useCache();\n * if (cache) {\n * await cache.set('query-123', result, 60000);\n * } else {\n * // No caching, compute every time\n * }\n * ```\n *\n * @returns Cache adapter or undefined if not configured\n *\n * @example\n * ```typescript\n * const cache = useCache();\n *\n * if (cache) {\n * // Check cache first\n * const cached = await cache.get<QueryResult>('query-123');\n * if (cached) {\n * return cached;\n * }\n *\n * // Compute result\n * const result = await expensiveQuery();\n *\n * // Cache for 5 minutes\n * await cache.set('query-123', result, 5 * 60 * 1000);\n *\n * return result;\n * }\n * ```\n */\nexport function useCache(): ICache | undefined {\n const platform = usePlatform();\n return platform.cache;\n}\n\n/**\n * Check if cache is available\n *\n * Useful for conditional logic (cached vs non-cached execution).\n *\n * @returns true if cache is configured and ready\n *\n * @example\n * ```typescript\n * if (isCacheAvailable()) {\n * // Use cached results\n * const result = await getCachedOrCompute(key);\n * } else {\n * // Compute every time\n * const result = await compute();\n * }\n * ```\n */\nexport function isCacheAvailable(): boolean {\n const cache = useCache();\n return !!cache;\n}\n"]}