@kb-labs/shared-command-kit 2.94.0 → 2.98.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/flags/types.ts","../../src/errors/format-validation.ts","../../src/errors/format.ts","../../src/errors/factory.ts"],"names":["json","message"],"mappings":";AAkHO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACkB,IAAA,EAChB,OAAA,EACgB,KAAA,EACA,QACA,WAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AANG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAEA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EARkB,IAAA;AAAA,EAEA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAKpB,CAAA;;;AC1GO,SAAS,qBAAA,CACd,KAAA,EACA,OAAA,GAGI,EAAC,EACG;AACR,EAAA,MAAM,EAAE,WAAA,EAAa,MAAA,EAAO,GAAI,OAAA;AAChC,EAAA,MAAM,QAAkB,EAAC;AAGzB,EAAA,MAAM,WAAW,KAAA,CAAM,OAAA;AAGvB,EAAA,IAAI,QAAA,CAAS,QAAA,CAAS,aAAa,CAAA,EAAG;AACpC,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,gCAAA,EAA8B,KAAA,CAAM,IAAI,CAAA,CAAE,CAAA;AAAA,EACvD,CAAA,MAAA,IAAW,QAAA,CAAS,QAAA,CAAS,gBAAgB,CAAA,EAAG;AAE9C,IAAA,MAAM,WAAW,KAAA,CAAM,KAAA,KAAU,SAAY,CAAA,CAAA,EAAI,KAAA,CAAM,KAAK,CAAA,CAAA,GAAK,EAAA;A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,OAAA,EAAS,CAAC,SAAA,KAAsB,CAAA,WAAA,EAAc,SAAS,CAAA,WAAA;AAAA,GACzD;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,EAAU;AAAA,IACR,IAAA,EAAM,GAAA;AAAA,IACN,OAAA,EAAS,CAAC,QAAA,KAAqB,CAAA,EAAG,QAAQ,CAAA,eAAA;AAAA;AAE9C","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/shared-command-kit/flags/types\n * Types for flag validation and schema definition\n */\n\n/**\n * Flag type definition\n */\nexport type FlagType = 'boolean' | 'string' | 'number' | 'array';\n\n/**\n * Base flag schema definition\n */\nexport interface BaseFlagSchema<T extends FlagType = FlagType> {\n /** Flag name */\n name?: string;\n /** Flag type */\n type: T;\n /** Short alias (e.g., 'n' for 'dry-run') */\n alias?: string;\n /** Description for help text */\n description?: string;\n /** Default value if flag is not provided */\n default?: unknown;\n /** Whether flag is required */\n required?: boolean;\n /** Flags that conflict with this flag */\n conflicts?: string[];\n /** Flags that this flag depends on */\n dependsOn?: string[];\n /** Flags that are implied when this flag is set */\n implies?: string[] | [string, unknown][];\n // Note: transform is defined in child interfaces with specific types\n}\n\n/**\n * Boolean flag schema\n */\nexport interface BooleanFlagSchema extends BaseFlagSchema<'boolean'> {\n type: 'boolean';\n default?: boolean;\n /** Transform function to apply to the value */\n transform?: (value: boolean) => boolean | Promise<boolean>;\n}\n\n/**\n * String flag schema\n */\nexport interface StringFlagSchema extends BaseFlagSchema<'string'> {\n type: 'string';\n default?: string;\n /** Allowed values (enum) */\n choices?: readonly string[];\n /** Regex pattern for validation */\n pattern?: RegExp;\n /** Minimum string length */\n minLength?: number;\n /** Maximum string length */\n maxLength?: number;\n /** Custom validation function */\n validate?: (value: string) => true | string | Promise<true | string>;\n /** Transform function to apply to the value */\n transform?: (value: string) => string | Promise<string>;\n}\n\n/**\n * Number flag schema\n */\nexport interface NumberFlagSchema extends BaseFlagSchema<'number'> {\n type: 'number';\n default?: number;\n /** Minimum value */\n min?: number;\n /** Maximum value */\n max?: number;\n /** Custom validation function */\n validate?: (value: number) => true | string | Promise<true | string>;\n /** Transform function to apply to the value */\n transform?: (value: number) => number | Promise<number>;\n}\n\n/**\n * Array flag schema\n */\nexport interface ArrayFlagSchema extends BaseFlagSchema<'array'> {\n type: 'array';\n default?: unknown[];\n /** Type of array items */\n items?: 'string' | 'number' | 'boolean';\n /** Minimum array length */\n minLength?: number;\n /** Maximum array length */\n maxLength?: number;\n /** Transform function to apply to the value */\n transform?: (value: unknown[]) => unknown[] | Promise<unknown[]>;\n}\n\n/**\n * Union of all flag schema types\n */\nexport type FlagSchema =\n | BooleanFlagSchema\n | StringFlagSchema\n | NumberFlagSchema\n | ArrayFlagSchema;\n\n/**\n * Flag schema definition object (for defineFlags)\n */\nexport type FlagSchemaDefinition = Record<string, Omit<FlagSchema, 'name'>>;\n\n/**\n * Validation error\n */\nexport class FlagValidationError extends Error {\n constructor(\n public readonly flag: string,\n message: string,\n public readonly value?: unknown,\n public readonly schema?: FlagSchemaDefinition,\n public readonly commandName?: string\n ) {\n super(message);\n this.name = 'FlagValidationError';\n }\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult<T = Record<string, unknown>> {\n success: boolean;\n data?: T;\n errors?: Array<{\n flag: string;\n message: string;\n value?: unknown;\n }>;\n}\n\n/**\n * Safe validation result (doesn't throw)\n */\nexport interface SafeValidationResult<T = Record<string, unknown>> {\n success: boolean;\n data?: T;\n errors: Array<{\n flag: string;\n message: string;\n value?: unknown;\n }>;\n}\n\n","/**\n * @module @kb-labs/shared-command-kit/errors/format-validation\n * User-friendly formatting for flag validation errors\n */\n\nimport type { FlagValidationError, StringFlagSchema } from '../flags/types';\nimport type { FlagSchemaDefinition } from '../flags/types';\n\n/**\n * Format a validation error into a user-friendly message\n *\n * @example\n * ```\n * ❌ Missing required flag: --text\n *\n * Usage: kb mind rag-query --text <query>\n * Hint: Try kb mind rag-query --help\n * ```\n */\nexport function formatValidationError(\n error: FlagValidationError,\n options: {\n commandName?: string;\n schema?: FlagSchemaDefinition;\n } = {}\n): string {\n const { commandName, schema } = options;\n const lines: string[] = [];\n\n // Main error message with emoji\n const errorMsg = error.message;\n\n // Determine error type and format accordingly\n if (errorMsg.includes('is required')) {\n lines.push(`❌ Missing required flag: --${error.flag}`);\n } else if (errorMsg.includes('must be one of')) {\n // Extract the invalid value if available\n const valueStr = error.value !== undefined ? ` ${error.value}` : '';\n lines.push(`❌ Invalid value for --${error.flag}:${valueStr}`);\n } else if (errorMsg.includes('must be a')) {\n lines.push(`❌ Invalid type for --${error.flag}`);\n } else if (errorMsg.includes('conflicts with')) {\n lines.push(`❌ Flag conflict: --${error.flag}`);\n } else if (errorMsg.includes('depends on')) {\n lines.push(`❌ Missing dependency for --${error.flag}`);\n } else {\n // Fallback: use the original message\n lines.push(`❌ ${errorMsg}`);\n }\n\n lines.push(''); // Empty line for spacing\n\n // Generate usage hint if we have schema and command name\n if (commandName && schema) {\n const usageLine = generateUsageLine(commandName, schema, error.flag);\n if (usageLine) {\n lines.push(`Usage: ${usageLine}`);\n }\n }\n\n // Add help hint\n if (commandName) {\n lines.push(`Hint: Try ${commandName} --help`);\n } else {\n lines.push('Hint: Try --help for more information');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate a usage line from command name and schema\n *\n * @example\n * generateUsageLine('kb mind rag-query', schema, 'text')\n * // Returns: 'kb mind rag-query --text <query> [options]'\n */\nfunction generateUsageLine(\n commandName: string,\n schema: FlagSchemaDefinition,\n errorFlag: string\n): string {\n const parts: string[] = [commandName];\n\n // Add the flag that caused the error first\n const errorFlagSchema = schema[errorFlag];\n if (errorFlagSchema) {\n const flagStr = formatFlagForUsage(errorFlag, errorFlagSchema);\n parts.push(flagStr);\n }\n\n // Check if there are other required flags\n const otherRequiredFlags = Object.entries(schema)\n .filter(([name, flagSchema]) =>\n name !== errorFlag && flagSchema.required\n );\n\n if (otherRequiredFlags.length > 0) {\n // Add other required flags\n for (const [name, flagSchema] of otherRequiredFlags) {\n parts.push(formatFlagForUsage(name, flagSchema));\n }\n }\n\n // Add [options] if there are optional flags\n const hasOptionalFlags = Object.values(schema).some(s => !s.required);\n if (hasOptionalFlags) {\n parts.push('[options]');\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format a single flag for usage display\n *\n * @example\n * formatFlagForUsage('text', { type: 'string', required: true })\n * // Returns: '--text <text>'\n *\n * formatFlagForUsage('mode', { type: 'string', choices: ['local', 'auto'] })\n * // Returns: '[--mode <local|auto>]'\n */\nfunction formatFlagForUsage(\n name: string,\n schema: FlagSchemaDefinition[string]\n): string {\n let valueHint: string;\n\n if ('choices' in schema && (schema as StringFlagSchema).choices && (schema as StringFlagSchema).choices!.length > 0) {\n // Show choices: <local|auto>\n valueHint = `<${(schema as StringFlagSchema).choices!.join('|')}>`;\n } else if (schema.type === 'boolean') {\n // Boolean flags don't need a value hint\n return schema.required ? `--${name}` : `[--${name}]`;\n } else {\n // Generic type hint: <text>, <number>, etc.\n valueHint = `<${name}>`;\n }\n\n const flagPart = `--${name} ${valueHint}`;\n\n return schema.required ? flagPart : `[${flagPart}]`;\n}\n","/**\n * @module @kb-labs/shared-command-kit/errors/format\n * Error formatting utilities\n */\n\nimport type { FormattedError, FormatErrorOptions } from './types';\nimport { FlagValidationError } from '../flags/types';\nimport { formatValidationError } from './format-validation';\n\n/**\n * Format error for display\n * \n * @example\n * ```typescript\n * const formatted = formatError(error, {\n * jsonMode: Boolean(flags.json),\n * showStack: Boolean(flags.debug),\n * timingMs: tracker.total(),\n * });\n * \n * if (flags.json) {\n * ctx.output?.json(formatted.json);\n * } else {\n * ctx.output?.error(formatted.message);\n * }\n * ```\n */\nexport function formatError(\n error: unknown,\n options: FormatErrorOptions = {}\n): FormattedError {\n const { showStack = false, timingMs } = options;\n\n // Special handling for FlagValidationError\n if (error instanceof FlagValidationError) {\n const friendlyMessage = formatValidationError(error, {\n commandName: error.commandName,\n schema: error.schema,\n });\n\n const json: FormattedError['json'] = {\n ok: false,\n error: error.message,\n };\n\n if (timingMs !== undefined) {\n json.timingMs = timingMs;\n }\n\n if (showStack && error.stack) {\n json.stack = error.stack;\n }\n\n let message = friendlyMessage;\n if (showStack && error.stack) {\n message = `${friendlyMessage}\\n\\nStack trace:\\n${error.stack}`;\n }\n\n return {\n message,\n json,\n };\n }\n\n // Standard error formatting for other errors\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n\n const json: FormattedError['json'] = {\n ok: false,\n error: errorMessage,\n };\n\n if (timingMs !== undefined) {\n json.timingMs = timingMs;\n }\n\n if (showStack && errorStack) {\n json.stack = errorStack;\n }\n\n let message = errorMessage;\n if (showStack && errorStack) {\n message = `${errorMessage}\\n\\n${errorStack}`;\n }\n\n return {\n message,\n json,\n };\n}\n\n","/**\n * Error Factory for KB Labs Plugins\n *\n * Optional helper for defining plugin errors without boilerplate.\n * You can always use standard Error classes - this is just convenience.\n *\n * @example\n * ```typescript\n * import { defineError } from '@kb-labs/shared-command-kit';\n *\n * export const MindError = defineError('MIND', {\n * ValidationFailed: { code: 400, message: 'Validation failed' },\n * IndexNotFound: { code: 404, message: (scope: string) => `Index '${scope}' not found` },\n * QueryFailed: { code: 500, message: 'Query execution failed' },\n * });\n *\n * // Usage:\n * throw new MindError.IndexNotFound('default');\n * throw new MindError.ValidationFailed({ details: { field: 'cwd' } });\n * ```\n */\n\n/**\n * Error definition with HTTP code and message\n */\nexport interface ErrorDefinition {\n /** HTTP status code (400, 404, 500, etc.) */\n code: number;\n /** Error message - can be string or function for parameterized messages */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n message: string | ((...args: any[]) => string);\n /** Optional additional details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Error definitions map\n */\nexport type ErrorDefinitions = Record<string, ErrorDefinition>;\n\n/**\n * Base error class with HTTP status code support\n */\nexport class PluginError extends Error {\n public readonly statusCode: number;\n public readonly errorCode: string;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n errorCode: string,\n message: string,\n statusCode: number,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'PluginError';\n this.errorCode = errorCode;\n this.statusCode = statusCode;\n this.details = details;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, PluginError);\n }\n }\n\n /**\n * Convert error to JSON for logging/serialization\n */\n toJSON() {\n return {\n name: this.name,\n errorCode: this.errorCode,\n message: this.message,\n statusCode: this.statusCode,\n details: this.details,\n stack: this.stack,\n };\n }\n\n /**\n * Check if error is a PluginError\n */\n static isPluginError(error: unknown): error is PluginError {\n return error instanceof PluginError;\n }\n}\n\n/**\n * Type for error constructor created by defineError\n */\ntype ErrorConstructor<TArgs extends unknown[] = unknown[]> = {\n new (details?: Record<string, unknown>): PluginError;\n new (...args: TArgs): PluginError;\n};\n\n/**\n * Type for error namespace created by defineError\n */\ntype ErrorNamespace<TDefs extends ErrorDefinitions> = {\n [K in keyof TDefs]: ErrorConstructor;\n} & {\n /** Check if error is from this namespace */\n is(error: unknown): error is PluginError;\n /** Check if error has specific error code */\n hasCode(error: unknown, code: keyof TDefs): boolean;\n};\n\n/**\n * Define a namespace of plugin errors\n *\n * @param prefix - Error code prefix (e.g., 'MIND', 'WORKFLOW')\n * @param definitions - Error definitions map\n * @returns Error namespace with error constructors\n *\n * @example\n * ```typescript\n * export const MindError = defineError('MIND', {\n * IndexNotFound: {\n * code: 404,\n * message: (scope: string) => `Index '${scope}' not found`\n * },\n * QueryFailed: {\n * code: 500,\n * message: 'Query execution failed'\n * },\n * });\n *\n * // Throw with template params\n * throw new MindError.IndexNotFound('default');\n * // Error message: \"Index 'default' not found\"\n *\n * // Throw with details\n * throw new MindError.QueryFailed({\n * details: { query: 'test', reason: 'timeout' }\n * });\n * ```\n */\nexport function defineError<TDefs extends ErrorDefinitions>(\n prefix: string,\n definitions: TDefs\n): ErrorNamespace<TDefs> {\n const errorNamespace: Record<string, unknown> = {};\n\n // Create error constructor for each definition\n for (const [key, def] of Object.entries(definitions)) {\n const errorCode = `${prefix}_${key.toUpperCase()}`;\n\n // Create error class\n class DefinedError extends PluginError {\n constructor(...args: unknown[]) {\n const { message, details } = buildMessageAndDetails(def, args);\n super(errorCode, message, def.code, details);\n this.name = `${prefix}Error`;\n }\n }\n\n errorNamespace[key] = DefinedError;\n }\n\n // Add helper methods\n errorNamespace.is = (error: unknown): error is PluginError => {\n return PluginError.isPluginError(error) && error.errorCode.startsWith(prefix + '_');\n };\n\n errorNamespace.hasCode = (error: unknown, code: keyof TDefs): boolean => {\n const errorCode = `${prefix}_${String(code).toUpperCase()}`;\n return PluginError.isPluginError(error) && error.errorCode === errorCode;\n };\n\n return errorNamespace as ErrorNamespace<TDefs>;\n}\n\n/**\n * Build error message and details from definition and constructor args\n */\nfunction buildMessageAndDetails(\n def: ErrorDefinition,\n args: unknown[]\n): { message: string; details?: Record<string, unknown> } {\n let message: string;\n let details: Record<string, unknown> | undefined;\n\n if (typeof def.message === 'function') {\n // Template message - args are template params\n const lastArg = args[args.length - 1];\n\n // Check if last arg is details object (has 'details' key)\n const hasDetails = lastArg && typeof lastArg === 'object' && 'details' in lastArg;\n\n if (hasDetails) {\n // Last arg is details, rest are template params\n const templateArgs = args.slice(0, -1);\n message = def.message(...templateArgs);\n details = { ...def.details, ...(lastArg as { details?: Record<string, unknown> }).details };\n } else {\n // All args are template params\n message = def.message(...args);\n details = def.details;\n }\n } else {\n // Static message\n message = def.message;\n\n // First arg can be details object\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n details = { ...def.details, ...(args[0] as { details?: Record<string, unknown> }).details };\n } else {\n details = def.details;\n }\n }\n\n return { message, details };\n}\n\n/**\n * Common error definitions that can be reused across plugins\n */\nexport const commonErrors = {\n /**\n * Validation error (400)\n */\n ValidationFailed: {\n code: 400,\n message: 'Validation failed',\n },\n\n /**\n * Resource not found (404)\n */\n NotFound: {\n code: 404,\n message: (resource: string) => `${resource} not found`,\n },\n\n /**\n * Unauthorized access (401)\n */\n Unauthorized: {\n code: 401,\n message: 'Unauthorized',\n },\n\n /**\n * Forbidden access (403)\n */\n Forbidden: {\n code: 403,\n message: 'Forbidden',\n },\n\n /**\n * Internal server error (500)\n */\n InternalError: {\n code: 500,\n message: 'Internal server error',\n },\n\n /**\n * Service unavailable (503)\n */\n ServiceUnavailable: {\n code: 503,\n message: (service: string) => `Service '${service}' is unavailable`,\n },\n\n /**\n * Timeout error (504)\n */\n Timeout: {\n code: 504,\n message: (operation: string) => `Operation '${operation}' timed out`,\n },\n\n /**\n * Conflict error (409)\n */\n Conflict: {\n code: 409,\n message: (resource: string) => `${resource} already exists`,\n },\n} satisfies ErrorDefinitions;\n"]}
1
+ {"version":3,"sources":["../../src/flags/types.ts","../../src/errors/format-validation.ts","../../src/errors/format.ts","../../src/errors/factory.ts"],"names":["json","message"],"mappings":";AAkHO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACkB,IAAA,EAChB,OAAA,EACgB,KAAA,EACA,QACA,WAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AANG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAEA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EARkB,IAAA;AAAA,EAEA,KAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAKpB,CAAA;;;AC1GO,SAAS,qBAAA,CACd,KAAA,EACA,OAAA,GAGI,EAAC,EACG;AACR,EAAA,MAAM,EAAE,WAAA,EAAa,MAAA,EAAO,GAAI,OAAA;AAChC,EAAA,MAAM,QAAkB,EAAC;AAGzB,EAAA,MAAM,WAAW,KAAA,CAAM,OAAA;AAGvB,EAAA,IAAI,QAAA,CAAS,QAAA,CAAS,aAAa,C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A,EAAM,GAAA;AAAA,IACN,OAAA,EAAS;AAAA,GACX;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAA,EAAoB;AAAA,IAClB,IAAA,EAAM,GAAA;AAAA,IACN,OAAA,EAAS,CAAC,OAAA,KAAoB,CAAA,SAAA,EAAY,OAAO,CAAA,gBAAA;AAAA,GACnD;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,EAAS;AAAA,IACP,IAAA,EAAM,GAAA;AAAA,IACN,OAAA,EAAS,CAAC,SAAA,KAAsB,CAAA,WAAA,EAAc,SAAS,CAAA,WAAA;AAAA,GACzD;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,EAAU;AAAA,IACR,IAAA,EAAM,GAAA;AAAA,IACN,OAAA,EAAS,CAAC,QAAA,KAAqB,CAAA,EAAG,QAAQ,CAAA,eAAA;AAAA;AAE9C","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/shared-command-kit/flags/types\n * Types for flag validation and schema definition\n */\n\n/**\n * Flag type definition\n */\nexport type FlagType = 'boolean' | 'string' | 'number' | 'array';\n\n/**\n * Base flag schema definition\n */\nexport interface BaseFlagSchema<T extends FlagType = FlagType> {\n /** Flag name */\n name?: string;\n /** Flag type */\n type: T;\n /** Short alias (e.g., 'n' for 'dry-run') */\n alias?: string;\n /** Description for help text */\n description?: string;\n /** Default value if flag is not provided */\n default?: unknown;\n /** Whether flag is required */\n required?: boolean;\n /** Flags that conflict with this flag */\n conflicts?: string[];\n /** Flags that this flag depends on */\n dependsOn?: string[];\n /** Flags that are implied when this flag is set */\n implies?: string[] | [string, unknown][];\n // Note: transform is defined in child interfaces with specific types\n}\n\n/**\n * Boolean flag schema\n */\nexport interface BooleanFlagSchema extends BaseFlagSchema<'boolean'> {\n type: 'boolean';\n default?: boolean;\n /** Transform function to apply to the value */\n transform?: (value: boolean) => boolean | Promise<boolean>;\n}\n\n/**\n * String flag schema\n */\nexport interface StringFlagSchema extends BaseFlagSchema<'string'> {\n type: 'string';\n default?: string;\n /** Allowed values (enum) */\n choices?: readonly string[];\n /** Regex pattern for validation */\n pattern?: RegExp;\n /** Minimum string length */\n minLength?: number;\n /** Maximum string length */\n maxLength?: number;\n /** Custom validation function */\n validate?: (value: string) => true | string | Promise<true | string>;\n /** Transform function to apply to the value */\n transform?: (value: string) => string | Promise<string>;\n}\n\n/**\n * Number flag schema\n */\nexport interface NumberFlagSchema extends BaseFlagSchema<'number'> {\n type: 'number';\n default?: number;\n /** Minimum value */\n min?: number;\n /** Maximum value */\n max?: number;\n /** Custom validation function */\n validate?: (value: number) => true | string | Promise<true | string>;\n /** Transform function to apply to the value */\n transform?: (value: number) => number | Promise<number>;\n}\n\n/**\n * Array flag schema\n */\nexport interface ArrayFlagSchema extends BaseFlagSchema<'array'> {\n type: 'array';\n default?: unknown[];\n /** Type of array items */\n items?: 'string' | 'number' | 'boolean';\n /** Minimum array length */\n minLength?: number;\n /** Maximum array length */\n maxLength?: number;\n /** Transform function to apply to the value */\n transform?: (value: unknown[]) => unknown[] | Promise<unknown[]>;\n}\n\n/**\n * Union of all flag schema types\n */\nexport type FlagSchema =\n | BooleanFlagSchema\n | StringFlagSchema\n | NumberFlagSchema\n | ArrayFlagSchema;\n\n/**\n * Flag schema definition object (for defineFlags)\n */\nexport type FlagSchemaDefinition = Record<string, Omit<FlagSchema, 'name'>>;\n\n/**\n * Validation error\n */\nexport class FlagValidationError extends Error {\n constructor(\n public readonly flag: string,\n message: string,\n public readonly value?: unknown,\n public readonly schema?: FlagSchemaDefinition,\n public readonly commandName?: string\n ) {\n super(message);\n this.name = 'FlagValidationError';\n }\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult<T = Record<string, unknown>> {\n success: boolean;\n data?: T;\n errors?: Array<{\n flag: string;\n message: string;\n value?: unknown;\n }>;\n}\n\n/**\n * Safe validation result (doesn't throw)\n */\nexport interface SafeValidationResult<T = Record<string, unknown>> {\n success: boolean;\n data?: T;\n errors: Array<{\n flag: string;\n message: string;\n value?: unknown;\n }>;\n}\n\n","/**\n * @module @kb-labs/shared-command-kit/errors/format-validation\n * User-friendly formatting for flag validation errors\n */\n\nimport type { FlagValidationError, StringFlagSchema } from '../flags/types';\nimport type { FlagSchemaDefinition } from '../flags/types';\n\n/**\n * Format a validation error into a user-friendly message\n *\n * @example\n * ```\n * ❌ Missing required flag: --text\n *\n * Usage: kb mind search --text <query>\n * Hint: Try kb mind search --help\n * ```\n */\nexport function formatValidationError(\n error: FlagValidationError,\n options: {\n commandName?: string;\n schema?: FlagSchemaDefinition;\n } = {}\n): string {\n const { commandName, schema } = options;\n const lines: string[] = [];\n\n // Main error message with emoji\n const errorMsg = error.message;\n\n // Determine error type and format accordingly\n if (errorMsg.includes('is required')) {\n lines.push(`❌ Missing required flag: --${error.flag}`);\n } else if (errorMsg.includes('must be one of')) {\n // Extract the invalid value if available\n const valueStr = error.value !== undefined ? ` ${error.value}` : '';\n lines.push(`❌ Invalid value for --${error.flag}:${valueStr}`);\n } else if (errorMsg.includes('must be a')) {\n lines.push(`❌ Invalid type for --${error.flag}`);\n } else if (errorMsg.includes('conflicts with')) {\n lines.push(`❌ Flag conflict: --${error.flag}`);\n } else if (errorMsg.includes('depends on')) {\n lines.push(`❌ Missing dependency for --${error.flag}`);\n } else {\n // Fallback: use the original message\n lines.push(`❌ ${errorMsg}`);\n }\n\n lines.push(''); // Empty line for spacing\n\n // Generate usage hint if we have schema and command name\n if (commandName && schema) {\n const usageLine = generateUsageLine(commandName, schema, error.flag);\n if (usageLine) {\n lines.push(`Usage: ${usageLine}`);\n }\n }\n\n // Add help hint\n if (commandName) {\n lines.push(`Hint: Try ${commandName} --help`);\n } else {\n lines.push('Hint: Try --help for more information');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Generate a usage line from command name and schema\n *\n * @example\n * generateUsageLine('kb mind search', schema, 'text')\n * // Returns: 'kb mind search --text <query> [options]'\n */\nfunction generateUsageLine(\n commandName: string,\n schema: FlagSchemaDefinition,\n errorFlag: string\n): string {\n const parts: string[] = [commandName];\n\n // Add the flag that caused the error first\n const errorFlagSchema = schema[errorFlag];\n if (errorFlagSchema) {\n const flagStr = formatFlagForUsage(errorFlag, errorFlagSchema);\n parts.push(flagStr);\n }\n\n // Check if there are other required flags\n const otherRequiredFlags = Object.entries(schema)\n .filter(([name, flagSchema]) =>\n name !== errorFlag && flagSchema.required\n );\n\n if (otherRequiredFlags.length > 0) {\n // Add other required flags\n for (const [name, flagSchema] of otherRequiredFlags) {\n parts.push(formatFlagForUsage(name, flagSchema));\n }\n }\n\n // Add [options] if there are optional flags\n const hasOptionalFlags = Object.values(schema).some(s => !s.required);\n if (hasOptionalFlags) {\n parts.push('[options]');\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format a single flag for usage display\n *\n * @example\n * formatFlagForUsage('text', { type: 'string', required: true })\n * // Returns: '--text <text>'\n *\n * formatFlagForUsage('mode', { type: 'string', choices: ['local', 'auto'] })\n * // Returns: '[--mode <local|auto>]'\n */\nfunction formatFlagForUsage(\n name: string,\n schema: FlagSchemaDefinition[string]\n): string {\n let valueHint: string;\n\n if ('choices' in schema && (schema as StringFlagSchema).choices && (schema as StringFlagSchema).choices!.length > 0) {\n // Show choices: <local|auto>\n valueHint = `<${(schema as StringFlagSchema).choices!.join('|')}>`;\n } else if (schema.type === 'boolean') {\n // Boolean flags don't need a value hint\n return schema.required ? `--${name}` : `[--${name}]`;\n } else {\n // Generic type hint: <text>, <number>, etc.\n valueHint = `<${name}>`;\n }\n\n const flagPart = `--${name} ${valueHint}`;\n\n return schema.required ? flagPart : `[${flagPart}]`;\n}\n","/**\n * @module @kb-labs/shared-command-kit/errors/format\n * Error formatting utilities\n */\n\nimport type { FormattedError, FormatErrorOptions } from './types';\nimport { FlagValidationError } from '../flags/types';\nimport { formatValidationError } from './format-validation';\n\n/**\n * Format error for display\n * \n * @example\n * ```typescript\n * const formatted = formatError(error, {\n * jsonMode: Boolean(flags.json),\n * showStack: Boolean(flags.debug),\n * timingMs: tracker.total(),\n * });\n * \n * if (flags.json) {\n * ctx.output?.json(formatted.json);\n * } else {\n * ctx.output?.error(formatted.message);\n * }\n * ```\n */\nexport function formatError(\n error: unknown,\n options: FormatErrorOptions = {}\n): FormattedError {\n const { showStack = false, timingMs } = options;\n\n // Special handling for FlagValidationError\n if (error instanceof FlagValidationError) {\n const friendlyMessage = formatValidationError(error, {\n commandName: error.commandName,\n schema: error.schema,\n });\n\n const json: FormattedError['json'] = {\n ok: false,\n error: error.message,\n };\n\n if (timingMs !== undefined) {\n json.timingMs = timingMs;\n }\n\n if (showStack && error.stack) {\n json.stack = error.stack;\n }\n\n let message = friendlyMessage;\n if (showStack && error.stack) {\n message = `${friendlyMessage}\\n\\nStack trace:\\n${error.stack}`;\n }\n\n return {\n message,\n json,\n };\n }\n\n // Standard error formatting for other errors\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStack = error instanceof Error ? error.stack : undefined;\n\n const json: FormattedError['json'] = {\n ok: false,\n error: errorMessage,\n };\n\n if (timingMs !== undefined) {\n json.timingMs = timingMs;\n }\n\n if (showStack && errorStack) {\n json.stack = errorStack;\n }\n\n let message = errorMessage;\n if (showStack && errorStack) {\n message = `${errorMessage}\\n\\n${errorStack}`;\n }\n\n return {\n message,\n json,\n };\n}\n\n","/**\n * Error Factory for KB Labs Plugins\n *\n * Optional helper for defining plugin errors without boilerplate.\n * You can always use standard Error classes - this is just convenience.\n *\n * @example\n * ```typescript\n * import { defineError } from '@kb-labs/shared-command-kit';\n *\n * export const MindError = defineError('MIND', {\n * ValidationFailed: { code: 400, message: 'Validation failed' },\n * IndexNotFound: { code: 404, message: (scope: string) => `Index '${scope}' not found` },\n * QueryFailed: { code: 500, message: 'Query execution failed' },\n * });\n *\n * // Usage:\n * throw new MindError.IndexNotFound('default');\n * throw new MindError.ValidationFailed({ details: { field: 'cwd' } });\n * ```\n */\n\n/**\n * Error definition with HTTP code and message\n */\nexport interface ErrorDefinition {\n /** HTTP status code (400, 404, 500, etc.) */\n code: number;\n /** Error message - can be string or function for parameterized messages */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n message: string | ((...args: any[]) => string);\n /** Optional additional details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Error definitions map\n */\nexport type ErrorDefinitions = Record<string, ErrorDefinition>;\n\n/**\n * Base error class with HTTP status code support\n */\nexport class PluginError extends Error {\n public readonly statusCode: number;\n public readonly errorCode: string;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n errorCode: string,\n message: string,\n statusCode: number,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'PluginError';\n this.errorCode = errorCode;\n this.statusCode = statusCode;\n this.details = details;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, PluginError);\n }\n }\n\n /**\n * Convert error to JSON for logging/serialization\n */\n toJSON() {\n return {\n name: this.name,\n errorCode: this.errorCode,\n message: this.message,\n statusCode: this.statusCode,\n details: this.details,\n stack: this.stack,\n };\n }\n\n /**\n * Check if error is a PluginError\n */\n static isPluginError(error: unknown): error is PluginError {\n return error instanceof PluginError;\n }\n}\n\n/**\n * Type for error constructor created by defineError\n */\ntype ErrorConstructor<TArgs extends unknown[] = unknown[]> = {\n new (details?: Record<string, unknown>): PluginError;\n new (...args: TArgs): PluginError;\n};\n\n/**\n * Type for error namespace created by defineError\n */\ntype ErrorNamespace<TDefs extends ErrorDefinitions> = {\n [K in keyof TDefs]: ErrorConstructor;\n} & {\n /** Check if error is from this namespace */\n is(error: unknown): error is PluginError;\n /** Check if error has specific error code */\n hasCode(error: unknown, code: keyof TDefs): boolean;\n};\n\n/**\n * Define a namespace of plugin errors\n *\n * @param prefix - Error code prefix (e.g., 'MIND', 'WORKFLOW')\n * @param definitions - Error definitions map\n * @returns Error namespace with error constructors\n *\n * @example\n * ```typescript\n * export const MindError = defineError('MIND', {\n * IndexNotFound: {\n * code: 404,\n * message: (scope: string) => `Index '${scope}' not found`\n * },\n * QueryFailed: {\n * code: 500,\n * message: 'Query execution failed'\n * },\n * });\n *\n * // Throw with template params\n * throw new MindError.IndexNotFound('default');\n * // Error message: \"Index 'default' not found\"\n *\n * // Throw with details\n * throw new MindError.QueryFailed({\n * details: { query: 'test', reason: 'timeout' }\n * });\n * ```\n */\nexport function defineError<TDefs extends ErrorDefinitions>(\n prefix: string,\n definitions: TDefs\n): ErrorNamespace<TDefs> {\n const errorNamespace: Record<string, unknown> = {};\n\n // Create error constructor for each definition\n for (const [key, def] of Object.entries(definitions)) {\n const errorCode = `${prefix}_${key.toUpperCase()}`;\n\n // Create error class\n class DefinedError extends PluginError {\n constructor(...args: unknown[]) {\n const { message, details } = buildMessageAndDetails(def, args);\n super(errorCode, message, def.code, details);\n this.name = `${prefix}Error`;\n }\n }\n\n errorNamespace[key] = DefinedError;\n }\n\n // Add helper methods\n errorNamespace.is = (error: unknown): error is PluginError => {\n return PluginError.isPluginError(error) && error.errorCode.startsWith(prefix + '_');\n };\n\n errorNamespace.hasCode = (error: unknown, code: keyof TDefs): boolean => {\n const errorCode = `${prefix}_${String(code).toUpperCase()}`;\n return PluginError.isPluginError(error) && error.errorCode === errorCode;\n };\n\n return errorNamespace as ErrorNamespace<TDefs>;\n}\n\n/**\n * Build error message and details from definition and constructor args\n */\nfunction buildMessageAndDetails(\n def: ErrorDefinition,\n args: unknown[]\n): { message: string; details?: Record<string, unknown> } {\n let message: string;\n let details: Record<string, unknown> | undefined;\n\n if (typeof def.message === 'function') {\n // Template message - args are template params\n const lastArg = args[args.length - 1];\n\n // Check if last arg is details object (has 'details' key)\n const hasDetails = lastArg && typeof lastArg === 'object' && 'details' in lastArg;\n\n if (hasDetails) {\n // Last arg is details, rest are template params\n const templateArgs = args.slice(0, -1);\n message = def.message(...templateArgs);\n details = { ...def.details, ...(lastArg as { details?: Record<string, unknown> }).details };\n } else {\n // All args are template params\n message = def.message(...args);\n details = def.details;\n }\n } else {\n // Static message\n message = def.message;\n\n // First arg can be details object\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n details = { ...def.details, ...(args[0] as { details?: Record<string, unknown> }).details };\n } else {\n details = def.details;\n }\n }\n\n return { message, details };\n}\n\n/**\n * Common error definitions that can be reused across plugins\n */\nexport const commonErrors = {\n /**\n * Validation error (400)\n */\n ValidationFailed: {\n code: 400,\n message: 'Validation failed',\n },\n\n /**\n * Resource not found (404)\n */\n NotFound: {\n code: 404,\n message: (resource: string) => `${resource} not found`,\n },\n\n /**\n * Unauthorized access (401)\n */\n Unauthorized: {\n code: 401,\n message: 'Unauthorized',\n },\n\n /**\n * Forbidden access (403)\n */\n Forbidden: {\n code: 403,\n message: 'Forbidden',\n },\n\n /**\n * Internal server error (500)\n */\n InternalError: {\n code: 500,\n message: 'Internal server error',\n },\n\n /**\n * Service unavailable (503)\n */\n ServiceUnavailable: {\n code: 503,\n message: (service: string) => `Service '${service}' is unavailable`,\n },\n\n /**\n * Timeout error (504)\n */\n Timeout: {\n code: 504,\n message: (operation: string) => `Operation '${operation}' timed out`,\n },\n\n /**\n * Conflict error (409)\n */\n Conflict: {\n code: 409,\n message: (resource: string) => `${resource} already exists`,\n },\n} satisfies ErrorDefinitions;\n"]}
@@ -1,6 +1,6 @@
1
1
  import { platform } from '@kb-labs/core-runtime';
2
2
  export { PluginContextV3 } from '@kb-labs/plugin-contracts';
3
- import { ILogger, LLMTier, UseLLMOptions, ILLM, IEmbeddings, IVectorStore, IAnalytics, IStorage, ICache } from '@kb-labs/core-platform';
3
+ import { ILogger, LLMTier, UseLLMOptions, ILLM, IEmbeddings, IVectorStore, IAnalytics, IStorage, ICache, IDocumentDatabase, IKVStore, INotifier } from '@kb-labs/core-platform';
4
4
  export { LLMTier, UseLLMOptions } from '@kb-labs/core-platform';
5
5
 
6
6
  /**
@@ -613,6 +613,151 @@ declare function useCache(): ICache | undefined;
613
613
  */
614
614
  declare function isCacheAvailable(): boolean;
615
615
 
616
+ /**
617
+ * @module @kb-labs/shared-command-kit/helpers/use-document-database
618
+ *
619
+ * Hook for the per-plugin document database — structured persistence with
620
+ * filters, transactions, and indexed collections.
621
+ *
622
+ * The adapter is resolved from the current `usePlatform()` context, so the
623
+ * instance you receive is already wrapped with this plugin's permissions:
624
+ * collection names are namespaced under `<pluginId>__<name>`, and any call
625
+ * to a collection the plugin didn't declare in
626
+ * `permissions.platform.database.document.owns` / `.access` rejects with
627
+ * `PermissionError`.
628
+ *
629
+ * @example
630
+ * ```typescript
631
+ * import { useDocumentDatabase } from '@kb-labs/shared-command-kit';
632
+ *
633
+ * interface Run extends BaseDocument {
634
+ * status: 'queued' | 'running' | 'done';
635
+ * startedAt: number;
636
+ * }
637
+ *
638
+ * async function handler() {
639
+ * const docs = useDocumentDatabase();
640
+ * if (!docs) {
641
+ * throw new Error('Plugin needs documentDatabase configured');
642
+ * }
643
+ *
644
+ * await docs.ensureCollection('runs', {
645
+ * indexes: [{ path: 'status' }],
646
+ * });
647
+ *
648
+ * const queued = await docs.find<Run>('runs', { status: { $eq: 'queued' } });
649
+ * return queued;
650
+ * }
651
+ * ```
652
+ */
653
+
654
+ /**
655
+ * Resolve the document database for the current execution.
656
+ *
657
+ * Returns `undefined` when no adapter is configured at all. When a plugin
658
+ * declared permissions but is missing the wiring (NoOp adapter on the
659
+ * platform side) you still get an instance — calls just throw on use.
660
+ *
661
+ * Always check before using:
662
+ *
663
+ * ```ts
664
+ * const docs = useDocumentDatabase();
665
+ * if (!docs) {
666
+ * // The platform was started without a document database;
667
+ * // either skip the feature or fail fast with a clear error.
668
+ * return;
669
+ * }
670
+ * ```
671
+ */
672
+ declare function useDocumentDatabase(): IDocumentDatabase | undefined;
673
+ /**
674
+ * Cheap check for "is the document database available?". Returns true even
675
+ * for NoOp adapters configured by the platform — use this to gate optional
676
+ * features, not as a security check.
677
+ */
678
+ declare function isDocumentDatabaseAvailable(): boolean;
679
+
680
+ /**
681
+ * @module @kb-labs/shared-command-kit/helpers/use-kv-store
682
+ *
683
+ * Hook for the per-plugin durable key-value store.
684
+ *
685
+ * Unlike `useCache`, KV is the source of truth — entries persist until
686
+ * explicitly deleted or until their TTL expires. Use it for sessions,
687
+ * distributed locks, idempotency keys, counters — anything where losing
688
+ * the entry is a bug.
689
+ *
690
+ * Keys are namespaced under `<pluginId>:` transparently. Two plugins
691
+ * setting `"counter"` do not collide. `scan` only yields the calling
692
+ * plugin's own keys.
693
+ *
694
+ * @example
695
+ * ```typescript
696
+ * import { useKVStore } from '@kb-labs/shared-command-kit';
697
+ *
698
+ * async function withLock<T>(name: string, fn: () => Promise<T>): Promise<T> {
699
+ * const kv = useKVStore();
700
+ * if (!kv) throw new Error('KV store not configured');
701
+ *
702
+ * const token = crypto.randomUUID();
703
+ * const acquired = await kv.setIfNotExists(`lock:${name}`, token, { ttlMs: 30_000 });
704
+ * if (!acquired) throw new Error('lock held');
705
+ *
706
+ * try {
707
+ * return await fn();
708
+ * } finally {
709
+ * // Release only if we still hold the token (cas guards against ttl-takeover).
710
+ * await kv.cas(`lock:${name}`, token, null);
711
+ * }
712
+ * }
713
+ * ```
714
+ */
715
+
716
+ /**
717
+ * Resolve the KV store for the current execution.
718
+ *
719
+ * Returns `undefined` only when no adapter is wired at all. A plugin
720
+ * that didn't declare `permissions.platform.database.kvStore` still gets
721
+ * an instance — every method throws `PermissionError` on use.
722
+ */
723
+ declare function useKVStore(): IKVStore | undefined;
724
+ /**
725
+ * Cheap check used to gate optional features. Note that it returns true
726
+ * even when the plugin lacks `permissions.platform.database.kvStore` —
727
+ * the runtime will replace the adapter with a deny stub in that case, so
728
+ * this check tells you "is the slot wired?", not "can I actually use it?".
729
+ */
730
+ declare function isKVStoreAvailable(): boolean;
731
+
732
+ /**
733
+ * @module @kb-labs/shared-command-kit/helpers/use-notifications
734
+ * Platform notifier access helper.
735
+ *
736
+ * @example
737
+ * ```typescript
738
+ * import { useNotifications } from '@kb-labs/shared-command-kit';
739
+ *
740
+ * async handler(ctx, argv, flags) {
741
+ * const notifier = useNotifications();
742
+ * await notifier?.notify({ title: 'Done', body: 'Workflow complete', severity: 'info' });
743
+ * }
744
+ * ```
745
+ */
746
+
747
+ /**
748
+ * Access the platform notifier adapter.
749
+ * Returns undefined if the notifier adapter is not configured.
750
+ *
751
+ * @example
752
+ * ```typescript
753
+ * const notifier = useNotifications();
754
+ * if (notifier) {
755
+ * await notifier.notify({ title: 'Alert', body: 'Something failed', severity: 'critical' });
756
+ * }
757
+ * ```
758
+ */
759
+ declare function useNotifications(): INotifier | undefined;
760
+
616
761
  /**
617
762
  * @module @kb-labs/shared-command-kit/helpers/use-env
618
763
  *
@@ -639,4 +784,4 @@ declare function isCacheAvailable(): boolean;
639
784
  */
640
785
  declare function useEnv(key: string): string | undefined;
641
786
 
642
- export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
787
+ export { getLLMTier, isCacheAvailable, isDocumentDatabaseAvailable, isEmbeddingsAvailable, isKVStoreAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useDocumentDatabase, useEmbeddings, useEnv, useKVStore, useLLM, useLogger, useLoggerWithContext, useNotifications, usePlatform, useStorage, useVectorStore };
@@ -52,12 +52,34 @@ async function useConfig(productId, profileId) {
52
52
  if (!effectiveProductId) {
53
53
  return void 0;
54
54
  }
55
+ const g = globalThis;
56
+ const rawConfig = g.__KB_EFFECTIVE_CONFIG__ ?? g.__KB_RAW_CONFIG__;
57
+ if (rawConfig) {
58
+ return selectProductSection(rawConfig, effectiveProductId, profileId);
59
+ }
55
60
  const { usePlatform: usePlatform2 } = await Promise.resolve().then(() => (init_use_platform(), use_platform_exports));
56
61
  const platform = usePlatform2();
57
- if (!platform) {
58
- return void 0;
62
+ if (platform?.config) {
63
+ return await platform.config.getConfig(effectiveProductId, profileId);
59
64
  }
60
- return await platform.config.getConfig(effectiveProductId, profileId);
65
+ return void 0;
66
+ }
67
+ function selectProductSection(rawConfig, productId, profileId) {
68
+ const effectiveProfileId = profileId ?? process.env.KB_PROFILE ?? "default";
69
+ const profilesField = rawConfig.profiles;
70
+ if (Array.isArray(profilesField)) {
71
+ const profiles = profilesField;
72
+ const profile = profiles.find((p) => p.id === effectiveProfileId) ?? profiles[0];
73
+ if (profile?.products?.[productId] !== void 0) {
74
+ return profile.products[productId];
75
+ }
76
+ }
77
+ const legacyKeyMap = { mind: "knowledge" };
78
+ const legacyKey = legacyKeyMap[productId] ?? productId;
79
+ if (rawConfig[legacyKey] !== void 0) {
80
+ return rawConfig[legacyKey];
81
+ }
82
+ return void 0;
61
83
  }
62
84
 
63
85
  // src/helpers/use-logger.ts
@@ -271,6 +293,33 @@ function isCacheAvailable() {
271
293
  const cache = useCache();
272
294
  return !!cache;
273
295
  }
296
+
297
+ // src/helpers/use-document-database.ts
298
+ init_use_platform();
299
+ function useDocumentDatabase() {
300
+ const platform = usePlatform();
301
+ return platform.documentDatabase;
302
+ }
303
+ function isDocumentDatabaseAvailable() {
304
+ return useDocumentDatabase() !== void 0;
305
+ }
306
+
307
+ // src/helpers/use-kv-store.ts
308
+ init_use_platform();
309
+ function useKVStore() {
310
+ const platform = usePlatform();
311
+ return platform.kvStore;
312
+ }
313
+ function isKVStoreAvailable() {
314
+ return useKVStore() !== void 0;
315
+ }
316
+
317
+ // src/helpers/use-notifications.ts
318
+ init_use_platform();
319
+ function useNotifications() {
320
+ const platform = usePlatform();
321
+ return platform.notifier;
322
+ }
274
323
  function useEnv(key) {
275
324
  const runtime = runtimeContext.getStore();
276
325
  if (runtime?.env) {
@@ -279,6 +328,6 @@ function useEnv(key) {
279
328
  return process.env[key];
280
329
  }
281
330
 
282
- export { getLLMTier, isCacheAvailable, isEmbeddingsAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useEmbeddings, useEnv, useLLM, useLogger, useLoggerWithContext, usePlatform, useStorage, useVectorStore };
331
+ export { getLLMTier, isCacheAvailable, isDocumentDatabaseAvailable, isEmbeddingsAvailable, isKVStoreAvailable, isLLMAvailable, isPlatformConfigured, isVectorStoreAvailable, trackAnalyticsEvent, useAnalytics, useCache, useConfig, useDocumentDatabase, useEmbeddings, useEnv, useKVStore, useLLM, useLogger, useLoggerWithContext, useNotifications, usePlatform, useStorage, useVectorStore };
283
332
  //# sourceMappingURL=index.js.map
284
333
  //# 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","../../src/helpers/use-env.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,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,YAAA,IAAgB,QAAA,IAAY,OAAO,QAAA,CAAS,eAAe,UAAA,EAAY;AACzE,IAAA,OAAO,QAAA,CAAS,WAAW,WAAqB,CAAA;AAAA,EAClD;AAIA,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA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S;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 string);\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 typeof globalThis & { __KB_CONFIG_SECTION__?: string }).__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"]}
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-document-database.ts","../../src/helpers/use-kv-store.ts","../../src/helpers/use-notifications.ts","../../src/helpers/use-env.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;AAGnD,EAAA,OAAQ,eAAA,CAAgB,UAAS,IAA0CA,QAAA;AAC7E;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,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,YAAA,IAAgB,QAAA,IAAY,OAAO,QAAA,CAAS,eAAe,UAAA,EAAY;AACzE,IAAA,OAAO,QAAA,CAA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;AACrD,EAAA,OAAO,qBAAoB,KAAM,MAAA;AACnC;;;AClCA,iBAAA,EAAA;AASO,SAAS,UAAA,GAAmC;AACjD,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,OAAO,QAAA,CAAS,OAAA;AAClB;AAQO,SAAS,kBAAA,GAA8B;AAC5C,EAAA,OAAO,YAAW,KAAM,MAAA;AAC1B;;;AC5CA,iBAAA,EAAA;AAeO,SAAS,gBAAA,GAA0C;AACxD,EAAA,MAAM,WAAW,WAAA,EAAY;AAC7B,EAAA,OAAO,QAAA,CAAS,QAAA;AAClB;ACNO,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 // ALS stores PlatformServices (governed wrapper); at runtime it is always\n // structurally compatible with PlatformContainer — the cast is safe.\n return (platformContext.getStore() as unknown 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 string);\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';\nexport { useDocumentDatabase, isDocumentDatabaseAvailable } from './use-document-database.js';\nexport { useKVStore, isKVStoreAvailable } from './use-kv-store.js';\n\n// Notifications\nexport { useNotifications } from './use-notifications.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 typeof globalThis & { __KB_CONFIG_SECTION__?: string }).__KB_CONFIG_SECTION__;\n }\n\n if (!effectiveProductId) {\n return undefined;\n }\n\n // ── EXPLICIT OVERRIDE (2026-06-07) ──────────────────────────────────────────\n // Config is read DIRECTLY from the global the service already loaded\n // (`service-bootstrap` sets `__KB_RAW_CONFIG__` / `__KB_EFFECTIVE_CONFIG__`),\n // NOT through the `platform.config` adapter.\n //\n // Rationale: in-process the adapter was pure indirection over this same global,\n // and on the isolated/worker path it crashed — config is attached post-assembly\n // only on the parent path, so `platform.config` was undefined in worker handlers\n // (the \"F2\" bug). The global IS populated even in those workers, so reading it\n // directly is correct AND removes the adapter from the hot path.\n //\n // The `platform.config` proxy is kept ONLY as a fallback for a genuinely remote\n // worker that has no shared memory (future client/server execution).\n // ────────────────────────────────────────────────────────────────────────────\n const g = globalThis as typeof globalThis & {\n __KB_EFFECTIVE_CONFIG__?: Record<string, unknown>;\n __KB_RAW_CONFIG__?: Record<string, unknown>;\n };\n const rawConfig = g.__KB_EFFECTIVE_CONFIG__ ?? g.__KB_RAW_CONFIG__;\n\n if (rawConfig) {\n return selectProductSection<T>(rawConfig, effectiveProductId, profileId);\n }\n\n // Fallback: no global in this process (genuinely remote/isolated worker without\n // shared memory) → use the platform.config IPC proxy if present.\n const { usePlatform } = await import('./use-platform.js');\n const platform = usePlatform();\n if (platform?.config) {\n return (await platform.config.getConfig(effectiveProductId, profileId)) as T | undefined;\n }\n\n return undefined;\n}\n\n/**\n * Select a product's config section from the raw kb.config.json object.\n *\n * Mirrors core-runtime `ConfigAdapter.getConfig`: Profiles v2 first\n * (`profiles[].products[productId]`), then the legacy flat structure\n * (top-level key, with the `mind` → `knowledge` alias). Returns ONLY the\n * product-specific section, never the whole config.\n */\nfunction selectProductSection<T = any>(\n rawConfig: Record<string, unknown>,\n productId: string,\n profileId?: string,\n): T | undefined {\n const effectiveProfileId = profileId ?? process.env.KB_PROFILE ?? 'default';\n\n // Profiles v2 structure\n const profilesField = (rawConfig as { profiles?: unknown }).profiles;\n if (Array.isArray(profilesField)) {\n type RawProfile = { id?: string; products?: Record<string, unknown> };\n const profiles = profilesField as RawProfile[];\n const profile = profiles.find((p) => p.id === effectiveProfileId) ?? profiles[0];\n if (profile?.products?.[productId] !== undefined) {\n return profile.products[productId] as T;\n }\n }\n\n // Legacy flat structure (mind → knowledge alias)\n const legacyKeyMap: Record<string, string> = { mind: 'knowledge' };\n const legacyKey = legacyKeyMap[productId] ?? productId;\n if (rawConfig[legacyKey] !== undefined) {\n return rawConfig[legacyKey] as T;\n }\n\n return 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-document-database\n *\n * Hook for the per-plugin document database — structured persistence with\n * filters, transactions, and indexed collections.\n *\n * The adapter is resolved from the current `usePlatform()` context, so the\n * instance you receive is already wrapped with this plugin's permissions:\n * collection names are namespaced under `<pluginId>__<name>`, and any call\n * to a collection the plugin didn't declare in\n * `permissions.platform.database.document.owns` / `.access` rejects with\n * `PermissionError`.\n *\n * @example\n * ```typescript\n * import { useDocumentDatabase } from '@kb-labs/shared-command-kit';\n *\n * interface Run extends BaseDocument {\n * status: 'queued' | 'running' | 'done';\n * startedAt: number;\n * }\n *\n * async function handler() {\n * const docs = useDocumentDatabase();\n * if (!docs) {\n * throw new Error('Plugin needs documentDatabase configured');\n * }\n *\n * await docs.ensureCollection('runs', {\n * indexes: [{ path: 'status' }],\n * });\n *\n * const queued = await docs.find<Run>('runs', { status: { $eq: 'queued' } });\n * return queued;\n * }\n * ```\n */\n\nimport type { IDocumentDatabase } from '@kb-labs/core-platform';\nimport { usePlatform } from './use-platform.js';\n\n/**\n * Resolve the document database for the current execution.\n *\n * Returns `undefined` when no adapter is configured at all. When a plugin\n * declared permissions but is missing the wiring (NoOp adapter on the\n * platform side) you still get an instance — calls just throw on use.\n *\n * Always check before using:\n *\n * ```ts\n * const docs = useDocumentDatabase();\n * if (!docs) {\n * // The platform was started without a document database;\n * // either skip the feature or fail fast with a clear error.\n * return;\n * }\n * ```\n */\nexport function useDocumentDatabase(): IDocumentDatabase | undefined {\n const platform = usePlatform();\n return platform.documentDatabase;\n}\n\n/**\n * Cheap check for \"is the document database available?\". Returns true even\n * for NoOp adapters configured by the platform — use this to gate optional\n * features, not as a security check.\n */\nexport function isDocumentDatabaseAvailable(): boolean {\n return useDocumentDatabase() !== undefined;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-kv-store\n *\n * Hook for the per-plugin durable key-value store.\n *\n * Unlike `useCache`, KV is the source of truth — entries persist until\n * explicitly deleted or until their TTL expires. Use it for sessions,\n * distributed locks, idempotency keys, counters — anything where losing\n * the entry is a bug.\n *\n * Keys are namespaced under `<pluginId>:` transparently. Two plugins\n * setting `\"counter\"` do not collide. `scan` only yields the calling\n * plugin's own keys.\n *\n * @example\n * ```typescript\n * import { useKVStore } from '@kb-labs/shared-command-kit';\n *\n * async function withLock<T>(name: string, fn: () => Promise<T>): Promise<T> {\n * const kv = useKVStore();\n * if (!kv) throw new Error('KV store not configured');\n *\n * const token = crypto.randomUUID();\n * const acquired = await kv.setIfNotExists(`lock:${name}`, token, { ttlMs: 30_000 });\n * if (!acquired) throw new Error('lock held');\n *\n * try {\n * return await fn();\n * } finally {\n * // Release only if we still hold the token (cas guards against ttl-takeover).\n * await kv.cas(`lock:${name}`, token, null);\n * }\n * }\n * ```\n */\n\nimport type { IKVStore } from '@kb-labs/core-platform';\nimport { usePlatform } from './use-platform.js';\n\n/**\n * Resolve the KV store for the current execution.\n *\n * Returns `undefined` only when no adapter is wired at all. A plugin\n * that didn't declare `permissions.platform.database.kvStore` still gets\n * an instance — every method throws `PermissionError` on use.\n */\nexport function useKVStore(): IKVStore | undefined {\n const platform = usePlatform();\n return platform.kvStore;\n}\n\n/**\n * Cheap check used to gate optional features. Note that it returns true\n * even when the plugin lacks `permissions.platform.database.kvStore` —\n * the runtime will replace the adapter with a deny stub in that case, so\n * this check tells you \"is the slot wired?\", not \"can I actually use it?\".\n */\nexport function isKVStoreAvailable(): boolean {\n return useKVStore() !== undefined;\n}\n","/**\n * @module @kb-labs/shared-command-kit/helpers/use-notifications\n * Platform notifier access helper.\n *\n * @example\n * ```typescript\n * import { useNotifications } from '@kb-labs/shared-command-kit';\n *\n * async handler(ctx, argv, flags) {\n * const notifier = useNotifications();\n * await notifier?.notify({ title: 'Done', body: 'Workflow complete', severity: 'info' });\n * }\n * ```\n */\n\nimport { usePlatform } from './use-platform';\nimport type { INotifier } from '@kb-labs/core-platform';\n\n/**\n * Access the platform notifier adapter.\n * Returns undefined if the notifier adapter is not configured.\n *\n * @example\n * ```typescript\n * const notifier = useNotifications();\n * if (notifier) {\n * await notifier.notify({ title: 'Alert', body: 'Something failed', severity: 'critical' });\n * }\n * ```\n */\nexport function useNotifications(): INotifier | undefined {\n const platform = usePlatform();\n return platform.notifier;\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"]}