@iworkforces/tracelattice 2.0.3 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +6 -12
  2. package/dist/cli.js +221 -2213
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/ConfigLoader.d.ts +3 -0
  5. package/dist/config/ConfigLoader.d.ts.map +1 -1
  6. package/dist/config/ConfigLoader.js +6 -0
  7. package/dist/config/ConfigLoader.js.map +1 -1
  8. package/dist/contracts/transport.d.ts +2 -2
  9. package/dist/contracts/transport.d.ts.map +1 -1
  10. package/dist/core/ThoughtProcessor.d.ts +1 -1
  11. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  12. package/dist/core/ThoughtProcessor.js +3 -6
  13. package/dist/core/ThoughtProcessor.js.map +1 -1
  14. package/dist/lib.d.ts +0 -10
  15. package/dist/lib.d.ts.map +1 -1
  16. package/dist/lib.js.map +1 -1
  17. package/dist/metrics/metrics.impl.d.ts +2 -7
  18. package/dist/metrics/metrics.impl.d.ts.map +1 -1
  19. package/dist/metrics/metrics.impl.js +32 -34
  20. package/dist/metrics/metrics.impl.js.map +1 -1
  21. package/dist/persistence/FileSnapshotV2.d.ts +2 -2
  22. package/dist/pool/ConnectionPool.d.ts +7 -3
  23. package/dist/pool/ConnectionPool.d.ts.map +1 -1
  24. package/dist/pool/ConnectionPool.js +65 -40
  25. package/dist/pool/ConnectionPool.js.map +1 -1
  26. package/dist/schema.d.ts +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/schema.js +4 -2
  29. package/dist/schema.js.map +1 -1
  30. package/dist/transport/HttpHelpers.d.ts +1 -1
  31. package/dist/transport/HttpHelpers.js.map +1 -1
  32. package/package.json +3 -3
  33. package/dist/transport/SseTransport.d.ts +0 -149
  34. package/dist/transport/SseTransport.d.ts.map +0 -1
  35. package/dist/transport/SseTransport.js +0 -470
  36. package/dist/transport/SseTransport.js.map +0 -1
@@ -15,7 +15,8 @@ class Session {
15
15
  _closePromise = null;
16
16
  _activeOperationCount = 0;
17
17
  _operationDrain = null;
18
- constructor(id, server, timeout, logger){
18
+ _onTimeout;
19
+ constructor(id, server, timeout, logger, onTimeout = null){
19
20
  this._server = server;
20
21
  this._id = id;
21
22
  this._createdAt = Date.now();
@@ -23,6 +24,7 @@ class Session {
23
24
  this._isActiveValue = true;
24
25
  this._timeout = timeout;
25
26
  this._logger = logger;
27
+ this._onTimeout = onTimeout;
26
28
  this._startTimeout();
27
29
  }
28
30
  get isActive() {
@@ -72,6 +74,9 @@ class Session {
72
74
  if (this._closePromise) return this._closePromise;
73
75
  const completion = Promise.withResolvers();
74
76
  this._closePromise = completion.promise;
77
+ completion.promise.then(void 0, ()=>{
78
+ if (this._closePromise === completion.promise) this._closePromise = null;
79
+ });
75
80
  this._isActiveValue = false;
76
81
  if (this._cleanupTimer) {
77
82
  clearTimeout(this._cleanupTimer);
@@ -98,7 +103,8 @@ class Session {
98
103
  this._cleanupTimer = setTimeout(()=>{
99
104
  if (this.isTimedOut()) {
100
105
  this._logger.warn(`Session ${this._id} timed out, closing`);
101
- this.close().catch((err)=>{
106
+ if (this._onTimeout) this._onTimeout(this._id);
107
+ else this.close().catch((err)=>{
102
108
  this._logger.error(`Error closing timed out session ${this._id}:`, err);
103
109
  });
104
110
  }
@@ -110,6 +116,7 @@ class Session {
110
116
  }
111
117
  class ConnectionPool {
112
118
  _sessions = new Map();
119
+ _ownedSessions = new Map();
113
120
  _closingSessions = new Map();
114
121
  _createSessionLock = null;
115
122
  _maxSessions;
@@ -120,9 +127,8 @@ class ConnectionPool {
120
127
  _terminated = false;
121
128
  _logger;
122
129
  _serverFactory;
123
- _terminatePromise = null;
130
+ _terminationGeneration = null;
124
131
  _admissionContext = new AsyncLocalStorage();
125
- _pendingCreateStopFailures = new Set();
126
132
  constructor(options = {}){
127
133
  this._maxSessions = options.maxSessions ?? 100;
128
134
  this._sessionTimeout = options.sessionTimeout ?? 300000;
@@ -145,7 +151,7 @@ class ConnectionPool {
145
151
  async createSession() {
146
152
  while(this._createSessionLock)await this._createSessionLock;
147
153
  if (this._terminated) throw new PoolTerminatedError();
148
- if (this._sessions.size >= this._maxSessions) throw new MaxSessionsReachedError(this._maxSessions);
154
+ if (this._ownedSessions.size >= this._maxSessions) throw new MaxSessionsReachedError(this._maxSessions);
149
155
  if (!this._serverFactory) throw new Error('ConnectionPool requires a serverFactory option to create sessions');
150
156
  let resolveLock;
151
157
  this._createSessionLock = new Promise((resolve)=>{
@@ -153,17 +159,16 @@ class ConnectionPool {
153
159
  });
154
160
  try {
155
161
  const sessionId = asSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`);
162
+ if (this._ownedSessions.has(sessionId)) throw new Error(`Session ID collision: ${sessionId}`);
156
163
  const server = await this._serverFactory();
164
+ const session = new Session(sessionId, server, this._sessionTimeout, this._logger, (timedOutSessionId)=>this._handleSessionTimeout(timedOutSessionId));
165
+ this._ownedSessions.set(sessionId, session);
157
166
  if (this._terminated) {
158
- try {
159
- await server.stop();
160
- } catch (error) {
161
- this._pendingCreateStopFailures.add(error);
162
- throw error;
163
- }
167
+ const generation = this._terminationGeneration;
168
+ if (generation) await this._coordinateCleanup(sessionId, generation);
169
+ else await this._coordinateCleanup(sessionId);
164
170
  throw new PoolTerminatedError();
165
171
  }
166
- const session = new Session(sessionId, server, this._sessionTimeout, this._logger);
167
172
  this._sessions.set(sessionId, session);
168
173
  this._logger.info(`Created session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`);
169
174
  return sessionId;
@@ -195,7 +200,7 @@ class ConnectionPool {
195
200
  value: await operation(activeFrame.session)
196
201
  }))();
197
202
  const session = this._sessions.get(sessionId);
198
- if (!session) return Promise.resolve(this._closingSessions.has(sessionId) ? {
203
+ if (!session) return Promise.resolve(this._ownedSessions.has(sessionId) ? {
199
204
  status: 'inactive'
200
205
  } : {
201
206
  status: 'missing'
@@ -216,20 +221,35 @@ class ConnectionPool {
216
221
  });
217
222
  }
218
223
  closeSession(sessionId) {
219
- const closing = this._closingSessions.get(sessionId);
220
- if (closing) return closing;
221
- const session = this._sessions.get(sessionId);
224
+ if (!this._ownedSessions.has(sessionId)) return Promise.reject(new SessionNotFoundError(sessionId));
225
+ const generation = this._terminationGeneration;
226
+ return generation ? this._coordinateCleanup(sessionId, generation) : this._coordinateCleanup(sessionId);
227
+ }
228
+ _coordinateCleanup(sessionId, generation) {
229
+ const generationAttempt = generation?.attempts.get(sessionId);
230
+ if (generationAttempt) return generationAttempt;
231
+ const session = this._ownedSessions.get(sessionId);
222
232
  if (!session) return Promise.reject(new SessionNotFoundError(sessionId));
223
233
  this._sessions.delete(sessionId);
224
- const closePromise = session.close();
225
- this._closingSessions.set(sessionId, closePromise);
226
- closePromise.then(()=>{
227
- this._closingSessions.delete(sessionId);
234
+ const currentAttempt = this._closingSessions.get(sessionId);
235
+ const attempt = currentAttempt ?? session.close();
236
+ if (!currentAttempt) this._closingSessions.set(sessionId, attempt);
237
+ generation?.attempts.set(sessionId, attempt);
238
+ if (!currentAttempt) attempt.then(()=>{
239
+ if (this._closingSessions.get(sessionId) === attempt) this._closingSessions.delete(sessionId);
240
+ if (this._ownedSessions.get(sessionId) === session) this._ownedSessions.delete(sessionId);
228
241
  this._logger.info(`Closed session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`);
229
242
  }, ()=>{
230
- this._closingSessions.delete(sessionId);
243
+ if (this._closingSessions.get(sessionId) === attempt) this._closingSessions.delete(sessionId);
244
+ });
245
+ return attempt;
246
+ }
247
+ _handleSessionTimeout(sessionId) {
248
+ const generation = this._terminationGeneration;
249
+ const attempt = generation ? this._coordinateCleanup(sessionId, generation) : this._coordinateCleanup(sessionId);
250
+ attempt.catch((err)=>{
251
+ this._logger.error(`Error closing timed out session ${sessionId}:`, err);
231
252
  });
232
- return closePromise;
233
253
  }
234
254
  getSessionInfo(sessionId) {
235
255
  return this._sessions.get(sessionId)?.getInfo();
@@ -255,8 +275,8 @@ class ConnectionPool {
255
275
  }
256
276
  _cleanupTimedOutSessions() {
257
277
  let cleaned = 0;
258
- for (const [sessionId, session] of this._sessions.entries())if (session.isTimedOut()) {
259
- this.closeSession(sessionId).catch((err)=>{
278
+ for (const [sessionId, session] of this._ownedSessions.entries())if (session.isTimedOut()) {
279
+ this._coordinateCleanup(sessionId).catch((err)=>{
260
280
  this._logger.error(`Error closing timed out session ${sessionId}:`, err);
261
281
  });
262
282
  cleaned++;
@@ -264,30 +284,35 @@ class ConnectionPool {
264
284
  if (cleaned > 0) this._logger.info(`Cleaned ${cleaned} timed-out sessions (${this._sessions.size}/${this._maxSessions} active sessions)`);
265
285
  }
266
286
  terminate() {
267
- if (this._terminatePromise) return this._terminatePromise;
287
+ if (this._terminationGeneration) return this._terminationGeneration.completion.promise;
268
288
  const completion = Promise.withResolvers();
269
- this._terminatePromise = completion.promise;
289
+ const generation = {
290
+ attempts: new Map(),
291
+ completion
292
+ };
293
+ this._terminationGeneration = generation;
270
294
  this._terminated = true;
271
295
  if (null !== this._cleanupTimerId) {
272
296
  clearInterval(this._cleanupTimerId);
273
297
  this._cleanupTimerId = null;
274
298
  }
275
- const sessions = Array.from(this._sessions.values());
276
- this._sessions.clear();
277
- const closePromises = new Set(this._closingSessions.values());
278
- if (this._createSessionLock) closePromises.add(this._createSessionLock);
279
- for (const session of sessions)closePromises.add(session.close());
280
- Promise.allSettled(closePromises).then((outcomes)=>{
281
- const failures = [
282
- ...this._pendingCreateStopFailures,
283
- ...outcomes.filter((outcome)=>'rejected' === outcome.status).map((outcome)=>outcome.reason)
284
- ];
285
- if (failures.length > 0) return void completion.reject(new AggregateError(failures, 'ConnectionPool termination failed'));
286
- this._logger.info('ConnectionPool terminated');
287
- completion.resolve();
288
- });
299
+ const pendingCreate = this._createSessionLock;
300
+ for (const sessionId of this._ownedSessions.keys())this._coordinateCleanup(sessionId, generation);
301
+ this._completeTerminationGeneration(generation, pendingCreate);
289
302
  return completion.promise;
290
303
  }
304
+ async _completeTerminationGeneration(generation, pendingCreate) {
305
+ if (pendingCreate) await pendingCreate;
306
+ const outcomes = await Promise.allSettled(generation.attempts.values());
307
+ const failures = outcomes.filter((outcome)=>'rejected' === outcome.status).map((outcome)=>outcome.reason);
308
+ if (failures.length > 0) {
309
+ if (this._terminationGeneration === generation) this._terminationGeneration = null;
310
+ generation.completion.reject(new AggregateError(failures, 'ConnectionPool termination failed'));
311
+ return;
312
+ }
313
+ this._logger.info('ConnectionPool terminated');
314
+ generation.completion.resolve();
315
+ }
291
316
  dispose() {
292
317
  return this.terminate();
293
318
  }
@@ -1 +1 @@
1
- {"version":3,"file":"pool/ConnectionPool.js","sources":["../../src/pool/ConnectionPool.ts"],"sourcesContent":["/**\n * Connection Pool for managing concurrent user sessions.\n *\n * This module provides session management for multi-user scenarios,\n * allowing multiple concurrent clients to each have isolated state.\n *\n * @example\n * ```typescript\n * const pool = new ConnectionPool({\n * maxSessions: 100,\n * sessionTimeout: 300000 // 5 minutes\n * });\n *\n * const sessionId = await pool.createSession();\n * await pool.process(sessionId, thought);\n * await pool.closeSession(sessionId);\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport {\n\tMaxSessionsReachedError,\n\tPoolTerminatedError,\n} from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport { asSessionId, type SessionId } from '../contracts/ids.js';\nimport { assertNever } from '../utils.js';\nimport { SessionNotActiveError, SessionNotFoundError } from './PoolErrors.js';\nimport type {\n\tConnectionPoolStats,\n\tIConnectionPool,\n\tProcessResult,\n\tSessionInfo,\n\tSessionRunResult,\n\tSessionServer,\n\tSessionThoughtInput,\n} from './IConnectionPool.js';\n\nexport interface SessionOptions {\n\t/**\n\t * Maximum number of concurrent sessions\n\t * @default 100\n\t */\n\tmaxSessions?: number;\n\n\t/**\n\t * Logger instance\n\t */\n\tlogger?: Logger;\n\n\tserverFactory?: () => Promise<SessionServer>;\n\n\t/**\n\t * Session timeout in milliseconds\n\t * @default 300000 (5 minutes)\n\t */\n\tsessionTimeout?: number;\n\n\t/**\n\t * Whether to enable automatic session cleanup\n\t * @default true\n\t */\n\tautoCleanup?: boolean;\n\n\t/**\n\t * Cleanup interval in milliseconds\n\t * @default 60000 (1 minute)\n\t */\n\tcleanupInterval?: number;\n}\n\n/**\n * Represents a user session with its own server instance.\n */\nexport class Session {\n\tprivate _server: SessionServer;\n\tprivate _id: SessionId;\n\tprivate _createdAt: number;\n\tprivate _lastActivityAt: number;\n\tprivate _isActiveValue: boolean;\n\tprivate _timeout: number;\n\tprivate _cleanupTimer: NodeJS.Timeout | null = null;\n\tprivate _logger: Logger;\n\tprivate _closePromise: Promise<void> | null = null;\n\tprivate _activeOperationCount = 0;\n\tprivate _operationDrain: PromiseWithResolvers<void> | null = null;\n\n\tconstructor(id: SessionId, server: SessionServer, timeout: number, logger: Logger) {\n\t\tthis._server = server;\n\t\tthis._id = id;\n\t\tthis._createdAt = Date.now();\n\t\tthis._lastActivityAt = this._createdAt;\n\t\tthis._isActiveValue = true;\n\t\tthis._timeout = timeout;\n\t\tthis._logger = logger;\n\n\t\t// Start session timeout timer\n\t\tthis._startTimeout();\n\t}\n\n\t/**\n\t * Check if the session is active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this._isActiveValue;\n\t}\n\n\t/**\n\t * Process a thought through this session's server instance.\n\t */\n\tasync process(input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tif (!this.isActive) {\n\t\t\tthrow new SessionNotActiveError(this._id);\n\t\t}\n\n\t\t// Update last activity\n\t\tthis._lastActivityAt = Date.now();\n\n\t\t// Reset timeout timer\n\t\tthis._resetTimeout();\n\n\t\t// Process the thought\n\t\treturn this._server.processThought(input);\n\t}\n\n\tprocessAdmitted(input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tthis._lastActivityAt = Date.now();\n\t\tif (this.isActive) this._resetTimeout();\n\t\treturn this._server.processThought(input);\n\t}\n\n\trunWhileActive<T>(operation: (session: Session) => Promise<T>): Promise<SessionRunResult<T>> {\n\t\tif (!this.isActive) return Promise.resolve({ status: 'inactive' });\n\t\tthis._activeOperationCount++;\n\t\treturn (async () => {\n\t\t\ttry {\n\t\t\t\treturn { status: 'completed', value: await operation(this) };\n\t\t\t} finally {\n\t\t\t\tthis._activeOperationCount--;\n\t\t\t\tif (this._activeOperationCount === 0) this._operationDrain?.resolve();\n\t\t\t}\n\t\t})();\n\t}\n\n\t/**\n\t * Get session information.\n\t */\n\tgetInfo(): SessionInfo {\n\t\treturn {\n\t\t\tid: this._id,\n\t\t\tserver: this._server,\n\t\t\tcreatedAt: this._createdAt,\n\t\t\tlastActivityAt: this._lastActivityAt,\n\t\t\tisActive: this.isActive,\n\t\t};\n\t}\n\n\t/**\n\t * Check if the session has timed out.\n\t */\n\tisTimedOut(): boolean {\n\t\treturn Date.now() - this._lastActivityAt > this._timeout;\n\t}\n\n\t/**\n\t * Close the session and stop the server.\n\t */\n\tclose(): Promise<void> {\n\t\tif (this._closePromise) {\n\t\t\treturn this._closePromise;\n\t\t}\n\n\t\tconst completion = Promise.withResolvers<void>();\n\t\tthis._closePromise = completion.promise;\n\t\tthis._isActiveValue = false;\n\n\t\t// Stop timeout timer\n\t\tif (this._cleanupTimer) {\n\t\t\tclearTimeout(this._cleanupTimer);\n\t\t\tthis._cleanupTimer = null;\n\t\t}\n\n\t\tif (this._activeOperationCount === 0) {\n\t\t\tthis._stopServer(completion);\n\t\t} else {\n\t\t\tthis._operationDrain = Promise.withResolvers<void>();\n\t\t\tvoid this._operationDrain.promise.then(() => this._stopServer(completion));\n\t\t}\n\n\t\treturn completion.promise;\n\t}\n\n\tprivate _stopServer(completion: PromiseWithResolvers<void>): void {\n\t\ttry {\n\t\t\tPromise.resolve(this._server.stop()).then(completion.resolve, completion.reject);\n\t\t} catch (error) {\n\t\t\tcompletion.reject(\n\t\t\t\terror instanceof Error ? error : new AggregateError([error], 'Session stop failed')\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Start the session timeout timer.\n\t */\n\tprivate _startTimeout(): void {\n\t\tif (this._cleanupTimer) {\n\t\t\tclearTimeout(this._cleanupTimer);\n\t\t}\n\n\t\tthis._cleanupTimer = setTimeout(() => {\n\t\t\tif (this.isTimedOut()) {\n\t\t\t\tthis._logger.warn(`Session ${this._id} timed out, closing`);\n\t\t\t\tthis.close().catch((err) => {\n\t\t\t\t\tthis._logger.error(`Error closing timed out session ${this._id}:`, err);\n\t\t\t\t});\n\t\t\t}\n\t\t}, this._timeout);\n\t}\n\n\t/**\n\t * Reset the timeout timer after activity.\n\t */\n\tprivate _resetTimeout(): void {\n\t\tthis._startTimeout();\n\t}\n}\n\n/**\n * ConnectionPool manages multiple concurrent user sessions.\n *\n * Each session has its own server instance with isolated state,\n * allowing multiple users to interact with the system simultaneously.\n */\nexport class ConnectionPool implements IConnectionPool {\n\tprivate _sessions: Map<SessionId, Session> = new Map();\n\tprivate readonly _closingSessions = new Map<SessionId, Promise<void>>();\n\tprivate _createSessionLock: Promise<void> | null = null;\n\tprivate _maxSessions: number;\n\tprivate _sessionTimeout: number;\n\tprivate _autoCleanup: boolean;\n\tprivate _cleanupInterval: number;\n\tprivate _cleanupTimerId: ReturnType<typeof setInterval> | null = null;\n\tprivate _terminated: boolean = false;\n\tprivate _logger: Logger;\n\tprivate _serverFactory: (() => Promise<SessionServer>) | null;\n\tprivate _terminatePromise: Promise<void> | null = null;\n\tprivate readonly _admissionContext = new AsyncLocalStorage<{\n\t\treadonly sessionId: SessionId;\n\t\treadonly session: Session;\n\t\topen: boolean;\n\t}>();\n\tprivate readonly _pendingCreateStopFailures = new Set<unknown>();\n\n\tconstructor(options: SessionOptions = {}) {\n\t\tthis._maxSessions = options.maxSessions ?? 100;\n\t\tthis._sessionTimeout = options.sessionTimeout ?? 300000; // 5 minutes\n\t\tthis._autoCleanup = options.autoCleanup ?? true;\n\t\tthis._cleanupInterval = options.cleanupInterval ?? 60000; // 1 minute\n\t\tthis._serverFactory = options.serverFactory ?? null;\n\t\tthis._logger = options.logger ?? this._createNoopLogger();\n\n\t\tif (this._autoCleanup) {\n\t\t\tthis._startCleanup();\n\t\t}\n\t}\n\n\t/**\n\t * Create a no-op logger when none is provided.\n\t */\n\tprivate _createNoopLogger(): Logger {\n\t\treturn {\n\t\t\tinfo: (): void => {},\n\t\t\twarn: (): void => {},\n\t\t\terror: (): void => {},\n\t\t\tdebug: (): void => {},\n\t\t\tsetLevel: (): void => {},\n\t\t\tgetLevel: (): 'info' => 'info',\n\t\t};\n\t}\n\n\t/**\n\t * Create a new session.\n\t *\n\t * @returns The session ID\n\t * @throws Error if max sessions reached\n\t */\n\tasync createSession(): Promise<SessionId> {\n\t\twhile (this._createSessionLock) {\n\t\t\tawait this._createSessionLock;\n\t\t}\n\n\t\tif (this._terminated) {\n\t\t\tthrow new PoolTerminatedError();\n\t\t}\n\n\t\tif (this._sessions.size >= this._maxSessions) {\n\t\t\tthrow new MaxSessionsReachedError(this._maxSessions);\n\t\t}\n\n\t\tif (!this._serverFactory) {\n\t\t\tthrow new Error('ConnectionPool requires a serverFactory option to create sessions');\n\t\t}\n\n\t\tlet resolveLock!: () => void;\n\t\tthis._createSessionLock = new Promise<void>((resolve) => {\n\t\t\tresolveLock = resolve;\n\t\t});\n\n\t\ttry {\n\t\t\t// Generate unique session ID\n\t\t\tconst sessionId = asSessionId(\n\t\t\t\t`session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`\n\t\t\t);\n\n\t\t\t// Create a new server instance for this session\n\t\t\tconst server = await this._serverFactory();\n\t\t\tif (this._terminated) {\n\t\t\t\ttry {\n\t\t\t\t\tawait server.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis._pendingCreateStopFailures.add(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthrow new PoolTerminatedError();\n\t\t\t}\n\n\t\t\t// Create session\n\t\t\tconst session = new Session(sessionId, server, this._sessionTimeout, this._logger);\n\t\t\tthis._sessions.set(sessionId, session);\n\n\t\t\tthis._logger.info(\n\t\t\t\t`Created session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t);\n\t\t\treturn sessionId;\n\t\t} finally {\n\t\t\tresolveLock();\n\t\t\tthis._createSessionLock = null;\n\t\t}\n\t}\n\n\t/**\n\t * Process a thought in the specified session.\n\t *\n\t * @param sessionId - The session ID\n\t * @param input - The thought data to process\n\t * @returns Promise with the processing result\n\t * @throws Error if session not found\n\t */\n\tasync process(sessionId: SessionId, input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tconst result = await this._runWithSession(sessionId, (session) =>\n\t\t\tsession.processAdmitted(input)\n\t\t);\n\t\tswitch (result.status) {\n\t\t\tcase 'completed':\n\t\t\t\treturn result.value;\n\t\t\tcase 'inactive':\n\t\t\t\tthrow new SessionNotActiveError(sessionId);\n\t\t\tcase 'missing':\n\t\t\t\tthrow new SessionNotFoundError(sessionId);\n\t\t\tdefault:\n\t\t\t\treturn assertNever(result);\n\t\t}\n\t}\n\n\trunWithSession<T>(\n\t\tsessionId: SessionId,\n\t\toperation: (session: SessionServer) => Promise<T>\n\t): Promise<SessionRunResult<T>> {\n\t\treturn this._runWithSession(sessionId, (session) => operation(session.getInfo().server));\n\t}\n\n\tprivate _runWithSession<T>(\n\t\tsessionId: SessionId,\n\t\toperation: (session: Session) => Promise<T>\n\t): Promise<SessionRunResult<T>> {\n\t\tconst activeFrame = this._admissionContext.getStore();\n\t\tif (activeFrame?.open === true && activeFrame.sessionId === sessionId) {\n\t\t\treturn (async () => ({ status: 'completed', value: await operation(activeFrame.session) }))();\n\t\t}\n\n\t\tconst session = this._sessions.get(sessionId);\n\t\tif (!session) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tthis._closingSessions.has(sessionId) ? { status: 'inactive' } : { status: 'missing' }\n\t\t\t);\n\t\t}\n\n\t\treturn session.runWhileActive((capturedSession) => {\n\t\t\tconst frame = { sessionId, session: capturedSession, open: true };\n\t\t\treturn this._admissionContext.run(frame, async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await operation(capturedSession);\n\t\t\t\t} finally {\n\t\t\t\t\tframe.open = false;\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Close a session and release resources.\n\t *\n\t * @param sessionId - The session ID to close\n\t * @throws Error if session not found\n\t */\n\tcloseSession(sessionId: SessionId): Promise<void> {\n\t\tconst closing = this._closingSessions.get(sessionId);\n\t\tif (closing) {\n\t\t\treturn closing;\n\t\t}\n\n\t\tconst session = this._sessions.get(sessionId);\n\n\t\tif (!session) {\n\t\t\treturn Promise.reject(new SessionNotFoundError(sessionId));\n\t\t}\n\n\t\tthis._sessions.delete(sessionId);\n\t\tconst closePromise = session.close();\n\t\tthis._closingSessions.set(sessionId, closePromise);\n\t\tvoid closePromise.then(\n\t\t\t() => {\n\t\t\t\tthis._closingSessions.delete(sessionId);\n\t\t\t\tthis._logger.info(\n\t\t\t\t\t`Closed session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t\t);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis._closingSessions.delete(sessionId);\n\t\t\t}\n\t\t);\n\t\treturn closePromise;\n\t}\n\n\t/**\n\t * Get information about a session.\n\t *\n\t * @param sessionId - The session ID\n\t * @returns Session info or undefined if not found\n\t */\n\tgetSessionInfo(sessionId: SessionId): SessionInfo | undefined {\n\t\treturn this._sessions.get(sessionId)?.getInfo();\n\t}\n\n\t/**\n\t * Get all active sessions.\n\t *\n\t * @returns Array of session information\n\t */\n\tgetActiveSessions(): SessionInfo[] {\n\t\treturn Array.from(this._sessions.values())\n\t\t\t.filter((s) => s.isActive)\n\t\t\t.map((s) => s.getInfo());\n\t}\n\n\t/**\n\t * Get connection pool statistics.\n\t */\n\tgetStats(): ConnectionPoolStats {\n\t\tconst activeSessions = this.getActiveSessions();\n\n\t\treturn {\n\t\t\ttotalSessions: this._sessions.size,\n\t\t\tactiveSessions: activeSessions.length,\n\t\t\tmaxSessions: this._maxSessions,\n\t\t\tcleanupEnabled: this._autoCleanup,\n\t\t\tsessionTimeout: this._sessionTimeout,\n\t\t};\n\t}\n\n\t/**\n\t * Start the automatic cleanup timer.\n\t */\n\tprivate _startCleanup(): void {\n\t\tif (this._cleanupTimerId !== null) {\n\t\t\tclearInterval(this._cleanupTimerId);\n\t\t}\n\n\t\tthis._cleanupTimerId = setInterval(() => {\n\t\t\tthis._cleanupTimedOutSessions();\n\t\t}, this._cleanupInterval);\n\t}\n\n\t/**\n\t * Remove timed-out sessions.\n\t */\n\tprivate _cleanupTimedOutSessions(): void {\n\t\tlet cleaned = 0;\n\n\t\tfor (const [sessionId, session] of this._sessions.entries()) {\n\t\t\tif (session.isTimedOut()) {\n\t\t\t\tthis.closeSession(sessionId).catch((err) => {\n\t\t\t\t\tthis._logger.error(`Error closing timed out session ${sessionId}:`, err);\n\t\t\t\t});\n\t\t\t\tcleaned++;\n\t\t\t}\n\t\t}\n\n\t\tif (cleaned > 0) {\n\t\t\tthis._logger.info(\n\t\t\t\t`Cleaned ${cleaned} timed-out sessions (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Close all sessions and stop the cleanup timer.\n\t */\n\tterminate(): Promise<void> {\n\t\tif (this._terminatePromise) {\n\t\t\treturn this._terminatePromise;\n\t\t}\n\n\t\tconst completion = Promise.withResolvers<void>();\n\t\tthis._terminatePromise = completion.promise;\n\t\tthis._terminated = true;\n\n\t\t// Stop cleanup timer\n\t\tif (this._cleanupTimerId !== null) {\n\t\t\tclearInterval(this._cleanupTimerId);\n\t\t\tthis._cleanupTimerId = null;\n\t\t}\n\n\t\tconst sessions = Array.from(this._sessions.values());\n\t\tthis._sessions.clear();\n\t\tconst closePromises = new Set<Promise<void>>(this._closingSessions.values());\n\t\tif (this._createSessionLock) {\n\t\t\tclosePromises.add(this._createSessionLock);\n\t\t}\n\t\tfor (const session of sessions) {\n\t\t\tclosePromises.add(session.close());\n\t\t}\n\n\t\tvoid Promise.allSettled(closePromises).then((outcomes) => {\n\t\t\tconst failures = [\n\t\t\t\t...this._pendingCreateStopFailures,\n\t\t\t\t...outcomes\n\t\t\t\t\t.filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n\t\t\t\t\t.map((outcome) => outcome.reason),\n\t\t\t];\n\t\t\tif (failures.length > 0) {\n\t\t\t\tcompletion.reject(new AggregateError(failures, 'ConnectionPool termination failed'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._logger.info('ConnectionPool terminated');\n\t\t\tcompletion.resolve();\n\t\t});\n\n\t\treturn completion.promise;\n\t}\n\n\t/**\n\t * Dispose of the connection pool, releasing all resources.\n\t * Implements the IDisposable interface.\n\t * Delegates to terminate() for backward compatibility.\n\t */\n\tdispose(): Promise<void> {\n\t\treturn this.terminate();\n\t}\n\n\t/**\n\t * Check if the connection pool is active.\n\t */\n\tisRunning(): boolean {\n\t\treturn !this._terminated;\n\t}\n}\n\n/**\n * Create a connection pool with the given options.\n *\n * @param options - Connection pool configuration\n * @returns A configured connection pool\n *\n * @example\n * ```typescript\n * const pool = createConnectionPool({\n * maxSessions: 50,\n * sessionTimeout: 300000\n * });\n * ```\n */\nexport function createConnectionPool(options?: SessionOptions): ConnectionPool {\n\treturn new ConnectionPool(options);\n}\n"],"names":["Session","id","server","timeout","logger","Date","input","SessionNotActiveError","operation","Promise","completion","clearTimeout","error","Error","AggregateError","setTimeout","err","ConnectionPool","Map","AsyncLocalStorage","Set","options","PoolTerminatedError","MaxSessionsReachedError","resolveLock","resolve","sessionId","asSessionId","Math","session","result","SessionNotFoundError","assertNever","activeFrame","capturedSession","frame","closing","closePromise","Array","s","activeSessions","clearInterval","setInterval","cleaned","sessions","closePromises","outcomes","failures","outcome","createConnectionPool"],"mappings":";;;;;AA0EO,MAAMA;IACJ,QAAuB;IACvB,IAAe;IACf,WAAmB;IACnB,gBAAwB;IACxB,eAAwB;IACxB,SAAiB;IACjB,gBAAuC,KAAK;IAC5C,QAAgB;IACh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AACoC,eAAe,IAAI,CAAC,CAACC;YAC5C,MAAMC,WAAW;mBACb,IAAI,CAAC,0BAA0B;mBAC/BD,SACD,MAAM,CAAC,CAACE,UAA8CA,AAAmB,eAAnBA,QAAQ,MAAM,EACpE,GAAG,CAAC,CAACA,UAAYA,QAAQ,MAAM;aACjC;YACD,IAAID,SAAS,MAAM,GAAG,GAAG,YACxBrC,WAAW,MAAM,CAAC,IAAII,eAAeiC,UAAU;YAGhD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAClBrC,WAAW,OAAO;QACnB;QAEA,OAAOA,WAAW,OAAO;IAC1B;IAOA,UAAyB;QACxB,OAAO,IAAI,CAAC,SAAS;IACtB;IAKA,YAAqB;QACpB,OAAO,CAAC,IAAI,CAAC,WAAW;IACzB;AACD;AAgBO,SAASuC,qBAAqB5B,OAAwB;IAC5D,OAAO,IAAIJ,eAAeI;AAC3B"}
1
+ {"version":3,"file":"pool/ConnectionPool.js","sources":["../../src/pool/ConnectionPool.ts"],"sourcesContent":["/**\n * Connection Pool for managing concurrent user sessions.\n *\n * This module provides session management for multi-user scenarios,\n * allowing multiple concurrent clients to each have isolated state.\n *\n * @example\n * ```typescript\n * const pool = new ConnectionPool({\n * maxSessions: 100,\n * sessionTimeout: 300000 // 5 minutes\n * });\n *\n * const sessionId = await pool.createSession();\n * await pool.process(sessionId, thought);\n * await pool.closeSession(sessionId);\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { MaxSessionsReachedError, PoolTerminatedError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport { asSessionId, type SessionId } from '../contracts/ids.js';\nimport { assertNever } from '../utils.js';\nimport { SessionNotActiveError, SessionNotFoundError } from './PoolErrors.js';\nimport type {\n\tConnectionPoolStats,\n\tIConnectionPool,\n\tProcessResult,\n\tSessionInfo,\n\tSessionRunResult,\n\tSessionServer,\n\tSessionThoughtInput,\n} from './IConnectionPool.js';\n\nexport interface SessionOptions {\n\t/**\n\t * Maximum number of concurrent sessions\n\t * @default 100\n\t */\n\tmaxSessions?: number;\n\n\t/**\n\t * Logger instance\n\t */\n\tlogger?: Logger;\n\n\tserverFactory?: () => Promise<SessionServer>;\n\n\t/**\n\t * Session timeout in milliseconds\n\t * @default 300000 (5 minutes)\n\t */\n\tsessionTimeout?: number;\n\n\t/**\n\t * Whether to enable automatic session cleanup\n\t * @default true\n\t */\n\tautoCleanup?: boolean;\n\n\t/**\n\t * Cleanup interval in milliseconds\n\t * @default 60000 (1 minute)\n\t */\n\tcleanupInterval?: number;\n}\n\n/**\n * Represents a user session with its own server instance.\n */\nexport class Session {\n\tprivate _server: SessionServer;\n\tprivate _id: SessionId;\n\tprivate _createdAt: number;\n\tprivate _lastActivityAt: number;\n\tprivate _isActiveValue: boolean;\n\tprivate _timeout: number;\n\tprivate _cleanupTimer: NodeJS.Timeout | null = null;\n\tprivate _logger: Logger;\n\tprivate _closePromise: Promise<void> | null = null;\n\tprivate _activeOperationCount = 0;\n\tprivate _operationDrain: PromiseWithResolvers<void> | null = null;\n\tprivate readonly _onTimeout: ((sessionId: SessionId) => void) | null;\n\n\tconstructor(\n\t\tid: SessionId,\n\t\tserver: SessionServer,\n\t\ttimeout: number,\n\t\tlogger: Logger,\n\t\tonTimeout: ((sessionId: SessionId) => void) | null = null\n\t) {\n\t\tthis._server = server;\n\t\tthis._id = id;\n\t\tthis._createdAt = Date.now();\n\t\tthis._lastActivityAt = this._createdAt;\n\t\tthis._isActiveValue = true;\n\t\tthis._timeout = timeout;\n\t\tthis._logger = logger;\n\t\tthis._onTimeout = onTimeout;\n\n\t\t// Start session timeout timer\n\t\tthis._startTimeout();\n\t}\n\n\t/**\n\t * Check if the session is active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this._isActiveValue;\n\t}\n\n\t/**\n\t * Process a thought through this session's server instance.\n\t */\n\tasync process(input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tif (!this.isActive) {\n\t\t\tthrow new SessionNotActiveError(this._id);\n\t\t}\n\n\t\t// Update last activity\n\t\tthis._lastActivityAt = Date.now();\n\n\t\t// Reset timeout timer\n\t\tthis._resetTimeout();\n\n\t\t// Process the thought\n\t\treturn this._server.processThought(input);\n\t}\n\n\tprocessAdmitted(input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tthis._lastActivityAt = Date.now();\n\t\tif (this.isActive) this._resetTimeout();\n\t\treturn this._server.processThought(input);\n\t}\n\n\trunWhileActive<T>(operation: (session: Session) => Promise<T>): Promise<SessionRunResult<T>> {\n\t\tif (!this.isActive) return Promise.resolve({ status: 'inactive' });\n\t\tthis._activeOperationCount++;\n\t\treturn (async () => {\n\t\t\ttry {\n\t\t\t\treturn { status: 'completed', value: await operation(this) };\n\t\t\t} finally {\n\t\t\t\tthis._activeOperationCount--;\n\t\t\t\tif (this._activeOperationCount === 0) this._operationDrain?.resolve();\n\t\t\t}\n\t\t})();\n\t}\n\n\t/**\n\t * Get session information.\n\t */\n\tgetInfo(): SessionInfo {\n\t\treturn {\n\t\t\tid: this._id,\n\t\t\tserver: this._server,\n\t\t\tcreatedAt: this._createdAt,\n\t\t\tlastActivityAt: this._lastActivityAt,\n\t\t\tisActive: this.isActive,\n\t\t};\n\t}\n\n\t/**\n\t * Check if the session has timed out.\n\t */\n\tisTimedOut(): boolean {\n\t\treturn Date.now() - this._lastActivityAt > this._timeout;\n\t}\n\n\t/**\n\t * Close the session and stop the server.\n\t */\n\tclose(): Promise<void> {\n\t\tif (this._closePromise) {\n\t\t\treturn this._closePromise;\n\t\t}\n\n\t\tconst completion = Promise.withResolvers<void>();\n\t\tthis._closePromise = completion.promise;\n\t\tvoid completion.promise.then(undefined, () => {\n\t\t\tif (this._closePromise === completion.promise) this._closePromise = null;\n\t\t});\n\t\tthis._isActiveValue = false;\n\n\t\t// Stop timeout timer\n\t\tif (this._cleanupTimer) {\n\t\t\tclearTimeout(this._cleanupTimer);\n\t\t\tthis._cleanupTimer = null;\n\t\t}\n\n\t\tif (this._activeOperationCount === 0) {\n\t\t\tthis._stopServer(completion);\n\t\t} else {\n\t\t\tthis._operationDrain = Promise.withResolvers<void>();\n\t\t\tvoid this._operationDrain.promise.then(() => this._stopServer(completion));\n\t\t}\n\n\t\treturn completion.promise;\n\t}\n\n\tprivate _stopServer(completion: PromiseWithResolvers<void>): void {\n\t\ttry {\n\t\t\tPromise.resolve(this._server.stop()).then(completion.resolve, completion.reject);\n\t\t} catch (error) {\n\t\t\tcompletion.reject(\n\t\t\t\terror instanceof Error ? error : new AggregateError([error], 'Session stop failed')\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Start the session timeout timer.\n\t */\n\tprivate _startTimeout(): void {\n\t\tif (this._cleanupTimer) {\n\t\t\tclearTimeout(this._cleanupTimer);\n\t\t}\n\n\t\tthis._cleanupTimer = setTimeout(() => {\n\t\t\tif (this.isTimedOut()) {\n\t\t\t\tthis._logger.warn(`Session ${this._id} timed out, closing`);\n\t\t\t\tif (this._onTimeout) {\n\t\t\t\t\tthis._onTimeout(this._id);\n\t\t\t\t} else {\n\t\t\t\t\tthis.close().catch((err) => {\n\t\t\t\t\t\tthis._logger.error(`Error closing timed out session ${this._id}:`, err);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}, this._timeout);\n\t}\n\n\t/**\n\t * Reset the timeout timer after activity.\n\t */\n\tprivate _resetTimeout(): void {\n\t\tthis._startTimeout();\n\t}\n}\n\ninterface TerminationGeneration {\n\treadonly attempts: Map<SessionId, Promise<void>>;\n\treadonly completion: PromiseWithResolvers<void>;\n}\n\n/**\n * ConnectionPool manages multiple concurrent user sessions.\n *\n * Each session has its own server instance with isolated state,\n * allowing multiple users to interact with the system simultaneously.\n */\nexport class ConnectionPool implements IConnectionPool {\n\tprivate _sessions: Map<SessionId, Session> = new Map();\n\tprivate readonly _ownedSessions = new Map<SessionId, Session>();\n\tprivate readonly _closingSessions = new Map<SessionId, Promise<void>>();\n\tprivate _createSessionLock: Promise<void> | null = null;\n\tprivate _maxSessions: number;\n\tprivate _sessionTimeout: number;\n\tprivate _autoCleanup: boolean;\n\tprivate _cleanupInterval: number;\n\tprivate _cleanupTimerId: ReturnType<typeof setInterval> | null = null;\n\tprivate _terminated: boolean = false;\n\tprivate _logger: Logger;\n\tprivate _serverFactory: (() => Promise<SessionServer>) | null;\n\tprivate _terminationGeneration: TerminationGeneration | null = null;\n\tprivate readonly _admissionContext = new AsyncLocalStorage<{\n\t\treadonly sessionId: SessionId;\n\t\treadonly session: Session;\n\t\topen: boolean;\n\t}>();\n\n\tconstructor(options: SessionOptions = {}) {\n\t\tthis._maxSessions = options.maxSessions ?? 100;\n\t\tthis._sessionTimeout = options.sessionTimeout ?? 300000; // 5 minutes\n\t\tthis._autoCleanup = options.autoCleanup ?? true;\n\t\tthis._cleanupInterval = options.cleanupInterval ?? 60000; // 1 minute\n\t\tthis._serverFactory = options.serverFactory ?? null;\n\t\tthis._logger = options.logger ?? this._createNoopLogger();\n\n\t\tif (this._autoCleanup) {\n\t\t\tthis._startCleanup();\n\t\t}\n\t}\n\n\t/**\n\t * Create a no-op logger when none is provided.\n\t */\n\tprivate _createNoopLogger(): Logger {\n\t\treturn {\n\t\t\tinfo: (): void => {},\n\t\t\twarn: (): void => {},\n\t\t\terror: (): void => {},\n\t\t\tdebug: (): void => {},\n\t\t\tsetLevel: (): void => {},\n\t\t\tgetLevel: (): 'info' => 'info',\n\t\t};\n\t}\n\n\t/**\n\t * Create a new session.\n\t *\n\t * @returns The session ID\n\t * @throws Error if max sessions reached\n\t */\n\tasync createSession(): Promise<SessionId> {\n\t\twhile (this._createSessionLock) {\n\t\t\tawait this._createSessionLock;\n\t\t}\n\n\t\tif (this._terminated) {\n\t\t\tthrow new PoolTerminatedError();\n\t\t}\n\n\t\tif (this._ownedSessions.size >= this._maxSessions) {\n\t\t\tthrow new MaxSessionsReachedError(this._maxSessions);\n\t\t}\n\n\t\tif (!this._serverFactory) {\n\t\t\tthrow new Error('ConnectionPool requires a serverFactory option to create sessions');\n\t\t}\n\n\t\tlet resolveLock!: () => void;\n\t\tthis._createSessionLock = new Promise<void>((resolve) => {\n\t\t\tresolveLock = resolve;\n\t\t});\n\n\t\ttry {\n\t\t\t// Generate unique session ID\n\t\t\tconst sessionId = asSessionId(\n\t\t\t\t`session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`\n\t\t\t);\n\t\t\tif (this._ownedSessions.has(sessionId)) {\n\t\t\t\tthrow new Error(`Session ID collision: ${sessionId}`);\n\t\t\t}\n\n\t\t\t// Create a new server instance for this session\n\t\t\tconst server = await this._serverFactory();\n\t\t\tconst session = new Session(\n\t\t\t\tsessionId,\n\t\t\t\tserver,\n\t\t\t\tthis._sessionTimeout,\n\t\t\t\tthis._logger,\n\t\t\t\t(timedOutSessionId) => this._handleSessionTimeout(timedOutSessionId)\n\t\t\t);\n\t\t\tthis._ownedSessions.set(sessionId, session);\n\t\t\tif (this._terminated) {\n\t\t\t\tconst generation = this._terminationGeneration;\n\t\t\t\tif (generation) {\n\t\t\t\t\tawait this._coordinateCleanup(sessionId, generation);\n\t\t\t\t} else {\n\t\t\t\t\tawait this._coordinateCleanup(sessionId);\n\t\t\t\t}\n\t\t\t\tthrow new PoolTerminatedError();\n\t\t\t}\n\n\t\t\tthis._sessions.set(sessionId, session);\n\n\t\t\tthis._logger.info(\n\t\t\t\t`Created session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t);\n\t\t\treturn sessionId;\n\t\t} finally {\n\t\t\tresolveLock();\n\t\t\tthis._createSessionLock = null;\n\t\t}\n\t}\n\n\t/**\n\t * Process a thought in the specified session.\n\t *\n\t * @param sessionId - The session ID\n\t * @param input - The thought data to process\n\t * @returns Promise with the processing result\n\t * @throws Error if session not found\n\t */\n\tasync process(sessionId: SessionId, input: SessionThoughtInput): Promise<ProcessResult> {\n\t\tconst result = await this._runWithSession(sessionId, (session) =>\n\t\t\tsession.processAdmitted(input)\n\t\t);\n\t\tswitch (result.status) {\n\t\t\tcase 'completed':\n\t\t\t\treturn result.value;\n\t\t\tcase 'inactive':\n\t\t\t\tthrow new SessionNotActiveError(sessionId);\n\t\t\tcase 'missing':\n\t\t\t\tthrow new SessionNotFoundError(sessionId);\n\t\t\tdefault:\n\t\t\t\treturn assertNever(result);\n\t\t}\n\t}\n\n\trunWithSession<T>(\n\t\tsessionId: SessionId,\n\t\toperation: (session: SessionServer) => Promise<T>\n\t): Promise<SessionRunResult<T>> {\n\t\treturn this._runWithSession(sessionId, (session) => operation(session.getInfo().server));\n\t}\n\n\tprivate _runWithSession<T>(\n\t\tsessionId: SessionId,\n\t\toperation: (session: Session) => Promise<T>\n\t): Promise<SessionRunResult<T>> {\n\t\tconst activeFrame = this._admissionContext.getStore();\n\t\tif (activeFrame?.open === true && activeFrame.sessionId === sessionId) {\n\t\t\treturn (async () => ({ status: 'completed', value: await operation(activeFrame.session) }))();\n\t\t}\n\n\t\tconst session = this._sessions.get(sessionId);\n\t\tif (!session) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tthis._ownedSessions.has(sessionId) ? { status: 'inactive' } : { status: 'missing' }\n\t\t\t);\n\t\t}\n\n\t\treturn session.runWhileActive((capturedSession) => {\n\t\t\tconst frame = { sessionId, session: capturedSession, open: true };\n\t\t\treturn this._admissionContext.run(frame, async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await operation(capturedSession);\n\t\t\t\t} finally {\n\t\t\t\t\tframe.open = false;\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Close a session and release resources.\n\t *\n\t * @param sessionId - The session ID to close\n\t * @throws Error if session not found\n\t */\n\tcloseSession(sessionId: SessionId): Promise<void> {\n\t\tif (!this._ownedSessions.has(sessionId)) {\n\t\t\treturn Promise.reject(new SessionNotFoundError(sessionId));\n\t\t}\n\n\t\tconst generation = this._terminationGeneration;\n\t\treturn generation\n\t\t\t? this._coordinateCleanup(sessionId, generation)\n\t\t\t: this._coordinateCleanup(sessionId);\n\t}\n\n\tprivate _coordinateCleanup(\n\t\tsessionId: SessionId,\n\t\tgeneration?: TerminationGeneration\n\t): Promise<void> {\n\t\tconst generationAttempt = generation?.attempts.get(sessionId);\n\t\tif (generationAttempt) return generationAttempt;\n\n\t\tconst session = this._ownedSessions.get(sessionId);\n\t\tif (!session) return Promise.reject(new SessionNotFoundError(sessionId));\n\n\t\tthis._sessions.delete(sessionId);\n\t\tconst currentAttempt = this._closingSessions.get(sessionId);\n\t\tconst attempt = currentAttempt ?? session.close();\n\t\tif (!currentAttempt) this._closingSessions.set(sessionId, attempt);\n\t\tgeneration?.attempts.set(sessionId, attempt);\n\n\t\tif (!currentAttempt)\n\t\t\tvoid attempt.then(\n\t\t\t\t() => {\n\t\t\t\t\tif (this._closingSessions.get(sessionId) === attempt) {\n\t\t\t\t\t\tthis._closingSessions.delete(sessionId);\n\t\t\t\t\t}\n\t\t\t\t\tif (this._ownedSessions.get(sessionId) === session) {\n\t\t\t\t\t\tthis._ownedSessions.delete(sessionId);\n\t\t\t\t\t}\n\t\t\t\t\tthis._logger.info(\n\t\t\t\t\t\t`Closed session ${sessionId} (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tif (this._closingSessions.get(sessionId) === attempt) {\n\t\t\t\t\t\tthis._closingSessions.delete(sessionId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\treturn attempt;\n\t}\n\n\tprivate _handleSessionTimeout(sessionId: SessionId): void {\n\t\tconst generation = this._terminationGeneration;\n\t\tconst attempt = generation\n\t\t\t? this._coordinateCleanup(sessionId, generation)\n\t\t\t: this._coordinateCleanup(sessionId);\n\t\tvoid attempt.catch((err) => {\n\t\t\tthis._logger.error(`Error closing timed out session ${sessionId}:`, err);\n\t\t});\n\t}\n\n\t/**\n\t * Get information about a session.\n\t *\n\t * @param sessionId - The session ID\n\t * @returns Session info or undefined if not found\n\t */\n\tgetSessionInfo(sessionId: SessionId): SessionInfo | undefined {\n\t\treturn this._sessions.get(sessionId)?.getInfo();\n\t}\n\n\t/**\n\t * Get all active sessions.\n\t *\n\t * @returns Array of session information\n\t */\n\tgetActiveSessions(): SessionInfo[] {\n\t\treturn Array.from(this._sessions.values())\n\t\t\t.filter((s) => s.isActive)\n\t\t\t.map((s) => s.getInfo());\n\t}\n\n\t/**\n\t * Get connection pool statistics.\n\t */\n\tgetStats(): ConnectionPoolStats {\n\t\tconst activeSessions = this.getActiveSessions();\n\n\t\treturn {\n\t\t\ttotalSessions: this._sessions.size,\n\t\t\tactiveSessions: activeSessions.length,\n\t\t\tmaxSessions: this._maxSessions,\n\t\t\tcleanupEnabled: this._autoCleanup,\n\t\t\tsessionTimeout: this._sessionTimeout,\n\t\t};\n\t}\n\n\t/**\n\t * Start the automatic cleanup timer.\n\t */\n\tprivate _startCleanup(): void {\n\t\tif (this._cleanupTimerId !== null) {\n\t\t\tclearInterval(this._cleanupTimerId);\n\t\t}\n\n\t\tthis._cleanupTimerId = setInterval(() => {\n\t\t\tthis._cleanupTimedOutSessions();\n\t\t}, this._cleanupInterval);\n\t}\n\n\t/**\n\t * Remove timed-out sessions.\n\t */\n\tprivate _cleanupTimedOutSessions(): void {\n\t\tlet cleaned = 0;\n\n\t\tfor (const [sessionId, session] of this._ownedSessions.entries()) {\n\t\t\tif (session.isTimedOut()) {\n\t\t\t\tthis._coordinateCleanup(sessionId).catch((err) => {\n\t\t\t\t\tthis._logger.error(`Error closing timed out session ${sessionId}:`, err);\n\t\t\t\t});\n\t\t\t\tcleaned++;\n\t\t\t}\n\t\t}\n\n\t\tif (cleaned > 0) {\n\t\t\tthis._logger.info(\n\t\t\t\t`Cleaned ${cleaned} timed-out sessions (${this._sessions.size}/${this._maxSessions} active sessions)`\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Close all sessions and stop the cleanup timer.\n\t */\n\tterminate(): Promise<void> {\n\t\tif (this._terminationGeneration) {\n\t\t\treturn this._terminationGeneration.completion.promise;\n\t\t}\n\n\t\tconst completion = Promise.withResolvers<void>();\n\t\tconst generation: TerminationGeneration = { attempts: new Map(), completion };\n\t\tthis._terminationGeneration = generation;\n\t\tthis._terminated = true;\n\n\t\t// Stop cleanup timer\n\t\tif (this._cleanupTimerId !== null) {\n\t\t\tclearInterval(this._cleanupTimerId);\n\t\t\tthis._cleanupTimerId = null;\n\t\t}\n\n\t\tconst pendingCreate = this._createSessionLock;\n\t\tfor (const sessionId of this._ownedSessions.keys()) {\n\t\t\tthis._coordinateCleanup(sessionId, generation);\n\t\t}\n\n\t\tvoid this._completeTerminationGeneration(generation, pendingCreate);\n\n\t\treturn completion.promise;\n\t}\n\n\tprivate async _completeTerminationGeneration(\n\t\tgeneration: TerminationGeneration,\n\t\tpendingCreate: Promise<void> | null\n\t): Promise<void> {\n\t\tif (pendingCreate) await pendingCreate;\n\t\tconst outcomes = await Promise.allSettled(generation.attempts.values());\n\t\tconst failures = outcomes\n\t\t\t.filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n\t\t\t.map((outcome) => outcome.reason);\n\t\tif (failures.length > 0) {\n\t\t\tif (this._terminationGeneration === generation) this._terminationGeneration = null;\n\t\t\tgeneration.completion.reject(\n\t\t\t\tnew AggregateError(failures, 'ConnectionPool termination failed')\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis._logger.info('ConnectionPool terminated');\n\t\tgeneration.completion.resolve();\n\t}\n\n\t/**\n\t * Dispose of the connection pool, releasing all resources.\n\t * Implements the IDisposable interface.\n\t * Delegates to terminate() for backward compatibility.\n\t */\n\tdispose(): Promise<void> {\n\t\treturn this.terminate();\n\t}\n\n\t/**\n\t * Check if the connection pool is active.\n\t */\n\tisRunning(): boolean {\n\t\treturn !this._terminated;\n\t}\n}\n\n/**\n * Create a connection pool with the given options.\n *\n * @param options - Connection pool configuration\n * @returns A configured connection pool\n *\n * @example\n * ```typescript\n * const pool = createConnectionPool({\n * maxSessions: 50,\n * sessionTimeout: 300000\n * });\n * ```\n */\nexport function createConnectionPool(options?: SessionOptions): ConnectionPool {\n\treturn new ConnectionPool(options);\n}\n"],"names":["Session","id","server","timeout","logger","onTimeout","Date","input","SessionNotActiveError","operation","Promise","completion","undefined","clearTimeout","error","Error","AggregateError","setTimeout","err","ConnectionPool","Map","AsyncLocalStorage","options","PoolTerminatedError","MaxSessionsReachedError","resolveLock","resolve","sessionId","asSessionId","Math","session","timedOutSessionId","generation","result","SessionNotFoundError","assertNever","activeFrame","capturedSession","frame","generationAttempt","currentAttempt","attempt","Array","s","activeSessions","clearInterval","setInterval","cleaned","pendingCreate","outcomes","failures","outcome","createConnectionPool"],"mappings":";;;;;AAuEO,MAAMA;IACJ,QAAuB;IACvB,IAAe;IACf,WAAmB;IACnB,gBAAwB;IACxB,eAAwB;IACxB,SAAiB;IACjB,gBAAuC,KAAK;IAC5C,QAAgB;IAChB,gBAAsC,KAAK;IAC3C,wBAAwB,EAAE;IAC1B,kBAAqD,KAAK;IACjD,WAAoD;IAErE,YACCC,EAAa,EACbC,MAAqB,EACrBC,OAAe,EACfC,MAAc,EACdC,YAAqD,IAAI,CACxD;QACD,IAAI,CAAC,OAAO,GAAGH;QACf,IAAI,CAAC,GAAG,GAAGD;QACX,IAAI,CAAC,UAAU,GAAGK,KAAK,GAAG;QAC1B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,UAAU;QACtC,IAAI,CAAC,cAAc,GAAG;QACtB,IAAI,CAAC,QAAQ,GAAGH;QAChB,IAAI,CAAC,OAAO,GAAGC;QACf,IAAI,CAAC,UAAU,GAAGC;QAGlB,IAAI,CAAC,aAAa;IACnB;IAKA,IAAI,WAAoB;QACvB,OAAO,IAAI,CAAC,cAAc;IAC3B;IAKA,MAAM,QAAQE,KAA0B,EAA0B;QACjE,IAAI,CAAC,IAAI,CAAC,QAAQ,EACjB,MAAM,IAAIC,sBAAsB,IAAI,CAAC,GAAG;QAIzC,IAAI,CAAC,eAAe,GAAGF,KAAK,GAAG;QAG/B,IAAI,CAAC,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;IACtB;IAKA,YAAqB;QACpB,OAAO,CAAC,IAAI,CAAC,WAAW;IACzB;AACD;AAgBO,SAASoB,qBAAqB9B,OAAwB;IAC5D,OAAO,IAAIH,eAAeG;AAC3B"}
package/dist/schema.d.ts CHANGED
@@ -331,7 +331,7 @@ export declare const SequentialThinkingSchema: v.ObjectSchema<{
331
331
  readonly available_skills: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, undefined>, v.DescriptionAction<string[], "Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])">]>, undefined>;
332
332
  readonly thought: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.DescriptionAction<string, "Your current thinking step">]>;
333
333
  readonly id: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>, v.MaxLengthAction<string, 30, undefined>, v.DescriptionAction<string, "Unique identifier for this thought. Auto-generated if not provided.">]>, undefined>;
334
- readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether another thought step is needed (defaults to true if not provided)">]>, undefined>;
334
+ readonly next_thought_needed: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Omission defaults to true; the effective next action is returned in strategy_hint.">]>, undefined>;
335
335
  readonly thought_number: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Current thought number">]>;
336
336
  readonly total_thoughts: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.MinValueAction<number, 1, undefined>, v.DescriptionAction<number, "Estimated total thoughts needed">]>;
337
337
  readonly is_revision: v.OptionalSchema<v.SchemaWithPipe<readonly [v.BooleanSchema<undefined>, v.DescriptionAction<boolean, "Whether this revises previous thinking">]>, undefined>;
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["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M,MAAM,YAAY,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,wBAAwB,EAAE,IAItC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB;;;;;;;aAmB/B,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,cAAc,kWASW,CAAC;AAEvC;;GAEG;AACH,eAAO,MAAM,UAAU;;;;;;;;aAQmH,CAAC"}
package/dist/schema.js CHANGED
@@ -5,6 +5,8 @@ Each thought can build on, question, or revise previous insights as understandin
5
5
 
6
6
  IMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.
7
7
 
8
+ Each invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.
9
+
8
10
  When to use this tool:
9
11
  - Breaking down complex problems into steps
10
12
  - Planning and design with room for revision
@@ -42,7 +44,7 @@ Parameters explained:
42
44
  * Hypothesis generation
43
45
  * Hypothesis verification
44
46
  * Tool recommendations and rationale
45
- - next_thought_needed: True if you need more thinking, even if at what seemed like the end
47
+ - next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.
46
48
  - thought_number: Current number in sequence (can go beyond initial total if needed)
47
49
  - total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)
48
50
  - is_revision: A boolean indicating if this thought revises previous thinking
@@ -158,7 +160,7 @@ const SequentialThinkingSchema = __rspack_external_valibot.object({
158
160
  available_skills: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Array of skill names available for use (e.g., ["commit", "review-pr", "pdf"])'))),
159
161
  thought: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Your current thinking step')),
160
162
  id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(30), __rspack_external_valibot.description('Unique identifier for this thought. Auto-generated if not provided.'))),
161
- next_thought_needed: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether another thought step is needed (defaults to true if not provided)'))),
163
+ next_thought_needed: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Omission defaults to true; the effective next action is returned in strategy_hint.'))),
162
164
  thought_number: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Current thought number')),
163
165
  total_thoughts: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Estimated total thoughts needed')),
164
166
  is_revision: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether this revises previous thinking'))),
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description('Whether another thought step is needed (defaults to true if not provided)')\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call', 'tool_observation', 'assumption', 'decomposition', 'backtrack']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Name of the tool being invoked (for tool_call thoughts)'))),\n\ttool_arguments: v.optional(v.pipe(v.record(v.string(), v.unknown()), v.description('Arguments passed to the tool (for tool_call thoughts)'))),\n\ttool_result: v.optional(v.pipe(v.unknown(), v.description('Result returned by the tool (for tool_observation thoughts)'))),\n\tcontinuation_token: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Token for resuming long-running tool invocations'))),\n\tdecomposition_children: v.optional(v.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))),\n\tbacktrack_target: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description('Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'))),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<Omit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & { id: string; from: string; to: string; sessionId: string }>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSchema","SEQUENTIAL_THINKING_TOOL","JsonRpcRequestSchema","EdgeKindSchema","EdgeSchema"],"mappings":";AAyCA,MAAMA,mBAAmB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yHAwG+F,CAAC;AA0BnH,MAAMC,2BAA2BC,0BAAAA,MAAQ,CAAC;IAChD,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,WAAa,CAAC;IAC5C,YAAYA,0BAAAA,IAAM,CACjBA,0BAAAA,MAAQ,IACRA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,QAAU,CAAC,IACXA,0BAAAA,WAAa,CAAC;IAEf,WAAWA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,OAAOA,0BAAAA,WAAa,CAAC;IAC/D,UAAUA,0BAAAA,QAAU,CACnBA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,WAAa,CAAC;IAElC,kBAAkBA,0BAAAA,QAAU,CAC3BA,0BAAAA,IAAM,CACLA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,KAAO,CAAC;QAACA,0BAAAA,MAAQ;QAAIA,0BAAAA,MAAQ;QAAIA,0BAAAA,OAAS;QAAIA,yBAAAA,CAAAA,OAAM;KAAG,IAC5EA,0BAAAA,WAAa,CAAC;IAGhB,cAAcA,0BAAAA,QAAU,CACvBA,0BAAAA,IAAM,CAACA,0BAAAA,KAAO,CAACA,0BAAAA,MAAQ,KAAKA,0BAAAA,WAAa,CAAC;AAE5C;AA4BO,MAAMC,4BAA4BD,0BAAAA,MAAQ,CAAC;IACjD,YAAYA,0BAAAA,IAA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BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACrD,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMQ;IACN,WAAWR,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC;IAC1C,WAAWA,0BAAAA,MAAQ;IACnB,UAAUA,0BAAAA,QAAU,CAACA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
1
+ {"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\nimport type { Edge, EdgeKind } from './core/graph/Edge.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nEach invocation records exactly one authored thought and returns. When strategy_hint.action is continue, invoke this tool again with the next thought; do not stop or provide a final answer. terminate permits stopping. The server does not author later thoughts or call itself.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end. Omission defaults to true; the effective next action is in strategy_hint.\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call' (requires toolInterleave flag), 'tool_observation' (requires toolInterleave flag), 'assumption' (requires newThoughtTypes flag), 'decomposition' (requires newThoughtTypes flag), 'backtrack' (requires newThoughtTypes flag; logically retracts the thought referenced by backtrack_target - the target remains in history but is excluded from quality calculations)\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). Weights: type_diversity=0.3, verification_coverage=0.3, depth_efficiency=0.2, confidence_stability=0.2 (weighted geometric mean). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5, null when fewer than 2 confidence values)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Hints are prioritized: confidence_drift > unverified_hypothesis > no_alternatives_explored > consecutive_without_verification, so the most actionable patterns fill the cap first. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts after it), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (5+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.maxLength(2000), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(\n\t\t\tv.record(v.string(), v.union([v.string(), v.number(), v.boolean(), v.null()])),\n\t\t\tv.description('Optional suggested parameters (flat key-value pairs only)')\n\t\t)\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(30),\n\t\t\tv.description('Unique identifier for this thought. Auto-generated if not provided.')\n\t\t)\n\t),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'Omission defaults to true; the effective next action is returned in strategy_hint.'\n\t\t\t)\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta', 'tool_call', 'tool_observation', 'assumption', 'decomposition', 'backtrack']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular (default), hypothesis, verification, critique, synthesis, meta, tool_call (requires toolInterleave), tool_observation (requires toolInterleave), assumption (requires newThoughtTypes), decomposition (requires newThoughtTypes), backtrack (requires newThoughtTypes)'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tverification_result: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.literal(0), v.literal(1)]),\n\t\t\tv.description('Exact verification outcome label: 0 for incorrect, 1 for correct')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n\ttool_name: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Name of the tool being invoked (for tool_call thoughts)'))),\n\ttool_arguments: v.optional(v.pipe(v.record(v.string(), v.unknown()), v.description('Arguments passed to the tool (for tool_call thoughts)'))),\n\ttool_result: v.optional(v.pipe(v.unknown(), v.description('Result returned by the tool (for tool_observation thoughts)'))),\n\tcontinuation_token: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Token for resuming long-running tool invocations'))),\n\tdecomposition_children: v.optional(v.pipe(v.array(v.string()), v.description('Child thought IDs produced by decomposition'))),\n\tbacktrack_target: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.description('Thought number to backtrack to. When the parent thought has thought_type=backtrack, this thought is logically retracted: it remains in history but is excluded from quality signals and reasoning stats.'))),\n\tregister_branch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'register_branch_id must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description(\n\t\t\t\t'Pre-declares a branch ID for this session before any thoughts reference it. Useful so that subsequent thoughts using merge_branch_ids can target a branch that has not yet received any thoughts.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/** Inferred output type of the sequential thinking schema (string IDs, no branded types). */\nexport type SchemaOutput = v.InferOutput<typeof SequentialThinkingSchema>;\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.array(v.unknown()), v.record(v.string(), v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n\n/**\n * Schema for {@link EdgeKind} — the semantic relationship between two thoughts.\n */\nexport const EdgeKindSchema = v.union([\n\tv.literal('sequence'),\n\tv.literal('branch'),\n\tv.literal('merge'),\n\tv.literal('verifies'),\n\tv.literal('critiques'),\n\tv.literal('derives_from'),\n\tv.literal('tool_invocation'),\n\tv.literal('revises'),\n]) satisfies v.GenericSchema<EdgeKind>;\n\n/**\n * Schema for {@link Edge} — a directed edge in the thought DAG.\n */\nexport const EdgeSchema = v.object({\n\tid: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tfrom: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tto: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),\n\tkind: EdgeKindSchema,\n\tsessionId: v.pipe(v.string(), v.minLength(1)),\n\tcreatedAt: v.number(),\n\tmetadata: v.optional(v.record(v.string(), v.unknown())),\n}) satisfies v.GenericSchema<Omit<Edge, 'id' | 'from' | 'to' | 'sessionId'> & { id: string; from: string; to: string; sessionId: string }>;\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSch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A,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACrD,IAAIA,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC,IAAIA,0BAAAA,SAAW,CAAC;IACnD,MAAMQ;IACN,WAAWR,0BAAAA,IAAM,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,SAAW,CAAC;IAC1C,WAAWA,0BAAAA,MAAQ;IACnB,UAAUA,0BAAAA,QAAU,CAACA,0BAAAA,MAAQ,CAACA,0BAAAA,MAAQ,IAAIA,0BAAAA,OAAS;AACpD"}
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Centralizes JSON-RPC response formatting, request body reading,
5
5
  * and common HTTP response patterns to eliminate duplication across
6
- * HttpTransport, StreamableHttpTransport, and SseTransport.
6
+ * HttpTransport and StreamableHttpTransport.
7
7
  *
8
8
  * @module transport/HttpHelpers
9
9
  */