@iworkforces/tracelattice 2.0.3 → 2.0.5

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/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 { 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 type { SseTransportOptions } from './transport/SseTransport.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\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\t/**\n\t * Transport type to use\n\t * @default 'stdio'\n\t */\n\ttransport?: 'stdio' | 'sse';\n\t/**\n\t * SSE transport options (used when transport: 'sse')\n\t */\n\tsseTransportOptions?: SseTransportOptions;\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/**\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 _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/**\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\tif (this._stopPromise) return this._stopPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst watcherResults = 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]);\n\t\t\tfor (const result of watcherResults) {\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\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 * // 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 * // With custom container for testing\n * const mockContainer = new Container();\n * mockContainer.registerInstance('Logger', mockLogger);\n * const server = await createServer({ container: mockContainer });\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","input","startTime","Date","result","durationSeconds","watcherResults","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,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;AA6EO,MAAMO,0CACJC;IAUR,aAAa,OAAOC,UAAyB,CAAC,CAAC,EAA8C;QAC5F,MAAMC,YAAY,MAAMH,kCAAkC,2BAA2B,CAACE;QACtF,IAAI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fD;QACAL;IACD;IAEAM,OAAO,IAAI,CAAC;IACZ,OAAOuD;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 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 { 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';\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/**\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 _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/**\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\tif (this._stopPromise) return this._stopPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst watcherResults = 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]);\n\t\t\tfor (const result of watcherResults) {\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\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 * // 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 * // With custom container for testing\n * const mockContainer = new Container();\n * mockContainer.registerInstance('Logger', mockLogger);\n * const server = await createServer({ container: mockContainer });\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","input","startTime","Date","result","durationSeconds","watcherResults","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,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;AA6EO,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,EAC9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,CAACA;QAC1C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,wBAAwB;YAAEA;QAAU;IACvD;IAGA,MAAa,WAA0B;QACtC,MAAM,IAAI,CAAC,iBAAiB,CAAC,QAAQ;QACrC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACnB;IAOO,UAAyB;QAC/B,IAAI,IAAI,CAAC,eAAe,EAAE,OAAO,IAAI,CAAC,eAAe;QACrD,IAAI,CAAC,eAAe,GAAI;YACvB,MAAMvD,WAAW,MAAMG,uBAAuB;gBAC7C,IAAM,IAAI,CAAC,IAAI;gBACf,IAAM,IAAI,CAAC,UAAU,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;AA8BO,eAAeiF,aACrBxE,UAAyB,CAAC,CAAC;IAE3B,OAAOF,kCAAkC,MAAM,CAACE;AACjD;AAGO,eAAeyE;IAErB,MAAMb,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,MAAM6D,iBAAiB,MAAMF,aAAa;QACzCrD;QACA,eAAe;QACfD;QACAL;IACD;IAEAM,OAAO,IAAI,CAAC;IACZ,OAAOuD;AACR"}
@@ -11,7 +11,7 @@ export declare const FileSnapshotV2Schema: v.StrictObjectSchema<{
11
11
  readonly available_skills: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, undefined>, v.DescriptionAction<string[], "Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])">]>, undefined>;
12
12
  readonly thought: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Your current thinking step">]>;
13
13
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 30, undefined>, v.DescriptionAction<string, "Unique identifier for this thought. Auto-generated if not provided.">]>, undefined>;
14
- readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether another thought step is needed (defaults to true if not provided)">]>, undefined>;
14
+ readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Omission defaults to true; the effective next action is returned in strategy_hint.">]>, undefined>;
15
15
  readonly thought_number: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Current thought number">]>;
16
16
  readonly total_thoughts: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Estimated total thoughts needed">]>;
17
17
  readonly is_revision: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether this revises previous thinking">]>, undefined>;
@@ -180,7 +180,7 @@ export declare const FileSnapshotV2Schema: v.StrictObjectSchema<{
180
180
  readonly available_skills: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, undefined>, v.DescriptionAction<string[], "Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])">]>, undefined>;
181
181
  readonly thought: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Your current thinking step">]>;
182
182
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 30, undefined>, v.DescriptionAction<string, "Unique identifier for this thought. Auto-generated if not provided.">]>, undefined>;
183
- readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether another thought step is needed (defaults to true if not provided)">]>, undefined>;
183
+ readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Omission defaults to true; the effective next action is returned in strategy_hint.">]>, undefined>;
184
184
  readonly thought_number: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Current thought number">]>;
185
185
  readonly total_thoughts: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Estimated total thoughts needed">]>;
186
186
  readonly is_revision: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether this revises previous thinking">]>, undefined>;
package/dist/schema.d.ts CHANGED
@@ -331,7 +331,7 @@ export declare const SequentialThinkingSchema: v.ObjectSchema<{
331
331
  readonly available_skills: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, undefined>, v.DescriptionAction<string[], "Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])">]>, undefined>;
332
332
  readonly thought: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Your current thinking step">]>;
333
333
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 30, undefined>, v.DescriptionAction<string, "Unique identifier for this thought. Auto-generated if not provided.">]>, undefined>;
334
- readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether another thought step is needed (defaults to true if not provided)">]>, undefined>;
334
+ readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Omission defaults to true; the effective next action is returned in strategy_hint.">]>, undefined>;
335
335
  readonly thought_number: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Current thought number">]>;
336
336
  readonly total_thoughts: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Estimated total thoughts needed">]>;
337
337
  readonly is_revision: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether this revises previous thinking">]>, undefined>;
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAC7B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAkH5C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;aAqBnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,yBAAyB;;;;;;;;aA4BpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAanC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,+BAA+B;;;;;;;;;aAyB1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAe1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;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;;aAyB1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAe1C,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAkMnC,CAAC;AAEH,6FAA6F;AAC7F,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,wBAAwB,EAAE,IAItC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB;;;;;;;aAmB/B,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,cAAc,kWASW,CAAC;AAEvC;;GAEG;AACH,eAAO,MAAM,UAAU;;;;;;;;aAQmH,CAAC"}
package/dist/schema.js CHANGED
@@ -5,6 +5,8 @@ Each thought can build on, question, or revise previous insights as understandin
5
5
 
6
6
  IMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.
7
7
 
8
+ Each invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.
9
+
8
10
  When to use this tool:
9
11
  - Breaking down complex problems into steps
10
12
  - Planning and design with room for revision
@@ -42,7 +44,7 @@ Parameters explained:
42
44
  * Hypothesis generation
43
45
  * Hypothesis verification
44
46
  * Tool recommendations and rationale
45
- - next_thought_needed: True if you need more thinking, even if at what seemed like the end
47
+ - next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.
46
48
  - thought_number: Current number in sequence (can go beyond initial total if needed)
47
49
  - total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)
48
50
  - is_revision: A boolean indicating if this thought revises previous thinking
@@ -158,7 +160,7 @@ const SequentialThinkingSchema = __rspack_external_valibot.object({
158
160
  available_skills: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Array of skill names available for use (e.g., ["commit", "review-pr", "pdf"])'))),
159
161
  thought: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Your current thinking step')),
160
162
  id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(30), __rspack_external_valibot.description('Unique identifier for this thought. Auto-generated if not provided.'))),
161
- next_thought_needed: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether another thought step is needed (defaults to true if not provided)'))),
163
+ next_thought_needed: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Omission defaults to true; the effective next action is returned in strategy_hint.'))),
162
164
  thought_number: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Current thought number')),
163
165
  total_thoughts: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Estimated total thoughts needed')),
164
166
  is_revision: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether this revises previous thinking'))),
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description('Whether another thought step is needed (defaults to true if not provided)')\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call', 'tool_observation', 'assumption', 'decomposition', 'backtrack']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Name of the tool being invoked (for tool_call thoughts)'))),\n\ttool_arguments: v.optional(v.pipe(v.record(v.string(), v.unknown()), v.description('Arguments passed to the tool (for tool_call thoughts)'))),\n\ttool_result: v.optional(v.pipe(v.unknown(), v.description('Result returned by the tool (for tool_observation thoughts)'))),\n\tcontinuation_token: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Token for resuming long-running tool invocations'))),\n\tdecomposition_children: v.optional(v.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))),\n\tbacktrack_target: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description('Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'))),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<Omit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & { id: string; from: string; to: string; sessionId: string }>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSchema","SEQUENTIAL_THINKING_TOOL","JsonRpcRequestSchema","EdgeKindSchema","EdgeSchema"],"mappings":";AAyCA,MAAMA,mBAAmB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yHAwG+F,CAAC;AA0BnH,MAAMC,2BAA2BC,0BAAAA,MAAQ,CAAC;IAChD,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,WAAa,CAAC;IAC5C,YAAYA,0BAAAA,IAAM,CACjBA,0BAAAA,MAAQ,IACRA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,WAAa,CAAC;IAEf,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,OAAOA,0BAAAA,WAAa,CAAC;IAC/D,UAAUA,0BAAAA,QAAU,CACnBA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,I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;QAACA,0BAAAA,MAAQ;QAAIA,0BAAAA,MAAQ;QAAIA,yBAAAA,CAAAA,OAAM;KAAG,GAC1CA,0BAAAA,WAAa,CAAC;AAGjB;AAKO,MAAMQ,iBAAiBR,0BAAAA,KAAO,CAAC;IACrCA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;CACV;AAKM,MAAMS,aAAaT,0BAAAA,MAAQ,CAAC;IAClC,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACrD,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMQ;IACN,WAAWR,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC;IAC1C,WAAWA,0BAAAA,MAAQ;IACnB,UAAUA,0BAAAA,QAAU,CAACA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
1
+ {"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nEach invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'Omission defaults to true; the effective next action is returned in strategy_hint.'\n\t\t\t)\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call', 'tool_observation', 'assumption', 'decomposition', 'backtrack']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Name of the tool being invoked (for tool_call thoughts)'))),\n\ttool_arguments: v.optional(v.pipe(v.record(v.string(), v.unknown()), v.description('Arguments passed to the tool (for tool_call thoughts)'))),\n\ttool_result: v.optional(v.pipe(v.unknown(), v.description('Result returned by the tool (for tool_observation thoughts)'))),\n\tcontinuation_token: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Token for resuming long-running tool invocations'))),\n\tdecomposition_children: v.optional(v.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))),\n\tbacktrack_target: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description('Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'))),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<Omit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & { id: string; from: string; to: string; sessionId: string }>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSchema","SEQUENTIAL_THINKING_TOOL","JsonRpcRequestSchema","EdgeKindSchema","EdgeSchema"],"mappings":";AAyCA,MAAMA,mBAAmB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yHA0G+F,CAAC;AA0BnH,MAAMC,2BAA2BC,0BAAAA,MAAQ,CAAC;IAChD,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,WAAa,CAAC;IAC5C,YAAYA,0BAAAA,IAAM,CACjBA,0BAAAA,MAAQ,IACRA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,WAAa,CAAC;IAEf,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,OAAOA,0BAAAA,WAAa,CAAC;IAC/D,UAAUA,0BAAAA,QAAU,CACnBA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,WAAa,CAAC;IAElC,kBAAkBA,0BAAAA,QAAU,CAC3BA,0BAAAA,IAA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G,GAC1CA,0BAAAA,WAAa,CAAC;AAGjB;AAKO,MAAMQ,iBAAiBR,0BAAAA,KAAO,CAAC;IACrCA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;IACVA,0BAAAA,OAAS,CAAC;CACV;AAKM,MAAMS,aAAaT,0BAAAA,MAAQ,CAAC;IAClC,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACrD,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMQ;IACN,WAAWR,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC;IAC1C,WAAWA,0BAAAA,MAAQ;IACnB,UAAUA,0BAAAA,QAAU,CAACA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Centralizes JSON-RPC response formatting, request body reading,
5
5
  * and common HTTP response patterns to eliminate duplication across
6
- * HttpTransport, StreamableHttpTransport, and SseTransport.
6
+ * HttpTransport and StreamableHttpTransport.
7
7
  *
8
8
  * @module transport/HttpHelpers
9
9
  */
@@ -1 +1 @@
1
- {"version":3,"file":"transport/HttpHelpers.js","sources":["../../src/transport/HttpHelpers.ts"],"sourcesContent":["/**\n * Shared HTTP helper utilities for MCP transport implementations.\n *\n * Centralizes JSON-RPC response formatting, request body reading,\n * and common HTTP response patterns to eliminate duplication across\n * HttpTransport, StreamableHttpTransport, and SseTransport.\n *\n * @module transport/HttpHelpers\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Send a JSON-RPC 2.0 error response.\n *\n * Standardizes error response formatting across all transport implementations.\n * All JSON-RPC errors use the standard `{ jsonrpc, id, error }` shape.\n *\n * @param res - The server response to write to\n * @param statusCode - HTTP status code (e.g. 400, 403, 429, 500)\n * @param code - JSON-RPC error code (e.g. -32700, -32600, -32603)\n * @param message - Human-readable error message\n * @param id - Optional JSON-RPC request ID (defaults to null)\n * @param data - Optional additional error data\n */\nexport function sendJsonRpcError(\n\tres: ServerResponse,\n\tstatusCode: number,\n\tcode: number,\n\tmessage: string,\n\tid: string | number | null = null,\n\tdata?: unknown\n): void {\n\tconst body: Record<string, unknown> = {\n\t\tjsonrpc: '2.0',\n\t\tid,\n\t\terror: { code, message },\n\t};\n\tif (data !== undefined) {\n\t\t(body.error as Record<string, unknown>).data = data;\n\t}\n\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\tres.end(JSON.stringify(body));\n}\n\n/**\n * Send a JSON-RPC 2.0 success response.\n *\n * @param res - The server response to write to\n * @param response - The JSON-RPC response object to send\n * @param statusCode - HTTP status code (default: 200)\n * @param headers - Optional additional response headers\n */\nexport function sendJsonRpcResponse(\n\tres: ServerResponse,\n\tresponse: unknown,\n\tstatusCode: number = 200,\n\theaders: Record<string, string> = {}\n): void {\n\tconst defaultHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\tres.writeHead(statusCode, { ...defaultHeaders, ...headers });\n\tres.end(JSON.stringify(response));\n}\n\n/**\n * Send a CORS preflight (OPTIONS) response.\n *\n * @param res - The server response to write to\n * @param extraAllowHeaders - Optional extra Access-Control-Allow-Headers values\n */\nexport function sendCorsPreflight(res: ServerResponse, extraAllowHeaders?: string[]): void {\n\tif (extraAllowHeaders && extraAllowHeaders.length > 0) {\n\t\tres.setHeader('Access-Control-Allow-Headers', `Content-Type, ${extraAllowHeaders.join(', ')}`);\n\t}\n\tres.writeHead(204);\n\tres.end();\n}\n\n/**\n * Read the full request body with optional size limit enforcement.\n *\n * Streams the request body chunks, tracking total size.\n * If the body exceeds `maxBodySize`, reading stops and `null` is returned\n * to indicate the payload is too large.\n *\n * @param req - The incoming HTTP request\n * @param maxBodySize - Maximum allowed body size in bytes (0 = unlimited)\n * @returns The body string, or `null` if the body exceeded the size limit\n */\nexport async function readRequestBody(\n\treq: IncomingMessage,\n\tmaxBodySize: number\n): Promise<string | null> {\n\tlet body = '';\n\tlet bodySize = 0;\n\n\tfor await (const chunk of req) {\n\t\tconst chunkStr = typeof chunk === 'string' ? chunk : (chunk as Buffer).toString();\n\t\tbodySize += chunkStr.length;\n\n\t\tif (maxBodySize > 0 && bodySize > maxBodySize) {\n\t\t\treturn null;\n\t\t}\n\n\t\tbody += chunkStr;\n\t}\n\n\treturn body;\n}\n\n"],"names":["sendJsonRpcError","res","statusCode","code","message","id","data","body","undefined","JSON","sendJsonRpcResponse","response","headers","defaultHeaders","sendCorsPreflight","extraAllowHeaders","readRequestBody","req","maxBodySize","bodySize","chunk","chunkStr"],"mappings":"AAyBO,SAASA,iBACfC,GAAmB,EACnBC,UAAkB,EAClBC,IAAY,EACZC,OAAe,EACfC,KAA6B,IAAI,EACjCC,IAAc;IAEd,MAAMC,OAAgC;QACrC,SAAS;QACTF;QACA,OAAO;YAAEF;YAAMC;QAAQ;IACxB;IACA,IAAIE,AAASE,WAATF,MACFC,KAAK,KAAK,CAA6B,IAAI,GAAGD;IAEhDL,IAAI,SAAS,CAACC,YAAY;QAAE,gBAAgB;IAAmB;IAC/DD,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACF;AACxB;AAUO,SAASG,oBACfT,GAAmB,EACnBU,QAAiB,EACjBT,aAAqB,GAAG,EACxBU,UAAkC,CAAC,CAAC;IAEpC,MAAMC,iBAAyC;QAAE,gBAAgB;IAAmB;IACpFZ,IAAI,SAAS,CAACC,YAAY;QAAE,GAAGW,cAAc;QAAE,GAAGD,OAAO;IAAC;IAC1DX,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACE;AACxB;AAQO,SAASG,kBAAkBb,GAAmB,EAAEc,iBAA4B;IAClF,IAAIA,qBAAqBA,kBAAkB,MAAM,GAAG,GACnDd,IAAI,SAAS,CAAC,gCAAgC,CAAC,cAAc,EAAEc,kBAAkB,IAAI,CAAC,OAAO;IAE9Fd,IAAI,SAAS,CAAC;IACdA,IAAI,GAAG;AACR;AAaO,eAAee,gBACrBC,GAAoB,EACpBC,WAAmB;IAEnB,IAAIX,OAAO;IACX,IAAIY,WAAW;IAEf,WAAW,MAAMC,SAASH,IAAK;QAC9B,MAAMI,WAAW,AAAiB,YAAjB,OAAOD,QAAqBA,QAASA,MAAiB,QAAQ;QAC/ED,YAAYE,SAAS,MAAM;QAE3B,IAAIH,cAAc,KAAKC,WAAWD,aACjC,OAAO;QAGRX,QAAQc;IACT;IAEA,OAAOd;AACR"}
1
+ {"version":3,"file":"transport/HttpHelpers.js","sources":["../../src/transport/HttpHelpers.ts"],"sourcesContent":["/**\n * Shared HTTP helper utilities for MCP transport implementations.\n *\n * Centralizes JSON-RPC response formatting, request body reading,\n * and common HTTP response patterns to eliminate duplication across\n * HttpTransport and StreamableHttpTransport.\n *\n * @module transport/HttpHelpers\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Send a JSON-RPC 2.0 error response.\n *\n * Standardizes error response formatting across all transport implementations.\n * All JSON-RPC errors use the standard `{ jsonrpc, id, error }` shape.\n *\n * @param res - The server response to write to\n * @param statusCode - HTTP status code (e.g. 400, 403, 429, 500)\n * @param code - JSON-RPC error code (e.g. -32700, -32600, -32603)\n * @param message - Human-readable error message\n * @param id - Optional JSON-RPC request ID (defaults to null)\n * @param data - Optional additional error data\n */\nexport function sendJsonRpcError(\n\tres: ServerResponse,\n\tstatusCode: number,\n\tcode: number,\n\tmessage: string,\n\tid: string | number | null = null,\n\tdata?: unknown\n): void {\n\tconst body: Record<string, unknown> = {\n\t\tjsonrpc: '2.0',\n\t\tid,\n\t\terror: { code, message },\n\t};\n\tif (data !== undefined) {\n\t\t(body.error as Record<string, unknown>).data = data;\n\t}\n\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\tres.end(JSON.stringify(body));\n}\n\n/**\n * Send a JSON-RPC 2.0 success response.\n *\n * @param res - The server response to write to\n * @param response - The JSON-RPC response object to send\n * @param statusCode - HTTP status code (default: 200)\n * @param headers - Optional additional response headers\n */\nexport function sendJsonRpcResponse(\n\tres: ServerResponse,\n\tresponse: unknown,\n\tstatusCode: number = 200,\n\theaders: Record<string, string> = {}\n): void {\n\tconst defaultHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\tres.writeHead(statusCode, { ...defaultHeaders, ...headers });\n\tres.end(JSON.stringify(response));\n}\n\n/**\n * Send a CORS preflight (OPTIONS) response.\n *\n * @param res - The server response to write to\n * @param extraAllowHeaders - Optional extra Access-Control-Allow-Headers values\n */\nexport function sendCorsPreflight(res: ServerResponse, extraAllowHeaders?: string[]): void {\n\tif (extraAllowHeaders && extraAllowHeaders.length > 0) {\n\t\tres.setHeader('Access-Control-Allow-Headers', `Content-Type, ${extraAllowHeaders.join(', ')}`);\n\t}\n\tres.writeHead(204);\n\tres.end();\n}\n\n/**\n * Read the full request body with optional size limit enforcement.\n *\n * Streams the request body chunks, tracking total size.\n * If the body exceeds `maxBodySize`, reading stops and `null` is returned\n * to indicate the payload is too large.\n *\n * @param req - The incoming HTTP request\n * @param maxBodySize - Maximum allowed body size in bytes (0 = unlimited)\n * @returns The body string, or `null` if the body exceeded the size limit\n */\nexport async function readRequestBody(\n\treq: IncomingMessage,\n\tmaxBodySize: number\n): Promise<string | null> {\n\tlet body = '';\n\tlet bodySize = 0;\n\n\tfor await (const chunk of req) {\n\t\tconst chunkStr = typeof chunk === 'string' ? chunk : (chunk as Buffer).toString();\n\t\tbodySize += chunkStr.length;\n\n\t\tif (maxBodySize > 0 && bodySize > maxBodySize) {\n\t\t\treturn null;\n\t\t}\n\n\t\tbody += chunkStr;\n\t}\n\n\treturn body;\n}\n"],"names":["sendJsonRpcError","res","statusCode","code","message","id","data","body","undefined","JSON","sendJsonRpcResponse","response","headers","defaultHeaders","sendCorsPreflight","extraAllowHeaders","readRequestBody","req","maxBodySize","bodySize","chunk","chunkStr"],"mappings":"AAyBO,SAASA,iBACfC,GAAmB,EACnBC,UAAkB,EAClBC,IAAY,EACZC,OAAe,EACfC,KAA6B,IAAI,EACjCC,IAAc;IAEd,MAAMC,OAAgC;QACrC,SAAS;QACTF;QACA,OAAO;YAAEF;YAAMC;QAAQ;IACxB;IACA,IAAIE,AAASE,WAATF,MACFC,KAAK,KAAK,CAA6B,IAAI,GAAGD;IAEhDL,IAAI,SAAS,CAACC,YAAY;QAAE,gBAAgB;IAAmB;IAC/DD,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACF;AACxB;AAUO,SAASG,oBACfT,GAAmB,EACnBU,QAAiB,EACjBT,aAAqB,GAAG,EACxBU,UAAkC,CAAC,CAAC;IAEpC,MAAMC,iBAAyC;QAAE,gBAAgB;IAAmB;IACpFZ,IAAI,SAAS,CAACC,YAAY;QAAE,GAAGW,cAAc;QAAE,GAAGD,OAAO;IAAC;IAC1DX,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACE;AACxB;AAQO,SAASG,kBAAkBb,GAAmB,EAAEc,iBAA4B;IAClF,IAAIA,qBAAqBA,kBAAkB,MAAM,GAAG,GACnDd,IAAI,SAAS,CAAC,gCAAgC,CAAC,cAAc,EAAEc,kBAAkB,IAAI,CAAC,OAAO;IAE9Fd,IAAI,SAAS,CAAC;IACdA,IAAI,GAAG;AACR;AAaO,eAAee,gBACrBC,GAAoB,EACpBC,WAAmB;IAEnB,IAAIX,OAAO;IACX,IAAIY,WAAW;IAEf,WAAW,MAAMC,SAASH,IAAK;QAC9B,MAAMI,WAAW,AAAiB,YAAjB,OAAOD,QAAqBA,QAASA,MAAiB,QAAQ;QAC/ED,YAAYE,SAAS,MAAM;QAE3B,IAAIH,cAAc,KAAKC,WAAWD,aACjC,OAAO;QAGRX,QAAQc;IACT;IAEA,OAAOd;AACR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iworkforces/tracelattice",
3
- "version": "2.0.3",
3
+ "version": "2.0.5",
4
4
  "description": "Semantic Sequential Thinking Layer For AI Agents.",
5
5
  "type": "module",
6
6
  "main": "dist/lib.js",