@iworkforces/tracelattice 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (422) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +260 -0
  3. package/dist/CliLifecycle.d.ts +31 -0
  4. package/dist/CliLifecycle.d.ts.map +1 -0
  5. package/dist/CliLifecycle.js +90 -0
  6. package/dist/CliLifecycle.js.map +1 -0
  7. package/dist/ServerConfig.d.ts +290 -0
  8. package/dist/ServerConfig.d.ts.map +1 -0
  9. package/dist/ServerConfig.js +175 -0
  10. package/dist/ServerConfig.js.map +1 -0
  11. package/dist/cache/DiscoveryCache.d.ts +269 -0
  12. package/dist/cache/DiscoveryCache.d.ts.map +1 -0
  13. package/dist/cache/DiscoveryCache.js +104 -0
  14. package/dist/cache/DiscoveryCache.js.map +1 -0
  15. package/dist/cli.d.ts +3 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +5177 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config/ConfigLoader.d.ts +270 -0
  20. package/dist/config/ConfigLoader.d.ts.map +1 -0
  21. package/dist/config/ConfigLoader.js +186 -0
  22. package/dist/config/ConfigLoader.js.map +1 -0
  23. package/dist/context/RequestContext.d.ts +43 -0
  24. package/dist/context/RequestContext.d.ts.map +1 -0
  25. package/dist/context/RequestContext.js +14 -0
  26. package/dist/context/RequestContext.js.map +1 -0
  27. package/dist/contracts/PersistenceBackend.d.ts +134 -0
  28. package/dist/contracts/PersistenceBackend.d.ts.map +1 -0
  29. package/dist/contracts/PersistenceBackend.js +6 -0
  30. package/dist/contracts/PersistenceBackend.js.map +1 -0
  31. package/dist/contracts/calibrator.d.ts +97 -0
  32. package/dist/contracts/calibrator.d.ts.map +1 -0
  33. package/dist/contracts/calibrator.js +1 -0
  34. package/dist/contracts/features.d.ts +35 -0
  35. package/dist/contracts/features.d.ts.map +1 -0
  36. package/dist/contracts/features.js +12 -0
  37. package/dist/contracts/features.js.map +1 -0
  38. package/dist/contracts/ids.d.ts +68 -0
  39. package/dist/contracts/ids.d.ts.map +1 -0
  40. package/dist/contracts/ids.js +40 -0
  41. package/dist/contracts/ids.js.map +1 -0
  42. package/dist/contracts/interfaces.d.ts +254 -0
  43. package/dist/contracts/interfaces.d.ts.map +1 -0
  44. package/dist/contracts/interfaces.js +1 -0
  45. package/dist/contracts/persistence-work.d.ts +96 -0
  46. package/dist/contracts/persistence-work.d.ts.map +1 -0
  47. package/dist/contracts/persistence-work.js +1 -0
  48. package/dist/contracts/reasoning-types.d.ts +21 -0
  49. package/dist/contracts/reasoning-types.d.ts.map +1 -0
  50. package/dist/contracts/reasoning-types.js +1 -0
  51. package/dist/contracts/strategy.d.ts +107 -0
  52. package/dist/contracts/strategy.d.ts.map +1 -0
  53. package/dist/contracts/strategy.js +1 -0
  54. package/dist/contracts/summary.d.ts +110 -0
  55. package/dist/contracts/summary.d.ts.map +1 -0
  56. package/dist/contracts/summary.js +1 -0
  57. package/dist/contracts/suspension.d.ts +215 -0
  58. package/dist/contracts/suspension.d.ts.map +1 -0
  59. package/dist/contracts/suspension.js +1 -0
  60. package/dist/contracts/transport.d.ts +26 -0
  61. package/dist/contracts/transport.d.ts.map +1 -0
  62. package/dist/contracts/transport.js +1 -0
  63. package/dist/core/CrossReferenceValidator.d.ts +18 -0
  64. package/dist/core/CrossReferenceValidator.d.ts.map +1 -0
  65. package/dist/core/CrossReferenceValidator.js +125 -0
  66. package/dist/core/CrossReferenceValidator.js.map +1 -0
  67. package/dist/core/HistoryManager.d.ts +215 -0
  68. package/dist/core/HistoryManager.d.ts.map +1 -0
  69. package/dist/core/HistoryManager.js +594 -0
  70. package/dist/core/HistoryManager.js.map +1 -0
  71. package/dist/core/IHistoryManager.d.ts +163 -0
  72. package/dist/core/IHistoryManager.d.ts.map +1 -0
  73. package/dist/core/IHistoryManager.js +1 -0
  74. package/dist/core/IThoughtFormatter.d.ts +51 -0
  75. package/dist/core/IThoughtFormatter.d.ts.map +1 -0
  76. package/dist/core/IThoughtFormatter.js +1 -0
  77. package/dist/core/InputNormalizer.d.ts +140 -0
  78. package/dist/core/InputNormalizer.d.ts.map +1 -0
  79. package/dist/core/InputNormalizer.js +95 -0
  80. package/dist/core/InputNormalizer.js.map +1 -0
  81. package/dist/core/PersistenceBuffer.d.ts +204 -0
  82. package/dist/core/PersistenceBuffer.d.ts.map +1 -0
  83. package/dist/core/PersistenceBuffer.js +382 -0
  84. package/dist/core/PersistenceBuffer.js.map +1 -0
  85. package/dist/core/PersistenceBufferErrors.d.ts +22 -0
  86. package/dist/core/PersistenceBufferErrors.d.ts.map +1 -0
  87. package/dist/core/PersistenceBufferErrors.js +30 -0
  88. package/dist/core/PersistenceBufferErrors.js.map +1 -0
  89. package/dist/core/PersistenceRestore.d.ts +21 -0
  90. package/dist/core/PersistenceRestore.d.ts.map +1 -0
  91. package/dist/core/PersistenceRestore.js +87 -0
  92. package/dist/core/PersistenceRestore.js.map +1 -0
  93. package/dist/core/PersistenceWorkQueue.d.ts +155 -0
  94. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -0
  95. package/dist/core/PersistenceWorkQueue.js +298 -0
  96. package/dist/core/PersistenceWorkQueue.js.map +1 -0
  97. package/dist/core/PersistenceWriter.d.ts +55 -0
  98. package/dist/core/PersistenceWriter.d.ts.map +1 -0
  99. package/dist/core/PersistenceWriter.js +112 -0
  100. package/dist/core/PersistenceWriter.js.map +1 -0
  101. package/dist/core/SessionErrors.d.ts +37 -0
  102. package/dist/core/SessionErrors.d.ts.map +1 -0
  103. package/dist/core/SessionErrors.js +50 -0
  104. package/dist/core/SessionErrors.js.map +1 -0
  105. package/dist/core/SessionLifecycleCoordinator.d.ts +74 -0
  106. package/dist/core/SessionLifecycleCoordinator.d.ts.map +1 -0
  107. package/dist/core/SessionLifecycleCoordinator.js +222 -0
  108. package/dist/core/SessionLifecycleCoordinator.js.map +1 -0
  109. package/dist/core/SessionLock.d.ts +59 -0
  110. package/dist/core/SessionLock.d.ts.map +1 -0
  111. package/dist/core/SessionLock.js +39 -0
  112. package/dist/core/SessionLock.js.map +1 -0
  113. package/dist/core/SessionManager.d.ts +62 -0
  114. package/dist/core/SessionManager.d.ts.map +1 -0
  115. package/dist/core/SessionManager.js +75 -0
  116. package/dist/core/SessionManager.js.map +1 -0
  117. package/dist/core/SessionResetCoordinator.d.ts +37 -0
  118. package/dist/core/SessionResetCoordinator.d.ts.map +1 -0
  119. package/dist/core/SessionResetCoordinator.js +80 -0
  120. package/dist/core/SessionResetCoordinator.js.map +1 -0
  121. package/dist/core/ThoughtEvaluator.d.ts +48 -0
  122. package/dist/core/ThoughtEvaluator.d.ts.map +1 -0
  123. package/dist/core/ThoughtEvaluator.js +85 -0
  124. package/dist/core/ThoughtEvaluator.js.map +1 -0
  125. package/dist/core/ThoughtFormatter.d.ts +134 -0
  126. package/dist/core/ThoughtFormatter.d.ts.map +1 -0
  127. package/dist/core/ThoughtFormatter.js +118 -0
  128. package/dist/core/ThoughtFormatter.js.map +1 -0
  129. package/dist/core/ThoughtProcessor.d.ts +259 -0
  130. package/dist/core/ThoughtProcessor.d.ts.map +1 -0
  131. package/dist/core/ThoughtProcessor.js +451 -0
  132. package/dist/core/ThoughtProcessor.js.map +1 -0
  133. package/dist/core/ThoughtReferenceIndex.d.ts +23 -0
  134. package/dist/core/ThoughtReferenceIndex.d.ts.map +1 -0
  135. package/dist/core/ThoughtReferenceIndex.js +66 -0
  136. package/dist/core/ThoughtReferenceIndex.js.map +1 -0
  137. package/dist/core/VerificationOutcomeAdmission.d.ts +15 -0
  138. package/dist/core/VerificationOutcomeAdmission.d.ts.map +1 -0
  139. package/dist/core/VerificationOutcomeAdmission.js +28 -0
  140. package/dist/core/VerificationOutcomeAdmission.js.map +1 -0
  141. package/dist/core/compression/CompressionService.d.ts +76 -0
  142. package/dist/core/compression/CompressionService.d.ts.map +1 -0
  143. package/dist/core/compression/CompressionService.js +160 -0
  144. package/dist/core/compression/CompressionService.js.map +1 -0
  145. package/dist/core/compression/DehydrationPolicy.d.ts +75 -0
  146. package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -0
  147. package/dist/core/compression/DehydrationPolicy.js +45 -0
  148. package/dist/core/compression/DehydrationPolicy.js.map +1 -0
  149. package/dist/core/compression/InMemorySummaryStore.d.ts +132 -0
  150. package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -0
  151. package/dist/core/compression/InMemorySummaryStore.js +69 -0
  152. package/dist/core/compression/InMemorySummaryStore.js.map +1 -0
  153. package/dist/core/compression/Summary.d.ts +74 -0
  154. package/dist/core/compression/Summary.d.ts.map +1 -0
  155. package/dist/core/compression/Summary.js +16 -0
  156. package/dist/core/compression/Summary.js.map +1 -0
  157. package/dist/core/evaluator/Aggregator.d.ts +40 -0
  158. package/dist/core/evaluator/Aggregator.d.ts.map +1 -0
  159. package/dist/core/evaluator/Aggregator.js +36 -0
  160. package/dist/core/evaluator/Aggregator.js.map +1 -0
  161. package/dist/core/evaluator/Calibrator.d.ts +52 -0
  162. package/dist/core/evaluator/Calibrator.d.ts.map +1 -0
  163. package/dist/core/evaluator/Calibrator.js +135 -0
  164. package/dist/core/evaluator/Calibrator.js.map +1 -0
  165. package/dist/core/evaluator/PatternDetector.d.ts +69 -0
  166. package/dist/core/evaluator/PatternDetector.d.ts.map +1 -0
  167. package/dist/core/evaluator/PatternDetector.js +192 -0
  168. package/dist/core/evaluator/PatternDetector.js.map +1 -0
  169. package/dist/core/evaluator/SignalComputer.d.ts +116 -0
  170. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -0
  171. package/dist/core/evaluator/SignalComputer.js +110 -0
  172. package/dist/core/evaluator/SignalComputer.js.map +1 -0
  173. package/dist/core/evaluator/calibration-math.d.ts +39 -0
  174. package/dist/core/evaluator/calibration-math.d.ts.map +1 -0
  175. package/dist/core/evaluator/calibration-math.js +42 -0
  176. package/dist/core/evaluator/calibration-math.js.map +1 -0
  177. package/dist/core/evaluator/internals.d.ts +36 -0
  178. package/dist/core/evaluator/internals.d.ts.map +1 -0
  179. package/dist/core/evaluator/internals.js +43 -0
  180. package/dist/core/evaluator/internals.js.map +1 -0
  181. package/dist/core/graph/Edge.d.ts +58 -0
  182. package/dist/core/graph/Edge.d.ts.map +1 -0
  183. package/dist/core/graph/Edge.js +1 -0
  184. package/dist/core/graph/EdgeEmitter.d.ts +68 -0
  185. package/dist/core/graph/EdgeEmitter.d.ts.map +1 -0
  186. package/dist/core/graph/EdgeEmitter.js +118 -0
  187. package/dist/core/graph/EdgeEmitter.js.map +1 -0
  188. package/dist/core/graph/EdgeStore.d.ts +116 -0
  189. package/dist/core/graph/EdgeStore.d.ts.map +1 -0
  190. package/dist/core/graph/EdgeStore.js +107 -0
  191. package/dist/core/graph/EdgeStore.js.map +1 -0
  192. package/dist/core/graph/GraphView.d.ts +157 -0
  193. package/dist/core/graph/GraphView.d.ts.map +1 -0
  194. package/dist/core/graph/GraphView.js +149 -0
  195. package/dist/core/graph/GraphView.js.map +1 -0
  196. package/dist/core/ids.d.ts +33 -0
  197. package/dist/core/ids.d.ts.map +1 -0
  198. package/dist/core/ids.js +11 -0
  199. package/dist/core/ids.js.map +1 -0
  200. package/dist/core/reasoning/OutcomeRecorder.d.ts +88 -0
  201. package/dist/core/reasoning/OutcomeRecorder.d.ts.map +1 -0
  202. package/dist/core/reasoning/OutcomeRecorder.js +51 -0
  203. package/dist/core/reasoning/OutcomeRecorder.js.map +1 -0
  204. package/dist/core/reasoning/strategies/SequentialStrategy.d.ts +54 -0
  205. package/dist/core/reasoning/strategies/SequentialStrategy.d.ts.map +1 -0
  206. package/dist/core/reasoning/strategies/SequentialStrategy.js +22 -0
  207. package/dist/core/reasoning/strategies/SequentialStrategy.js.map +1 -0
  208. package/dist/core/reasoning/strategies/StrategyFactory.d.ts +25 -0
  209. package/dist/core/reasoning/strategies/StrategyFactory.d.ts.map +1 -0
  210. package/dist/core/reasoning/strategies/StrategyFactory.js +16 -0
  211. package/dist/core/reasoning/strategies/StrategyFactory.js.map +1 -0
  212. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +58 -0
  213. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -0
  214. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +103 -0
  215. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -0
  216. package/dist/core/reasoning/strategies/plateau.d.ts +18 -0
  217. package/dist/core/reasoning/strategies/plateau.d.ts.map +1 -0
  218. package/dist/core/reasoning/strategies/plateau.js +12 -0
  219. package/dist/core/reasoning/strategies/plateau.js.map +1 -0
  220. package/dist/core/reasoning/strategies/totScoring.d.ts +91 -0
  221. package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -0
  222. package/dist/core/reasoning/strategies/totScoring.js +88 -0
  223. package/dist/core/reasoning/strategies/totScoring.js.map +1 -0
  224. package/dist/core/reasoning.d.ts +179 -0
  225. package/dist/core/reasoning.d.ts.map +1 -0
  226. package/dist/core/reasoning.js +1 -0
  227. package/dist/core/step.d.ts +50 -0
  228. package/dist/core/step.d.ts.map +1 -0
  229. package/dist/core/step.js +1 -0
  230. package/dist/core/thought.d.ts +113 -0
  231. package/dist/core/thought.d.ts.map +1 -0
  232. package/dist/core/thought.js +1 -0
  233. package/dist/core/tools/InMemorySuspensionStore.d.ts +66 -0
  234. package/dist/core/tools/InMemorySuspensionStore.d.ts.map +1 -0
  235. package/dist/core/tools/InMemorySuspensionStore.js +121 -0
  236. package/dist/core/tools/InMemorySuspensionStore.js.map +1 -0
  237. package/dist/di/Container.d.ts +253 -0
  238. package/dist/di/Container.d.ts.map +1 -0
  239. package/dist/di/Container.js +111 -0
  240. package/dist/di/Container.js.map +1 -0
  241. package/dist/di/ServiceRegistry.d.ts +50 -0
  242. package/dist/di/ServiceRegistry.d.ts.map +1 -0
  243. package/dist/di/ServiceRegistry.js +1 -0
  244. package/dist/errors.d.ts +663 -0
  245. package/dist/errors.d.ts.map +1 -0
  246. package/dist/errors.js +282 -0
  247. package/dist/errors.js.map +1 -0
  248. package/dist/health/HealthChecker.d.ts +73 -0
  249. package/dist/health/HealthChecker.d.ts.map +1 -0
  250. package/dist/health/HealthChecker.js +70 -0
  251. package/dist/health/HealthChecker.js.map +1 -0
  252. package/dist/lib.d.ts +273 -0
  253. package/dist/lib.d.ts.map +1 -0
  254. package/dist/lib.js +409 -0
  255. package/dist/lib.js.map +1 -0
  256. package/dist/logger/NullLogger.d.ts +154 -0
  257. package/dist/logger/NullLogger.d.ts.map +1 -0
  258. package/dist/logger/NullLogger.js +24 -0
  259. package/dist/logger/NullLogger.js.map +1 -0
  260. package/dist/logger/StructuredLogger.d.ts +327 -0
  261. package/dist/logger/StructuredLogger.d.ts.map +1 -0
  262. package/dist/logger/StructuredLogger.js +72 -0
  263. package/dist/logger/StructuredLogger.js.map +1 -0
  264. package/dist/metrics/metrics.impl.d.ts +252 -0
  265. package/dist/metrics/metrics.impl.d.ts.map +1 -0
  266. package/dist/metrics/metrics.impl.js +197 -0
  267. package/dist/metrics/metrics.impl.js.map +1 -0
  268. package/dist/persistence/FileLegacyImport.d.ts +2 -0
  269. package/dist/persistence/FileLegacyImport.d.ts.map +1 -0
  270. package/dist/persistence/FileLegacyImport.js +183 -0
  271. package/dist/persistence/FileLegacyImport.js.map +1 -0
  272. package/dist/persistence/FilePersistence.d.ts +53 -0
  273. package/dist/persistence/FilePersistence.d.ts.map +1 -0
  274. package/dist/persistence/FilePersistence.js +312 -0
  275. package/dist/persistence/FilePersistence.js.map +1 -0
  276. package/dist/persistence/FileSnapshotTypes.d.ts +29 -0
  277. package/dist/persistence/FileSnapshotTypes.d.ts.map +1 -0
  278. package/dist/persistence/FileSnapshotTypes.js +1 -0
  279. package/dist/persistence/FileSnapshotV2.d.ts +377 -0
  280. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -0
  281. package/dist/persistence/FileSnapshotV2.js +124 -0
  282. package/dist/persistence/FileSnapshotV2.js.map +1 -0
  283. package/dist/persistence/FileSnapshotValidation.d.ts +15 -0
  284. package/dist/persistence/FileSnapshotValidation.d.ts.map +1 -0
  285. package/dist/persistence/FileSnapshotValidation.js +64 -0
  286. package/dist/persistence/FileSnapshotValidation.js.map +1 -0
  287. package/dist/persistence/FileWriter.d.ts +30 -0
  288. package/dist/persistence/FileWriter.d.ts.map +1 -0
  289. package/dist/persistence/FileWriter.js +155 -0
  290. package/dist/persistence/FileWriter.js.map +1 -0
  291. package/dist/persistence/MemoryPersistence.d.ts +45 -0
  292. package/dist/persistence/MemoryPersistence.d.ts.map +1 -0
  293. package/dist/persistence/MemoryPersistence.js +180 -0
  294. package/dist/persistence/MemoryPersistence.js.map +1 -0
  295. package/dist/persistence/PersistenceCodec.d.ts +7 -0
  296. package/dist/persistence/PersistenceCodec.d.ts.map +1 -0
  297. package/dist/persistence/PersistenceCodec.js +97 -0
  298. package/dist/persistence/PersistenceCodec.js.map +1 -0
  299. package/dist/persistence/PersistenceErrors.d.ts +23 -0
  300. package/dist/persistence/PersistenceErrors.d.ts.map +1 -0
  301. package/dist/persistence/PersistenceErrors.js +26 -0
  302. package/dist/persistence/PersistenceErrors.js.map +1 -0
  303. package/dist/persistence/PersistenceFactory.d.ts +21 -0
  304. package/dist/persistence/PersistenceFactory.d.ts.map +1 -0
  305. package/dist/persistence/PersistenceFactory.js +28 -0
  306. package/dist/persistence/PersistenceFactory.js.map +1 -0
  307. package/dist/persistence/PersistenceScope.d.ts +42 -0
  308. package/dist/persistence/PersistenceScope.d.ts.map +1 -0
  309. package/dist/persistence/PersistenceScope.js +93 -0
  310. package/dist/persistence/PersistenceScope.js.map +1 -0
  311. package/dist/persistence/SessionScopedPersistence.d.ts +4 -0
  312. package/dist/persistence/SessionScopedPersistence.d.ts.map +1 -0
  313. package/dist/persistence/SessionScopedPersistence.js +9 -0
  314. package/dist/persistence/SessionScopedPersistence.js.map +1 -0
  315. package/dist/persistence/SqliteDriver.d.ts +22 -0
  316. package/dist/persistence/SqliteDriver.d.ts.map +1 -0
  317. package/dist/persistence/SqliteDriver.js +29 -0
  318. package/dist/persistence/SqliteDriver.js.map +1 -0
  319. package/dist/persistence/SqliteLegacyImport.d.ts +14 -0
  320. package/dist/persistence/SqliteLegacyImport.d.ts.map +1 -0
  321. package/dist/persistence/SqliteLegacyImport.js +136 -0
  322. package/dist/persistence/SqliteLegacyImport.js.map +1 -0
  323. package/dist/persistence/SqliteLegacySchema.d.ts +15 -0
  324. package/dist/persistence/SqliteLegacySchema.d.ts.map +1 -0
  325. package/dist/persistence/SqliteLegacySchema.js +72 -0
  326. package/dist/persistence/SqliteLegacySchema.js.map +1 -0
  327. package/dist/persistence/SqlitePayload.d.ts +11 -0
  328. package/dist/persistence/SqlitePayload.d.ts.map +1 -0
  329. package/dist/persistence/SqlitePayload.js +86 -0
  330. package/dist/persistence/SqlitePayload.js.map +1 -0
  331. package/dist/persistence/SqlitePersistence.d.ts +49 -0
  332. package/dist/persistence/SqlitePersistence.d.ts.map +1 -0
  333. package/dist/persistence/SqlitePersistence.js +248 -0
  334. package/dist/persistence/SqlitePersistence.js.map +1 -0
  335. package/dist/persistence/SqliteSchemaV2.d.ts +14 -0
  336. package/dist/persistence/SqliteSchemaV2.d.ts.map +1 -0
  337. package/dist/persistence/SqliteSchemaV2.js +129 -0
  338. package/dist/persistence/SqliteSchemaV2.js.map +1 -0
  339. package/dist/persistence/SqliteSnapshotWriter.d.ts +17 -0
  340. package/dist/persistence/SqliteSnapshotWriter.d.ts.map +1 -0
  341. package/dist/persistence/SqliteSnapshotWriter.js +30 -0
  342. package/dist/persistence/SqliteSnapshotWriter.js.map +1 -0
  343. package/dist/pool/ConnectionPool.d.ts +203 -0
  344. package/dist/pool/ConnectionPool.d.ts.map +1 -0
  345. package/dist/pool/ConnectionPool.js +303 -0
  346. package/dist/pool/ConnectionPool.js.map +1 -0
  347. package/dist/pool/IConnectionPool.d.ts +143 -0
  348. package/dist/pool/IConnectionPool.d.ts.map +1 -0
  349. package/dist/pool/IConnectionPool.js +1 -0
  350. package/dist/pool/PoolErrors.d.ts +11 -0
  351. package/dist/pool/PoolErrors.d.ts.map +1 -0
  352. package/dist/pool/PoolErrors.js +16 -0
  353. package/dist/pool/PoolErrors.js.map +1 -0
  354. package/dist/registry/BaseRegistry.d.ts +219 -0
  355. package/dist/registry/BaseRegistry.d.ts.map +1 -0
  356. package/dist/registry/BaseRegistry.js +215 -0
  357. package/dist/registry/BaseRegistry.js.map +1 -0
  358. package/dist/registry/SkillRegistry.d.ts +67 -0
  359. package/dist/registry/SkillRegistry.d.ts.map +1 -0
  360. package/dist/registry/SkillRegistry.js +87 -0
  361. package/dist/registry/SkillRegistry.js.map +1 -0
  362. package/dist/registry/ToolRegistry.d.ts +70 -0
  363. package/dist/registry/ToolRegistry.d.ts.map +1 -0
  364. package/dist/registry/ToolRegistry.js +96 -0
  365. package/dist/registry/ToolRegistry.js.map +1 -0
  366. package/dist/sanitize.d.ts +164 -0
  367. package/dist/sanitize.d.ts.map +1 -0
  368. package/dist/sanitize.js +100 -0
  369. package/dist/sanitize.js.map +1 -0
  370. package/dist/schema.d.ts +562 -0
  371. package/dist/schema.d.ts.map +1 -0
  372. package/dist/schema.js +251 -0
  373. package/dist/schema.js.map +1 -0
  374. package/dist/transport/BaseTransport.d.ts +166 -0
  375. package/dist/transport/BaseTransport.d.ts.map +1 -0
  376. package/dist/transport/BaseTransport.js +199 -0
  377. package/dist/transport/BaseTransport.js.map +1 -0
  378. package/dist/transport/HttpHelpers.d.ts +53 -0
  379. package/dist/transport/HttpHelpers.d.ts.map +1 -0
  380. package/dist/transport/HttpHelpers.js +44 -0
  381. package/dist/transport/HttpHelpers.js.map +1 -0
  382. package/dist/transport/HttpRequestLifecycle.d.ts +37 -0
  383. package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -0
  384. package/dist/transport/HttpRequestLifecycle.js +87 -0
  385. package/dist/transport/HttpRequestLifecycle.js.map +1 -0
  386. package/dist/transport/HttpTransport.d.ts +140 -0
  387. package/dist/transport/HttpTransport.d.ts.map +1 -0
  388. package/dist/transport/HttpTransport.js +245 -0
  389. package/dist/transport/HttpTransport.js.map +1 -0
  390. package/dist/transport/SseTransport.d.ts +149 -0
  391. package/dist/transport/SseTransport.d.ts.map +1 -0
  392. package/dist/transport/SseTransport.js +470 -0
  393. package/dist/transport/SseTransport.js.map +1 -0
  394. package/dist/transport/StreamableHttpTransport.d.ts +225 -0
  395. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -0
  396. package/dist/transport/StreamableHttpTransport.js +449 -0
  397. package/dist/transport/StreamableHttpTransport.js.map +1 -0
  398. package/dist/types/disposable.d.ts +22 -0
  399. package/dist/types/disposable.d.ts.map +1 -0
  400. package/dist/types/disposable.js +1 -0
  401. package/dist/types/server-config.d.ts +32 -0
  402. package/dist/types/server-config.d.ts.map +1 -0
  403. package/dist/types/server-config.js +1 -0
  404. package/dist/types/skill.d.ts +74 -0
  405. package/dist/types/skill.d.ts.map +1 -0
  406. package/dist/types/skill.js +1 -0
  407. package/dist/types/tool.d.ts +78 -0
  408. package/dist/types/tool.d.ts.map +1 -0
  409. package/dist/types/tool.js +1 -0
  410. package/dist/utils.d.ts +27 -0
  411. package/dist/utils.d.ts.map +1 -0
  412. package/dist/utils.js +6 -0
  413. package/dist/utils.js.map +1 -0
  414. package/dist/watchers/SkillWatcher.d.ts +25 -0
  415. package/dist/watchers/SkillWatcher.d.ts.map +1 -0
  416. package/dist/watchers/SkillWatcher.js +96 -0
  417. package/dist/watchers/SkillWatcher.js.map +1 -0
  418. package/dist/watchers/ToolWatcher.d.ts +24 -0
  419. package/dist/watchers/ToolWatcher.d.ts.map +1 -0
  420. package/dist/watchers/ToolWatcher.js +92 -0
  421. package/dist/watchers/ToolWatcher.js.map +1 -0
  422. package/package.json +106 -0
@@ -0,0 +1,451 @@
1
+ import { NullLogger } from "../logger/NullLogger.js";
2
+ import { GLOBAL_SESSION_ID, asBranchId, asSessionId } from "../contracts/ids.js";
3
+ import { DEFAULT_FLAGS } from "../contracts/features.js";
4
+ import { InvalidBacktrackError, InvalidToolCallError, SequentialThinkingError, UnknownToolError, ValidationError, WARNING_CODES, getErrorMessage } from "../errors.js";
5
+ import { JsonShapeError, enforceJsonShape } from "../sanitize.js";
6
+ import { SequentialThinkingSchema } from "../schema.js";
7
+ import { GraphView } from "./graph/GraphView.js";
8
+ import { assertNever } from "../utils.js";
9
+ import { normalizeInput } from "./InputNormalizer.js";
10
+ import { SequentialStrategy } from "./reasoning/strategies/SequentialStrategy.js";
11
+ import { validateThoughtCrossReferences } from "./CrossReferenceValidator.js";
12
+ import { SessionLifecycleCoordinator } from "./SessionLifecycleCoordinator.js";
13
+ import { prepareVerificationOutcome } from "./VerificationOutcomeAdmission.js";
14
+ import * as __rspack_external_valibot from "valibot";
15
+ class ThoughtProcessor {
16
+ historyManager;
17
+ thoughtFormatter;
18
+ strategy;
19
+ _compressionService;
20
+ _suspensionStore;
21
+ _toolRegistry;
22
+ _features;
23
+ _sessionLock;
24
+ _outcomeRecorder;
25
+ _lifecycle;
26
+ _calibrator;
27
+ _logger;
28
+ _thoughtEvaluator;
29
+ _hintCooldowns = new Map();
30
+ constructor(historyManager, thoughtFormatter, thoughtEvaluator, logger, strategy = new SequentialStrategy(), _compressionService, _suspensionStore, _toolRegistry, _features = DEFAULT_FLAGS, _sessionLock, _outcomeRecorder, _lifecycle = new SessionLifecycleCoordinator(), _calibrator){
31
+ this.historyManager = historyManager;
32
+ this.thoughtFormatter = thoughtFormatter;
33
+ this.strategy = strategy;
34
+ this._compressionService = _compressionService;
35
+ this._suspensionStore = _suspensionStore;
36
+ this._toolRegistry = _toolRegistry;
37
+ this._features = _features;
38
+ this._sessionLock = _sessionLock;
39
+ this._outcomeRecorder = _outcomeRecorder;
40
+ this._lifecycle = _lifecycle;
41
+ this._calibrator = _calibrator;
42
+ this._thoughtEvaluator = thoughtEvaluator;
43
+ this._logger = logger ?? new NullLogger();
44
+ }
45
+ log(message, meta) {
46
+ this._logger.info(message, meta);
47
+ }
48
+ static _HINT_PRIORITY = {
49
+ confidence_drift: 1,
50
+ unverified_hypothesis: 2,
51
+ no_alternatives_explored: 3,
52
+ consecutive_without_verification: 4
53
+ };
54
+ _generateHints(patterns, currentThoughtNumber, sessionId) {
55
+ const warnings = patterns.filter((p)=>'warning' === p.severity);
56
+ if (0 === warnings.length) return [];
57
+ warnings.sort((a, b)=>{
58
+ const pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;
59
+ const pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;
60
+ return pa - pb;
61
+ });
62
+ const sessionKey = sessionId ?? GLOBAL_SESSION_ID;
63
+ if (!this._hintCooldowns.has(sessionKey)) this._hintCooldowns.set(sessionKey, new Map());
64
+ const cooldowns = this._hintCooldowns.get(sessionKey);
65
+ const hints = [];
66
+ for (const warning of warnings){
67
+ if (hints.length >= 3) break;
68
+ const lastFired = cooldowns.get(warning.pattern);
69
+ if (void 0 === lastFired || !(currentThoughtNumber - lastFired < 3)) {
70
+ hints.push(warning.message);
71
+ cooldowns.set(warning.pattern, currentThoughtNumber);
72
+ }
73
+ }
74
+ return hints;
75
+ }
76
+ async process(input) {
77
+ try {
78
+ const prepared = this._prepareInput(input);
79
+ const operation = async ()=>{
80
+ if (void 0 !== this._sessionLock) return await this._sessionLock.withLock(prepared.sessionId, ()=>this._processInner(prepared));
81
+ return await this._processInner(prepared);
82
+ };
83
+ if (prepared.resetState) {
84
+ this.historyManager.inspectSession(prepared.sessionId);
85
+ return await this._lifecycle.withSessionReset(prepared.sessionId, operation);
86
+ }
87
+ return await this._lifecycle.runOperation(prepared.sessionId, operation);
88
+ } catch (error) {
89
+ return this._buildErrorResponse(error);
90
+ }
91
+ }
92
+ async resetSession(sessionId) {
93
+ const canonicalSessionId = asSessionId(sessionId);
94
+ this.historyManager.inspectSession(canonicalSessionId);
95
+ const operation = async ()=>{
96
+ await this.historyManager.resetSessionWithinExclusive(canonicalSessionId, ()=>this.clearSessionAuxiliaryState(canonicalSessionId));
97
+ };
98
+ await this._lifecycle.withSessionReset(canonicalSessionId, async ()=>{
99
+ if (void 0 !== this._sessionLock) return void await this._sessionLock.withLock(canonicalSessionId, operation);
100
+ await operation();
101
+ });
102
+ }
103
+ async resetAll() {
104
+ await this._lifecycle.withGlobalReset(async ()=>await this.historyManager.resetAllWithinExclusive(()=>this.clearAllAuxiliaryState()));
105
+ }
106
+ _prepareInput(input) {
107
+ const normalized = normalizeInput(input);
108
+ if ('object' == typeof normalized && null !== normalized) this._validateToolArgumentsShape(normalized.tool_arguments);
109
+ const parsed = __rspack_external_valibot.safeParse(SequentialThinkingSchema, normalized);
110
+ if (!parsed.success) {
111
+ const firstIssue = parsed.issues[0];
112
+ const field = firstIssue?.path?.map((item)=>String(item.key)).join('.') || 'input';
113
+ throw new ValidationError(field, firstIssue?.message ?? 'Invalid input');
114
+ }
115
+ const internal = normalizeInput(parsed.output);
116
+ const exposeSessionId = void 0 !== internal.session_id;
117
+ const sessionId = internal.session_id ?? GLOBAL_SESSION_ID;
118
+ const registerBranchId = void 0 === internal.register_branch_id ? void 0 : asBranchId(internal.register_branch_id);
119
+ const thought = {
120
+ ...internal
121
+ };
122
+ delete thought.register_branch_id;
123
+ const { result, warnings } = this.validateInput(thought);
124
+ this._validateStatelessNewTypes(result);
125
+ return {
126
+ thought: result,
127
+ sessionId,
128
+ exposeSessionId,
129
+ resetState: true === result.reset_state,
130
+ registerBranchId,
131
+ validationWarnings: warnings
132
+ };
133
+ }
134
+ _buildErrorResponse(error) {
135
+ return {
136
+ content: [
137
+ {
138
+ type: 'text',
139
+ text: JSON.stringify({
140
+ ...error instanceof SequentialThinkingError && {
141
+ code: error.code
142
+ },
143
+ error: getErrorMessage(error),
144
+ message: getErrorMessage(error),
145
+ status: 'failed'
146
+ }, null, 2)
147
+ }
148
+ ],
149
+ isError: true
150
+ };
151
+ }
152
+ static _emptySessionSnapshot() {
153
+ return {
154
+ history: [],
155
+ branches: {},
156
+ branchIds: [],
157
+ availableMcpTools: void 0,
158
+ availableSkills: void 0
159
+ };
160
+ }
161
+ clearSessionAuxiliaryState(sessionId) {
162
+ this._hintCooldowns.delete(sessionId);
163
+ this._suspensionStore?.clearSession(sessionId);
164
+ this._outcomeRecorder?.clearOutcomes(sessionId);
165
+ this._calibrator?.clearSession(sessionId);
166
+ }
167
+ clearAllAuxiliaryState() {
168
+ this._suspensionStore?.clearAll();
169
+ this._outcomeRecorder?.clearAllOutcomes();
170
+ this._calibrator?.clearAll();
171
+ this._hintCooldowns.clear();
172
+ }
173
+ _validateToolArgumentsShape(toolArguments) {
174
+ try {
175
+ enforceJsonShape(toolArguments ?? {});
176
+ } catch (error) {
177
+ if (error instanceof JsonShapeError) throw new ValidationError('tool_arguments', error.reason);
178
+ throw error;
179
+ }
180
+ }
181
+ async _processInner(prepared) {
182
+ const { thought, sessionId, exposeSessionId, resetState, registerBranchId } = prepared;
183
+ const existingSnapshot = this.historyManager.inspectSession(sessionId);
184
+ const validationSnapshot = resetState ? ThoughtProcessor._emptySessionSnapshot() : existingSnapshot;
185
+ if (!resetState) {
186
+ if (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) thought.available_mcp_tools = [
187
+ ...validationSnapshot.availableMcpTools
188
+ ];
189
+ if (!thought.available_skills && validationSnapshot.availableSkills) thought.available_skills = [
190
+ ...validationSnapshot.availableSkills
191
+ ];
192
+ }
193
+ const resolveThoughtReference = resetState ? ()=>({
194
+ kind: 'missing'
195
+ }) : (thoughtNumber)=>this.historyManager.resolveThoughtReference(sessionId, thoughtNumber);
196
+ const { result: checkedInput, warnings: refWarnings, resolvedReferences } = validateThoughtCrossReferences(thought, {
197
+ snapshot: validationSnapshot,
198
+ resolveThoughtReference,
199
+ strictBranchReferences: resetState || void 0 !== registerBranchId,
200
+ logger: this._logger
201
+ });
202
+ const verificationOutcome = prepareVerificationOutcome({
203
+ input: checkedInput,
204
+ snapshot: validationSnapshot,
205
+ resolvedReferences,
206
+ sessionId,
207
+ recorder: this._outcomeRecorder
208
+ });
209
+ const allWarnings = [
210
+ ...prepared.validationWarnings,
211
+ ...refWarnings
212
+ ];
213
+ const validated = this._validateNewTypes(checkedInput);
214
+ const admissionContext = {
215
+ resolvedReferences
216
+ };
217
+ if (resetState && 'tool_observation' === validated.thought_type) throw new ValidationError('thought_type', 'tool_observation cannot resume a suspension in reset replacement state');
218
+ if (resetState) {
219
+ await this.historyManager.resetSessionWithinExclusive(sessionId, ()=>this.clearSessionAuxiliaryState(sessionId));
220
+ this.log('State reset for session', {
221
+ sessionId
222
+ });
223
+ }
224
+ if (void 0 !== registerBranchId) this.historyManager.registerBranch(sessionId, registerBranchId);
225
+ if ('tool_call' === validated.thought_type && this._suspensionStore) return this._handleToolCall(validated, sessionId, exposeSessionId, admissionContext);
226
+ if ('tool_observation' === validated.thought_type && this._suspensionStore) await this._handleToolObservation(validated, sessionId, admissionContext);
227
+ else this.historyManager.addThought(checkedInput, admissionContext);
228
+ this._recordVerificationOutcome(verificationOutcome, sessionId);
229
+ const formattedThought = this.thoughtFormatter.formatThought(checkedInput);
230
+ this.log(formattedThought, {
231
+ sessionId
232
+ });
233
+ const signals = this._collectReasoningSignals(checkedInput, sessionId);
234
+ const decision = this._runStrategy(checkedInput, signals.history, signals.reasoningStats, sessionId);
235
+ return this._buildSuccessResponse({
236
+ thought: checkedInput,
237
+ sessionId,
238
+ exposeSessionId,
239
+ reasoning: {
240
+ confidenceSignals: signals.confidenceSignals,
241
+ reasoningStats: signals.reasoningStats,
242
+ reasoningHints: signals.reasoningHints
243
+ },
244
+ decision,
245
+ warnings: allWarnings
246
+ });
247
+ }
248
+ _recordVerificationOutcome(outcome, sessionId) {
249
+ if (void 0 === outcome) return;
250
+ if (this._outcomeRecorder?.enabled === true) this._outcomeRecorder.recordVerification(outcome);
251
+ if (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);
252
+ }
253
+ _collectReasoningSignals(input, sessionId) {
254
+ const history = this.historyManager.getHistory(sessionId);
255
+ const branches = this.historyManager.getBranches(sessionId);
256
+ const confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {
257
+ currentThought: input,
258
+ sessionId: sessionId ?? GLOBAL_SESSION_ID
259
+ });
260
+ const reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);
261
+ const patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);
262
+ const reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);
263
+ return {
264
+ history,
265
+ confidenceSignals,
266
+ reasoningStats,
267
+ reasoningHints
268
+ };
269
+ }
270
+ _buildSuccessResponse(state) {
271
+ return {
272
+ content: [
273
+ {
274
+ type: 'text',
275
+ text: JSON.stringify({
276
+ thought_number: state.thought.thought_number,
277
+ total_thoughts: state.thought.total_thoughts,
278
+ next_thought_needed: state.thought.next_thought_needed ?? true,
279
+ branches: this.historyManager.getBranchIds(state.sessionId),
280
+ thought_history_length: this.historyManager.getHistoryLength(state.sessionId),
281
+ available_mcp_tools: state.thought.available_mcp_tools,
282
+ available_skills: state.thought.available_skills,
283
+ current_step: state.thought.current_step,
284
+ previous_steps: state.thought.previous_steps,
285
+ remaining_steps: state.thought.remaining_steps,
286
+ thought_type: state.thought.thought_type,
287
+ quality_score: state.thought.quality_score,
288
+ confidence: state.thought.confidence,
289
+ hypothesis_id: state.thought.hypothesis_id,
290
+ confidence_signals: state.reasoning.confidenceSignals,
291
+ reasoning_stats: state.reasoning.reasoningStats,
292
+ ...state.reasoning.reasoningHints.length > 0 && {
293
+ reasoning_hints: state.reasoning.reasoningHints
294
+ },
295
+ ...'continue' !== state.decision.action && {
296
+ strategy_hint: state.decision
297
+ },
298
+ ...state.warnings.length > 0 && {
299
+ warnings: state.warnings.slice(0, 3)
300
+ },
301
+ ...state.exposeSessionId ? {
302
+ session_id: state.sessionId
303
+ } : {}
304
+ }, null, 2)
305
+ }
306
+ ]
307
+ };
308
+ }
309
+ _runStrategy(currentThought, history, stats, sessionId) {
310
+ let decision;
311
+ try {
312
+ const edgeStore = this._getEdgeStore();
313
+ const graph = edgeStore ? new GraphView(edgeStore) : void 0;
314
+ decision = this.strategy.decide({
315
+ sessionId: sessionId ?? GLOBAL_SESSION_ID,
316
+ history,
317
+ graph,
318
+ stats,
319
+ currentThought
320
+ });
321
+ } catch (error) {
322
+ this._logger.warn('Reasoning strategy threw — defaulting to continue', {
323
+ strategy: this.strategy.name,
324
+ error: getErrorMessage(error)
325
+ });
326
+ decision = {
327
+ action: 'continue'
328
+ };
329
+ }
330
+ if ('terminate' === decision.action && this._compressionService && currentThought.branch_id) try {
331
+ const sid = sessionId ?? GLOBAL_SESSION_ID;
332
+ const branchRoot = this._findBranchRoot(sid, currentThought.branch_id);
333
+ if (branchRoot) this._compressionService.compressBranch(sid, currentThought.branch_id, branchRoot);
334
+ } catch (err) {
335
+ this._logger.debug('Compression auto-trigger failed', {
336
+ error: getErrorMessage(err)
337
+ });
338
+ }
339
+ return decision;
340
+ }
341
+ _findBranchRoot(sessionId, branchId) {
342
+ const edgeStore = this._getEdgeStore();
343
+ const branches = this.historyManager.getBranches(sessionId);
344
+ const branchList = branches[branchId];
345
+ const firstId = branchList?.[0]?.id;
346
+ if (edgeStore && firstId) {
347
+ const graph = new GraphView(edgeStore);
348
+ const ids = graph.branchThoughts(sessionId, firstId);
349
+ if (ids.length > 0) return ids[0];
350
+ }
351
+ return firstId;
352
+ }
353
+ _getEdgeStore() {
354
+ return this.historyManager.getEdgeStore();
355
+ }
356
+ validateInput(input) {
357
+ const warnings = [];
358
+ if (input.thought_number > input.total_thoughts) {
359
+ const originalTotal = input.total_thoughts;
360
+ warnings.push(`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`);
361
+ this._logger.warn('Auto-adjusted total_thoughts to match thought_number', {
362
+ thought_number: input.thought_number,
363
+ original_total_thoughts: originalTotal,
364
+ adjusted_total_thoughts: input.thought_number
365
+ });
366
+ input.total_thoughts = input.thought_number;
367
+ }
368
+ return {
369
+ result: input,
370
+ warnings
371
+ };
372
+ }
373
+ _validateStatelessNewTypes(input) {
374
+ const t = input.thought_type;
375
+ if (('tool_call' === t || 'tool_observation' === t) && !this._features.toolInterleave) throw new ValidationError('thought_type', `Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`);
376
+ if (('assumption' === t || 'decomposition' === t || 'backtrack' === t) && !this._features.newThoughtTypes) throw new ValidationError('thought_type', `Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`);
377
+ if ('tool_call' === t) {
378
+ if (!input.tool_name) throw new InvalidToolCallError('tool_call thought ' + input.thought_number + ' missing required tool_name');
379
+ this._validateToolName(input.tool_name);
380
+ }
381
+ if ('tool_observation' === t && !input.continuation_token) throw new ValidationError('continuation_token', 'tool_observation thought ' + input.thought_number + ' missing continuation_token');
382
+ if ('backtrack' === t) {
383
+ if (void 0 === input.backtrack_target) throw new ValidationError('backtrack_target', 'backtrack thought ' + input.thought_number + ' requires backtrack_target');
384
+ if (input.backtrack_target > input.thought_number) throw new InvalidBacktrackError('backtrack_target ' + input.backtrack_target + ' must be <= thought_number ' + input.thought_number);
385
+ }
386
+ if ('tool_call' === t) this._validateToolArgumentsShape(input.tool_arguments);
387
+ }
388
+ _validateNewTypes(input) {
389
+ return input;
390
+ }
391
+ _validateToolName(toolName) {
392
+ if (!this._toolRegistry) throw new UnknownToolError(toolName, `Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`);
393
+ if (!this._toolRegistry.has(toolName)) throw new UnknownToolError(toolName);
394
+ }
395
+ static _getWorkaroundType(t) {
396
+ switch(t){
397
+ case 'assumption':
398
+ return 'regular';
399
+ case 'decomposition':
400
+ return 'hypothesis';
401
+ case 'backtrack':
402
+ return 'regular';
403
+ default:
404
+ assertNever(t);
405
+ }
406
+ }
407
+ _handleToolCall(input, sessionId, exposeSessionId, admissionContext) {
408
+ if (void 0 === input.id) throw new ValidationError('id', 'tool_call requires an admitted thought id');
409
+ this.historyManager.addThought(input, admissionContext);
410
+ if (!this._suspensionStore) throw new ValidationError('thought_type', 'tool_call requires suspensionStore');
411
+ const record = this._suspensionStore.suspend({
412
+ sessionId,
413
+ toolCallThoughtNumber: input.thought_number,
414
+ toolCallThoughtId: input.id,
415
+ toolName: input.tool_name,
416
+ toolArguments: input.tool_arguments ?? {},
417
+ expiresAt: 0
418
+ });
419
+ return {
420
+ content: [
421
+ {
422
+ type: 'text',
423
+ text: JSON.stringify({
424
+ status: 'suspended',
425
+ continuation_token: record.token,
426
+ tool_name: record.toolName,
427
+ tool_arguments: record.toolArguments,
428
+ expires_at: record.expiresAt,
429
+ thought_number: input.thought_number,
430
+ total_thoughts: input.total_thoughts,
431
+ ...exposeSessionId ? {
432
+ session_id: sessionId
433
+ } : {}
434
+ }, null, 2)
435
+ }
436
+ ]
437
+ };
438
+ }
439
+ async _handleToolObservation(input, sessionId, admissionContext) {
440
+ if (!this._suspensionStore) throw new ValidationError('thought_type', 'tool_observation requires suspensionStore');
441
+ await this._suspensionStore.compareAndAdmit(input.continuation_token, sessionId, (record)=>{
442
+ this.historyManager.addThought(input, {
443
+ ...admissionContext,
444
+ toolInvocationSourceThoughtId: record.toolCallThoughtId
445
+ });
446
+ });
447
+ }
448
+ }
449
+ export { ThoughtProcessor };
450
+
451
+ //# sourceMappingURL=ThoughtProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\tGLOBAL_SESSION_ID,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type { IReasoningStrategy, StrategyDecision } from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName, PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly history: ThoughtData[];\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({ thought: '...', thought_number: 1, total_thoughts: 5, next_thought_needed: true });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\tconfidence_drift: 1, // Most actionable — degrading confidence\n\t\tunverified_hypothesis: 2, // Important for quality\n\t\tno_alternatives_explored: 3, // Breadth gap\n\t\tconsecutive_without_verification: 4, // Routine pattern\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId?: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tconst sessionKey = sessionId ?? GLOBAL_SESSION_ID;\n\t\tif (!this._hintCooldowns.has(sessionKey)) {\n\t\t\tthis._hintCooldowns.set(sessionKey, new Map());\n\t\t}\n\t\tconst cooldowns = this._hintCooldowns.get(sessionKey)!;\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(prepared.sessionId, () =>\n\t\t\t\t\t\tthis._processInner(prepared)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.inspectSession(prepared.sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(prepared.sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(prepared.sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.inspectSession(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst exposeSessionId = internal.session_id !== undefined;\n\t\tconst sessionId = internal.session_id ?? GLOBAL_SESSION_ID;\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tsessionId,\n\t\t\texposeSessionId,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, sessionId, exposeSessionId, resetState, registerBranchId } = prepared;\n\t\tconst existingSnapshot = this.historyManager.inspectSession(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: existingSnapshot;\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, sessionId, exposeSessionId, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, sessionId, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput, sessionId);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(\n\t\t\tcheckedInput,\n\t\t\tsignals.history,\n\t\t\tsignals.reasoningStats,\n\t\t\tsessionId\n\t\t);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\tsessionId,\n\t\t\texposeSessionId,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(\n\t\tinput: ThoughtData,\n\t\tsessionId?: SessionId\n\t): ReasoningSignalBundle {\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\thistory,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(state.sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(state.sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision.action !== 'continue' && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\t...(state.exposeSessionId ? { session_id: state.sessionId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors degrade to `{ action: 'continue' }`.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\thistory: ThoughtData[],\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>,\n\t\tsessionId?: SessionId\n\t): StrategyDecision {\n\t\tlet decision: StrategyDecision;\n\t\ttry {\n\t\t\tconst edgeStore = this._getEdgeStore();\n\t\t\tconst graph = edgeStore ? new GraphView(edgeStore) : undefined;\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t\t\thistory,\n\t\t\t\tgraph,\n\t\t\t\tstats,\n\t\t\t\tcurrentThought,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — defaulting to continue', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\tdecision = { action: 'continue' };\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst sid = sessionId ?? GLOBAL_SESSION_ID;\n\t\t\t\tconst branchRoot = this._findBranchRoot(sid, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsid,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches()[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tsessionId: SessionId,\n\t\texposeSessionId: boolean,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\t...(exposeSessionId ? { session_id: sessionId } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tsessionId: SessionId,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(input.continuation_token, sessionId, (record) => {\n\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t...admissionContext,\n\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t});\n\t\t});\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","sessionKey","GLOBAL_SESSION_ID","cooldowns","hints","warning","lastFired","undefined","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","exposeSessionId","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","existingSnapshot","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","outcome","history","branches","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","edgeStore","graph","GraphView","sid","branchRoot","err","branchId","branchList","firstId","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;AA2IO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,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,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAI1B,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAACf,MAAM,kBAAkB,EAAEd,WAAW,CAACuF;YACjF,IAAI,CAAC,cAAc,CAAC,UAAU,CAACzE,OAAO;gBACrC,GAAGyC,gBAAgB;gBACnB,+BAA+BgC,OAAO,iBAAiB;YACxD;QACD;IACD;AACD"}
@@ -0,0 +1,23 @@
1
+ import type { SessionId, ThoughtId } from '../contracts/ids.js';
2
+ import type { ThoughtData } from './thought.js';
3
+ export type ThoughtReferenceResolution = {
4
+ readonly kind: 'missing';
5
+ } | {
6
+ readonly kind: 'unique';
7
+ readonly thoughtId: ThoughtId;
8
+ } | {
9
+ readonly kind: 'ambiguous';
10
+ readonly thoughtIds: readonly ThoughtId[];
11
+ };
12
+ /** Ref-counted stable-ID lookup for retained thoughts in each session. */
13
+ export declare class ThoughtReferenceIndex {
14
+ private readonly _sessions;
15
+ add(sessionId: SessionId, thought: ThoughtData): void;
16
+ remove(sessionId: SessionId, thought: ThoughtData): void;
17
+ resolve(sessionId: SessionId, thoughtNumber: number): ThoughtReferenceResolution;
18
+ replaceSession(sessionId: SessionId, thoughts: Iterable<ThoughtData>): void;
19
+ clearSession(sessionId: SessionId): void;
20
+ clearAll(): void;
21
+ private _addToSession;
22
+ }
23
+ //# sourceMappingURL=ThoughtReferenceIndex.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ThoughtReferenceIndex.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtReferenceIndex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,MAAM,0BAA0B,GACnC;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAA;CAAE,GAC1D;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,SAAS,SAAS,EAAE,CAAA;CAAE,CAAC;AAI7E,0EAA0E;AAC1E,qBAAa,qBAAqB;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6D;IAEhF,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,GAAG,IAAI;IAUrD,MAAM,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,GAAG,IAAI;IAexD,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,GAAG,0BAA0B;IAWhF,cAAc,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,CAAC,WAAW,CAAC,GAAG,IAAI;IAU3E,YAAY,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAIxC,QAAQ,IAAI,IAAI;IAIvB,OAAO,CAAC,aAAa;CASrB"}
@@ -0,0 +1,66 @@
1
+ const MISSING = Object.freeze({
2
+ kind: 'missing'
3
+ });
4
+ class ThoughtReferenceIndex {
5
+ _sessions = new Map();
6
+ add(sessionId, thought) {
7
+ if (void 0 === thought.id) return;
8
+ let session = this._sessions.get(sessionId);
9
+ if (void 0 === session) {
10
+ session = new Map();
11
+ this._sessions.set(sessionId, session);
12
+ }
13
+ this._addToSession(session, thought);
14
+ }
15
+ remove(sessionId, thought) {
16
+ if (void 0 === thought.id) return;
17
+ const session = this._sessions.get(sessionId);
18
+ const bucket = session?.get(thought.thought_number);
19
+ const count = bucket?.get(thought.id);
20
+ if (void 0 === session || void 0 === bucket || void 0 === count) return;
21
+ if (count > 1) bucket.set(thought.id, count - 1);
22
+ else bucket.delete(thought.id);
23
+ if (0 === bucket.size) session.delete(thought.thought_number);
24
+ if (0 === session.size) this._sessions.delete(sessionId);
25
+ }
26
+ resolve(sessionId, thoughtNumber) {
27
+ const bucket = this._sessions.get(sessionId)?.get(thoughtNumber);
28
+ if (void 0 === bucket || 0 === bucket.size) return MISSING;
29
+ if (1 === bucket.size) {
30
+ const thoughtId = bucket.keys().next().value;
31
+ return void 0 === thoughtId ? MISSING : {
32
+ kind: 'unique',
33
+ thoughtId
34
+ };
35
+ }
36
+ const thoughtIds = Object.freeze(Array.from(bucket.keys()).sort());
37
+ return Object.freeze({
38
+ kind: 'ambiguous',
39
+ thoughtIds
40
+ });
41
+ }
42
+ replaceSession(sessionId, thoughts) {
43
+ const replacement = new Map();
44
+ for (const thought of thoughts)this._addToSession(replacement, thought);
45
+ if (0 === replacement.size) this._sessions.delete(sessionId);
46
+ else this._sessions.set(sessionId, replacement);
47
+ }
48
+ clearSession(sessionId) {
49
+ this._sessions.delete(sessionId);
50
+ }
51
+ clearAll() {
52
+ this._sessions.clear();
53
+ }
54
+ _addToSession(session, thought) {
55
+ if (void 0 === thought.id) return;
56
+ let bucket = session.get(thought.thought_number);
57
+ if (void 0 === bucket) {
58
+ bucket = new Map();
59
+ session.set(thought.thought_number, bucket);
60
+ }
61
+ bucket.set(thought.id, (bucket.get(thought.id) ?? 0) + 1);
62
+ }
63
+ }
64
+ export { ThoughtReferenceIndex };
65
+
66
+ //# sourceMappingURL=ThoughtReferenceIndex.js.map