@iworkforces/tracelattice 2.0.6 → 2.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -1
- package/dist/cli.js +296 -196
- package/dist/contracts/summary.d.ts +0 -1
- package/dist/contracts/summary.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.d.ts +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtFormatter.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/compression/CompressionService.d.ts +6 -4
- package/dist/core/compression/CompressionService.d.ts.map +1 -1
- package/dist/core/compression/CompressionService.js +19 -10
- package/dist/core/compression/CompressionService.js.map +1 -1
- package/dist/core/compression/DehydrationPolicy.d.ts +4 -4
- package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -1
- package/dist/core/compression/DehydrationPolicy.js +3 -6
- package/dist/core/compression/DehydrationPolicy.js.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts +2 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.js.map +1 -1
- package/dist/core/evaluator/Calibrator.d.ts +1 -1
- package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
- package/dist/core/evaluator/Calibrator.js.map +1 -1
- package/dist/core/evaluator/SignalComputer.d.ts +2 -1
- package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
- package/dist/core/evaluator/SignalComputer.js.map +1 -1
- package/dist/core/evaluator/internals.d.ts +1 -1
- package/dist/core/evaluator/internals.d.ts.map +1 -1
- package/dist/core/evaluator/internals.js.map +1 -1
- package/dist/core/graph/GraphView.d.ts +13 -1
- package/dist/core/graph/GraphView.d.ts.map +1 -1
- package/dist/core/graph/GraphView.js +34 -0
- package/dist/core/graph/GraphView.js.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +6 -6
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +16 -2
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.js.map +1 -1
- package/dist/core/reasoning.d.ts +1 -3
- package/dist/core/reasoning.d.ts.map +1 -1
- package/dist/core/thought.d.ts +1 -1
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/lib.d.ts +20 -6
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +52 -3
- package/dist/lib.js.map +1 -1
- package/dist/transport/HttpHelpers.d.ts +4 -1
- package/dist/transport/HttpHelpers.d.ts.map +1 -1
- package/dist/transport/HttpHelpers.js +61 -11
- package/dist/transport/HttpHelpers.js.map +1 -1
- package/dist/transport/HttpRequestLifecycle.d.ts +15 -1
- package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -1
- package/dist/transport/HttpRequestLifecycle.js +66 -4
- package/dist/transport/HttpRequestLifecycle.js.map +1 -1
- package/dist/transport/HttpTransport.d.ts +2 -0
- package/dist/transport/HttpTransport.d.ts.map +1 -1
- package/dist/transport/HttpTransport.js +75 -38
- package/dist/transport/HttpTransport.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +17 -29
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +153 -124
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/package.json +4 -4
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 { 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,EAC1D,MAAMG,QAAQ,GAAG,CAAC;g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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"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport type * as v from 'valibot';\nimport type { ThoughtData } from './core/thought.js';\nimport type { BranchId } from './contracts/ids.js';\nimport type { SequentialThinkingSchema } from './schema.js';\nimport { SEQUENTIAL_THINKING_TOOL } from './schema.js';\nimport type { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\nimport { assertNever } from './utils.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport { SessionLifecycleClosedError } from './core/SessionErrors.js';\nimport { SessionLifecycleCoordinator } from './core/SessionLifecycleCoordinator.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';\nimport type { HttpTransportOptions } from './transport/HttpTransport.js';\nimport type { TransportOptions } from './transport/BaseTransport.js';\nimport type { ITransport, TransportKind } from './contracts/transport.js';\n\nexport { HttpTransport, createHttpTransport };\nexport type { HttpTransportOptions, TransportOptions, ITransport, TransportKind };\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Enable automatic tool and skill discovery on server startup.\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Suppress startup discovery so callers can discover through registry APIs explicitly.\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\ntype CleanupOperation = () => void | Promise<void>;\n\nfunction appendCleanupFailure(failures: unknown[], failure: unknown): void {\n\tif (failure instanceof AggregateError) {\n\t\tfailures.push(...failure.errors);\n\t\treturn;\n\t}\n\tfailures.push(failure);\n}\n\nasync function collectCleanupFailures(operations: readonly CleanupOperation[]): Promise<unknown[]> {\n\tconst failures: unknown[] = [];\n\tfor (const operation of operations) {\n\t\ttry {\n\t\t\tawait operation();\n\t\t} catch (error) {\n\t\t\tappendCleanupFailure(failures, error);\n\t\t}\n\t}\n\treturn failures;\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/** Rescan configured tool and skill directories. */\n\trefreshDiscovery(): Promise<{ tools: number; skills: number }>;\n\n\t/**\n\t * Get all branches from the history manager.\n\t *\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/**\n\t * Clear all server state (history, tools, skills).\n\t */\n\tclear(): void;\n\n\t/** Awaitably reset one session and all matching auxiliary state. */\n\tresetSession(sessionId: string): Promise<void>;\n\n\t/** Awaitably reset all state from a trusted ownerless context. */\n\tresetAll(): Promise<void>;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer\n\textends EventEmitter\n\timplements IToolAwareSequentialThinkingServer\n{\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\t\tlet server: ToolAwareSequentialThinkingServer | undefined;\n\t\ttry {\n\t\t\tserver = new ToolAwareSequentialThinkingServer({\n\t\t\t\t...options,\n\t\t\t\tcontainer,\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\tserver._skillWatcher?.ready() ?? Promise.resolve(),\n\t\t\t\tserver._toolWatcher?.ready() ?? Promise.resolve(),\n\t\t\t]);\n\n\t\t\tif (options.loadFromPersistence !== false) {\n\t\t\t\tawait server.history.loadFromPersistence();\n\t\t\t}\n\n\t\t\tif (options.autoDiscover !== false && options.lazyDiscovery !== true) {\n\t\t\t\tawait Promise.all([server.tools.discoverAsync(), server.discoverSkillsAsync()]);\n\t\t\t}\n\n\t\t\treturn server;\n\t\t} catch (error) {\n\t\t\tconst startedServer = server;\n\t\t\tconst cleanupFailures = await collectCleanupFailures(\n\t\t\t\tstartedServer\n\t\t\t\t\t? [() => startedServer.dispose()]\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tif (container.has('suspensionStore')) {\n\t\t\t\t\t\t\t\t\tcontainer.resolve('suspensionStore').stop();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t() => container.resolve('Persistence')?.close(),\n\t\t\t\t\t\t\t() => container.dispose(),\n\t\t\t\t\t\t]\n\t\t\t);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Server startup failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\tprivate _acceptingDiscoveryRefreshes = true;\n\tprivate _refreshPromise: Promise<{ tools: number; skills: number }> | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\tprivate _disposePromise: Promise<void> | null = null;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory();\n\t * server.history.clear();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.addTool(tool);\n\t * server.tools.getTool('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.addSkill(skill);\n\t * server.skills.getSkill('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve('Logger');\n\t\tthis._historyManager = this._container.resolve('HistoryManager');\n\t\tthis._historyManager.bindShutdownOwner(() => this.stop());\n\t\tthis._thoughtProcessor = this._container.resolve('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve('Metrics');\n\t\tthis._config = this._container.resolve('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve('ToolRegistry');\n\t\tthis.skills = this._container.resolve('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.addTool(SEQUENTIAL_THINKING_TOOL);\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\tconst config = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tToolAwareSequentialThinkingServer._registerDiscoveryRegistries(\n\t\t\tcontainer,\n\t\t\toptions.lazyDiscovery\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve('HistoryManager');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\treturn new CompressionService({\n\t\t\t\thistoryManager,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tonSummaryCreated: (summary) => {\n\t\t\t\t\thistoryManager.bufferSummaries(\n\t\t\t\t\t\tsummary.sessionId,\n\t\t\t\t\t\tsummaryStore.forSession(summary.sessionId)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tlogger: log,\n\t\t\t});\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy)\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\t\tcontainer.register('sessionLifecycle', () => new SessionLifecycleCoordinator());\n\n\t\tToolAwareSequentialThinkingServer._registerHistoryManager(container);\n\t\tToolAwareSequentialThinkingServer._registerThoughtPipeline(container, config);\n\n\t\treturn container;\n\t}\n\n\tprivate static _resolveEffectiveConfig(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null\n\t): ServerConfig {\n\t\tif (options.config) return options.config;\n\t\tconst loadedOptions = new ConfigLoader().toServerConfigOptions(fileConfig ?? {});\n\t\treturn new ServerConfig({\n\t\t\t...loadedOptions,\n\t\t\tmaxHistorySize: options.maxHistorySize ?? loadedOptions.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? loadedOptions.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? loadedOptions.maxBranchSize,\n\t\t});\n\t}\n\n\tprivate static _registerDiscoveryRegistries(\n\t\tcontainer: Container,\n\t\tlazyDiscovery: ServerOptions['lazyDiscovery']\n\t): void {\n\t\tconst logger = container.resolve('Logger');\n\t\tconst config = container.resolve('Config');\n\t\tconst metrics = container.resolve('Metrics');\n\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\ttoolDirs: config.toolDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t}\n\n\tprivate static _registerHistoryManager(container: Container): void {\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve('Config');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst pers = container.resolve('Persistence');\n\t\t\tconst componentMetrics = container.resolve('Metrics');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tdagEdges: cfg.features.dagEdges,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t\tsessionLock: container.resolve('sessionLock'),\n\t\t\t\tlifecycleCoordinator: container.resolve('sessionLifecycle'),\n\t\t\t\tclearSessionAuxiliaryState: (sessionId) =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearSessionAuxiliaryState(sessionId),\n\t\t\t\tclearAllAuxiliaryState: () =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearAllAuxiliaryState(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate static _registerThoughtPipeline(container: Container, config: ServerConfig): void {\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false })\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(container.resolve('outcomeRecorder'), config.features.calibration ?? false)\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator'))\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve('HistoryManager');\n\t\t\tconst formatter = container.resolve('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve('ThoughtEvaluator');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst strategy = container.resolve('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\tcontainer.resolve('sessionLifecycle'),\n\t\t\t\tcontainer.resolve('calibrator')\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tlet fileConfig: ConfigFileOptions | null;\n\t\tlet config: ServerConfig;\n\t\tif (options.config) {\n\t\t\tfileConfig = options.fileConfig ?? null;\n\t\t\tconfig = options.config;\n\t\t} else {\n\t\t\tconst configLoader = new ConfigLoader();\n\t\t\tfileConfig =\n\t\t\t\toptions.fileConfig === undefined\n\t\t\t\t\t? configLoader.load()\n\t\t\t\t\t: configLoader.applyEnvironmentOverrides(options.fileConfig);\n\t\t\tconfig = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\t\t}\n\n\t\tlet persistence: PersistenceBackend | null = null;\n\t\ttry {\n\t\t\tpersistence = await createPersistenceBackend(config.persistence);\n\t\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(\n\t\t\t\t{ ...options, config },\n\t\t\t\tfileConfig,\n\t\t\t\tpersistence\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst acquiredPersistence = persistence;\n\t\t\tconst cleanupFailures =\n\t\t\t\tacquiredPersistence === null\n\t\t\t\t\t? []\n\t\t\t\t\t: await collectCleanupFailures([() => acquiredPersistence.close()]);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Container construction failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/** Rescan configured tool and skill directories. */\n\tpublic refreshDiscovery(): Promise<{ tools: number; skills: number }> {\n\t\tif (!this._acceptingDiscoveryRefreshes) {\n\t\t\treturn Promise.reject(new SessionLifecycleClosedError(undefined, 'shutting_down'));\n\t\t}\n\t\tif (this._refreshPromise !== null) return this._refreshPromise;\n\n\t\tconst refreshPromise = Promise.allSettled([\n\t\t\tthis.tools.refreshAsync(),\n\t\t\tthis.skills.refreshAsync(),\n\t\t]).then(([toolResult, skillResult]) => {\n\t\t\tif (toolResult.status === 'rejected') {\n\t\t\t\tif (skillResult.status === 'rejected') {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[toolResult.reason, skillResult.reason],\n\t\t\t\t\t\t'Failed to refresh tool and skill discovery'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow toolResult.reason;\n\t\t\t}\n\t\t\tif (skillResult.status === 'rejected') throw skillResult.reason;\n\t\t\treturn { tools: toolResult.value, skills: skillResult.value };\n\t\t});\n\t\tthis._refreshPromise = refreshPromise;\n\t\tconst clearRefreshPromise = (): void => {\n\t\t\tif (this._refreshPromise === refreshPromise) this._refreshPromise = null;\n\t\t};\n\t\tvoid refreshPromise.then(clearRefreshPromise, clearRefreshPromise);\n\t\treturn refreshPromise;\n\t}\n\n\t/**\n\t * Get all branches from the history manager\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(): Record<BranchId, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches();\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst result = await this._thoughtProcessor.process(input as ThoughtData);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic stop(): Promise<void> {\n\t\tthis._acceptingDiscoveryRefreshes = false;\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tconst acceptedRefresh = this._refreshPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([\n\t\t\t\tthis._skillWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tthis._toolWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tacceptedRefresh ?? Promise.resolve(),\n\t\t\t]);\n\t\t\tfor (const result of [skillWatcherResult, toolWatcherResult]) {\n\t\t\t\tswitch (result.status) {\n\t\t\t\t\tcase 'fulfilled':\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'rejected':\n\t\t\t\t\t\tappendCleanupFailure(failures, result.reason);\n\t\t\t\t\t\tthis._logger.error('Error stopping watcher', {\n\t\t\t\t\t\t\terror: getErrorMessage(result.reason),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (refreshResult.status) {\n\t\t\t\tcase 'fulfilled':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'rejected':\n\t\t\t\t\tappendCleanupFailure(failures, refreshResult.reason);\n\t\t\t\t\tthis._logger.error('Error refreshing discovery during shutdown', {\n\t\t\t\t\t\terror: getErrorMessage(refreshResult.reason),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(refreshResult);\n\t\t\t}\n\n\t\t\t// Stop suspension store sweeper if registered\n\t\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst suspensionStore = this._container.resolve('suspensionStore');\n\t\t\t\t\tsuspensionStore.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Flush any buffered writes before closing persistence\n\t\t\ttry {\n\t\t\t\tawait this._historyManager.shutdownWithinLifecycle();\n\t\t\t} catch (error) {\n\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Close persistence backend if available\n\t\t\tconst persistence = this._container.resolve('Persistence');\n\t\t\tif (persistence) {\n\t\t\t\ttry {\n\t\t\t\t\tawait persistence.close();\n\t\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to stop server cleanly');\n\t\t\t}\n\t\t\tthis._historyManager.clearLiveStateAfterShutdown();\n\t\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t\t});\n\t\treturn this._stopPromise;\n\t}\n\n\t/**\n\t * Clear all server state (history, tools, skills)\n\t * Useful for testing to reset state between tests\n\t */\n\tpublic clear(): void {\n\t\tthis._historyManager.clear();\n\t\tthis._logger.info('Server state cleared');\n\t}\n\n\t/** Awaitably resets one session and matching processor-owned state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tawait this._thoughtProcessor.resetSession(sessionId);\n\t\tthis._logger.info('Server session reset', { sessionId });\n\t}\n\n\t/** Awaitably resets all server state from a trusted ownerless context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._thoughtProcessor.resetAll();\n\t\tthis._logger.info('All server sessions reset');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic dispose(): Promise<void> {\n\t\tif (this._disposePromise) return this._disposePromise;\n\t\tthis._disposePromise = (async () => {\n\t\t\tconst failures = await collectCleanupFailures([\n\t\t\t\t() => this.stop(),\n\t\t\t\t() => this._container.dispose(),\n\t\t\t]);\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to dispose server cleanly');\n\t\t\t}\n\t\t\tthis._logger.info('Server disposed, all resources released');\n\t\t})();\n\t\treturn this._disposePromise;\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * import { createServer } from '@iworkforces/tracelattice';\n *\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load() ?? {};\n\tconst config = new ServerConfig(configLoader.toServerConfigOptions(fileConfig));\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t\tconfig,\n\t\tfileConfig,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["appendCleanupFailure","failures","failure","AggregateError","collectCleanupFailures","operations","operation","error","ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","Promise","startedServer","cleanupFailures","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","persistence","Container","metrics","Metrics","config","logger","StructuredLogger","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","summary","createReasoningStrategy","SessionLock","SessionLifecycleCoordinator","loadedOptions","ConfigLoader","ServerConfig","lazyDiscovery","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","cfg","pers","componentMetrics","HistoryManager","sessionId","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","createPersistenceBackend","acquiredPersistence","discovered","SessionLifecycleClosedError","refreshPromise","toolResult","skillResult","clearRefreshPromise","input","startTime","Date","result","durationSeconds","acceptedRefresh","skillWatcherResult","toolWatcherResult","refreshResult","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,SAASA,qBAAqBC,QAAmB,EAAEC,OAAgB;IAClE,IAAIA,mBAAmBC,gBAAgB,YACtCF,SAAS,IAAI,IAAIC,QAAQ,MAAM;IAGhCD,SAAS,IAAI,CAACC;AACf;AAEA,eAAeE,uBAAuBC,UAAuC;IAC5E,MAAMJ,WAAsB,EAAE;IAC9B,KAAK,MAAMK,aAAaD,WACvB,IAAI;QACH,MAAMC;IACP,EAAE,OAAOC,OAAO;QACfP,qBAAqBC,UAAUM;IAChC;IAED,OAAON;AACR;AAgFO,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,A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import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
11
|
+
export declare class RequestBodyAbortedError extends Error {
|
|
12
|
+
readonly name = "RequestBodyAbortedError";
|
|
13
|
+
}
|
|
11
14
|
/**
|
|
12
15
|
* Send a JSON-RPC 2.0 error response.
|
|
13
16
|
*
|
|
@@ -49,5 +52,5 @@ export declare function sendCorsPreflight(res: ServerResponse, extraAllowHeaders
|
|
|
49
52
|
* @param maxBodySize - Maximum allowed body size in bytes (0 = unlimited)
|
|
50
53
|
* @returns The body string, or `null` if the body exceeded the size limit
|
|
51
54
|
*/
|
|
52
|
-
export declare function readRequestBody(req: IncomingMessage, maxBodySize: number): Promise<string | null>;
|
|
55
|
+
export declare function readRequestBody(req: IncomingMessage, maxBodySize: number, signal?: AbortSignal): Promise<string | null>;
|
|
53
56
|
//# sourceMappingURL=HttpHelpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpHelpers.d.ts","sourceRoot":"","sources":["../../src/transport/HttpHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"HttpHelpers.d.ts","sourceRoot":"","sources":["../../src/transport/HttpHelpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGjE,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,SAAkB,IAAI,6BAA6B;CACnD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAC/B,GAAG,EAAE,cAAc,EACnB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,EAAE,GAAE,MAAM,GAAG,MAAM,GAAG,IAAW,EACjC,IAAI,CAAC,EAAE,OAAO,GACZ,IAAI,CAWN;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAClC,GAAG,EAAE,cAAc,EACnB,QAAQ,EAAE,OAAO,EACjB,UAAU,GAAE,MAAY,EACxB,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,GAClC,IAAI,CAIN;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,cAAc,EAAE,iBAAiB,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,CAMzF;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,eAAe,CACpC,GAAG,EAAE,eAAe,EACpB,WAAW,EAAE,MAAM,EACnB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAwDxB"}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
class RequestBodyAbortedError extends Error {
|
|
3
|
+
name = 'RequestBodyAbortedError';
|
|
4
|
+
}
|
|
1
5
|
function sendJsonRpcError(res, statusCode, code, message, id = null, data) {
|
|
2
6
|
const body = {
|
|
3
7
|
jsonrpc: '2.0',
|
|
@@ -28,17 +32,63 @@ function sendCorsPreflight(res, extraAllowHeaders) {
|
|
|
28
32
|
res.writeHead(204);
|
|
29
33
|
res.end();
|
|
30
34
|
}
|
|
31
|
-
async function readRequestBody(req, maxBodySize) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
35
|
+
async function readRequestBody(req, maxBodySize, signal) {
|
|
36
|
+
return new Promise((resolve, reject)=>{
|
|
37
|
+
let body = '';
|
|
38
|
+
let bodySize = 0;
|
|
39
|
+
let settled = false;
|
|
40
|
+
const decoder = new StringDecoder('utf8');
|
|
41
|
+
const cleanup = ()=>{
|
|
42
|
+
req.off('data', onData);
|
|
43
|
+
req.off('end', onEnd);
|
|
44
|
+
req.off('aborted', onAborted);
|
|
45
|
+
req.off('close', onAborted);
|
|
46
|
+
req.off('error', onError);
|
|
47
|
+
signal?.removeEventListener('abort', onAborted);
|
|
48
|
+
};
|
|
49
|
+
const onData = (chunk)=>{
|
|
50
|
+
if (settled) return;
|
|
51
|
+
const chunkSize = 'string' == typeof chunk ? Buffer.byteLength(chunk) : chunk.byteLength;
|
|
52
|
+
bodySize += chunkSize;
|
|
53
|
+
if (maxBodySize > 0 && bodySize > maxBodySize) {
|
|
54
|
+
settled = true;
|
|
55
|
+
cleanup();
|
|
56
|
+
req.resume();
|
|
57
|
+
resolve(null);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
body += 'string' == typeof chunk ? chunk : decoder.write(chunk);
|
|
61
|
+
};
|
|
62
|
+
const onEnd = ()=>{
|
|
63
|
+
if (settled) return;
|
|
64
|
+
settled = true;
|
|
65
|
+
cleanup();
|
|
66
|
+
resolve(body + decoder.end());
|
|
67
|
+
};
|
|
68
|
+
const onAborted = ()=>{
|
|
69
|
+
if (settled) return;
|
|
70
|
+
settled = true;
|
|
71
|
+
cleanup();
|
|
72
|
+
req.resume();
|
|
73
|
+
reject(new RequestBodyAbortedError());
|
|
74
|
+
};
|
|
75
|
+
const onError = (error)=>{
|
|
76
|
+
if (settled) return;
|
|
77
|
+
settled = true;
|
|
78
|
+
cleanup();
|
|
79
|
+
reject(error);
|
|
80
|
+
};
|
|
81
|
+
req.on('data', onData);
|
|
82
|
+
req.once('end', onEnd);
|
|
83
|
+
req.once('aborted', onAborted);
|
|
84
|
+
req.once('close', onAborted);
|
|
85
|
+
req.once('error', onError);
|
|
86
|
+
signal?.addEventListener('abort', onAborted, {
|
|
87
|
+
once: true
|
|
88
|
+
});
|
|
89
|
+
if (signal?.aborted) onAborted();
|
|
90
|
+
});
|
|
41
91
|
}
|
|
42
|
-
export { readRequestBody, sendCorsPreflight, sendJsonRpcError, sendJsonRpcResponse };
|
|
92
|
+
export { RequestBodyAbortedError, readRequestBody, sendCorsPreflight, sendJsonRpcError, sendJsonRpcResponse };
|
|
43
93
|
|
|
44
94
|
//# sourceMappingURL=HttpHelpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport/HttpHelpers.js","sources":["../../src/transport/HttpHelpers.ts"],"sourcesContent":["/**\n * Shared HTTP helper utilities for MCP transport implementations.\n *\n * Centralizes JSON-RPC response formatting, request body reading,\n * and common HTTP response patterns to eliminate duplication across\n * HttpTransport and StreamableHttpTransport.\n *\n * @module transport/HttpHelpers\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\n/**\n * Send a JSON-RPC 2.0 error response.\n *\n * Standardizes error response formatting across all transport implementations.\n * All JSON-RPC errors use the standard `{ jsonrpc, id, error }` shape.\n *\n * @param res - The server response to write to\n * @param statusCode - HTTP status code (e.g. 400, 403, 429, 500)\n * @param code - JSON-RPC error code (e.g. -32700, -32600, -32603)\n * @param message - Human-readable error message\n * @param id - Optional JSON-RPC request ID (defaults to null)\n * @param data - Optional additional error data\n */\nexport function sendJsonRpcError(\n\tres: ServerResponse,\n\tstatusCode: number,\n\tcode: number,\n\tmessage: string,\n\tid: string | number | null = null,\n\tdata?: unknown\n): void {\n\tconst body: Record<string, unknown> = {\n\t\tjsonrpc: '2.0',\n\t\tid,\n\t\terror: { code, message },\n\t};\n\tif (data !== undefined) {\n\t\t(body.error as Record<string, unknown>).data = data;\n\t}\n\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\tres.end(JSON.stringify(body));\n}\n\n/**\n * Send a JSON-RPC 2.0 success response.\n *\n * @param res - The server response to write to\n * @param response - The JSON-RPC response object to send\n * @param statusCode - HTTP status code (default: 200)\n * @param headers - Optional additional response headers\n */\nexport function sendJsonRpcResponse(\n\tres: ServerResponse,\n\tresponse: unknown,\n\tstatusCode: number = 200,\n\theaders: Record<string, string> = {}\n): void {\n\tconst defaultHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\tres.writeHead(statusCode, { ...defaultHeaders, ...headers });\n\tres.end(JSON.stringify(response));\n}\n\n/**\n * Send a CORS preflight (OPTIONS) response.\n *\n * @param res - The server response to write to\n * @param extraAllowHeaders - Optional extra Access-Control-Allow-Headers values\n */\nexport function sendCorsPreflight(res: ServerResponse, extraAllowHeaders?: string[]): void {\n\tif (extraAllowHeaders && extraAllowHeaders.length > 0) {\n\t\tres.setHeader('Access-Control-Allow-Headers', `Content-Type, ${extraAllowHeaders.join(', ')}`);\n\t}\n\tres.writeHead(204);\n\tres.end();\n}\n\n/**\n * Read the full request body with optional size limit enforcement.\n *\n * Streams the request body chunks, tracking total size.\n * If the body exceeds `maxBodySize`, reading stops and `null` is returned\n * to indicate the payload is too large.\n *\n * @param req - The incoming HTTP request\n * @param maxBodySize - Maximum allowed body size in bytes (0 = unlimited)\n * @returns The body string, or `null` if the body exceeded the size limit\n */\nexport async function readRequestBody(\n\treq: IncomingMessage,\n\tmaxBodySize: number\n): Promise<string | null> {\n\tlet body = '';\n\tlet bodySize = 0;\n\n\
|
|
1
|
+
{"version":3,"file":"transport/HttpHelpers.js","sources":["../../src/transport/HttpHelpers.ts"],"sourcesContent":["/**\n * Shared HTTP helper utilities for MCP transport implementations.\n *\n * Centralizes JSON-RPC response formatting, request body reading,\n * and common HTTP response patterns to eliminate duplication across\n * HttpTransport and StreamableHttpTransport.\n *\n * @module transport/HttpHelpers\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { StringDecoder } from 'node:string_decoder';\n\nexport class RequestBodyAbortedError extends Error {\n\toverride readonly name = 'RequestBodyAbortedError';\n}\n\n/**\n * Send a JSON-RPC 2.0 error response.\n *\n * Standardizes error response formatting across all transport implementations.\n * All JSON-RPC errors use the standard `{ jsonrpc, id, error }` shape.\n *\n * @param res - The server response to write to\n * @param statusCode - HTTP status code (e.g. 400, 403, 429, 500)\n * @param code - JSON-RPC error code (e.g. -32700, -32600, -32603)\n * @param message - Human-readable error message\n * @param id - Optional JSON-RPC request ID (defaults to null)\n * @param data - Optional additional error data\n */\nexport function sendJsonRpcError(\n\tres: ServerResponse,\n\tstatusCode: number,\n\tcode: number,\n\tmessage: string,\n\tid: string | number | null = null,\n\tdata?: unknown\n): void {\n\tconst body: Record<string, unknown> = {\n\t\tjsonrpc: '2.0',\n\t\tid,\n\t\terror: { code, message },\n\t};\n\tif (data !== undefined) {\n\t\t(body.error as Record<string, unknown>).data = data;\n\t}\n\tres.writeHead(statusCode, { 'Content-Type': 'application/json' });\n\tres.end(JSON.stringify(body));\n}\n\n/**\n * Send a JSON-RPC 2.0 success response.\n *\n * @param res - The server response to write to\n * @param response - The JSON-RPC response object to send\n * @param statusCode - HTTP status code (default: 200)\n * @param headers - Optional additional response headers\n */\nexport function sendJsonRpcResponse(\n\tres: ServerResponse,\n\tresponse: unknown,\n\tstatusCode: number = 200,\n\theaders: Record<string, string> = {}\n): void {\n\tconst defaultHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n\tres.writeHead(statusCode, { ...defaultHeaders, ...headers });\n\tres.end(JSON.stringify(response));\n}\n\n/**\n * Send a CORS preflight (OPTIONS) response.\n *\n * @param res - The server response to write to\n * @param extraAllowHeaders - Optional extra Access-Control-Allow-Headers values\n */\nexport function sendCorsPreflight(res: ServerResponse, extraAllowHeaders?: string[]): void {\n\tif (extraAllowHeaders && extraAllowHeaders.length > 0) {\n\t\tres.setHeader('Access-Control-Allow-Headers', `Content-Type, ${extraAllowHeaders.join(', ')}`);\n\t}\n\tres.writeHead(204);\n\tres.end();\n}\n\n/**\n * Read the full request body with optional size limit enforcement.\n *\n * Streams the request body chunks, tracking total size.\n * If the body exceeds `maxBodySize`, reading stops and `null` is returned\n * to indicate the payload is too large.\n *\n * @param req - The incoming HTTP request\n * @param maxBodySize - Maximum allowed body size in bytes (0 = unlimited)\n * @returns The body string, or `null` if the body exceeded the size limit\n */\nexport async function readRequestBody(\n\treq: IncomingMessage,\n\tmaxBodySize: number,\n\tsignal?: AbortSignal\n): Promise<string | null> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet body = '';\n\t\tlet bodySize = 0;\n\t\tlet settled = false;\n\t\tconst decoder = new StringDecoder('utf8');\n\n\t\tconst cleanup = (): void => {\n\t\t\treq.off('data', onData);\n\t\t\treq.off('end', onEnd);\n\t\t\treq.off('aborted', onAborted);\n\t\t\treq.off('close', onAborted);\n\t\t\treq.off('error', onError);\n\t\t\tsignal?.removeEventListener('abort', onAborted);\n\t\t};\n\t\tconst onData = (chunk: Buffer | string): void => {\n\t\t\tif (settled) return;\n\t\t\tconst chunkSize = typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n\t\t\tbodySize += chunkSize;\n\t\t\tif (maxBodySize > 0 && bodySize > maxBodySize) {\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treq.resume();\n\t\t\t\tresolve(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbody += typeof chunk === 'string' ? chunk : decoder.write(chunk);\n\t\t};\n\t\tconst onEnd = (): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(body + decoder.end());\n\t\t};\n\t\tconst onAborted = (): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treq.resume();\n\t\t\treject(new RequestBodyAbortedError());\n\t\t};\n\t\tconst onError = (error: Error): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\n\t\treq.on('data', onData);\n\t\treq.once('end', onEnd);\n\t\treq.once('aborted', onAborted);\n\t\treq.once('close', onAborted);\n\t\treq.once('error', onError);\n\t\tsignal?.addEventListener('abort', onAborted, { once: true });\n\t\tif (signal?.aborted) onAborted();\n\t});\n}\n"],"names":["RequestBodyAbortedError","Error","sendJsonRpcError","res","statusCode","code","message","id","data","body","undefined","JSON","sendJsonRpcResponse","response","headers","defaultHeaders","sendCorsPreflight","extraAllowHeaders","readRequestBody","req","maxBodySize","signal","Promise","resolve","reject","bodySize","settled","decoder","StringDecoder","cleanup","onData","onEnd","onAborted","onError","chunk","chunkSize","Buffer","error"],"mappings":";AAaO,MAAMA,gCAAgCC;IAC1B,OAAO,0BAA0B;AACpD;AAeO,SAASC,iBACfC,GAAmB,EACnBC,UAAkB,EAClBC,IAAY,EACZC,OAAe,EACfC,KAA6B,IAAI,EACjCC,IAAc;IAEd,MAAMC,OAAgC;QACrC,SAAS;QACTF;QACA,OAAO;YAAEF;YAAMC;QAAQ;IACxB;IACA,IAAIE,AAASE,WAATF,MACFC,KAAK,KAAK,CAA6B,IAAI,GAAGD;IAEhDL,IAAI,SAAS,CAACC,YAAY;QAAE,gBAAgB;IAAmB;IAC/DD,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACF;AACxB;AAUO,SAASG,oBACfT,GAAmB,EACnBU,QAAiB,EACjBT,aAAqB,GAAG,EACxBU,UAAkC,CAAC,CAAC;IAEpC,MAAMC,iBAAyC;QAAE,gBAAgB;IAAmB;IACpFZ,IAAI,SAAS,CAACC,YAAY;QAAE,GAAGW,cAAc;QAAE,GAAGD,OAAO;IAAC;IAC1DX,IAAI,GAAG,CAACQ,KAAK,SAAS,CAACE;AACxB;AAQO,SAASG,kBAAkBb,GAAmB,EAAEc,iBAA4B;IAClF,IAAIA,qBAAqBA,kBAAkB,MAAM,GAAG,GACnDd,IAAI,SAAS,CAAC,gCAAgC,CAAC,cAAc,EAAEc,kBAAkB,IAAI,CAAC,OAAO;IAE9Fd,IAAI,SAAS,CAAC;IACdA,IAAI,GAAG;AACR;AAaO,eAAee,gBACrBC,GAAoB,EACpBC,WAAmB,EACnBC,MAAoB;IAEpB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC5B,IAAIf,OAAO;QACX,IAAIgB,WAAW;QACf,IAAIC,UAAU;QACd,MAAMC,UAAU,IAAIC,cAAc;QAElC,MAAMC,UAAU;YACfV,IAAI,GAAG,CAAC,QAAQW;YAChBX,IAAI,GAAG,CAAC,OAAOY;YACfZ,IAAI,GAAG,CAAC,WAAWa;YACnBb,IAAI,GAAG,CAAC,SAASa;YACjBb,IAAI,GAAG,CAAC,SAASc;YACjBZ,QAAQ,oBAAoB,SAASW;QACtC;QACA,MAAMF,SAAS,CAACI;YACf,IAAIR,SAAS;YACb,MAAMS,YAAY,AAAiB,YAAjB,OAAOD,QAAqBE,OAAO,UAAU,CAACF,SAASA,MAAM,UAAU;YACzFT,YAAYU;YACZ,IAAIf,cAAc,KAAKK,WAAWL,aAAa;gBAC9CM,UAAU;gBACVG;gBACAV,IAAI,MAAM;gBACVI,QAAQ;gBACR;YACD;YACAd,QAAQ,AAAiB,YAAjB,OAAOyB,QAAqBA,QAAQP,QAAQ,KAAK,CAACO;QAC3D;QACA,MAAMH,QAAQ;YACb,IAAIL,SAAS;YACbA,UAAU;YACVG;YACAN,QAAQd,OAAOkB,QAAQ,GAAG;QAC3B;QACA,MAAMK,YAAY;YACjB,IAAIN,SAAS;YACbA,UAAU;YACVG;YACAV,IAAI,MAAM;YACVK,OAAO,IAAIxB;QACZ;QACA,MAAMiC,UAAU,CAACI;YAChB,IAAIX,SAAS;YACbA,UAAU;YACVG;YACAL,OAAOa;QACR;QAEAlB,IAAI,EAAE,CAAC,QAAQW;QACfX,IAAI,IAAI,CAAC,OAAOY;QAChBZ,IAAI,IAAI,CAAC,WAAWa;QACpBb,IAAI,IAAI,CAAC,SAASa;QAClBb,IAAI,IAAI,CAAC,SAASc;QAClBZ,QAAQ,iBAAiB,SAASW,WAAW;YAAE,MAAM;QAAK;QAC1D,IAAIX,QAAQ,SAASW;IACtB;AACD"}
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import type { ServerResponse } from 'node:http';
|
|
2
2
|
type ResponseWriter = (response: ServerResponse) => void;
|
|
3
3
|
type WorkFailureHandler = (error: unknown) => void;
|
|
4
|
+
export type PreDispatchCancellationReason = 'peer' | 'shutdown' | 'timeout';
|
|
5
|
+
export interface PreDispatchLease {
|
|
6
|
+
readonly signal: AbortSignal;
|
|
7
|
+
readonly cancellationReason: PreDispatchCancellationReason | null;
|
|
8
|
+
cancel(reason: PreDispatchCancellationReason): void;
|
|
9
|
+
release(): void;
|
|
10
|
+
}
|
|
11
|
+
export declare class PreDispatchTracker {
|
|
12
|
+
private readonly _leases;
|
|
13
|
+
private _accepting;
|
|
14
|
+
acquire(): PreDispatchLease | null;
|
|
15
|
+
closeAdmission(reason: PreDispatchCancellationReason): void;
|
|
16
|
+
join(): Promise<void>;
|
|
17
|
+
}
|
|
4
18
|
export type LifecycleReportingFailure = {
|
|
5
19
|
readonly lifecycleError: unknown;
|
|
6
20
|
readonly reportingError: unknown;
|
|
@@ -30,7 +44,7 @@ export declare class AcceptedWorkTracker {
|
|
|
30
44
|
private readonly _work;
|
|
31
45
|
constructor(_failureReporter: LifecycleFailureReporter);
|
|
32
46
|
get size(): number;
|
|
33
|
-
|
|
47
|
+
transfer(lease: PreDispatchLease, start: () => Promise<void>): Promise<void>;
|
|
34
48
|
join(): Promise<void>;
|
|
35
49
|
}
|
|
36
50
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpRequestLifecycle.d.ts","sourceRoot":"","sources":["../../src/transport/HttpRequestLifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;AACzD,KAAK,kBAAkB,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAEnD,MAAM,MAAM,yBAAyB,GAAG;IACvC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IACjC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;CACjC,CAAC;AAEF,qEAAqE;AACrE,eAAO,MAAM,oCAAoC,KAAK,CAAC;AAEvD,qBAAa,wBAAwB;IAKxB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAJvC,OAA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AQ,CAAC,KAAK,CAA4B;gBAErB,gBAAgB,EAAE,wBAAwB;IAEvE,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,QAAQ,CAAC,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAyBtE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAK3B"}
|
|
@@ -1,3 +1,52 @@
|
|
|
1
|
+
class TrackedPreDispatchLease {
|
|
2
|
+
_onRelease;
|
|
3
|
+
_controller = new AbortController();
|
|
4
|
+
_settled = Promise.withResolvers();
|
|
5
|
+
_active = true;
|
|
6
|
+
_cancellationReason = null;
|
|
7
|
+
constructor(_onRelease){
|
|
8
|
+
this._onRelease = _onRelease;
|
|
9
|
+
}
|
|
10
|
+
get signal() {
|
|
11
|
+
return this._controller.signal;
|
|
12
|
+
}
|
|
13
|
+
get cancellationReason() {
|
|
14
|
+
return this._cancellationReason;
|
|
15
|
+
}
|
|
16
|
+
get settled() {
|
|
17
|
+
return this._settled.promise;
|
|
18
|
+
}
|
|
19
|
+
cancel(reason) {
|
|
20
|
+
if (!this._active || this._controller.signal.aborted) return;
|
|
21
|
+
this._cancellationReason = reason;
|
|
22
|
+
this._controller.abort();
|
|
23
|
+
}
|
|
24
|
+
release() {
|
|
25
|
+
if (!this._active) return;
|
|
26
|
+
this._active = false;
|
|
27
|
+
this._onRelease(this);
|
|
28
|
+
this._settled.resolve();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
class PreDispatchTracker {
|
|
32
|
+
_leases = new Set();
|
|
33
|
+
_accepting = true;
|
|
34
|
+
acquire() {
|
|
35
|
+
if (!this._accepting) return null;
|
|
36
|
+
const lease = new TrackedPreDispatchLease((released)=>this._leases.delete(released));
|
|
37
|
+
this._leases.add(lease);
|
|
38
|
+
return lease;
|
|
39
|
+
}
|
|
40
|
+
closeAdmission(reason) {
|
|
41
|
+
this._accepting = false;
|
|
42
|
+
for (const lease of this._leases)lease.cancel(reason);
|
|
43
|
+
}
|
|
44
|
+
async join() {
|
|
45
|
+
while(this._leases.size > 0)await Promise.all([
|
|
46
|
+
...this._leases
|
|
47
|
+
].map((lease)=>lease.settled));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
1
50
|
const LIFECYCLE_REPORTING_FAILURE_CAPACITY = 32;
|
|
2
51
|
class LifecycleFailureReporter {
|
|
3
52
|
_onFailure;
|
|
@@ -69,19 +118,32 @@ class AcceptedWorkTracker {
|
|
|
69
118
|
get size() {
|
|
70
119
|
return this._work.size;
|
|
71
120
|
}
|
|
72
|
-
|
|
121
|
+
transfer(lease, start) {
|
|
122
|
+
lease.signal.throwIfAborted();
|
|
123
|
+
const reservation = Promise.withResolvers();
|
|
124
|
+
this._work.add(reservation.promise);
|
|
125
|
+
lease.release();
|
|
126
|
+
let work;
|
|
127
|
+
try {
|
|
128
|
+
work = start();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
this._work.delete(reservation.promise);
|
|
131
|
+
reservation.resolve();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
73
134
|
const observed = work.catch((error)=>{
|
|
74
135
|
this._failureReporter.report(error);
|
|
75
136
|
});
|
|
76
|
-
this._work.add(observed);
|
|
77
137
|
observed.then(()=>{
|
|
78
|
-
this._work.delete(
|
|
138
|
+
this._work.delete(reservation.promise);
|
|
139
|
+
reservation.resolve();
|
|
79
140
|
});
|
|
141
|
+
return work;
|
|
80
142
|
}
|
|
81
143
|
async join() {
|
|
82
144
|
while(this._work.size > 0)await Promise.all(this._work);
|
|
83
145
|
}
|
|
84
146
|
}
|
|
85
|
-
export { AcceptedWorkTracker, LIFECYCLE_REPORTING_FAILURE_CAPACITY, LifecycleFailureReporter, ResponseFinalizer };
|
|
147
|
+
export { AcceptedWorkTracker, LIFECYCLE_REPORTING_FAILURE_CAPACITY, LifecycleFailureReporter, PreDispatchTracker, ResponseFinalizer };
|
|
86
148
|
|
|
87
149
|
//# sourceMappingURL=HttpRequestLifecycle.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport/HttpRequestLifecycle.js","sources":["../../src/transport/HttpRequestLifecycle.ts"],"sourcesContent":["import type { ServerResponse } from 'node:http';\n\ntype ResponseWriter = (response: ServerResponse) => void;\ntype WorkFailureHandler = (error: unknown) => void;\n\nexport type LifecycleReportingFailure = {\n\treadonly lifecycleError: unknown;\n\treadonly reportingError: unknown;\n};\n\n/** Maximum number of reporting failures retained for diagnostics. */\nexport const LIFECYCLE_REPORTING_FAILURE_CAPACITY = 32;\n\nexport class LifecycleFailureReporter {\n\tprivate readonly _reportingFailures: LifecycleReportingFailure[] = [];\n\tprivate _reportingFailureCount = 0;\n\tprivate _droppedReportingFailureCount = 0;\n\n\tconstructor(private readonly _onFailure: WorkFailureHandler) {}\n\n\tget reportingFailures(): readonly LifecycleReportingFailure[] {\n\t\treturn [...this._reportingFailures];\n\t}\n\n\tget reportingFailureCount(): number {\n\t\treturn this._reportingFailureCount;\n\t}\n\n\tget droppedReportingFailureCount(): number {\n\t\treturn this._droppedReportingFailureCount;\n\t}\n\n\treport(error: unknown): void {\n\t\ttry {\n\t\t\tthis._onFailure(error);\n\t\t} catch (reportingError) {\n\t\t\tthis._reportingFailureCount++;\n\t\t\tif (this._reportingFailures.length === LIFECYCLE_REPORTING_FAILURE_CAPACITY) {\n\t\t\t\tthis._reportingFailures.shift();\n\t\t\t\tthis._droppedReportingFailureCount++;\n\t\t\t}\n\t\t\tthis._reportingFailures.push({ lifecycleError: error, reportingError });\n\t\t}\n\t}\n}\n\nexport class ResponseFinalizer {\n\tprivate _isFinalized = false;\n\n\tconstructor(\n\t\tprivate readonly _response: ServerResponse,\n\t\tprivate readonly _failureReporter: LifecycleFailureReporter\n\t) {\n\t\tthis._response.once('close', () => {\n\t\t\tthis._isFinalized = true;\n\t\t});\n\t}\n\n\tfinalize(writer: ResponseWriter): boolean {\n\t\tif (this._isFinalized || this._response.destroyed || this._response.writableEnded) {\n\t\t\tthis._isFinalized = true;\n\t\t\treturn false;\n\t\t}\n\n\t\tthis._isFinalized = true;\n\t\ttry {\n\t\t\twriter(this._response);\n\t\t} catch (error) {\n\t\t\tthis._failureReporter.report(error);\n\t\t\tthis._response.destroy();\n\t\t}\n\t\treturn true;\n\t}\n}\n\nexport class AcceptedWorkTracker {\n\tprivate readonly _work = new Set<Promise<void>>();\n\n\tconstructor(private readonly _failureReporter: LifecycleFailureReporter) {}\n\n\tget size(): number {\n\t\treturn this._work.size;\n\t}\n\n\
|
|
1
|
+
{"version":3,"file":"transport/HttpRequestLifecycle.js","sources":["../../src/transport/HttpRequestLifecycle.ts"],"sourcesContent":["import type { ServerResponse } from 'node:http';\n\ntype ResponseWriter = (response: ServerResponse) => void;\ntype WorkFailureHandler = (error: unknown) => void;\n\nexport type PreDispatchCancellationReason = 'peer' | 'shutdown' | 'timeout';\n\nexport interface PreDispatchLease {\n\treadonly signal: AbortSignal;\n\treadonly cancellationReason: PreDispatchCancellationReason | null;\n\tcancel(reason: PreDispatchCancellationReason): void;\n\trelease(): void;\n}\n\nclass TrackedPreDispatchLease implements PreDispatchLease {\n\tprivate readonly _controller = new AbortController();\n\tprivate readonly _settled = Promise.withResolvers<void>();\n\tprivate _active = true;\n\tprivate _cancellationReason: PreDispatchCancellationReason | null = null;\n\n\tconstructor(private readonly _onRelease: (lease: TrackedPreDispatchLease) => void) {}\n\n\tget signal(): AbortSignal {\n\t\treturn this._controller.signal;\n\t}\n\n\tget cancellationReason(): PreDispatchCancellationReason | null {\n\t\treturn this._cancellationReason;\n\t}\n\n\tget settled(): Promise<void> {\n\t\treturn this._settled.promise;\n\t}\n\n\tcancel(reason: PreDispatchCancellationReason): void {\n\t\tif (!this._active || this._controller.signal.aborted) return;\n\t\tthis._cancellationReason = reason;\n\t\tthis._controller.abort();\n\t}\n\n\trelease(): void {\n\t\tif (!this._active) return;\n\t\tthis._active = false;\n\t\tthis._onRelease(this);\n\t\tthis._settled.resolve();\n\t}\n}\n\nexport class PreDispatchTracker {\n\tprivate readonly _leases = new Set<TrackedPreDispatchLease>();\n\tprivate _accepting = true;\n\n\tacquire(): PreDispatchLease | null {\n\t\tif (!this._accepting) return null;\n\t\tconst lease = new TrackedPreDispatchLease((released) => this._leases.delete(released));\n\t\tthis._leases.add(lease);\n\t\treturn lease;\n\t}\n\n\tcloseAdmission(reason: PreDispatchCancellationReason): void {\n\t\tthis._accepting = false;\n\t\tfor (const lease of this._leases) lease.cancel(reason);\n\t}\n\n\tasync join(): Promise<void> {\n\t\twhile (this._leases.size > 0) {\n\t\t\tawait Promise.all([...this._leases].map((lease) => lease.settled));\n\t\t}\n\t}\n}\n\nexport type LifecycleReportingFailure = {\n\treadonly lifecycleError: unknown;\n\treadonly reportingError: unknown;\n};\n\n/** Maximum number of reporting failures retained for diagnostics. */\nexport const LIFECYCLE_REPORTING_FAILURE_CAPACITY = 32;\n\nexport class LifecycleFailureReporter {\n\tprivate readonly _reportingFailures: LifecycleReportingFailure[] = [];\n\tprivate _reportingFailureCount = 0;\n\tprivate _droppedReportingFailureCount = 0;\n\n\tconstructor(private readonly _onFailure: WorkFailureHandler) {}\n\n\tget reportingFailures(): readonly LifecycleReportingFailure[] {\n\t\treturn [...this._reportingFailures];\n\t}\n\n\tget reportingFailureCount(): number {\n\t\treturn this._reportingFailureCount;\n\t}\n\n\tget droppedReportingFailureCount(): number {\n\t\treturn this._droppedReportingFailureCount;\n\t}\n\n\treport(error: unknown): void {\n\t\ttry {\n\t\t\tthis._onFailure(error);\n\t\t} catch (reportingError) {\n\t\t\tthis._reportingFailureCount++;\n\t\t\tif (this._reportingFailures.length === LIFECYCLE_REPORTING_FAILURE_CAPACITY) {\n\t\t\t\tthis._reportingFailures.shift();\n\t\t\t\tthis._droppedReportingFailureCount++;\n\t\t\t}\n\t\t\tthis._reportingFailures.push({ lifecycleError: error, reportingError });\n\t\t}\n\t}\n}\n\nexport class ResponseFinalizer {\n\tprivate _isFinalized = false;\n\n\tconstructor(\n\t\tprivate readonly _response: ServerResponse,\n\t\tprivate readonly _failureReporter: LifecycleFailureReporter\n\t) {\n\t\tthis._response.once('close', () => {\n\t\t\tthis._isFinalized = true;\n\t\t});\n\t}\n\n\tfinalize(writer: ResponseWriter): boolean {\n\t\tif (this._isFinalized || this._response.destroyed || this._response.writableEnded) {\n\t\t\tthis._isFinalized = true;\n\t\t\treturn false;\n\t\t}\n\n\t\tthis._isFinalized = true;\n\t\ttry {\n\t\t\twriter(this._response);\n\t\t} catch (error) {\n\t\t\tthis._failureReporter.report(error);\n\t\t\tthis._response.destroy();\n\t\t}\n\t\treturn true;\n\t}\n}\n\nexport class AcceptedWorkTracker {\n\tprivate readonly _work = new Set<Promise<void>>();\n\n\tconstructor(private readonly _failureReporter: LifecycleFailureReporter) {}\n\n\tget size(): number {\n\t\treturn this._work.size;\n\t}\n\n\ttransfer(lease: PreDispatchLease, start: () => Promise<void>): Promise<void> {\n\t\tlease.signal.throwIfAborted();\n\t\tconst reservation = Promise.withResolvers<void>();\n\t\tthis._work.add(reservation.promise);\n\t\tlease.release();\n\n\t\tlet work: Promise<void>;\n\t\ttry {\n\t\t\twork = start();\n\t\t} catch (error) {\n\t\t\tthis._work.delete(reservation.promise);\n\t\t\treservation.resolve();\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst observed = work.catch((error: unknown) => {\n\t\t\tthis._failureReporter.report(error);\n\t\t});\n\t\tvoid observed.then(() => {\n\t\t\tthis._work.delete(reservation.promise);\n\t\t\treservation.resolve();\n\t\t});\n\t\treturn work;\n\t}\n\n\tasync join(): Promise<void> {\n\t\twhile (this._work.size > 0) {\n\t\t\tawait Promise.all(this._work);\n\t\t}\n\t}\n}\n"],"names":["TrackedPreDispatchLease","AbortController","Promise","_onRelease","reason","PreDispatchTracker","Set","lease","released","LIFECYCLE_REPORTING_FAILURE_CAPACITY","LifecycleFailureReporter","_onFailure","error","reportingError","ResponseFinalizer","_response","_failureReporter","writer","AcceptedWorkTracker","start","reservation","work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ACpB,IAAI;YACHA,OAAO,IAAI,CAAC,SAAS;QACtB,EAAE,OAAOL,OAAO;YACf,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAACA;YAC7B,IAAI,CAAC,SAAS,CAAC,OAAO;QACvB;QACA,OAAO;IACR;AACD;AAEO,MAAMM;;IACK,QAAQ,IAAIZ,MAAqB;IAElD,YAA6BU,gBAA0C,CAAE;aAA5CA,gBAAgB,GAAhBA;IAA6C;IAE1E,IAAI,OAAe;QAClB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI;IACvB;IAEA,SAAST,KAAuB,EAAEY,KAA0B,EAAiB;QAC5EZ,MAAM,MAAM,CAAC,cAAc;QAC3B,MAAMa,cAAclB,QAAQ,aAAa;QACzC,IAAI,CAAC,KAAK,CAAC,GAAG,CAACkB,YAAY,OAAO;QAClCb,MAAM,OAAO;QAEb,IAAIc;QACJ,IAAI;YACHA,OAAOF;QACR,EAAE,OAAOP,OAAO;YACf,IAAI,CAAC,KAAK,CAAC,MAAM,CAACQ,YAAY,OAAO;YACrCA,YAAY,OAAO;YACnB,MAAMR;QACP;QAEA,MAAMU,WAAWD,KAAK,KAAK,CAAC,CAACT;YAC5B,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAACA;QAC9B;QACKU,SAAS,IAAI,CAAC;YAClB,IAAI,CAAC,KAAK,CAAC,MAAM,CAACF,YAAY,OAAO;YACrCA,YAAY,OAAO;QACpB;QACA,OAAOC;IACR;IAEA,MAAM,OAAsB;QAC3B,MAAO,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,EACxB,MAAMnB,QAAQ,GAAG,CAAC,IAAI,CAAC,KAAK;IAE9B;AACD"}
|
|
@@ -86,6 +86,7 @@ export declare class HttpTransport extends BaseTransport implements ITransport {
|
|
|
86
86
|
private _metricsProvider;
|
|
87
87
|
private readonly _lifecycleFailureReporter;
|
|
88
88
|
private readonly _acceptedWork;
|
|
89
|
+
private readonly _preDispatch;
|
|
89
90
|
private _stopPromise;
|
|
90
91
|
constructor(options?: HttpTransportOptions);
|
|
91
92
|
private _requireMcpServer;
|
|
@@ -101,6 +102,7 @@ export declare class HttpTransport extends BaseTransport implements ITransport {
|
|
|
101
102
|
* Track an error in metrics.
|
|
102
103
|
*/
|
|
103
104
|
private _trackError;
|
|
105
|
+
private _parseJsonRpcRequest;
|
|
104
106
|
/**
|
|
105
107
|
* Route and handle incoming HTTP requests.
|
|
106
108
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpTransport.d.ts","sourceRoot":"","sources":["../../src/transport/HttpTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAG3D,OAAO,EAAE,aAAa,EAAE,KAAK,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"HttpTransport.d.ts","sourceRoot":"","sources":["../../src/transport/HttpTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAG3D,OAAO,EAAE,aAAa,EAAE,KAAK,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAgB3E,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;IAC7D;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,QAAQ,CAAC;IACnB,eAAe,CAAC,EAAE,MAAM,MAAM,CAAC;IAE/B;;;OAGG;IACH,mBAAm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