@iworkforces/tracelattice 2.0.8 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -64
- package/dist/ServerConfig.d.ts +1 -1
- package/dist/ServerConfig.js.map +1 -1
- package/dist/cli.js +18 -73
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigLoader.d.ts +29 -26
- package/dist/config/ConfigLoader.d.ts.map +1 -1
- package/dist/config/ConfigLoader.js +40 -36
- package/dist/config/ConfigLoader.js.map +1 -1
- package/dist/contracts/PersistenceBackend.d.ts +7 -108
- package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
- package/dist/contracts/PersistenceBackend.js +1 -6
- package/dist/contracts/calibrator.d.ts +6 -6
- package/dist/contracts/calibrator.d.ts.map +1 -1
- package/dist/contracts/ids.d.ts +1 -8
- package/dist/contracts/ids.d.ts.map +1 -1
- package/dist/contracts/ids.js +2 -3
- package/dist/contracts/ids.js.map +1 -1
- package/dist/contracts/interfaces.d.ts +4 -6
- package/dist/contracts/interfaces.d.ts.map +1 -1
- package/dist/contracts/persistence-work.d.ts +2 -3
- package/dist/contracts/persistence-work.d.ts.map +1 -1
- package/dist/core/HistoryManager.d.ts +12 -16
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +19 -40
- package/dist/core/HistoryManager.js.map +1 -1
- package/dist/core/IHistoryManager.d.ts +22 -30
- package/dist/core/IHistoryManager.d.ts.map +1 -1
- package/dist/core/InputNormalizer.d.ts +7 -24
- package/dist/core/InputNormalizer.d.ts.map +1 -1
- package/dist/core/InputNormalizer.js +3 -9
- package/dist/core/InputNormalizer.js.map +1 -1
- package/dist/core/PersistenceBuffer.d.ts +3 -20
- package/dist/core/PersistenceBuffer.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.js +1 -4
- package/dist/core/PersistenceBuffer.js.map +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js +4 -10
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/PersistenceWriter.d.ts.map +1 -1
- package/dist/core/PersistenceWriter.js +3 -12
- package/dist/core/PersistenceWriter.js.map +1 -1
- package/dist/core/SessionErrors.d.ts +0 -11
- package/dist/core/SessionErrors.d.ts.map +1 -1
- package/dist/core/SessionErrors.js +1 -14
- package/dist/core/SessionErrors.js.map +1 -1
- package/dist/core/SessionLock.d.ts +4 -5
- package/dist/core/SessionLock.d.ts.map +1 -1
- package/dist/core/SessionLock.js +5 -10
- package/dist/core/SessionLock.js.map +1 -1
- package/dist/core/SessionManager.d.ts +0 -2
- package/dist/core/SessionManager.d.ts.map +1 -1
- package/dist/core/SessionManager.js +3 -5
- package/dist/core/SessionManager.js.map +1 -1
- package/dist/core/SessionResetCoordinator.d.ts +10 -7
- package/dist/core/SessionResetCoordinator.d.ts.map +1 -1
- package/dist/core/SessionResetCoordinator.js +10 -28
- package/dist/core/SessionResetCoordinator.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts +5 -5
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js +4 -40
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts +10 -3
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +34 -38
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -1
- package/dist/core/VerificationOutcomeAdmission.js +5 -7
- package/dist/core/VerificationOutcomeAdmission.js.map +1 -1
- package/dist/core/evaluator/Calibrator.d.ts +1 -1
- package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
- package/dist/core/evaluator/Calibrator.js +2 -5
- package/dist/core/evaluator/Calibrator.js.map +1 -1
- package/dist/core/evaluator/internals.d.ts +0 -4
- package/dist/core/evaluator/internals.d.ts.map +1 -1
- package/dist/core/evaluator/internals.js +1 -3
- package/dist/core/evaluator/internals.js.map +1 -1
- package/dist/core/graph/Edge.d.ts +1 -1
- package/dist/core/graph/EdgeEmitter.d.ts +2 -4
- package/dist/core/graph/EdgeEmitter.d.ts.map +1 -1
- package/dist/core/graph/EdgeEmitter.js +2 -4
- package/dist/core/graph/EdgeEmitter.js.map +1 -1
- package/dist/core/reasoning/OutcomeRecorder.d.ts +0 -1
- package/dist/core/reasoning/OutcomeRecorder.d.ts.map +1 -1
- package/dist/core/reasoning/OutcomeRecorder.js.map +1 -1
- package/dist/core/reasoning/strategies/SequentialStrategy.d.ts +3 -3
- package/dist/core/reasoning/strategies/SequentialStrategy.js.map +1 -1
- package/dist/core/thought.d.ts +2 -1
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/errors.d.ts +4 -20
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -28
- package/dist/errors.js.map +1 -1
- package/dist/lib.d.ts +13 -20
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +4 -7
- package/dist/lib.js.map +1 -1
- package/dist/logger/NullLogger.d.ts +9 -11
- package/dist/logger/NullLogger.d.ts.map +1 -1
- package/dist/logger/NullLogger.js.map +1 -1
- package/dist/persistence/FilePersistence.d.ts +3 -12
- package/dist/persistence/FilePersistence.d.ts.map +1 -1
- package/dist/persistence/FilePersistence.js +9 -61
- package/dist/persistence/FilePersistence.js.map +1 -1
- package/dist/persistence/FileSnapshotV2.d.ts +2 -2
- package/dist/persistence/FileSnapshotV2.js +2 -2
- package/dist/persistence/FileSnapshotV2.js.map +1 -1
- package/dist/persistence/FileWriter.d.ts +1 -0
- package/dist/persistence/FileWriter.d.ts.map +1 -1
- package/dist/persistence/FileWriter.js +3 -3
- package/dist/persistence/FileWriter.js.map +1 -1
- package/dist/persistence/MemoryPersistence.d.ts +5 -15
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
- package/dist/persistence/MemoryPersistence.js +6 -40
- package/dist/persistence/MemoryPersistence.js.map +1 -1
- package/dist/persistence/PersistenceCodec.js +1 -3
- package/dist/persistence/PersistenceCodec.js.map +1 -1
- package/dist/persistence/PersistenceErrors.d.ts +0 -6
- package/dist/persistence/PersistenceErrors.d.ts.map +1 -1
- package/dist/persistence/PersistenceErrors.js +1 -9
- package/dist/persistence/PersistenceErrors.js.map +1 -1
- package/dist/persistence/PersistenceScope.d.ts.map +1 -1
- package/dist/persistence/PersistenceScope.js +2 -2
- package/dist/persistence/PersistenceScope.js.map +1 -1
- package/dist/persistence/SqlitePersistence.d.ts +3 -10
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
- package/dist/persistence/SqlitePersistence.js +2 -26
- package/dist/persistence/SqlitePersistence.js.map +1 -1
- package/dist/persistence/SqliteSchemaV2.d.ts.map +1 -1
- package/dist/persistence/SqliteSchemaV2.js +3 -12
- package/dist/persistence/SqliteSchemaV2.js.map +1 -1
- package/dist/pool/ConnectionPool.d.ts +3 -12
- package/dist/pool/ConnectionPool.d.ts.map +1 -1
- package/dist/pool/ConnectionPool.js +5 -8
- package/dist/pool/ConnectionPool.js.map +1 -1
- package/dist/pool/IConnectionPool.d.ts +3 -9
- package/dist/pool/IConnectionPool.d.ts.map +1 -1
- package/dist/registry/SkillRegistry.d.ts +1 -7
- package/dist/registry/SkillRegistry.d.ts.map +1 -1
- package/dist/registry/SkillRegistry.js +0 -15
- package/dist/registry/SkillRegistry.js.map +1 -1
- package/dist/registry/ToolRegistry.d.ts +1 -9
- package/dist/registry/ToolRegistry.d.ts.map +1 -1
- package/dist/registry/ToolRegistry.js +0 -21
- package/dist/registry/ToolRegistry.js.map +1 -1
- package/dist/schema.d.ts +2 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +3 -3
- package/dist/schema.js.map +1 -1
- package/dist/transport/BaseTransport.d.ts +0 -9
- package/dist/transport/BaseTransport.d.ts.map +1 -1
- package/dist/transport/BaseTransport.js +0 -11
- package/dist/transport/BaseTransport.js.map +1 -1
- package/dist/watchers/SkillWatcher.d.ts.map +1 -1
- package/dist/watchers/SkillWatcher.js +1 -1
- package/dist/watchers/SkillWatcher.js.map +1 -1
- package/package.json +1 -1
- package/dist/contracts/PersistenceBackend.js.map +0 -1
- package/dist/persistence/FileLegacyImport.d.ts +0 -2
- package/dist/persistence/FileLegacyImport.d.ts.map +0 -1
- package/dist/persistence/FileLegacyImport.js +0 -183
- package/dist/persistence/FileLegacyImport.js.map +0 -1
- package/dist/persistence/SessionScopedPersistence.d.ts +0 -4
- package/dist/persistence/SessionScopedPersistence.d.ts.map +0 -1
- package/dist/persistence/SessionScopedPersistence.js +0 -9
- package/dist/persistence/SessionScopedPersistence.js.map +0 -1
- package/dist/persistence/SqliteLegacyImport.d.ts +0 -14
- package/dist/persistence/SqliteLegacyImport.d.ts.map +0 -1
- package/dist/persistence/SqliteLegacyImport.js +0 -136
- package/dist/persistence/SqliteLegacyImport.js.map +0 -1
- package/dist/persistence/SqliteLegacySchema.d.ts +0 -15
- package/dist/persistence/SqliteLegacySchema.d.ts.map +0 -1
- package/dist/persistence/SqliteLegacySchema.js +0 -72
- package/dist/persistence/SqliteLegacySchema.js.map +0 -1
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n\tUNKNOWN_TOOL: 'UNKNOWN_TOOL',\n\tLOCK_TIMEOUT: 'LOCK_TIMEOUT',\n\tCLI_SHUTDOWN_TIMEOUT: 'CLI_SHUTDOWN_TIMEOUT',\n\tSESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',\n\tSESSION_LIFECYCLE_CLOSED: 'SESSION_LIFECYCLE_CLOSED',\n\tPERSISTENCE_OWNERSHIP: 'PERSISTENCE_OWNERSHIP',\n\tPERSISTENCE_CORRUPTION: 'PERSISTENCE_CORRUPTION',\n\tPERSISTENCE_PUBLICATION: 'PERSISTENCE_PUBLICATION',\n\tPERSISTENCE_CLOSED: 'PERSISTENCE_CLOSED',\n\tPERSISTENCE_DRAIN: 'PERSISTENCE_DRAIN',\n\tPERSISTENCE_SESSION_ADMISSION_CLOSED: 'PERSISTENCE_SESSION_ADMISSION_CLOSED',\n\tPERSISTENCE_SESSION_BARRIER_REENTRANCY: 'PERSISTENCE_SESSION_BARRIER_REENTRANCY',\n\tASYNC_RESET_REQUIRED: 'ASYNC_RESET_REQUIRED',\n\tPERSISTENCE_CAPABILITY_UNSUPPORTED: 'PERSISTENCE_CAPABILITY_UNSUPPORTED',\n\tPERSISTENCE_SCOPE_MISMATCH: 'PERSISTENCE_SCOPE_MISMATCH',\n\tPERSISTENCE_UNAVAILABLE: 'PERSISTENCE_UNAVAILABLE',\n\tPERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY',\n\tPERSISTENCE_IMPORT_REQUIRED: 'PERSISTENCE_IMPORT_REQUIRED',\n\tPERSISTENCE_LEGACY_AMBIGUITY: 'PERSISTENCE_LEGACY_AMBIGUITY',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * All known warning codes as a const object.\n * Warnings are non-fatal advisory signals returned alongside successful results.\n */\nexport const WARNING_CODES = {\n\tTOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED',\n} as const;\n\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.getTool('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.getSkill('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(\n\t\t\t`History size ${currentSize} exceeds limit ${maxSize}`,\n\t\t\tERROR_CODES.HISTORY_LIMIT_EXCEEDED\n\t\t);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.hasSkill(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.hasTool(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Error thrown when a tool_call references a tool not registered with the server.\n *\n * Acts as an allowlist gate: only tools registered in the ToolRegistry may be\n * invoked through tool interleave. Prevents arbitrary tool name injection.\n */\nexport class UnknownToolError extends SequentialThinkingError {\n\tpublic readonly toolName: string;\n\n\tconstructor(toolName: string, message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? `Unknown tool '${toolName}': not registered with the server`,\n\t\t\tERROR_CODES.UNKNOWN_TOOL\n\t\t);\n\t\tthis.name = 'UnknownToolError';\n\t\tthis.toolName = toolName;\n\t}\n}\n\n/** Error thrown when the CLI's complete shutdown exceeds its outer deadline. */\nexport class CliShutdownTimeoutError extends SequentialThinkingError {\n\tpublic readonly timeoutMs: number;\n\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`CLI shutdown timed out after ${timeoutMs}ms`, ERROR_CODES.CLI_SHUTDOWN_TIMEOUT);\n\t\tthis.name = 'CliShutdownTimeoutError';\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nexport class PersistenceOwnershipError extends SequentialThinkingError {\n\tpublic readonly canonicalDataDir: string;\n\tpublic readonly lockPath: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(canonicalDataDir: string, lockPath: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persistence directory '${canonicalDataDir}' already has an active writer`,\n\t\t\tERROR_CODES.PERSISTENCE_OWNERSHIP\n\t\t);\n\t\tthis.name = 'PersistenceOwnershipError';\n\t\tthis.canonicalDataDir = canonicalDataDir;\n\t\tthis.lockPath = lockPath;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceCorruptionError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${path}' is corrupt or incompatible`,\n\t\t\tERROR_CODES.PERSISTENCE_CORRUPTION\n\t\t);\n\t\tthis.name = 'PersistenceCorruptionError';\n\t\tthis.path = path;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Error raised when startup cannot read from an unhealthy persistence backend. */\nexport class PersistenceUnavailableError extends SequentialThinkingError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Persistence backend is unavailable during startup restore',\n\t\t\tERROR_CODES.PERSISTENCE_UNAVAILABLE\n\t\t);\n\t\tthis.name = 'PersistenceUnavailableError';\n\t}\n}\n\nexport type PersistencePublicationStage = 'temporary-write' | 'atomic-replacement' | 'cleanup';\n\nexport class PersistencePublicationError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic readonly stage: PersistencePublicationStage;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, stage: PersistencePublicationStage, cause: unknown) {\n\t\tsuper(\n\t\t\t`Failed persistence publication for '${path}' during ${stage}`,\n\t\t\tERROR_CODES.PERSISTENCE_PUBLICATION\n\t\t);\n\t\tthis.name = 'PersistencePublicationError';\n\t\tthis.path = path;\n\t\tthis.stage = stage;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceClosedError extends SequentialThinkingError {\n\tpublic readonly dataDir: string;\n\n\tconstructor(dataDir: string) {\n\t\tsuper(`Persistence writer for '${dataDir}' is closed`, ERROR_CODES.PERSISTENCE_CLOSED);\n\t\tthis.name = 'PersistenceClosedError';\n\t\tthis.dataDir = dataDir;\n\t}\n}\n\n/** Error raised for well-formed but unsupported or drifted persisted data. */\nexport class PersistenceCompatibilityError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly detail: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(sourcePath: string, detail: string, cause?: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${sourcePath}' is incompatible: ${detail}`,\n\t\t\tERROR_CODES.PERSISTENCE_COMPATIBILITY\n\t\t);\n\t\tthis.name = 'PersistenceCompatibilityError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.detail = detail;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Error raised when legacy files require an explicit one-way import. */\nexport class PersistenceImportRequiredError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly legacyArtifacts: readonly string[];\n\n\tconstructor(sourcePath: string, legacyArtifacts: readonly string[]) {\n\t\tsuper(\n\t\t\t`Legacy persistence at '${sourcePath}' requires explicit import`,\n\t\t\tERROR_CODES.PERSISTENCE_IMPORT_REQUIRED\n\t\t);\n\t\tthis.name = 'PersistenceImportRequiredError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.legacyArtifacts = [...legacyArtifacts];\n\t}\n}\n\n/** Error raised when legacy bytes do not identify one durable namespace. */\nexport class PersistenceLegacyAmbiguityError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly detail: string;\n\n\tconstructor(sourcePath: string, detail: string) {\n\t\tsuper(\n\t\t\t`Legacy persistence at '${sourcePath}' is ambiguous: ${detail}`,\n\t\t\tERROR_CODES.PERSISTENCE_LEGACY_AMBIGUITY\n\t\t);\n\t\tthis.name = 'PersistenceLegacyAmbiguityError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.detail = detail;\n\t}\n}\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","WARNING_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","UnknownToolError","CliShutdownTimeoutError","timeoutMs","PersistenceOwnershipError","canonicalDataDir","lockPath","PersistenceCorruptionError","path","PersistenceUnavailableError","PersistencePublicationError","stage","PersistenceClosedError","dataDir","PersistenceCompatibilityError","sourcePath","detail","PersistenceImportRequiredError","legacyArtifacts","PersistenceLegacyAmbiguityError","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBA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;QAClB,IAAI,CAAC,MAAM,GAAGC;QACd,IAAI,CAAC,KAAK,GAAGlC;IACd;AACD;AAGO,MAAMmC,uCAAuClD;IACnC,WAAmB;IACnB,gBAAmC;IAEnD,YAAYgD,UAAkB,EAAEG,eAAkC,CAAE;QACnE,KAAK,CACJ,CAAC,uBAAuB,EAAEH,WAAW,0BAA0B,CAAC,EAChElD,YAAY,2BAA2B;QAExC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAGkD;QAClB,IAAI,CAAC,eAAe,GAAG;eAAIG;SAAgB;IAC5C;AACD;AAGO,MAAMC,wCAAwCpD;IACpC,WAAmB;IACnB,OAAe;IAE/B,YAAYgD,UAAkB,EAAEC,MAAc,CAAE;QAC/C,KAAK,CACJ,CAAC,uBAAuB,EAAED,WAAW,gBAAgB,EAAEC,QAAQ,EAC/DnD,YAAY,4BAA4B;QAEzC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAGkD;QAClB,IAAI,CAAC,MAAM,GAAGC;IACf;AACD;AAKO,SAASI,YACfC,GAAY,EACZnD,IAAO;IAEP,OAAOmD,eAAetD,2BAA2BsD,IAAI,IAAI,KAAKnD;AAC/D;AAoBO,SAASoD,gBAAgBC,KAAc;IAC7C,OAAOA,iBAAiBvD,QAAQuD,MAAM,OAAO,GAAGC,OAAOD;AACxD"}
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n\tUNKNOWN_TOOL: 'UNKNOWN_TOOL',\n\tLOCK_TIMEOUT: 'LOCK_TIMEOUT',\n\tCLI_SHUTDOWN_TIMEOUT: 'CLI_SHUTDOWN_TIMEOUT',\n\tSESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',\n\tSESSION_LIFECYCLE_CLOSED: 'SESSION_LIFECYCLE_CLOSED',\n\tPERSISTENCE_OWNERSHIP: 'PERSISTENCE_OWNERSHIP',\n\tPERSISTENCE_CORRUPTION: 'PERSISTENCE_CORRUPTION',\n\tPERSISTENCE_PUBLICATION: 'PERSISTENCE_PUBLICATION',\n\tPERSISTENCE_CLOSED: 'PERSISTENCE_CLOSED',\n\tPERSISTENCE_DRAIN: 'PERSISTENCE_DRAIN',\n\tPERSISTENCE_SESSION_ADMISSION_CLOSED: 'PERSISTENCE_SESSION_ADMISSION_CLOSED',\n\tPERSISTENCE_SESSION_BARRIER_REENTRANCY: 'PERSISTENCE_SESSION_BARRIER_REENTRANCY',\n\tPERSISTENCE_SCOPE_MISMATCH: 'PERSISTENCE_SCOPE_MISMATCH',\n\tPERSISTENCE_UNAVAILABLE: 'PERSISTENCE_UNAVAILABLE',\n\tPERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * All known warning codes as a const object.\n * Warnings are non-fatal advisory signals returned alongside successful results.\n */\nexport const WARNING_CODES = {\n\tTOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED',\n} as const;\n\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.get('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.get('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(\n\t\t\t`History size ${currentSize} exceeds limit ${maxSize}`,\n\t\t\tERROR_CODES.HISTORY_LIMIT_EXCEEDED\n\t\t);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.has(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.has(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Error thrown when a tool_call references a tool not registered with the server.\n *\n * Acts as an allowlist gate: only tools registered in the ToolRegistry may be\n * invoked through tool interleave. Prevents arbitrary tool name injection.\n */\nexport class UnknownToolError extends SequentialThinkingError {\n\tpublic readonly toolName: string;\n\n\tconstructor(toolName: string, message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? `Unknown tool '${toolName}': not registered with the server`,\n\t\t\tERROR_CODES.UNKNOWN_TOOL\n\t\t);\n\t\tthis.name = 'UnknownToolError';\n\t\tthis.toolName = toolName;\n\t}\n}\n\n/** Error thrown when the CLI's complete shutdown exceeds its outer deadline. */\nexport class CliShutdownTimeoutError extends SequentialThinkingError {\n\tpublic readonly timeoutMs: number;\n\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`CLI shutdown timed out after ${timeoutMs}ms`, ERROR_CODES.CLI_SHUTDOWN_TIMEOUT);\n\t\tthis.name = 'CliShutdownTimeoutError';\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nexport class PersistenceOwnershipError extends SequentialThinkingError {\n\tpublic readonly canonicalDataDir: string;\n\tpublic readonly lockPath: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(canonicalDataDir: string, lockPath: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persistence directory '${canonicalDataDir}' already has an active writer`,\n\t\t\tERROR_CODES.PERSISTENCE_OWNERSHIP\n\t\t);\n\t\tthis.name = 'PersistenceOwnershipError';\n\t\tthis.canonicalDataDir = canonicalDataDir;\n\t\tthis.lockPath = lockPath;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceCorruptionError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${path}' is corrupt or incompatible`,\n\t\t\tERROR_CODES.PERSISTENCE_CORRUPTION\n\t\t);\n\t\tthis.name = 'PersistenceCorruptionError';\n\t\tthis.path = path;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Error raised when startup cannot read from an unhealthy persistence backend. */\nexport class PersistenceUnavailableError extends SequentialThinkingError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Persistence backend is unavailable during startup restore',\n\t\t\tERROR_CODES.PERSISTENCE_UNAVAILABLE\n\t\t);\n\t\tthis.name = 'PersistenceUnavailableError';\n\t}\n}\n\nexport type PersistencePublicationStage = 'temporary-write' | 'atomic-replacement' | 'cleanup';\n\nexport class PersistencePublicationError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic readonly stage: PersistencePublicationStage;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, stage: PersistencePublicationStage, cause: unknown) {\n\t\tsuper(\n\t\t\t`Failed persistence publication for '${path}' during ${stage}`,\n\t\t\tERROR_CODES.PERSISTENCE_PUBLICATION\n\t\t);\n\t\tthis.name = 'PersistencePublicationError';\n\t\tthis.path = path;\n\t\tthis.stage = stage;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceClosedError extends SequentialThinkingError {\n\tpublic readonly dataDir: string;\n\n\tconstructor(dataDir: string) {\n\t\tsuper(`Persistence writer for '${dataDir}' is closed`, ERROR_CODES.PERSISTENCE_CLOSED);\n\t\tthis.name = 'PersistenceClosedError';\n\t\tthis.dataDir = dataDir;\n\t}\n}\n\n/** Error raised for well-formed but unsupported or drifted persisted data. */\nexport class PersistenceCompatibilityError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly detail: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(sourcePath: string, detail: string, cause?: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${sourcePath}' is incompatible: ${detail}`,\n\t\t\tERROR_CODES.PERSISTENCE_COMPATIBILITY\n\t\t);\n\t\tthis.name = 'PersistenceCompatibilityError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.detail = detail;\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","WARNING_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","UnknownToolError","CliShutdownTimeoutError","timeoutMs","PersistenceOwnershipError","canonicalDataDir","lockPath","PersistenceCorruptionError","path","PersistenceUnavailableError","PersistencePublicationError","stage","PersistenceClosedError","dataDir","PersistenceCompatibilityError","sourcePath","detail","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,wBAAwB;IACxB,wBAAwB;IACxB,iBAAiB;IACjB,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,oBAAoB;IACpB,mBAAmB;IACnB,sBAAsB;IACtB,iBAAiB;IACjB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,sBAAsB;IACtB,oBAAoB;IACpB,mBAAmB;IACnB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;IACd,cAAc;IACd,sBAAsB;IACtB,uBAAuB;IACvB,0BAA0B;IAC1B,uBAAuB;IACvB,wBAAwB;IACxB,yBAAyB;IACzB,oBAAoB;IACpB,mBAAmB;IACnB,sCAAsC;IACtC,wCAAwC;IACxC,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;AAC5B;AAQO,MAAMC,gBAAgB;IAC5B,yBAAyB;AAC1B;AA+BO,MAAMC,gCAAgCC;IAE5B,KAAgB;IAiBhC,YAAYC,OAAe,EAAEC,IAAe,CAAE;QAC7C,KAAK,CAACD;QACN,IAAI,CAAC,IAAI,GAAGC;QACZ,IAAI,CAAC,IAAI,GAAG;QACZF,MAAM,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW;IAC/C;AACD;AAEO,MAAMG,2BAA2BJ;IACvC,YAAYE,OAAe,CAAE;QAC5B,KAAK,CAACA,SAASJ,YAAY,mBAAmB;QAC9C,IAAI,CAAC,IAAI,GAA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MAAMC,sCAAsC/C;IAClC,WAAmB;IACnB,OAAe;IACN,MAAe;IAExC,YAAYgD,UAAkB,EAAEC,MAAc,EAAElC,KAAe,CAAE;QAChE,KAAK,CACJ,CAAC,mBAAmB,EAAEiC,WAAW,mBAAmB,EAAEC,QAAQ,EAC9DnD,YAAY,yBAAyB;QAEtC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAGkD;QAClB,IAAI,CAAC,MAAM,GAAGC;QACd,IAAI,CAAC,KAAK,GAAGlC;IACd;AACD;AAKO,SAASmC,YACfC,GAAY,EACZhD,IAAO;IAEP,OAAOgD,eAAenD,2BAA2BmD,IAAI,IAAI,KAAKhD;AAC/D;AAoBO,SAASiD,gBAAgBC,KAAc;IAC7C,OAAOA,iBAAiBpD,QAAQoD,MAAM,OAAO,GAAGC,OAAOD;AACxD"}
|
package/dist/lib.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EventEmitter } from 'node:events';
|
|
2
2
|
import type * as v from 'valibot';
|
|
3
3
|
import type { ThoughtData } from './core/thought.js';
|
|
4
|
-
import type
|
|
4
|
+
import { type BranchId } from './contracts/ids.js';
|
|
5
5
|
import type { SequentialThinkingSchema } from './schema.js';
|
|
6
6
|
import type { IDisposable } from './types/disposable.js';
|
|
7
7
|
import type { ConfigFileOptions } from './config/ConfigLoader.js';
|
|
@@ -92,11 +92,12 @@ export interface IToolAwareSequentialThinkingServer extends IDisposable {
|
|
|
92
92
|
skills: number;
|
|
93
93
|
}>;
|
|
94
94
|
/**
|
|
95
|
-
* Get all branches
|
|
95
|
+
* Get all branches for one explicit thought session.
|
|
96
96
|
*
|
|
97
|
+
* @param sessionId - Valid thought-session identifier
|
|
97
98
|
* @returns Map of branch IDs to thought arrays
|
|
98
99
|
*/
|
|
99
|
-
getBranches(): Record<string, ThoughtData[]>;
|
|
100
|
+
getBranches(sessionId: string): Record<string, ThoughtData[]>;
|
|
100
101
|
/**
|
|
101
102
|
* Process a thought through the configured pipeline.
|
|
102
103
|
*
|
|
@@ -117,10 +118,6 @@ export interface IToolAwareSequentialThinkingServer extends IDisposable {
|
|
|
117
118
|
* Stop the server and clean up watchers, suspension stores, and persistence.
|
|
118
119
|
*/
|
|
119
120
|
stop(): Promise<void>;
|
|
120
|
-
/**
|
|
121
|
-
* Clear all server state (history, tools, skills).
|
|
122
|
-
*/
|
|
123
|
-
clear(): void;
|
|
124
121
|
/** Awaitably reset one session and all matching auxiliary state. */
|
|
125
122
|
resetSession(sessionId: string): Promise<void>;
|
|
126
123
|
/** Awaitably reset all state from a trusted ownerless context. */
|
|
@@ -157,8 +154,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
|
|
|
157
154
|
* Direct access to the history manager
|
|
158
155
|
* @example
|
|
159
156
|
* ```typescript
|
|
160
|
-
* server.history.getHistory();
|
|
161
|
-
* server.
|
|
157
|
+
* server.history.getHistory('analysis-session');
|
|
158
|
+
* await server.resetAll();
|
|
162
159
|
* ```
|
|
163
160
|
*/
|
|
164
161
|
readonly history: HistoryManager;
|
|
@@ -166,8 +163,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
|
|
|
166
163
|
* Direct access to the tool registry
|
|
167
164
|
* @example
|
|
168
165
|
* ```typescript
|
|
169
|
-
* server.tools.
|
|
170
|
-
* server.tools.
|
|
166
|
+
* server.tools.add(tool);
|
|
167
|
+
* server.tools.get('my-tool');
|
|
171
168
|
* ```
|
|
172
169
|
*/
|
|
173
170
|
readonly tools: ToolRegistry;
|
|
@@ -175,8 +172,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
|
|
|
175
172
|
* Direct access to the skill registry
|
|
176
173
|
* @example
|
|
177
174
|
* ```typescript
|
|
178
|
-
* server.skills.
|
|
179
|
-
* server.skills.
|
|
175
|
+
* server.skills.add(skill);
|
|
176
|
+
* server.skills.get('my-skill');
|
|
180
177
|
* ```
|
|
181
178
|
*/
|
|
182
179
|
readonly skills: SkillRegistry;
|
|
@@ -220,10 +217,11 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
|
|
|
220
217
|
skills: number;
|
|
221
218
|
}>;
|
|
222
219
|
/**
|
|
223
|
-
* Get all branches
|
|
220
|
+
* Get all branches for one explicit thought session.
|
|
221
|
+
* @param sessionId - Valid thought-session identifier
|
|
224
222
|
* @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays
|
|
225
223
|
*/
|
|
226
|
-
getBranches(): Record<BranchId, ThoughtData[]>;
|
|
224
|
+
getBranches(sessionId: string): Record<BranchId, ThoughtData[]>;
|
|
227
225
|
processThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;
|
|
228
226
|
getMetricsSnapshot(): string;
|
|
229
227
|
/**
|
|
@@ -231,11 +229,6 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
|
|
|
231
229
|
* Closes persistence backend gracefully to ensure data is flushed.
|
|
232
230
|
*/
|
|
233
231
|
stop(): Promise<void>;
|
|
234
|
-
/**
|
|
235
|
-
* Clear all server state (history, tools, skills)
|
|
236
|
-
* Useful for testing to reset state between tests
|
|
237
|
-
*/
|
|
238
|
-
clear(): void;
|
|
239
232
|
/** Awaitably resets one session and matching processor-owned state. */
|
|
240
233
|
resetSession(sessionId: string): Promise<void>;
|
|
241
234
|
/** Awaitably resets all server state from a trusted ownerless context. */
|
package/dist/lib.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,KAAK,CAAC,MAAM,SAAS,CAAC;AAClC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAIA,OA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MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3D,0EAA0E;IAC7D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAKtC;;;;OAIG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAc/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,YAAY,CACjC,OAAO,GAAE,aAAkB,GACzB,OAAO,CAAC,iCAAiC,CAAC,CAE5C;AAGD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,iCAAiC,CAAC,CAsBnF"}
|
package/dist/lib.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from "node:events";
|
|
2
|
+
import { asSessionId } from "./contracts/ids.js";
|
|
2
3
|
import { SEQUENTIAL_THINKING_TOOL } from "./schema.js";
|
|
3
4
|
import { getErrorMessage } from "./errors.js";
|
|
4
5
|
import { assertNever } from "./utils.js";
|
|
@@ -116,7 +117,7 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
|
|
|
116
117
|
this.tools = this._container.resolve('ToolRegistry');
|
|
117
118
|
this.skills = this._container.resolve('SkillRegistry');
|
|
118
119
|
this.config = this._config;
|
|
119
|
-
this.tools.
|
|
120
|
+
this.tools.add(SEQUENTIAL_THINKING_TOOL);
|
|
120
121
|
if (options.enableWatcher) {
|
|
121
122
|
this._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);
|
|
122
123
|
this._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);
|
|
@@ -320,8 +321,8 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
|
|
|
320
321
|
refreshPromise.then(clearRefreshPromise, clearRefreshPromise);
|
|
321
322
|
return refreshPromise;
|
|
322
323
|
}
|
|
323
|
-
getBranches() {
|
|
324
|
-
return this._historyManager.getBranches();
|
|
324
|
+
getBranches(sessionId) {
|
|
325
|
+
return this._historyManager.getBranches(asSessionId(sessionId));
|
|
325
326
|
}
|
|
326
327
|
async processThought(input) {
|
|
327
328
|
const startTime = Date.now();
|
|
@@ -404,10 +405,6 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
|
|
|
404
405
|
});
|
|
405
406
|
return this._stopPromise;
|
|
406
407
|
}
|
|
407
|
-
clear() {
|
|
408
|
-
this._historyManager.clear();
|
|
409
|
-
this._logger.info('Server state cleared');
|
|
410
|
-
}
|
|
411
408
|
async resetSession(sessionId) {
|
|
412
409
|
await this._thoughtProcessor.resetSession(sessionId);
|
|
413
410
|
this._logger.info('Server session reset', {
|
package/dist/lib.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport type * as v from 'valibot';\nimport type { ThoughtData } from './core/thought.js';\nimport type { BranchId } from './contracts/ids.js';\nimport type { SequentialThinkingSchema } from './schema.js';\nimport { SEQUENTIAL_THINKING_TOOL } from './schema.js';\nimport type { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\nimport { assertNever } from './utils.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport { SessionLifecycleClosedError } from './core/SessionErrors.js';\nimport { SessionLifecycleCoordinator } from './core/SessionLifecycleCoordinator.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';\nimport type { HttpTransportOptions } from './transport/HttpTransport.js';\nimport type { TransportOptions } from './transport/BaseTransport.js';\nimport type { ITransport, TransportKind } from './contracts/transport.js';\n\nexport { HttpTransport, createHttpTransport };\nexport type { HttpTransportOptions, TransportOptions, ITransport, TransportKind };\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Enable automatic tool and skill discovery on server startup.\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Suppress startup discovery so callers can discover through registry APIs explicitly.\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\ntype CleanupOperation = () => void | Promise<void>;\n\nfunction appendCleanupFailure(failures: unknown[], failure: unknown): void {\n\tif (failure instanceof AggregateError) {\n\t\tfailures.push(...failure.errors);\n\t\treturn;\n\t}\n\tfailures.push(failure);\n}\n\nasync function collectCleanupFailures(operations: readonly CleanupOperation[]): Promise<unknown[]> {\n\tconst failures: unknown[] = [];\n\tfor (const operation of operations) {\n\t\ttry {\n\t\t\tawait operation();\n\t\t} catch (error) {\n\t\t\tappendCleanupFailure(failures, error);\n\t\t}\n\t}\n\treturn failures;\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/** Rescan configured tool and skill directories. */\n\trefreshDiscovery(): Promise<{ tools: number; skills: number }>;\n\n\t/**\n\t * Get all branches from the history manager.\n\t *\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/**\n\t * Clear all server state (history, tools, skills).\n\t */\n\tclear(): void;\n\n\t/** Awaitably reset one session and all matching auxiliary state. */\n\tresetSession(sessionId: string): Promise<void>;\n\n\t/** Awaitably reset all state from a trusted ownerless context. */\n\tresetAll(): Promise<void>;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer\n\textends EventEmitter\n\timplements IToolAwareSequentialThinkingServer\n{\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\t\tlet server: ToolAwareSequentialThinkingServer | undefined;\n\t\ttry {\n\t\t\tserver = new ToolAwareSequentialThinkingServer({\n\t\t\t\t...options,\n\t\t\t\tcontainer,\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\tserver._skillWatcher?.ready() ?? Promise.resolve(),\n\t\t\t\tserver._toolWatcher?.ready() ?? Promise.resolve(),\n\t\t\t]);\n\n\t\t\tif (options.loadFromPersistence !== false) {\n\t\t\t\tawait server.history.loadFromPersistence();\n\t\t\t}\n\n\t\t\tif (options.autoDiscover !== false && options.lazyDiscovery !== true) {\n\t\t\t\tawait Promise.all([server.tools.discoverAsync(), server.discoverSkillsAsync()]);\n\t\t\t}\n\n\t\t\treturn server;\n\t\t} catch (error) {\n\t\t\tconst startedServer = server;\n\t\t\tconst cleanupFailures = await collectCleanupFailures(\n\t\t\t\tstartedServer\n\t\t\t\t\t? [() => startedServer.dispose()]\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tif (container.has('suspensionStore')) {\n\t\t\t\t\t\t\t\t\tcontainer.resolve('suspensionStore').stop();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t() => container.resolve('Persistence')?.close(),\n\t\t\t\t\t\t\t() => container.dispose(),\n\t\t\t\t\t\t]\n\t\t\t);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Server startup failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\tprivate _acceptingDiscoveryRefreshes = true;\n\tprivate _refreshPromise: Promise<{ tools: number; skills: number }> | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\tprivate _disposePromise: Promise<void> | null = null;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory();\n\t * server.history.clear();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.addTool(tool);\n\t * server.tools.getTool('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.addSkill(skill);\n\t * server.skills.getSkill('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve('Logger');\n\t\tthis._historyManager = this._container.resolve('HistoryManager');\n\t\tthis._historyManager.bindShutdownOwner(() => this.stop());\n\t\tthis._thoughtProcessor = this._container.resolve('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve('Metrics');\n\t\tthis._config = this._container.resolve('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve('ToolRegistry');\n\t\tthis.skills = this._container.resolve('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.addTool(SEQUENTIAL_THINKING_TOOL);\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\tconst config = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tToolAwareSequentialThinkingServer._registerDiscoveryRegistries(\n\t\t\tcontainer,\n\t\t\toptions.lazyDiscovery\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve('HistoryManager');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\treturn new CompressionService({\n\t\t\t\thistoryManager,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tonSummaryCreated: (summary) => {\n\t\t\t\t\thistoryManager.bufferSummaries(\n\t\t\t\t\t\tsummary.sessionId,\n\t\t\t\t\t\tsummaryStore.forSession(summary.sessionId)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tlogger: log,\n\t\t\t});\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy)\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\t\tcontainer.register('sessionLifecycle', () => new SessionLifecycleCoordinator());\n\n\t\tToolAwareSequentialThinkingServer._registerHistoryManager(container);\n\t\tToolAwareSequentialThinkingServer._registerThoughtPipeline(container, config);\n\n\t\treturn container;\n\t}\n\n\tprivate static _resolveEffectiveConfig(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null\n\t): ServerConfig {\n\t\tif (options.config) return options.config;\n\t\tconst loadedOptions = new ConfigLoader().toServerConfigOptions(fileConfig ?? {});\n\t\treturn new ServerConfig({\n\t\t\t...loadedOptions,\n\t\t\tmaxHistorySize: options.maxHistorySize ?? loadedOptions.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? loadedOptions.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? loadedOptions.maxBranchSize,\n\t\t});\n\t}\n\n\tprivate static _registerDiscoveryRegistries(\n\t\tcontainer: Container,\n\t\tlazyDiscovery: ServerOptions['lazyDiscovery']\n\t): void {\n\t\tconst logger = container.resolve('Logger');\n\t\tconst config = container.resolve('Config');\n\t\tconst metrics = container.resolve('Metrics');\n\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\ttoolDirs: config.toolDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t}\n\n\tprivate static _registerHistoryManager(container: Container): void {\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve('Config');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst pers = container.resolve('Persistence');\n\t\t\tconst componentMetrics = container.resolve('Metrics');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tdagEdges: cfg.features.dagEdges,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t\tsessionLock: container.resolve('sessionLock'),\n\t\t\t\tlifecycleCoordinator: container.resolve('sessionLifecycle'),\n\t\t\t\tclearSessionAuxiliaryState: (sessionId) =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearSessionAuxiliaryState(sessionId),\n\t\t\t\tclearAllAuxiliaryState: () =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearAllAuxiliaryState(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate static _registerThoughtPipeline(container: Container, config: ServerConfig): void {\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false })\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(container.resolve('outcomeRecorder'), config.features.calibration ?? false)\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator'))\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve('HistoryManager');\n\t\t\tconst formatter = container.resolve('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve('ThoughtEvaluator');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst strategy = container.resolve('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\tcontainer.resolve('sessionLifecycle'),\n\t\t\t\tcontainer.resolve('calibrator')\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tlet fileConfig: ConfigFileOptions | null;\n\t\tlet config: ServerConfig;\n\t\tif (options.config) {\n\t\t\tfileConfig = options.fileConfig ?? null;\n\t\t\tconfig = options.config;\n\t\t} else {\n\t\t\tconst configLoader = new ConfigLoader();\n\t\t\tfileConfig =\n\t\t\t\toptions.fileConfig === undefined\n\t\t\t\t\t? configLoader.load()\n\t\t\t\t\t: configLoader.applyEnvironmentOverrides(options.fileConfig);\n\t\t\tconfig = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\t\t}\n\n\t\tlet persistence: PersistenceBackend | null = null;\n\t\ttry {\n\t\t\tpersistence = await createPersistenceBackend(config.persistence);\n\t\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(\n\t\t\t\t{ ...options, config },\n\t\t\t\tfileConfig,\n\t\t\t\tpersistence\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst acquiredPersistence = persistence;\n\t\t\tconst cleanupFailures =\n\t\t\t\tacquiredPersistence === null\n\t\t\t\t\t? []\n\t\t\t\t\t: await collectCleanupFailures([() => acquiredPersistence.close()]);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Container construction failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/** Rescan configured tool and skill directories. */\n\tpublic refreshDiscovery(): Promise<{ tools: number; skills: number }> {\n\t\tif (!this._acceptingDiscoveryRefreshes) {\n\t\t\treturn Promise.reject(new SessionLifecycleClosedError(undefined, 'shutting_down'));\n\t\t}\n\t\tif (this._refreshPromise !== null) return this._refreshPromise;\n\n\t\tconst refreshPromise = Promise.allSettled([\n\t\t\tthis.tools.refreshAsync(),\n\t\t\tthis.skills.refreshAsync(),\n\t\t]).then(([toolResult, skillResult]) => {\n\t\t\tif (toolResult.status === 'rejected') {\n\t\t\t\tif (skillResult.status === 'rejected') {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[toolResult.reason, skillResult.reason],\n\t\t\t\t\t\t'Failed to refresh tool and skill discovery'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow toolResult.reason;\n\t\t\t}\n\t\t\tif (skillResult.status === 'rejected') throw skillResult.reason;\n\t\t\treturn { tools: toolResult.value, skills: skillResult.value };\n\t\t});\n\t\tthis._refreshPromise = refreshPromise;\n\t\tconst clearRefreshPromise = (): void => {\n\t\t\tif (this._refreshPromise === refreshPromise) this._refreshPromise = null;\n\t\t};\n\t\tvoid refreshPromise.then(clearRefreshPromise, clearRefreshPromise);\n\t\treturn refreshPromise;\n\t}\n\n\t/**\n\t * Get all branches from the history manager\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(): Record<BranchId, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches();\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst result = await this._thoughtProcessor.process(input as ThoughtData);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic stop(): Promise<void> {\n\t\tthis._acceptingDiscoveryRefreshes = false;\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tconst acceptedRefresh = this._refreshPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([\n\t\t\t\tthis._skillWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tthis._toolWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tacceptedRefresh ?? Promise.resolve(),\n\t\t\t]);\n\t\t\tfor (const result of [skillWatcherResult, toolWatcherResult]) {\n\t\t\t\tswitch (result.status) {\n\t\t\t\t\tcase 'fulfilled':\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'rejected':\n\t\t\t\t\t\tappendCleanupFailure(failures, result.reason);\n\t\t\t\t\t\tthis._logger.error('Error stopping watcher', {\n\t\t\t\t\t\t\terror: getErrorMessage(result.reason),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (refreshResult.status) {\n\t\t\t\tcase 'fulfilled':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'rejected':\n\t\t\t\t\tappendCleanupFailure(failures, refreshResult.reason);\n\t\t\t\t\tthis._logger.error('Error refreshing discovery during shutdown', {\n\t\t\t\t\t\terror: getErrorMessage(refreshResult.reason),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(refreshResult);\n\t\t\t}\n\n\t\t\t// Stop suspension store sweeper if registered\n\t\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst suspensionStore = this._container.resolve('suspensionStore');\n\t\t\t\t\tsuspensionStore.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Flush any buffered writes before closing persistence\n\t\t\ttry {\n\t\t\t\tawait this._historyManager.shutdownWithinLifecycle();\n\t\t\t} catch (error) {\n\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Close persistence backend if available\n\t\t\tconst persistence = this._container.resolve('Persistence');\n\t\t\tif (persistence) {\n\t\t\t\ttry {\n\t\t\t\t\tawait persistence.close();\n\t\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to stop server cleanly');\n\t\t\t}\n\t\t\tthis._historyManager.clearLiveStateAfterShutdown();\n\t\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t\t});\n\t\treturn this._stopPromise;\n\t}\n\n\t/**\n\t * Clear all server state (history, tools, skills)\n\t * Useful for testing to reset state between tests\n\t */\n\tpublic clear(): void {\n\t\tthis._historyManager.clear();\n\t\tthis._logger.info('Server state cleared');\n\t}\n\n\t/** Awaitably resets one session and matching processor-owned state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tawait this._thoughtProcessor.resetSession(sessionId);\n\t\tthis._logger.info('Server session reset', { sessionId });\n\t}\n\n\t/** Awaitably resets all server state from a trusted ownerless context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._thoughtProcessor.resetAll();\n\t\tthis._logger.info('All server sessions reset');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic dispose(): Promise<void> {\n\t\tif (this._disposePromise) return this._disposePromise;\n\t\tthis._disposePromise = (async () => {\n\t\t\tconst failures = await collectCleanupFailures([\n\t\t\t\t() => this.stop(),\n\t\t\t\t() => this._container.dispose(),\n\t\t\t]);\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to dispose server cleanly');\n\t\t\t}\n\t\t\tthis._logger.info('Server disposed, all resources released');\n\t\t})();\n\t\treturn this._disposePromise;\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * import { createServer } from '@iworkforces/tracelattice';\n *\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load() ?? {};\n\tconst config = new ServerConfig(configLoader.toServerConfigOptions(fileConfig));\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t\tconfig,\n\t\tfileConfig,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["appendCleanupFailure","failures","failure","AggregateError","collectCleanupFailures","operations","operation","error","ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","Promise","startedServer","cleanupFailures","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","persistence","Container","metrics","Metrics","config","logger","StructuredLogger","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","summary","createReasoningStrategy","SessionLock","SessionLifecycleCoordinator","loadedOptions","ConfigLoader","ServerConfig","lazyDiscovery","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","cfg","pers","componentMetrics","HistoryManager","sessionId","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","createPersistenceBackend","acquiredPersistence","discovered","SessionLifecycleClosedError","refreshPromise","toolResult","skillResult","clearRefreshPromise","input","startTime","Date","result","durationSeconds","acceptedRefresh","skillWatcherResult","toolWatcherResult","refreshResult","getErrorMessage","assertNever","createServer","initializeServer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,CAAC,OAAO;aAC7B;YACD,IAAIH,SAAS,MAAM,GAAG,GACrB,MAAM,IAAIE,eAAeF,UAAU;YAEpC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QACnB;QACA,OAAO,IAAI,CAAC,eAAe;IAC5B;AACD;AA2BO,eAAeyF,aACrBhF,UAAyB,CAAC,CAAC;IAE3B,OAAOF,kCAAkC,MAAM,CAACE;AACjD;AAGO,eAAeiF;IAErB,MAAMrB,eAAe,IAAIzB;IACzB,MAAMtB,aAAa+C,aAAa,IAAI,MAAM,CAAC;IAC3C,MAAM1C,SAAS,IAAIkB,aAAawB,aAAa,qBAAqB,CAAC/C;IAEnE,MAAMM,SAAS,IAAIC,iBAAiB;QACnC,OAAOP,WAAW,QAAQ,IAAI;QAC9B,SAAS;QACT,QAAQA,WAAW,SAAS,IAAI;IACjC;IAGA,MAAMqE,iBAAiB,MAAMF,aAAa;QACzC7D;QACA,eAAe;QACfD;QACAL;IACD;IAEAM,OAAO,IAAI,CAAC;IACZ,OAAO+D;AACR"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport type * as v from 'valibot';\nimport type { ThoughtData } from './core/thought.js';\nimport { asSessionId, type BranchId } from './contracts/ids.js';\nimport type { SequentialThinkingSchema } from './schema.js';\nimport { SEQUENTIAL_THINKING_TOOL } from './schema.js';\nimport type { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\nimport { assertNever } from './utils.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport { SessionLifecycleClosedError } from './core/SessionErrors.js';\nimport { SessionLifecycleCoordinator } from './core/SessionLifecycleCoordinator.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';\nimport type { HttpTransportOptions } from './transport/HttpTransport.js';\nimport type { TransportOptions } from './transport/BaseTransport.js';\nimport type { ITransport, TransportKind } from './contracts/transport.js';\n\nexport { HttpTransport, createHttpTransport };\nexport type { HttpTransportOptions, TransportOptions, ITransport, TransportKind };\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Enable automatic tool and skill discovery on server startup.\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Suppress startup discovery so callers can discover through registry APIs explicitly.\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\ntype CleanupOperation = () => void | Promise<void>;\n\nfunction appendCleanupFailure(failures: unknown[], failure: unknown): void {\n\tif (failure instanceof AggregateError) {\n\t\tfailures.push(...failure.errors);\n\t\treturn;\n\t}\n\tfailures.push(failure);\n}\n\nasync function collectCleanupFailures(operations: readonly CleanupOperation[]): Promise<unknown[]> {\n\tconst failures: unknown[] = [];\n\tfor (const operation of operations) {\n\t\ttry {\n\t\t\tawait operation();\n\t\t} catch (error) {\n\t\t\tappendCleanupFailure(failures, error);\n\t\t}\n\t}\n\treturn failures;\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/** Rescan configured tool and skill directories. */\n\trefreshDiscovery(): Promise<{ tools: number; skills: number }>;\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t *\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(sessionId: string): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/** Awaitably reset one session and all matching auxiliary state. */\n\tresetSession(sessionId: string): Promise<void>;\n\n\t/** Awaitably reset all state from a trusted ownerless context. */\n\tresetAll(): Promise<void>;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer\n\textends EventEmitter\n\timplements IToolAwareSequentialThinkingServer\n{\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\t\tlet server: ToolAwareSequentialThinkingServer | undefined;\n\t\ttry {\n\t\t\tserver = new ToolAwareSequentialThinkingServer({\n\t\t\t\t...options,\n\t\t\t\tcontainer,\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\tserver._skillWatcher?.ready() ?? Promise.resolve(),\n\t\t\t\tserver._toolWatcher?.ready() ?? Promise.resolve(),\n\t\t\t]);\n\n\t\t\tif (options.loadFromPersistence !== false) {\n\t\t\t\tawait server.history.loadFromPersistence();\n\t\t\t}\n\n\t\t\tif (options.autoDiscover !== false && options.lazyDiscovery !== true) {\n\t\t\t\tawait Promise.all([server.tools.discoverAsync(), server.discoverSkillsAsync()]);\n\t\t\t}\n\n\t\t\treturn server;\n\t\t} catch (error) {\n\t\t\tconst startedServer = server;\n\t\t\tconst cleanupFailures = await collectCleanupFailures(\n\t\t\t\tstartedServer\n\t\t\t\t\t? [() => startedServer.dispose()]\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tif (container.has('suspensionStore')) {\n\t\t\t\t\t\t\t\t\tcontainer.resolve('suspensionStore').stop();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t() => container.resolve('Persistence')?.close(),\n\t\t\t\t\t\t\t() => container.dispose(),\n\t\t\t\t\t\t]\n\t\t\t);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Server startup failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\tprivate _acceptingDiscoveryRefreshes = true;\n\tprivate _refreshPromise: Promise<{ tools: number; skills: number }> | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\tprivate _disposePromise: Promise<void> | null = null;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory('analysis-session');\n\t * await server.resetAll();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.add(tool);\n\t * server.tools.get('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.add(skill);\n\t * server.skills.get('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve('Logger');\n\t\tthis._historyManager = this._container.resolve('HistoryManager');\n\t\tthis._historyManager.bindShutdownOwner(() => this.stop());\n\t\tthis._thoughtProcessor = this._container.resolve('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve('Metrics');\n\t\tthis._config = this._container.resolve('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve('ToolRegistry');\n\t\tthis.skills = this._container.resolve('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.add(SEQUENTIAL_THINKING_TOOL);\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\tconst config = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tToolAwareSequentialThinkingServer._registerDiscoveryRegistries(\n\t\t\tcontainer,\n\t\t\toptions.lazyDiscovery\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve('HistoryManager');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\treturn new CompressionService({\n\t\t\t\thistoryManager,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tonSummaryCreated: (summary) => {\n\t\t\t\t\thistoryManager.bufferSummaries(\n\t\t\t\t\t\tsummary.sessionId,\n\t\t\t\t\t\tsummaryStore.forSession(summary.sessionId)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tlogger: log,\n\t\t\t});\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy)\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\t\tcontainer.register('sessionLifecycle', () => new SessionLifecycleCoordinator());\n\n\t\tToolAwareSequentialThinkingServer._registerHistoryManager(container);\n\t\tToolAwareSequentialThinkingServer._registerThoughtPipeline(container, config);\n\n\t\treturn container;\n\t}\n\n\tprivate static _resolveEffectiveConfig(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null\n\t): ServerConfig {\n\t\tif (options.config) return options.config;\n\t\tconst loadedOptions = new ConfigLoader().toServerConfigOptions(fileConfig ?? {});\n\t\treturn new ServerConfig({\n\t\t\t...loadedOptions,\n\t\t\tmaxHistorySize: options.maxHistorySize ?? loadedOptions.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? loadedOptions.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? loadedOptions.maxBranchSize,\n\t\t});\n\t}\n\n\tprivate static _registerDiscoveryRegistries(\n\t\tcontainer: Container,\n\t\tlazyDiscovery: ServerOptions['lazyDiscovery']\n\t): void {\n\t\tconst logger = container.resolve('Logger');\n\t\tconst config = container.resolve('Config');\n\t\tconst metrics = container.resolve('Metrics');\n\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\ttoolDirs: config.toolDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t}\n\n\tprivate static _registerHistoryManager(container: Container): void {\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve('Config');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst pers = container.resolve('Persistence');\n\t\t\tconst componentMetrics = container.resolve('Metrics');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tdagEdges: cfg.features.dagEdges,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t\tsessionLock: container.resolve('sessionLock'),\n\t\t\t\tlifecycleCoordinator: container.resolve('sessionLifecycle'),\n\t\t\t\tclearSessionAuxiliaryState: (sessionId) =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearSessionAuxiliaryState(sessionId),\n\t\t\t\tclearAllAuxiliaryState: () =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearAllAuxiliaryState(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate static _registerThoughtPipeline(container: Container, config: ServerConfig): void {\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false })\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(container.resolve('outcomeRecorder'), config.features.calibration ?? false)\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator'))\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve('HistoryManager');\n\t\t\tconst formatter = container.resolve('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve('ThoughtEvaluator');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst strategy = container.resolve('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\tcontainer.resolve('sessionLifecycle'),\n\t\t\t\tcontainer.resolve('calibrator')\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tlet fileConfig: ConfigFileOptions | null;\n\t\tlet config: ServerConfig;\n\t\tif (options.config) {\n\t\t\tfileConfig = options.fileConfig ?? null;\n\t\t\tconfig = options.config;\n\t\t} else {\n\t\t\tconst configLoader = new ConfigLoader();\n\t\t\tfileConfig =\n\t\t\t\toptions.fileConfig === undefined\n\t\t\t\t\t? configLoader.load()\n\t\t\t\t\t: configLoader.applyEnvironmentOverrides(options.fileConfig);\n\t\t\tconfig = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\t\t}\n\n\t\tlet persistence: PersistenceBackend | null = null;\n\t\ttry {\n\t\t\tpersistence = await createPersistenceBackend(config.persistence);\n\t\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(\n\t\t\t\t{ ...options, config },\n\t\t\t\tfileConfig,\n\t\t\t\tpersistence\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst acquiredPersistence = persistence;\n\t\t\tconst cleanupFailures =\n\t\t\t\tacquiredPersistence === null\n\t\t\t\t\t? []\n\t\t\t\t\t: await collectCleanupFailures([() => acquiredPersistence.close()]);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Container construction failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/** Rescan configured tool and skill directories. */\n\tpublic refreshDiscovery(): Promise<{ tools: number; skills: number }> {\n\t\tif (!this._acceptingDiscoveryRefreshes) {\n\t\t\treturn Promise.reject(new SessionLifecycleClosedError(undefined, 'shutting_down'));\n\t\t}\n\t\tif (this._refreshPromise !== null) return this._refreshPromise;\n\n\t\tconst refreshPromise = Promise.allSettled([\n\t\t\tthis.tools.refreshAsync(),\n\t\t\tthis.skills.refreshAsync(),\n\t\t]).then(([toolResult, skillResult]) => {\n\t\t\tif (toolResult.status === 'rejected') {\n\t\t\t\tif (skillResult.status === 'rejected') {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[toolResult.reason, skillResult.reason],\n\t\t\t\t\t\t'Failed to refresh tool and skill discovery'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow toolResult.reason;\n\t\t\t}\n\t\t\tif (skillResult.status === 'rejected') throw skillResult.reason;\n\t\t\treturn { tools: toolResult.value, skills: skillResult.value };\n\t\t});\n\t\tthis._refreshPromise = refreshPromise;\n\t\tconst clearRefreshPromise = (): void => {\n\t\t\tif (this._refreshPromise === refreshPromise) this._refreshPromise = null;\n\t\t};\n\t\tvoid refreshPromise.then(clearRefreshPromise, clearRefreshPromise);\n\t\treturn refreshPromise;\n\t}\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(sessionId: string): Record<BranchId, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches(asSessionId(sessionId));\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst result = await this._thoughtProcessor.process(input as ThoughtData);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic stop(): Promise<void> {\n\t\tthis._acceptingDiscoveryRefreshes = false;\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tconst acceptedRefresh = this._refreshPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([\n\t\t\t\tthis._skillWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tthis._toolWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tacceptedRefresh ?? Promise.resolve(),\n\t\t\t]);\n\t\t\tfor (const result of [skillWatcherResult, toolWatcherResult]) {\n\t\t\t\tswitch (result.status) {\n\t\t\t\t\tcase 'fulfilled':\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'rejected':\n\t\t\t\t\t\tappendCleanupFailure(failures, result.reason);\n\t\t\t\t\t\tthis._logger.error('Error stopping watcher', {\n\t\t\t\t\t\t\terror: getErrorMessage(result.reason),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (refreshResult.status) {\n\t\t\t\tcase 'fulfilled':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'rejected':\n\t\t\t\t\tappendCleanupFailure(failures, refreshResult.reason);\n\t\t\t\t\tthis._logger.error('Error refreshing discovery during shutdown', {\n\t\t\t\t\t\terror: getErrorMessage(refreshResult.reason),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(refreshResult);\n\t\t\t}\n\n\t\t\t// Stop suspension store sweeper if registered\n\t\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst suspensionStore = this._container.resolve('suspensionStore');\n\t\t\t\t\tsuspensionStore.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Flush any buffered writes before closing persistence\n\t\t\ttry {\n\t\t\t\tawait this._historyManager.shutdownWithinLifecycle();\n\t\t\t} catch (error) {\n\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Close persistence backend if available\n\t\t\tconst persistence = this._container.resolve('Persistence');\n\t\t\tif (persistence) {\n\t\t\t\ttry {\n\t\t\t\t\tawait persistence.close();\n\t\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to stop server cleanly');\n\t\t\t}\n\t\t\tthis._historyManager.clearLiveStateAfterShutdown();\n\t\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t\t});\n\t\treturn this._stopPromise;\n\t}\n\n\t/** Awaitably resets one session and matching processor-owned state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tawait this._thoughtProcessor.resetSession(sessionId);\n\t\tthis._logger.info('Server session reset', { sessionId });\n\t}\n\n\t/** Awaitably resets all server state from a trusted ownerless context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._thoughtProcessor.resetAll();\n\t\tthis._logger.info('All server sessions reset');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic dispose(): Promise<void> {\n\t\tif (this._disposePromise) return this._disposePromise;\n\t\tthis._disposePromise = (async () => {\n\t\t\tconst failures = await collectCleanupFailures([\n\t\t\t\t() => this.stop(),\n\t\t\t\t() => this._container.dispose(),\n\t\t\t]);\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to dispose server cleanly');\n\t\t\t}\n\t\t\tthis._logger.info('Server disposed, all resources released');\n\t\t})();\n\t\treturn this._disposePromise;\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * import { createServer } from '@iworkforces/tracelattice';\n *\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load() ?? {};\n\tconst config = new ServerConfig(configLoader.toServerConfigOptions(fileConfig));\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t\tconfig,\n\t\tfileConfig,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["appendCleanupFailure","failures","failure","AggregateError","collectCleanupFailures","operations","operation","error","ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","Promise","startedServer","cleanupFailures","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","persistence","Container","metrics","Metrics","config","logger","StructuredLogger","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","summary","createReasoningStrategy","SessionLock","SessionLifecycleCoordinator","loadedOptions","ConfigLoader","ServerConfig","lazyDiscovery","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","cfg","pers","componentMetrics","HistoryManager","sessionId","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","createPersistenceBackend","acquiredPersistence","discovered","SessionLifecycleClosedError","refreshPromise","toolResult","skillResult","clearRefreshPromise","asSessionId","input","startTime","Date","result","durationSeconds","acceptedRefresh","skillWatcherResult","toolWatcherResult","refreshResult","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,SAASA,qBAAqBC,QAAmB,EAAEC,OAAgB;IAClE,IAAIA,mBAAmBC,gBAAgB,YACtCF,SAAS,IAAI,IAAIC,QAAQ,MAAM;IAGhCD,SAAS,IAAI,CAACC;AACf;AAEA,eAAeE,uBAAuBC,UAAuC;IAC5E,MAAMJ,WAAsB,EAAE;IAC9B,KAAK,MAAMK,aAAaD,WACvB,IAAI;QACH,MAAMC;IACP,EAAE,OAAOC,OAAO;QACfP,qBAAqBC,UAAUM;IAChC;IAED,OAAON;AACR;AA4EO,MAAMO,0CACJC;IAUR,aAAa,OAAOC,UAAyB,CAAC,CAAC,EAA8C;QAC5F,MAAMC,YAAY,MAAMH,kCAAkC,2BAA2B,CAACE;QACtF,IAAIE;QACJ,IAAI;YACHA,SAAS,IAAIJ,kCAAkC;gBAC9C,GAAGE,OAAO;gBACVC;YACD;YACA,MAAME,QAAQ,GAAG,CAAC;gBACjBD,OAAO,aAAa,EAAE,WAAWC,QAAQ,OAAO;gBAChDD,OAAO,YAAY,EAAE,WAAWC,QAAQ,OAAO;aAC/C;YAED,IAAIH,AAAgC,UAAhCA,QAAQ,mBAAmB,EAC9B,MAAME,OAAO,OAAO,CAAC,mBAAmB;YAGzC,IAAIF,AAAyB,UAAzBA,QAAQ,YAAY,IAAcA,AAA0B,SAA1BA,QAAQ,aAAa,EAC1D,MAAMG,QAAQ,GAAG,CAAC;gBAACD,OAAO,KAAK,CAAC,aAAa;gBAAIA,OAAO,mBAAmB;aAAG;YAG/E,OAAOA;QACR,EAAE,OAAOL,OAAO;YACf,MAAMO,gBAAgBF;YACtB,MAAMG,kBAAkB,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