@iworkforces/tracelattice 2.0.3 → 2.0.6

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.
Files changed (36) hide show
  1. package/README.md +6 -12
  2. package/dist/cli.js +221 -2213
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/ConfigLoader.d.ts +3 -0
  5. package/dist/config/ConfigLoader.d.ts.map +1 -1
  6. package/dist/config/ConfigLoader.js +6 -0
  7. package/dist/config/ConfigLoader.js.map +1 -1
  8. package/dist/contracts/transport.d.ts +2 -2
  9. package/dist/contracts/transport.d.ts.map +1 -1
  10. package/dist/core/ThoughtProcessor.d.ts +1 -1
  11. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  12. package/dist/core/ThoughtProcessor.js +3 -6
  13. package/dist/core/ThoughtProcessor.js.map +1 -1
  14. package/dist/lib.d.ts +0 -10
  15. package/dist/lib.d.ts.map +1 -1
  16. package/dist/lib.js.map +1 -1
  17. package/dist/metrics/metrics.impl.d.ts +2 -7
  18. package/dist/metrics/metrics.impl.d.ts.map +1 -1
  19. package/dist/metrics/metrics.impl.js +32 -34
  20. package/dist/metrics/metrics.impl.js.map +1 -1
  21. package/dist/persistence/FileSnapshotV2.d.ts +2 -2
  22. package/dist/pool/ConnectionPool.d.ts +7 -3
  23. package/dist/pool/ConnectionPool.d.ts.map +1 -1
  24. package/dist/pool/ConnectionPool.js +65 -40
  25. package/dist/pool/ConnectionPool.js.map +1 -1
  26. package/dist/schema.d.ts +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/schema.js +4 -2
  29. package/dist/schema.js.map +1 -1
  30. package/dist/transport/HttpHelpers.d.ts +1 -1
  31. package/dist/transport/HttpHelpers.js.map +1 -1
  32. package/package.json +3 -3
  33. package/dist/transport/SseTransport.d.ts +0 -149
  34. package/dist/transport/SseTransport.d.ts.map +0 -1
  35. package/dist/transport/SseTransport.js +0 -470
  36. package/dist/transport/SseTransport.js.map +0 -1
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,IAAIE;QACJ,IAAI;YACHA,SAAS,IAAIJ,kCAAkC;gBAC9C,GAAGE,OAAO;gBACVC;YACD;YACA,MAAME,QAAQ,GAAG,CAAC;gBACjBD,O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ports 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,EAC9B,MAAME,OAAO,OAAO,CAAC,mBAAmB;YAGzC,IAAIF,AAAyB,UAAzBA,QAAQ,YAAY,IAAcA,AAA0B,SAA1BA,QAAQ,aAAa,EA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AAC,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"}
@@ -241,12 +241,7 @@ export declare class Metrics {
241
241
  * @private
242
242
  */
243
243
  private _metricKey;
244
- /**
245
- * Parses a metric key back into name and labels.
246
- * @param key - Metric key
247
- * @returns Name and labels
248
- * @private
249
- */
250
- private _parseMetricKey;
244
+ private _formatLabels;
245
+ private _escapeLabelValue;
251
246
  }
252
247
  //# sourceMappingURL=metrics.impl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metrics.impl.d.ts","sourceRoot":"","sources":["../../src/metrics/metrics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EACZ,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,EACnC,OAAO,WAAkB,GACvB,IAAI;IAkCP;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,GAAG,MAAM,GAAG,SAAS;IAO1E;;;;;;;;;;OAUG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI;IAIxD;;;;;;;;;;OAUG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI;IAKxD;;;;;;;;OAQG;IACH,KAAK,IAAI,IAAI;IAMb;;;;;;;;;;OAUG;IACH,iBAAiB,IAAI,MAAM;IAI3B;;;;;;;;;;;;;;OAcG;IACH,MAAM,IAAI,MAAM;IA8DhB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IASjB;;;;;;OAMG;IACH,OAAO,CAAC,UAAU;IAKlB,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,iBAAiB;CAGzB"}
@@ -27,7 +27,9 @@ class Metrics {
27
27
  this._metrics = new Map();
28
28
  this._histograms = new Map();
29
29
  this._prefix = options.prefix ?? '';
30
- this._defaultLabels = options.defaultLabels ?? {};
30
+ this._defaultLabels = {
31
+ ...options.defaultLabels
32
+ };
31
33
  }
32
34
  counter(name, value = 1, labels = {}, help) {
33
35
  const fullName = this._fullName(name);
@@ -44,7 +46,9 @@ class Metrics {
44
46
  name: fullName,
45
47
  type: "counter",
46
48
  value,
47
- labels: allLabels,
49
+ labels: {
50
+ ...allLabels
51
+ },
48
52
  help
49
53
  });
50
54
  this._operationsCounter++;
@@ -61,7 +65,9 @@ class Metrics {
61
65
  name: fullName,
62
66
  type: "gauge",
63
67
  value,
64
- labels: allLabels,
68
+ labels: {
69
+ ...allLabels
70
+ },
65
71
  help: help ?? existing?.help
66
72
  });
67
73
  this._operationsCounter++;
@@ -82,6 +88,10 @@ class Metrics {
82
88
  histogram.buckets.set(1 / 0, (histogram.buckets.get(1 / 0) ?? 0) + 1);
83
89
  } else {
84
90
  const histogramData = {
91
+ name: fullName,
92
+ labels: {
93
+ ...allLabels
94
+ },
85
95
  sum: value,
86
96
  count: 1,
87
97
  buckets: new Map()
@@ -119,7 +129,7 @@ class Metrics {
119
129
  export() {
120
130
  const lines = [];
121
131
  const metrics = Array.from(this._metrics.values());
122
- const histograms = Array.from(this._histograms.entries());
132
+ const histograms = Array.from(this._histograms.values());
123
133
  const helpEntries = new Map();
124
134
  const typeEntries = new Map();
125
135
  for (const metric of metrics){
@@ -132,17 +142,17 @@ class Metrics {
132
142
  lines.push(`# TYPE ${metric.name} ${metric.type}`);
133
143
  typeEntries.set(metric.name, metric.type);
134
144
  }
135
- const labelStr = Object.entries(metric.labels).map(([k, v])=>`${k}="${v}"`).join(',');
145
+ const labelStr = this._formatLabels(metric.labels);
136
146
  lines.push(`${metric.name}{${labelStr}} ${metric.value}`);
137
147
  }
138
- for (const [key, histogram] of histograms){
139
- const { name: fullName, labels } = this._parseMetricKey(key);
148
+ for (const histogram of histograms){
149
+ const { name: fullName, labels } = histogram;
140
150
  if (histogram.count > 0) {
141
151
  if (!typeEntries.has(fullName)) {
142
152
  lines.push(`# TYPE ${fullName} histogram`);
143
153
  typeEntries.set(fullName, "histogram");
144
154
  }
145
- const labelStr = Object.entries(labels).map(([k, v])=>`${k}="${v}"`).join(',');
155
+ const labelStr = this._formatLabels(labels);
146
156
  const formatMetricLine = (suffix, value)=>{
147
157
  if (0 === labelStr.length) return `${fullName}${suffix} ${value}`;
148
158
  return `${fullName}${suffix}{${labelStr}} ${value}`;
@@ -151,7 +161,10 @@ class Metrics {
151
161
  lines.push(formatMetricLine('_count', histogram.count));
152
162
  for (const [boundary, count] of histogram.buckets.entries()){
153
163
  const boundaryLabel = 1 / 0 === boundary ? '+Inf' : Number.isFinite(boundary) ? String(boundary) : String(boundary);
154
- const bucketLabels = 0 === labelStr.length ? `le="${boundaryLabel}"` : `${labelStr},le="${boundaryLabel}"`;
164
+ const boundaryLabelStr = this._formatLabels({
165
+ le: boundaryLabel
166
+ });
167
+ const bucketLabels = 0 === labelStr.length ? boundaryLabelStr : `${labelStr},${boundaryLabelStr}`;
155
168
  lines.push(`${fullName}_bucket{${bucketLabels}} ${count}`);
156
169
  }
157
170
  }
@@ -164,32 +177,17 @@ class Metrics {
164
177
  return name.startsWith(prefix) ? name : `${prefix}${name}`;
165
178
  }
166
179
  _metricKey(name, labels) {
167
- const sortedLabels = Object.entries(labels).sort(([a], [b])=>a.localeCompare(b)).map(([k, v])=>`${k}=${v}`).join(',');
168
- return `${name}{${sortedLabels}}`;
169
- }
170
- _parseMetricKey(key) {
171
- const match = key.match(/^([^{}]+)\{([^{}]*)\}$/);
172
- if (!match) return {
173
- name: key,
174
- labels: {}
175
- };
176
- const [, name, labelsPart] = match;
177
- if (!labelsPart) return {
180
+ const sortedLabels = Object.entries(labels).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0);
181
+ return JSON.stringify([
178
182
  name,
179
- labels: {}
180
- };
181
- const labels = {};
182
- for (const label of labelsPart.split(',')){
183
- const separatorIndex = label.indexOf('=');
184
- if (separatorIndex <= 0) continue;
185
- const labelKey = label.slice(0, separatorIndex);
186
- const labelValue = label.slice(separatorIndex + 1);
187
- labels[labelKey] = labelValue;
188
- }
189
- return {
190
- name,
191
- labels
192
- };
183
+ sortedLabels
184
+ ]);
185
+ }
186
+ _formatLabels(labels) {
187
+ return Object.entries(labels).map(([key, value])=>`${key}="${this._escapeLabelValue(value)}"`).join(',');
188
+ }
189
+ _escapeLabelValue(value) {
190
+ return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n');
193
191
  }
194
192
  }
195
193
  export { Metrics, metrics_impl_MetricType as MetricType };
@@ -1 +1 @@
1
- {"version":3,"file":"metrics/metrics.impl.js","sources":["../../src/metrics/metrics.impl.ts"],"sourcesContent":["/**\n * Prometheus-compatible metrics collection.\n *\n * This module provides metrics collection and export in Prometheus text format.\n * Supports counters, gauges, and histograms for observability.\n *\n * @module metrics\n */\n\n/**\n * Metric types supported by the metrics collector.\n */\nexport enum MetricType {\n\t/** Counter - a cumulative metric that only increases */\n\tCounter = 'counter',\n\n\t/** Gauge - a metric that can go up and down */\n\tGauge = 'gauge',\n\n\t/** Histogram - a metric for sampling observations */\n\tHistogram = 'histogram',\n}\n\n/**\n * A collected metric with its value and labels.\n */\nexport interface Metric {\n\t/** Name of the metric */\n\tname: string;\n\n\t/** Type of metric (counter, gauge, histogram) */\n\ttype: MetricType;\n\n\t/** Current value */\n\tvalue: number;\n\n\t/** Labels for the metric */\n\tlabels: Record<string, string>;\n\n\t/** Help text describing the metric */\n\thelp?: string;\n\n\t/** Timestamp when metric was recorded (Unix epoch) */\n\ttimestamp?: number;\n}\n\n/**\n * Histogram bucket boundaries for latency tracking.\n */\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\n\n/**\n * Prometheus-compatible metrics collector.\n *\n * Collects and exports metrics in Prometheus text format for scraping.\n * Thread-safe and supports counters, gauges, and histograms.\n *\n * @remarks\n * **Metric Types:**\n * - **Counter**: Cumulative value that only increases (e.g., request counts)\n * - **Gauge**: Value that can go up or down (e.g., active connections)\n * - **Histogram**: Sampling observations (e.g., request latency)\n *\n * **Labels:**\n * Metrics can have labels for dimensional data:\n * ```typescript\n * counter('http_requests_total', { method: 'GET', status: '200' });\n * ```\n *\n * **Export Format:**\n * Metrics are exported in Prometheus text format:\n * ```\n * # HELP http_requests_total Total HTTP requests\n * # TYPE http_requests_total counter\n * http_requests_total{method=\"GET\",status=\"200\"} 1234\n * ```\n *\n * @example\n * ```typescript\n * const metrics = new Metrics({ prefix: 'mcp_server' });\n *\n * // Count requests\n * metrics.counter('requests_total', { method: 'GET' }).inc();\n *\n * // Track active connections\n * const activeConnections = metrics.gauge('active_connections');\n * activeConnections.set(5);\n * activeConnections.dec();\n *\n * // Record latency\n * metrics.histogram('request_duration_seconds').observe(0.023);\n *\n * // Export for Prometheus\n * const prometheusText = metrics.export();\n * ```\n */\nexport class Metrics {\n\t/** Metrics storage indexed by name and label hash */\n\tprivate _metrics: Map<string, Metric>;\n\n\t/** Histogram samples */\n\tprivate _histograms: Map<string, { sum: number; count: number; buckets: Map<number, number> }>;\n\n\t/** Prefix for all metric names */\n\tprivate _prefix: string;\n\n\t/** Default labels to apply to all metrics */\n\tprivate _defaultLabels: Record<string, string>;\n\n\t/** Counter for metric collection operations */\n\tprivate _operationsCounter: number = 0;\n\n\t/**\n\t * Creates a new Metrics instance.\n\t *\n\t * @param options - Configuration options\n\t *\n\t * @example\n\t * ```typescript\n\t * const metrics = new Metrics({ prefix: 'mcp_server' });\n\t * ```\n\t */\n\tconstructor(options: { prefix?: string; defaultLabels?: Record<string, string> } = {}) {\n\t\tthis._metrics = new Map();\n\t\tthis._histograms = new Map();\n\t\tthis._prefix = options.prefix ?? '';\n\t\tthis._defaultLabels = options.defaultLabels ?? {};\n\t}\n\n\t/**\n\t * Creates a counter metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Increment value (default: 1)\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.counter('requests_total', 1, { method: 'GET' });\n\t * metrics.counter('errors_total', 1, { type: 'timeout' });\n\t * ```\n\t */\n\tcounter(name: string, value = 1, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\n\t\tif (existing) {\n\t\t\texisting.value += value;\n\t\t\tif (help && !existing.help) {\n\t\t\t\texisting.help = help;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._metrics.set(key, {\n\t\t\t\tname: fullName,\n\t\t\t\ttype: MetricType.Counter,\n\t\t\t\tvalue,\n\t\t\t\tlabels: allLabels,\n\t\t\t\thelp,\n\t\t\t});\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Creates a gauge metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Current value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * const activeConnections = metrics.gauge('active_connections');\n\t * activeConnections.set(5);\n\t * activeConnections.dec();\n\t * ```\n\t */\n\tgauge(name: string, value: number, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\t\tthis._metrics.set(key, {\n\t\t\tname: fullName,\n\t\t\ttype: MetricType.Gauge,\n\t\t\tvalue,\n\t\t\tlabels: allLabels,\n\t\t\thelp: help ?? existing?.help,\n\t\t});\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Records a histogram observation.\n\t *\n\t * @param name - Histogram name\n\t * @param value - Observed value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t * @param buckets - Custom bucket boundaries\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.histogram('request_duration_seconds').observe(0.023);\n\t * metrics.histogram('thought_processing_ms').observe(45);\n\t * ```\n\t */\n\thistogram(\n\t\tname: string,\n\t\tvalue: number,\n\t\tlabels: Record<string, string> = {},\n\t\tbuckets = DEFAULT_BUCKETS\n\t): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst histogram = this._histograms.get(key);\n\n\t\tif (histogram) {\n\t\t\thistogram.sum += value;\n\t\t\thistogram.count += 1;\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\tif (value <= boundary) {\n\t\t\t\t\thistogram.buckets.set(boundary, (histogram.buckets.get(boundary) ?? 0) + 1);\n\t\t\t\t} else {\n\t\t\t\t\thistogram.buckets.set(boundary, histogram.buckets.get(boundary) ?? 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\thistogram.buckets.set(Infinity, (histogram.buckets.get(Infinity) ?? 0) + 1);\n\t\t} else {\n\t\t\tconst histogramData = {\n\t\t\t\tsum: value,\n\t\t\t\tcount: 1,\n\t\t\t\tbuckets: new Map<number, number>(),\n\t\t\t};\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\thistogramData.buckets.set(boundary, value <= boundary ? 1 : 0);\n\t\t\t}\n\t\t\thistogramData.buckets.set(Infinity, 1);\n\t\t\tthis._histograms.set(key, histogramData);\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Gets the current value of a metric.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Current value or undefined if not found\n\t *\n\t * @example\n\t * ```typescript\n\t * const count = metrics.get('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tget(name: string, labels: Record<string, string> = {}): number | undefined {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\treturn this._metrics.get(key)?.value;\n\t}\n\n\t/**\n\t * Increments a counter by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.inc('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tinc(name: string, labels?: Record<string, string>): void {\n\t\tthis.counter(name, 1, labels);\n\t}\n\n\t/**\n\t * Decrements a gauge by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.dec('active_connections');\n\t * ```\n\t */\n\tdec(name: string, labels?: Record<string, string>): void {\n\t\tconst value = this.get(name, labels) ?? 0;\n\t\tthis.gauge(name, value - 1, labels);\n\t}\n\n\t/**\n\t * Resets all metrics to zero.\n\t * Useful for testing or on server restart.\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.reset();\n\t * ```\n\t */\n\treset(): void {\n\t\tthis._metrics.clear();\n\t\tthis._histograms.clear();\n\t\tthis._operationsCounter = 0;\n\t}\n\n\t/**\n\t * Gets the number of metric operations performed.\n\t * Useful for testing.\n\t *\n\t * @returns Operation count\n\t *\n\t * @example\n\t * ```typescript\n\t * const ops = metrics.getOperationCount();\n\t * ```\n\t */\n\tgetOperationCount(): number {\n\t\treturn this._operationsCounter;\n\t}\n\n\t/**\n\t * Exports metrics in Prometheus text format.\n\t *\n\t * @returns Prometheus text format string\n\t *\n\t * @example\n\t * ```typescript\n\t * const prometheusText = metrics.export();\n\t * console.log(prometheusText);\n\t * // Output:\n\t * // # HELP http_requests_total Total HTTP requests\n\t * // # TYPE http_requests_total counter\n\t * // http_requests_total{method=\"GET\",status=\"200\"} 1234\n\t * ```\n\t */\n\texport(): string {\n\t\tconst lines: string[] = [];\n\n\t\tconst metrics = Array.from(this._metrics.values());\n\t\tconst histograms = Array.from(this._histograms.entries());\n\n\t\tconst helpEntries = new Map<string, string>();\n\t\tconst typeEntries = new Map<string, MetricType>();\n\n\t\tfor (const metric of metrics) {\n\t\t\tif (!helpEntries.has(metric.name)) {\n\t\t\t\tconst helpText = metric.help ?? `${metric.name} metric`;\n\t\t\t\tlines.push(`# HELP ${metric.name} ${helpText}`);\n\t\t\t\thelpEntries.set(metric.name, helpText);\n\t\t\t}\n\t\t\tif (!typeEntries.has(metric.name)) {\n\t\t\t\tlines.push(`# TYPE ${metric.name} ${metric.type}`);\n\t\t\t\ttypeEntries.set(metric.name, metric.type);\n\t\t\t}\n\n\t\t\tconst labelStr = Object.entries(metric.labels)\n\t\t\t\t.map(([k, v]) => `${k}=\"${v}\"`)\n\t\t\t\t.join(',');\n\t\t\tlines.push(`${metric.name}{${labelStr}} ${metric.value}`);\n\t\t}\n\n\t\tfor (const [key, histogram] of histograms) {\n\t\t\tconst { name: fullName, labels } = this._parseMetricKey(key);\n\t\t\tif (histogram.count > 0) {\n\t\t\t\tif (!typeEntries.has(fullName)) {\n\t\t\t\t\tlines.push(`# TYPE ${fullName} histogram`);\n\t\t\t\t\ttypeEntries.set(fullName, MetricType.Histogram);\n\t\t\t\t}\n\n\t\t\t\tconst labelStr = Object.entries(labels)\n\t\t\t\t\t.map(([k, v]) => `${k}=\"${v}\"`)\n\t\t\t\t\t.join(',');\n\t\t\t\tconst formatMetricLine = (suffix: string, value: number): string => {\n\t\t\t\t\tif (labelStr.length === 0) {\n\t\t\t\t\t\treturn `${fullName}${suffix} ${value}`;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn `${fullName}${suffix}{${labelStr}} ${value}`;\n\t\t\t\t};\n\n\t\t\t\tlines.push(formatMetricLine('_sum', histogram.sum));\n\t\t\t\tlines.push(formatMetricLine('_count', histogram.count));\n\n\t\t\t\tfor (const [boundary, count] of histogram.buckets.entries()) {\n\t\t\t\t\tconst boundaryLabel =\n\t\t\t\t\t\tboundary === Infinity\n\t\t\t\t\t\t\t? '+Inf'\n\t\t\t\t\t\t\t: Number.isFinite(boundary)\n\t\t\t\t\t\t\t\t? String(boundary)\n\t\t\t\t\t\t\t\t: String(boundary);\n\t\t\t\t\tconst bucketLabels =\n\t\t\t\t\t\tlabelStr.length === 0 ? `le=\"${boundaryLabel}\"` : `${labelStr},le=\"${boundaryLabel}\"`;\n\t\t\t\t\tlines.push(`${fullName}_bucket{${bucketLabels}} ${count}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n\n\t/**\n\t * Gets metric name with prefix.\n\t * @param name - Metric name\n\t * @returns Full metric name\n\t * @private\n\t */\n\tprivate _fullName(name: string): string {\n\t\tif (!this._prefix) {\n\t\t\treturn name;\n\t\t}\n\n\t\tconst prefix = `${this._prefix}_`;\n\t\treturn name.startsWith(prefix) ? name : `${prefix}${name}`;\n\t}\n\n\t/**\n\t * Creates a unique key for a metric with labels.\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Unique key\n\t * @private\n\t */\n\tprivate _metricKey(name: string, labels: Record<string, string>): string {\n\t\tconst sortedLabels = Object.entries(labels)\n\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t.map(([k, v]) => `${k}=${v}`)\n\t\t\t.join(',');\n\t\treturn `${name}{${sortedLabels}}`;\n\t}\n\n\t/**\n\t * Parses a metric key back into name and labels.\n\t * @param key - Metric key\n\t * @returns Name and labels\n\t * @private\n\t */\n\tprivate _parseMetricKey(key: string): { name: string; labels: Record<string, string> } {\n\t\tconst match = key.match(/^([^{}]+)\\{([^{}]*)\\}$/);\n\t\tif (!match) {\n\t\t\treturn { name: key, labels: {} };\n\t\t}\n\n\t\tconst [, name, labelsPart] = match as [string, string, string | undefined];\n\t\tif (!labelsPart) {\n\t\t\treturn { name, labels: {} };\n\t\t}\n\n\t\tconst labels: Record<string, string> = {};\n\t\tfor (const label of labelsPart.split(',')) {\n\t\t\tconst separatorIndex = label.indexOf('=');\n\t\t\tif (separatorIndex <= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst labelKey = label.slice(0, separatorIndex);\n\t\t\tconst labelValue = label.slice(separatorIndex + 1);\n\t\t\tlabels[labelKey] = labelValue;\n\t\t}\n\n\t\treturn { name, labels };\n\t}\n}\n"],"names":["MetricType","DEFAULT_BUCKETS","Metrics","options","Map","name","value","labels","help","fullName","allLabels","key","existing","buckets","histogram","boundary","Infinity","histogramData","lines","metrics","Array","histograms","helpEntries","typeEntries","metric","helpText","labelStr","Object","k","v","formatMetricLine","suffix","count","boundaryLabel","Number","String","bucketLabels","prefix","sortedLabels","a","b","match","labelsPart","label","separatorIndex","labelKey","labelValue"],"mappings":"AAYO,IAAKA,0BAAUA,WAAAA,GAAAA,SAAVA,UAAU;IACiC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AAE,MAAM9B;YAAK,QAAQ,CAAC;QAAE;QAGhC,MAAM,GAAGN,MAAMqC,WAAW,GAAGD;QAC7B,IAAI,CAACC,YACJ,OAAO;YAAErC;YAAM,QAAQ,CAAC;QAAE;QAG3B,MAAME,SAAiC,CAAC;QACxC,KAAK,MAAMoC,SAASD,WAAW,KAAK,CAAC,KAAM;YAC1C,MAAME,iBAAiBD,MAAM,OAAO,CAAC;YACrC,IAAIC,kBAAkB,GACrB;YAGD,MAAMC,WAAWF,MAAM,KAAK,CAAC,GAAGC;YAChC,MAAME,aAAaH,MAAM,KAAK,CAACC,iBAAiB;YAChDrC,MAAM,CAACsC,SAAS,GAAGC;QACpB;QAEA,OAAO;YAAEzC;YAAME;QAAO;IACvB;AACD"}
1
+ {"version":3,"file":"metrics/metrics.impl.js","sources":["../../src/metrics/metrics.impl.ts"],"sourcesContent":["/**\n * Prometheus-compatible metrics collection.\n *\n * This module provides metrics collection and export in Prometheus text format.\n * Supports counters, gauges, and histograms for observability.\n *\n * @module metrics\n */\n\n/**\n * Metric types supported by the metrics collector.\n */\nexport enum MetricType {\n\t/** Counter - a cumulative metric that only increases */\n\tCounter = 'counter',\n\n\t/** Gauge - a metric that can go up and down */\n\tGauge = 'gauge',\n\n\t/** Histogram - a metric for sampling observations */\n\tHistogram = 'histogram',\n}\n\n/**\n * A collected metric with its value and labels.\n */\nexport interface Metric {\n\t/** Name of the metric */\n\tname: string;\n\n\t/** Type of metric (counter, gauge, histogram) */\n\ttype: MetricType;\n\n\t/** Current value */\n\tvalue: number;\n\n\t/** Labels for the metric */\n\tlabels: Record<string, string>;\n\n\t/** Help text describing the metric */\n\thelp?: string;\n\n\t/** Timestamp when metric was recorded (Unix epoch) */\n\ttimestamp?: number;\n}\n\ninterface HistogramMetric {\n\tname: string;\n\tlabels: Record<string, string>;\n\tsum: number;\n\tcount: number;\n\tbuckets: Map<number, number>;\n}\n\n/**\n * Histogram bucket boundaries for latency tracking.\n */\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\n\n/**\n * Prometheus-compatible metrics collector.\n *\n * Collects and exports metrics in Prometheus text format for scraping.\n * Thread-safe and supports counters, gauges, and histograms.\n *\n * @remarks\n * **Metric Types:**\n * - **Counter**: Cumulative value that only increases (e.g., request counts)\n * - **Gauge**: Value that can go up or down (e.g., active connections)\n * - **Histogram**: Sampling observations (e.g., request latency)\n *\n * **Labels:**\n * Metrics can have labels for dimensional data:\n * ```typescript\n * counter('http_requests_total', { method: 'GET', status: '200' });\n * ```\n *\n * **Export Format:**\n * Metrics are exported in Prometheus text format:\n * ```\n * # HELP http_requests_total Total HTTP requests\n * # TYPE http_requests_total counter\n * http_requests_total{method=\"GET\",status=\"200\"} 1234\n * ```\n *\n * @example\n * ```typescript\n * const metrics = new Metrics({ prefix: 'mcp_server' });\n *\n * // Count requests\n * metrics.counter('requests_total', { method: 'GET' }).inc();\n *\n * // Track active connections\n * const activeConnections = metrics.gauge('active_connections');\n * activeConnections.set(5);\n * activeConnections.dec();\n *\n * // Record latency\n * metrics.histogram('request_duration_seconds').observe(0.023);\n *\n * // Export for Prometheus\n * const prometheusText = metrics.export();\n * ```\n */\nexport class Metrics {\n\t/** Metrics storage indexed by name and label hash */\n\tprivate _metrics: Map<string, Metric>;\n\n\t/** Histogram samples */\n\tprivate _histograms: Map<string, HistogramMetric>;\n\n\t/** Prefix for all metric names */\n\tprivate _prefix: string;\n\n\t/** Default labels to apply to all metrics */\n\tprivate _defaultLabels: Record<string, string>;\n\n\t/** Counter for metric collection operations */\n\tprivate _operationsCounter: number = 0;\n\n\t/**\n\t * Creates a new Metrics instance.\n\t *\n\t * @param options - Configuration options\n\t *\n\t * @example\n\t * ```typescript\n\t * const metrics = new Metrics({ prefix: 'mcp_server' });\n\t * ```\n\t */\n\tconstructor(options: { prefix?: string; defaultLabels?: Record<string, string> } = {}) {\n\t\tthis._metrics = new Map();\n\t\tthis._histograms = new Map();\n\t\tthis._prefix = options.prefix ?? '';\n\t\tthis._defaultLabels = { ...options.defaultLabels };\n\t}\n\n\t/**\n\t * Creates a counter metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Increment value (default: 1)\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.counter('requests_total', 1, { method: 'GET' });\n\t * metrics.counter('errors_total', 1, { type: 'timeout' });\n\t * ```\n\t */\n\tcounter(name: string, value = 1, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\n\t\tif (existing) {\n\t\t\texisting.value += value;\n\t\t\tif (help && !existing.help) {\n\t\t\t\texisting.help = help;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._metrics.set(key, {\n\t\t\t\tname: fullName,\n\t\t\t\ttype: MetricType.Counter,\n\t\t\t\tvalue,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\thelp,\n\t\t\t});\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Creates a gauge metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Current value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * const activeConnections = metrics.gauge('active_connections');\n\t * activeConnections.set(5);\n\t * activeConnections.dec();\n\t * ```\n\t */\n\tgauge(name: string, value: number, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\t\tthis._metrics.set(key, {\n\t\t\tname: fullName,\n\t\t\ttype: MetricType.Gauge,\n\t\t\tvalue,\n\t\t\tlabels: { ...allLabels },\n\t\t\thelp: help ?? existing?.help,\n\t\t});\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Records a histogram observation.\n\t *\n\t * @param name - Histogram name\n\t * @param value - Observed value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t * @param buckets - Custom bucket boundaries\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.histogram('request_duration_seconds').observe(0.023);\n\t * metrics.histogram('thought_processing_ms').observe(45);\n\t * ```\n\t */\n\thistogram(\n\t\tname: string,\n\t\tvalue: number,\n\t\tlabels: Record<string, string> = {},\n\t\tbuckets = DEFAULT_BUCKETS\n\t): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst histogram = this._histograms.get(key);\n\n\t\tif (histogram) {\n\t\t\thistogram.sum += value;\n\t\t\thistogram.count += 1;\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\tif (value <= boundary) {\n\t\t\t\t\thistogram.buckets.set(boundary, (histogram.buckets.get(boundary) ?? 0) + 1);\n\t\t\t\t} else {\n\t\t\t\t\thistogram.buckets.set(boundary, histogram.buckets.get(boundary) ?? 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\thistogram.buckets.set(Infinity, (histogram.buckets.get(Infinity) ?? 0) + 1);\n\t\t} else {\n\t\t\tconst histogramData = {\n\t\t\t\tname: fullName,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\tsum: value,\n\t\t\t\tcount: 1,\n\t\t\t\tbuckets: new Map<number, number>(),\n\t\t\t};\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\thistogramData.buckets.set(boundary, value <= boundary ? 1 : 0);\n\t\t\t}\n\t\t\thistogramData.buckets.set(Infinity, 1);\n\t\t\tthis._histograms.set(key, histogramData);\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Gets the current value of a metric.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Current value or undefined if not found\n\t *\n\t * @example\n\t * ```typescript\n\t * const count = metrics.get('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tget(name: string, labels: Record<string, string> = {}): number | undefined {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\treturn this._metrics.get(key)?.value;\n\t}\n\n\t/**\n\t * Increments a counter by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.inc('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tinc(name: string, labels?: Record<string, string>): void {\n\t\tthis.counter(name, 1, labels);\n\t}\n\n\t/**\n\t * Decrements a gauge by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.dec('active_connections');\n\t * ```\n\t */\n\tdec(name: string, labels?: Record<string, string>): void {\n\t\tconst value = this.get(name, labels) ?? 0;\n\t\tthis.gauge(name, value - 1, labels);\n\t}\n\n\t/**\n\t * Resets all metrics to zero.\n\t * Useful for testing or on server restart.\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.reset();\n\t * ```\n\t */\n\treset(): void {\n\t\tthis._metrics.clear();\n\t\tthis._histograms.clear();\n\t\tthis._operationsCounter = 0;\n\t}\n\n\t/**\n\t * Gets the number of metric operations performed.\n\t * Useful for testing.\n\t *\n\t * @returns Operation count\n\t *\n\t * @example\n\t * ```typescript\n\t * const ops = metrics.getOperationCount();\n\t * ```\n\t */\n\tgetOperationCount(): number {\n\t\treturn this._operationsCounter;\n\t}\n\n\t/**\n\t * Exports metrics in Prometheus text format.\n\t *\n\t * @returns Prometheus text format string\n\t *\n\t * @example\n\t * ```typescript\n\t * const prometheusText = metrics.export();\n\t * console.log(prometheusText);\n\t * // Output:\n\t * // # HELP http_requests_total Total HTTP requests\n\t * // # TYPE http_requests_total counter\n\t * // http_requests_total{method=\"GET\",status=\"200\"} 1234\n\t * ```\n\t */\n\texport(): string {\n\t\tconst lines: string[] = [];\n\n\t\tconst metrics = Array.from(this._metrics.values());\n\t\tconst histograms = Array.from(this._histograms.values());\n\n\t\tconst helpEntries = new Map<string, string>();\n\t\tconst typeEntries = new Map<string, MetricType>();\n\n\t\tfor (const metric of metrics) {\n\t\t\tif (!helpEntries.has(metric.name)) {\n\t\t\t\tconst helpText = metric.help ?? `${metric.name} metric`;\n\t\t\t\tlines.push(`# HELP ${metric.name} ${helpText}`);\n\t\t\t\thelpEntries.set(metric.name, helpText);\n\t\t\t}\n\t\t\tif (!typeEntries.has(metric.name)) {\n\t\t\t\tlines.push(`# TYPE ${metric.name} ${metric.type}`);\n\t\t\t\ttypeEntries.set(metric.name, metric.type);\n\t\t\t}\n\n\t\t\tconst labelStr = this._formatLabels(metric.labels);\n\t\t\tlines.push(`${metric.name}{${labelStr}} ${metric.value}`);\n\t\t}\n\n\t\tfor (const histogram of histograms) {\n\t\t\tconst { name: fullName, labels } = histogram;\n\t\t\tif (histogram.count > 0) {\n\t\t\t\tif (!typeEntries.has(fullName)) {\n\t\t\t\t\tlines.push(`# TYPE ${fullName} histogram`);\n\t\t\t\t\ttypeEntries.set(fullName, MetricType.Histogram);\n\t\t\t\t}\n\n\t\t\t\tconst labelStr = this._formatLabels(labels);\n\t\t\t\tconst formatMetricLine = (suffix: string, value: number): string => {\n\t\t\t\t\tif (labelStr.length === 0) {\n\t\t\t\t\t\treturn `${fullName}${suffix} ${value}`;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn `${fullName}${suffix}{${labelStr}} ${value}`;\n\t\t\t\t};\n\n\t\t\t\tlines.push(formatMetricLine('_sum', histogram.sum));\n\t\t\t\tlines.push(formatMetricLine('_count', histogram.count));\n\n\t\t\t\tfor (const [boundary, count] of histogram.buckets.entries()) {\n\t\t\t\t\tconst boundaryLabel =\n\t\t\t\t\t\tboundary === Infinity\n\t\t\t\t\t\t\t? '+Inf'\n\t\t\t\t\t\t\t: Number.isFinite(boundary)\n\t\t\t\t\t\t\t\t? String(boundary)\n\t\t\t\t\t\t\t\t: String(boundary);\n\t\t\t\t\tconst boundaryLabelStr = this._formatLabels({ le: boundaryLabel });\n\t\t\t\t\tconst bucketLabels =\n\t\t\t\t\t\tlabelStr.length === 0 ? boundaryLabelStr : `${labelStr},${boundaryLabelStr}`;\n\t\t\t\t\tlines.push(`${fullName}_bucket{${bucketLabels}} ${count}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n\n\t/**\n\t * Gets metric name with prefix.\n\t * @param name - Metric name\n\t * @returns Full metric name\n\t * @private\n\t */\n\tprivate _fullName(name: string): string {\n\t\tif (!this._prefix) {\n\t\t\treturn name;\n\t\t}\n\n\t\tconst prefix = `${this._prefix}_`;\n\t\treturn name.startsWith(prefix) ? name : `${prefix}${name}`;\n\t}\n\n\t/**\n\t * Creates a unique key for a metric with labels.\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Unique key\n\t * @private\n\t */\n\tprivate _metricKey(name: string, labels: Record<string, string>): string {\n\t\tconst sortedLabels = Object.entries(labels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\treturn JSON.stringify([name, sortedLabels]);\n\t}\n\n\tprivate _formatLabels(labels: Record<string, string>): string {\n\t\treturn Object.entries(labels)\n\t\t\t.map(([key, value]) => `${key}=\"${this._escapeLabelValue(value)}\"`)\n\t\t\t.join(',');\n\t}\n\n\tprivate _escapeLabelValue(value: string): string {\n\t\treturn value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n');\n\t}\n}\n"],"names":["MetricType","DEFAULT_BUCKETS","Metrics","options","Map","name","value","labels","help","fullName","allLabels","key","existing","buckets","histogram","boundary","Infinity","histogramData","lines","metrics","Array","histograms","helpEntries","typeEntries","metric","helpText","labelStr","formatMetricLine","suffix","count","boundaryLabel","Number","String","boundaryLabelStr","bucketLabels","prefix","sortedLabels","Object","a","b","JSON"],"mappings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AM,UAAU,CAAC,MAAM,QAAQ,UAAU,CAAC,KAAK,OAAO,UAAU,CAAC,MAAM;IAC/E;AACD"}
@@ -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>;
@@ -61,7 +61,8 @@ export declare class Session {
61
61
  private _closePromise;
62
62
  private _activeOperationCount;
63
63
  private _operationDrain;
64
- constructor(id: SessionId, server: SessionServer, timeout: number, logger: Logger);
64
+ private readonly _onTimeout;
65
+ constructor(id: SessionId, server: SessionServer, timeout: number, logger: Logger, onTimeout?: ((sessionId: SessionId) => void) | null);
65
66
  /**
66
67
  * Check if the session is active.
67
68
  */
@@ -102,6 +103,7 @@ export declare class Session {
102
103
  */
103
104
  export declare class ConnectionPool implements IConnectionPool {
104
105
  private _sessions;
106
+ private readonly _ownedSessions;
105
107
  private readonly _closingSessions;
106
108
  private _createSessionLock;
107
109
  private _maxSessions;
@@ -112,9 +114,8 @@ export declare class ConnectionPool implements IConnectionPool {
112
114
  private _terminated;
113
115
  private _logger;
114
116
  private _serverFactory;
115
- private _terminatePromise;
117
+ private _terminationGeneration;
116
118
  private readonly _admissionContext;
117
- private readonly _pendingCreateStopFailures;
118
119
  constructor(options?: SessionOptions);
119
120
  /**
120
121
  * Create a no-op logger when none is provided.
@@ -145,6 +146,8 @@ export declare class ConnectionPool implements IConnectionPool {
145
146
  * @throws Error if session not found
146
147
  */
147
148
  closeSession(sessionId: SessionId): Promise<void>;
149
+ private _coordinateCleanup;
150
+ private _handleSessionTimeout;
148
151
  /**
149
152
  * Get information about a session.
150
153
  *
@@ -174,6 +177,7 @@ export declare class ConnectionPool implements IConnectionPool {
174
177
  * Close all sessions and stop the cleanup timer.
175
178
  */
176
179
  terminate(): Promise<void>;
180
+ private _completeTerminationGeneration;
177
181
  /**
178
182
  * Dispose of the connection pool, releasing all resources.
179
183
  * Implements the IDisposable interface.
@@ -1 +1 @@
1
- {"version":3,"file":"ConnectionPool.d.ts","sourceRoot":"","sources":["../../src/pool/ConnectionPool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAOH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAAe,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAGlE,OAAO,KAAK,EACX,mBAAmB,EACnB,eAAe,EACf,aAAa,EACb,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,mBAAmB,EACnB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,WAAW,cAAc;IAC9B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,aAAa,CAAC,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,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