@kb-labs/shared-command-kit 2.15.0 → 2.17.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.
@@ -613,4 +613,30 @@ declare function useCache(): ICache | undefined;
613
613
  */
614
614
  declare function isCacheAvailable(): boolean;
615
615
 
616
- export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
616
+ /**
617
+ * @module @kb-labs/shared-command-kit/helpers/use-env
618
+ *
619
+ * Sandboxed environment variable access.
620
+ *
621
+ * Reads from runtimeContext (AsyncLocalStorage) when running inside
622
+ * a governed handler execution (worker-pool, subprocess).
623
+ * Falls back to process.env when no runtime context is set
624
+ * (direct CLI, tests, code outside handler).
625
+ *
626
+ * @example
627
+ * ```typescript
628
+ * import { useEnv } from '@kb-labs/sdk';
629
+ *
630
+ * const token = useEnv('NPM_TOKEN');
631
+ * const ci = useEnv('CI');
632
+ * ```
633
+ */
634
+ /**
635
+ * Read an environment variable through the sandboxed runtime context.
636
+ *
637
+ * Inside a governed handler: reads through env-shim (permission-checked).
638
+ * Outside handler context: reads process.env directly (backward compat).
639
+ */
640
+ declare function useEnv(key: string): string | undefined;
641
+
642
+ export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
@@ -1,4 +1,4 @@
1
- import { platformContext } from '@kb-labs/plugin-contracts';
1
+ import { platformContext, runtimeContext } from '@kb-labs/plugin-contracts';
2
2
  import { platform } from '@kb-labs/core-runtime';
3
3
 
4
4
  var __defProp = Object.defineProperty;
@@ -271,7 +271,14 @@ function isCacheAvailable() {
271
271
  const cache = useCache();
272
272
  return !!cache;
273
273
  }
274
+ function useEnv(key) {
275
+ const runtime = runtimeContext.getStore();
276
+ if (runtime?.env) {
277
+ return runtime.env(key);
278
+ }
279
+ return process.env[key];
280
+ }
274
281
 
275
- export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
282
+ export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
276
283
  //# sourceMappingURL=index.js.map
277
284
  //# sourceMappingURL=index.js.map
@@ -1 +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;AAgCO,SAAS,WAAA,GAAqC;AACnD,EAAA,OAAQ,eAAA,CAAgB,UAAS,IAA+BA,QAAA;AAClE;AAmBO,SAAS,qBAAqB,WAAA,EAAmD;AACtF,EAAA,MAAM,WAAW,WAAA,EAAY;AAG7B,EAAA,MAAM,OAAA,GAAU,SAAS,WAAW,CAAA;AAEpC,EAAA,IAAI,CAAC,OAAA,EAAS;AACZ,IA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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 * Platform access hook with execution-scoped context.\n *\n * Uses AsyncLocalStorage to return the correct platform for the current\n * handler execution (governed, with correct permissions and proxy adapters).\n * Falls back to global singleton for code running outside handler context.\n *\n * @example\n * ```typescript\n * import { usePlatform } from '@kb-labs/shared-command-kit';\n *\n * // In any command handler — automatically gets the right platform\n * async handler(ctx, argv, flags) {\n * const platform = usePlatform();\n * const result = await platform.llm.complete('prompt');\n * }\n * ```\n */\n\nimport { platformContext } from '@kb-labs/plugin-contracts';\nimport { platform as globalPlatform } from '@kb-labs/core-runtime';\n\n/**\n * Access platform services for the current execution context.\n *\n * Priority:\n * 1. AsyncLocalStorage context (set by runInProcess) — per-execution, governed\n * 2. Global singleton fallback (core-runtime) — for code outside handler context\n *\n * @returns Platform services with correct adapters for current context\n */\nexport function usePlatform(): typeof globalPlatform {\n return (platformContext.getStore() as typeof globalPlatform) ?? 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"]}
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","../../src/helpers/use-env.ts"],"names":["global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7B,EAAA,OAAO,QAAA,CAAS,SAAA;AAClB;AAsBA,eAAsB,mBAAA,CACpB,OACA,UAAA,EACe;AACf,EAAA,MAAM,YAAY,YAAA,EAAa;AAC/B,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,MAAM,SAAA,CAAU,KAAA,CAAM,KAAA,EAAO,UAAU,CAAA;AAAA,EACzC;AACF;;;ACzEA,iBAAA,EAAA;AA8CO,SAAS,UAAA,GAAmC;AACjD,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,OAAO,QAAA,CAAS,OAAA;AAClB;;;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;ACrEO,SAAS,OAAO,GAAA,EAAiC;AACtD,EAAA,MAAM,OAAA,GAAU,eAAe,QAAA,EAAS;AACxC,EAAA,IAAI,SAAS,GAAA,EAAK;AAChB,IAAA,OAAO,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACxB;AACA,EAAA,OAAO,OAAA,CAAQ,IAAI,GAAG,CAAA;AACxB","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/shared-command-kit/helpers/use-platform\n * Platform access hook with execution-scoped context.\n *\n * Uses AsyncLocalStorage to return the correct platform for the current\n * handler execution (governed, with correct permissions and proxy adapters).\n * Falls back to global singleton for code running outside handler context.\n *\n * @example\n * ```typescript\n * import { usePlatform } from '@kb-labs/shared-command-kit';\n *\n * // In any command handler — automatically gets the right platform\n * async handler(ctx, argv, flags) {\n * const platform = usePlatform();\n * const result = await platform.llm.complete('prompt');\n * }\n * ```\n */\n\nimport { platformContext } from '@kb-labs/plugin-contracts';\nimport { platform as globalPlatform } from '@kb-labs/core-runtime';\n\n/**\n * Access platform services for the current execution context.\n *\n * Priority:\n * 1. AsyncLocalStorage context (set by runInProcess) — per-execution, governed\n * 2. Global singleton fallback (core-runtime) — for code outside handler context\n *\n * @returns Platform services with correct adapters for current context\n */\nexport function usePlatform(): typeof globalPlatform {\n return (platformContext.getStore() as typeof globalPlatform) ?? 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// Runtime shims\nexport { useEnv } from './use-env.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","/**\n * @module @kb-labs/shared-command-kit/helpers/use-env\n *\n * Sandboxed environment variable access.\n *\n * Reads from runtimeContext (AsyncLocalStorage) when running inside\n * a governed handler execution (worker-pool, subprocess).\n * Falls back to process.env when no runtime context is set\n * (direct CLI, tests, code outside handler).\n *\n * @example\n * ```typescript\n * import { useEnv } from '@kb-labs/sdk';\n *\n * const token = useEnv('NPM_TOKEN');\n * const ci = useEnv('CI');\n * ```\n */\n\nimport { runtimeContext } from '@kb-labs/plugin-contracts';\n\n/**\n * Read an environment variable through the sandboxed runtime context.\n *\n * Inside a governed handler: reads through env-shim (permission-checked).\n * Outside handler context: reads process.env directly (backward compat).\n */\nexport function useEnv(key: string): string | undefined {\n const runtime = runtimeContext.getStore();\n if (runtime?.env) {\n return runtime.env(key);\n }\n return process.env[key];\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { FlagSchemaDefinition as FlagSchemaDefinition$1, InferFlags } from './fl
4
4
  export { ArrayFlagSchema, BaseFlagSchema, BooleanFlagSchema, FlagSchema, FlagSchemaWithInfer, FlagType, FlagValidationError, NumberFlagSchema, SafeValidationResult, StringFlagSchema, ValidationResult, defineFlags, validateFlags, validateFlagsSafe } from './flags/index.js';
5
5
  export { AnalyticsContext, AnalyticsEvents, createAnalyticsWrapper, trackEvent, withAnalytics } from './analytics/index.js';
6
6
  export { ErrorDefinition, ErrorDefinitions, FormatErrorOptions, FormattedError, PluginError, commonErrors, defineError, formatError } from './errors/index.js';
7
- export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore } from './helpers/index.js';
7
+ export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore } from './helpers/index.js';
8
8
  import { z } from 'zod';
9
9
  export { CommandOutput } from '@kb-labs/shared-cli-ui';
10
10
  export { LLMTier, UseLLMOptions } from '@kb-labs/core-platform';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { platformContext } from '@kb-labs/plugin-contracts';
1
+ import { platformContext, runtimeContext } from '@kb-labs/plugin-contracts';
2
2
  import { platform } from '@kb-labs/core-runtime';
3
3
  import { z } from 'zod';
4
4
  import * as fs from 'fs/promises';
@@ -878,6 +878,13 @@ function isCacheAvailable() {
878
878
  const cache = useCache();
879
879
  return !!cache;
880
880
  }
881
+ function useEnv(key) {
882
+ const runtime = runtimeContext.getStore();
883
+ if (runtime?.env) {
884
+ return runtime.env(key);
885
+ }
886
+ return process.env[key];
887
+ }
881
888
 
882
889
  // src/define-system-command.ts
883
890
  function convertFlagSchema(schema2) {
@@ -1546,6 +1553,6 @@ var MessageRouter = class {
1546
1553
  }
1547
1554
  };
1548
1555
 
1549
- export { FlagValidationError, MessageBuilder, MessageRouter, PluginError, array, artifactId, boolean, commandId, commonErrors, createAnalyticsWrapper, cwd, datetime, defineAction, defineCommand, defineCommandFlags, defineDestroyHandler, defineError, defineFlags, defineHandler, defineJob, defineManifest, defineMessage, defineRoute, defineSetupHandler, defineSystemCommand, defineSystemCommandGroup, defineWebSocket, defineWebhook, email, enumSchema, filePath, formatError, getLLMTier, isCLIHost, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isRESTHost, isVectorStoreAvailable, isWSHost, isWebhookHost, isWorkflowHost, json, nonNegativeInt, object, pluginId, positiveInt, schema, scopeId, text, trackAnalyticsEvent, trackEvent, url, useAnalytics, useCache, useConfig, useEmbeddings, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore, uuid, validateFlags, validateFlagsSafe, withAnalytics };
1556
+ export { FlagValidationError, MessageBuilder, MessageRouter, PluginError, array, artifactId, boolean, commandId, commonErrors, createAnalyticsWrapper, cwd, datetime, defineAction, defineCommand, defineCommandFlags, defineDestroyHandler, defineError, defineFlags, defineHandler, defineJob, defineManifest, defineMessage, defineRoute, defineSetupHandler, defineSystemCommand, defineSystemCommandGroup, defineWebSocket, defineWebhook, email, enumSchema, filePath, formatError, getLLMTier, isCLIHost, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isRESTHost, isVectorStoreAvailable, isWSHost, isWebhookHost, isWorkflowHost, json, nonNegativeInt, object, pluginId, positiveInt, schema, scopeId, text, trackAnalyticsEvent, trackEvent, url, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore, uuid, validateFlags, validateFlagsSafe, withAnalytics };
1550
1557
  //# sourceMappingURL=index.js.map
1551
1558
  //# sourceMappingURL=index.js.map