tracelattice 1.3.3 → 1.3.4

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 (83) hide show
  1. package/dist/ServerConfig.d.ts +14 -0
  2. package/dist/ServerConfig.d.ts.map +1 -1
  3. package/dist/ServerConfig.js +12 -1
  4. package/dist/ServerConfig.js.map +1 -1
  5. package/dist/__tests__/core/HistoryManager.ownership.test.d.ts +2 -0
  6. package/dist/__tests__/core/HistoryManager.ownership.test.d.ts.map +1 -0
  7. package/dist/__tests__/core/SessionLock.test.d.ts +6 -0
  8. package/dist/__tests__/core/SessionLock.test.d.ts.map +1 -0
  9. package/dist/__tests__/core/SessionManager.test.d.ts +8 -0
  10. package/dist/__tests__/core/SessionManager.test.d.ts.map +1 -0
  11. package/dist/__tests__/core/ThoughtProcessor.toolAllowlist.test.d.ts +2 -0
  12. package/dist/__tests__/core/ThoughtProcessor.toolAllowlist.test.d.ts.map +1 -0
  13. package/dist/__tests__/helpers/factories.d.ts +7 -0
  14. package/dist/__tests__/helpers/factories.d.ts.map +1 -1
  15. package/dist/__tests__/sanitize.enforceJsonShape.test.d.ts +2 -0
  16. package/dist/__tests__/sanitize.enforceJsonShape.test.d.ts.map +1 -0
  17. package/dist/__tests__/transport-owner-context.test.d.ts +8 -0
  18. package/dist/__tests__/transport-owner-context.test.d.ts.map +1 -0
  19. package/dist/cli.js +176 -57
  20. package/dist/config/ConfigLoader.d.ts +7 -0
  21. package/dist/config/ConfigLoader.d.ts.map +1 -1
  22. package/dist/config/ConfigLoader.js +6 -1
  23. package/dist/config/ConfigLoader.js.map +1 -1
  24. package/dist/context/RequestContext.d.ts +26 -0
  25. package/dist/context/RequestContext.d.ts.map +1 -1
  26. package/dist/context/RequestContext.js +7 -1
  27. package/dist/context/RequestContext.js.map +1 -1
  28. package/dist/contracts/features.d.ts +2 -2
  29. package/dist/contracts/features.js.map +1 -1
  30. package/dist/contracts/interfaces.d.ts +42 -0
  31. package/dist/contracts/interfaces.d.ts.map +1 -1
  32. package/dist/core/HistoryManager.d.ts +13 -1
  33. package/dist/core/HistoryManager.d.ts.map +1 -1
  34. package/dist/core/HistoryManager.js +25 -14
  35. package/dist/core/HistoryManager.js.map +1 -1
  36. package/dist/core/InputNormalizer.d.ts.map +1 -1
  37. package/dist/core/InputNormalizer.js +5 -2
  38. package/dist/core/InputNormalizer.js.map +1 -1
  39. package/dist/core/SessionLock.d.ts +56 -0
  40. package/dist/core/SessionLock.d.ts.map +1 -0
  41. package/dist/core/SessionLock.js +43 -0
  42. package/dist/core/SessionLock.js.map +1 -0
  43. package/dist/core/SessionManager.d.ts +18 -3
  44. package/dist/core/SessionManager.d.ts.map +1 -1
  45. package/dist/core/SessionManager.js +34 -1
  46. package/dist/core/SessionManager.js.map +1 -1
  47. package/dist/core/ThoughtProcessor.d.ts +21 -2
  48. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  49. package/dist/core/ThoughtProcessor.js +33 -13
  50. package/dist/core/ThoughtProcessor.js.map +1 -1
  51. package/dist/di/ServiceRegistry.d.ts +3 -3
  52. package/dist/di/ServiceRegistry.d.ts.map +1 -1
  53. package/dist/errors.d.ts +48 -0
  54. package/dist/errors.d.ts.map +1 -1
  55. package/dist/errors.js +38 -2
  56. package/dist/errors.js.map +1 -1
  57. package/dist/lib.d.ts.map +1 -1
  58. package/dist/lib.js +9 -3
  59. package/dist/lib.js.map +1 -1
  60. package/dist/registry/ToolRegistry.d.ts +1 -0
  61. package/dist/registry/ToolRegistry.d.ts.map +1 -1
  62. package/dist/registry/ToolRegistry.js +3 -0
  63. package/dist/registry/ToolRegistry.js.map +1 -1
  64. package/dist/sanitize.d.ts +70 -0
  65. package/dist/sanitize.d.ts.map +1 -1
  66. package/dist/sanitize.js +77 -1
  67. package/dist/sanitize.js.map +1 -1
  68. package/dist/schema.d.ts +35 -35
  69. package/dist/schema.d.ts.map +1 -1
  70. package/dist/schema.js +15 -5
  71. package/dist/schema.js.map +1 -1
  72. package/dist/transport/HttpTransport.d.ts.map +1 -1
  73. package/dist/transport/HttpTransport.js +9 -3
  74. package/dist/transport/HttpTransport.js.map +1 -1
  75. package/dist/transport/SseTransport.d.ts.map +1 -1
  76. package/dist/transport/SseTransport.js +10 -3
  77. package/dist/transport/SseTransport.js.map +1 -1
  78. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
  79. package/dist/transport/StreamableHttpTransport.js +8 -3
  80. package/dist/transport/StreamableHttpTransport.js.map +1 -1
  81. package/dist/types/tool.d.ts +1 -1
  82. package/dist/types/tool.d.ts.map +1 -1
  83. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceRegistry.d.ts","sourceRoot":"","sources":["../../src/di/ServiceRegistry.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAE7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACtE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,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AAC;IACrB,iBAAiB,EAAE,kBAAkB,CAAC;IACtC,eAAe,EAAE,gBAAgB,CAAC;IAClC,UAAU,EAAE,WAAW,CAAC;IACxB,YAAY,EAAE,aAAa,CAAC;IAC5B,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,eAAe,EAAE,gBAAgB,CAAC;IAClC,WAAW,EAAE,YAAY,CAAC;CAC1B;AAED,MAAM,MAAM,UAAU,GAAG,MAAM,eAAe,CAAC"}
package/dist/errors.d.ts CHANGED
@@ -51,8 +51,19 @@ export declare const ERROR_CODES: {
51
51
  readonly INVALID_TOOL_CALL: "INVALID_TOOL_CALL";
52
52
  readonly INVALID_BACKTRACK: "INVALID_BACKTRACK";
53
53
  readonly DUPLICATE_SUMMARY: "DUPLICATE_SUMMARY";
54
+ readonly UNKNOWN_TOOL: "UNKNOWN_TOOL";
55
+ readonly LOCK_TIMEOUT: "LOCK_TIMEOUT";
56
+ readonly SESSION_ACCESS_DENIED: "SESSION_ACCESS_DENIED";
54
57
  };
55
58
  export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
59
+ /**
60
+ * All known warning codes as a const object.
61
+ * Warnings are non-fatal advisory signals returned alongside successful results.
62
+ */
63
+ export declare const WARNING_CODES: {
64
+ readonly TOTAL_THOUGHTS_ADJUSTED: "TOTAL_THOUGHTS_ADJUSTED";
65
+ };
66
+ export type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];
56
67
  /**
57
68
  * Base error class for all Sequential Thinking server errors.
58
69
  *
@@ -605,6 +616,43 @@ export declare class InvalidToolCallError extends SequentialThinkingError {
605
616
  export declare class InvalidBacktrackError extends SequentialThinkingError {
606
617
  constructor(message: string);
607
618
  }
619
+ /**
620
+ * Error thrown when a tool_call references a tool not registered with the server.
621
+ *
622
+ * Acts as an allowlist gate: only tools registered in the ToolRegistry may be
623
+ * invoked through tool interleave. Prevents arbitrary tool name injection.
624
+ */
625
+ export declare class UnknownToolError extends SequentialThinkingError {
626
+ readonly toolName: string;
627
+ constructor(toolName: string, message?: string);
628
+ }
629
+ /**
630
+ * Error thrown when a per-session async lock cannot be acquired in time.
631
+ *
632
+ * Indicates that a critical section held the lock for longer than the
633
+ * configured timeout, suggesting a stuck handler or deadlock.
634
+ */
635
+ export declare class LockTimeoutError extends SequentialThinkingError {
636
+ readonly sessionId: string;
637
+ readonly timeoutMs: number;
638
+ constructor(sessionId: string, timeoutMs: number);
639
+ }
640
+ /**
641
+ * Error thrown when a session is accessed by a non-owner.
642
+ *
643
+ * Sessions are bound to an owner identifier on first creation when accessed
644
+ * via a multi-user transport (SSE/HTTP). Subsequent access attempts using a
645
+ * different owner are rejected to prevent IDOR (Insecure Direct Object
646
+ * Reference) vulnerabilities.
647
+ *
648
+ * The stdio transport does not set an owner, so its sessions are unaffected.
649
+ */
650
+ export declare class SessionAccessDeniedError extends SequentialThinkingError {
651
+ readonly sessionId: string;
652
+ readonly expectedOwner: string;
653
+ readonly actualOwner: string | undefined;
654
+ constructor(sessionId: string, expectedOwner: string, actualOwner?: string);
655
+ }
608
656
  /**
609
657
  * Type guard to check if an error has a specific error code.
610
658
  */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;GAEG;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;CAuBd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,sDAAsD;IACtD,SAAgB,IAAI,EAAE,SAAS,CAAC;IAEhC;;;;;;;;;;;;;;OAcG;gBACS,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS;CAM5C;AAED,qBAAa,kBAAmB,SAAQ,u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AS,EAAE,MAAM,CAAC;IAClC,SAAgB,SAAS,EAAE,MAAM,CAAC;gBAEtB,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAShD;AAED;;;;;;;;;GASG;AACH,qBAAa,wBAAyB,SAAQ,uBAAuB;IACpE,SAAgB,SAAS,EAAE,MAAM,CAAC;IAClC,SAAgB,aAAa,EAAE,MAAM,CAAC;IACtC,SAAgB,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;gBAEpC,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM;CAU1E;AAGD;;GAEG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAC9C,GAAG,EAAE,OAAO,EACZ,IAAI,EAAE,CAAC,GACL,GAAG,IAAI,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;CAAE,CAEvD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEtD"}
package/dist/errors.js CHANGED
@@ -20,7 +20,13 @@ const ERROR_CODES = {
20
20
  SUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',
21
21
  INVALID_TOOL_CALL: 'INVALID_TOOL_CALL',
22
22
  INVALID_BACKTRACK: 'INVALID_BACKTRACK',
23
- DUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY'
23
+ DUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',
24
+ UNKNOWN_TOOL: 'UNKNOWN_TOOL',
25
+ LOCK_TIMEOUT: 'LOCK_TIMEOUT',
26
+ SESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED'
27
+ };
28
+ const WARNING_CODES = {
29
+ TOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED'
24
30
  };
25
31
  class SequentialThinkingError extends Error {
26
32
  code;
@@ -163,12 +169,42 @@ class InvalidBacktrackError extends SequentialThinkingError {
163
169
  this.name = 'InvalidBacktrackError';
164
170
  }
165
171
  }
172
+ class UnknownToolError extends SequentialThinkingError {
173
+ toolName;
174
+ constructor(toolName, message){
175
+ super(message ?? `Unknown tool '${toolName}': not registered with the server`, ERROR_CODES.UNKNOWN_TOOL);
176
+ this.name = 'UnknownToolError';
177
+ this.toolName = toolName;
178
+ }
179
+ }
180
+ class LockTimeoutError extends SequentialThinkingError {
181
+ sessionId;
182
+ timeoutMs;
183
+ constructor(sessionId, timeoutMs){
184
+ super(`Lock timeout for session '${sessionId}' after ${timeoutMs}ms`, ERROR_CODES.LOCK_TIMEOUT);
185
+ this.name = 'LockTimeoutError';
186
+ this.sessionId = sessionId;
187
+ this.timeoutMs = timeoutMs;
188
+ }
189
+ }
190
+ class SessionAccessDeniedError extends SequentialThinkingError {
191
+ sessionId;
192
+ expectedOwner;
193
+ actualOwner;
194
+ constructor(sessionId, expectedOwner, actualOwner){
195
+ super(`Access denied to session '${sessionId}': owned by '${expectedOwner}', accessed by '${actualOwner ?? 'anonymous'}'`, ERROR_CODES.SESSION_ACCESS_DENIED);
196
+ this.name = 'SessionAccessDeniedError';
197
+ this.sessionId = sessionId;
198
+ this.expectedOwner = expectedOwner;
199
+ this.actualOwner = actualOwner;
200
+ }
201
+ }
166
202
  function isErrorCode(err, code) {
167
203
  return err instanceof SequentialThinkingError && err.code === code;
168
204
  }
169
205
  function getErrorMessage(error) {
170
206
  return error instanceof Error ? error.message : String(error);
171
207
  }
172
- export { ConfigurationError, CycleDetectedError, DuplicateSkillError, DuplicateToolError, ERROR_CODES, HistoryLimitExceededError, InvalidBacktrackError, InvalidEdgeError, InvalidSkillError, InvalidThoughtError, InvalidToolCallError, InvalidToolError, MaxSessionsReachedError, PoolTerminatedError, SequentialThinkingError, SessionNotActiveError, SessionNotFoundError, SkillDiscoveryError, SkillNotFoundError, SuspensionExpiredError, SuspensionNotFoundError, ToolNotFoundError, ValidationError, getErrorMessage, isErrorCode };
208
+ export { ConfigurationError, CycleDetectedError, DuplicateSkillError, DuplicateToolError, ERROR_CODES, HistoryLimitExceededError, InvalidBacktrackError, InvalidEdgeError, InvalidSkillError, InvalidThoughtError, InvalidToolCallError, InvalidToolError, LockTimeoutError, MaxSessionsReachedError, PoolTerminatedError, SequentialThinkingError, SessionAccessDeniedError, SessionNotActiveError, SessionNotFoundError, SkillDiscoveryError, SkillNotFoundError, SuspensionExpiredError, SuspensionNotFoundError, ToolNotFoundError, UnknownToolError, ValidationError, WARNING_CODES, getErrorMessage, isErrorCode };
173
209
 
174
210
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.getTool('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.getSkill('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED,\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(`History size ${currentSize} exceeds limit ${maxSize}`, ERROR_CODES.HISTORY_LIMIT_EXCEEDED);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.hasSkill(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.hasTool(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when attempting to process a session that is not active.\n *\n * This error is thrown when trying to use a session that has been closed\n * or deactivated.\n *\n * @example\n * ```typescript\n * if (!session.isActive) {\n * throw new SessionNotActiveError(sessionId);\n * }\n * ```\n */\nexport class SessionNotActiveError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SessionNotActiveError.\n\t *\n\t * @param sessionId - The ID of the inactive session\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SessionNotActiveError('session-123');\n\t * // Error: Session 'session-123' is not active\n\t * // Code: SESSION_NOT_ACTIVE\n\t * ```\n\t */\n\tconstructor(sessionId: string) {\n\t\tsuper(`Session '${sessionId}' is not active`, ERROR_CODES.SESSION_NOT_ACTIVE);\n\t\tthis.name = 'SessionNotActiveError';\n\t}\n}\n\n/**\n * Error thrown when a requested session is not found in the pool.\n *\n * This error is thrown when attempting to retrieve, process, or close\n * a session that doesn't exist in the session pool.\n *\n * @example\n * ```typescript\n * const session = pool.getSession('non-existent-session');\n * if (!session) {\n * throw new SessionNotFoundError('non-existent-session');\n * }\n * ```\n */\nexport class SessionNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SessionNotFoundError.\n\t *\n\t * @param sessionId - The ID of the session that was not found\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SessionNotFoundError('session-123');\n\t * // Error: Session not found: session-123\n\t * // Code: SESSION_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(sessionId: string) {\n\t\tsuper(`Session not found: ${sessionId}`, ERROR_CODES.SESSION_NOT_FOUND);\n\t\tthis.name = 'SessionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED,\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C,\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","SessionNotActiveError","sessionId","SessionNotFoundError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,wBAAwB;IACxB,wBAAwB;IACxB,iBAAiB;IACjB,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,oBAAoB;IACpB,mBAAmB;IACnB,sBAAsB;IACtB,iBAAiB;IACjB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,sBAAsB;IACtB,oBAAoB;IACpB,m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AAI,CAAC,IAAI,GAAG;IACb;AACD;AAQO,MAAMqC,8BAA8BpC;IAC1C,YAAYE,OAAe,CAAE;QAC5B,KAAK,CAACA,SAASH,YAAY,iBAAiB;QAC5C,IAAI,CAAC,IAAI,GAAG;IACb;AACD;AAKO,SAASsC,YACfC,GAAY,EACZnC,IAAO;IAEP,OAAOmC,eAAetC,2BAA2BsC,IAAI,IAAI,KAAKnC;AAC/D;AAoBO,SAASoC,gBAAgBC,KAAc;IAC7C,OAAOA,iBAAiBvC,QAAQuC,MAAM,OAAO,GAAGC,OAAOD;AACxD"}
1
+ {"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n\tUNKNOWN_TOOL: 'UNKNOWN_TOOL',\n\tLOCK_TIMEOUT: 'LOCK_TIMEOUT',\n\tSESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * All known warning codes as a const object.\n * Warnings are non-fatal advisory signals returned alongside successful results.\n */\nexport const WARNING_CODES = {\n\tTOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED',\n} as const;\n\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.getTool('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.getSkill('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED,\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(`History size ${currentSize} exceeds limit ${maxSize}`, ERROR_CODES.HISTORY_LIMIT_EXCEEDED);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.hasSkill(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.hasTool(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when attempting to process a session that is not active.\n *\n * This error is thrown when trying to use a session that has been closed\n * or deactivated.\n *\n * @example\n * ```typescript\n * if (!session.isActive) {\n * throw new SessionNotActiveError(sessionId);\n * }\n * ```\n */\nexport class SessionNotActiveError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SessionNotActiveError.\n\t *\n\t * @param sessionId - The ID of the inactive session\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SessionNotActiveError('session-123');\n\t * // Error: Session 'session-123' is not active\n\t * // Code: SESSION_NOT_ACTIVE\n\t * ```\n\t */\n\tconstructor(sessionId: string) {\n\t\tsuper(`Session '${sessionId}' is not active`, ERROR_CODES.SESSION_NOT_ACTIVE);\n\t\tthis.name = 'SessionNotActiveError';\n\t}\n}\n\n/**\n * Error thrown when a requested session is not found in the pool.\n *\n * This error is thrown when attempting to retrieve, process, or close\n * a session that doesn't exist in the session pool.\n *\n * @example\n * ```typescript\n * const session = pool.getSession('non-existent-session');\n * if (!session) {\n * throw new SessionNotFoundError('non-existent-session');\n * }\n * ```\n */\nexport class SessionNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SessionNotFoundError.\n\t *\n\t * @param sessionId - The ID of the session that was not found\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SessionNotFoundError('session-123');\n\t * // Error: Session not found: session-123\n\t * // Code: SESSION_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(sessionId: string) {\n\t\tsuper(`Session not found: ${sessionId}`, ERROR_CODES.SESSION_NOT_FOUND);\n\t\tthis.name = 'SessionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED,\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Error thrown when a tool_call references a tool not registered with the server.\n *\n * Acts as an allowlist gate: only tools registered in the ToolRegistry may be\n * invoked through tool interleave. Prevents arbitrary tool name injection.\n */\nexport class UnknownToolError extends SequentialThinkingError {\n\tpublic readonly toolName: string;\n\n\tconstructor(toolName: string, message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? `Unknown tool '${toolName}': not registered with the server`,\n\t\t\tERROR_CODES.UNKNOWN_TOOL\n\t\t);\n\t\tthis.name = 'UnknownToolError';\n\t\tthis.toolName = toolName;\n\t}\n}\n\n/**\n * Error thrown when a per-session async lock cannot be acquired in time.\n *\n * Indicates that a critical section held the lock for longer than the\n * configured timeout, suggesting a stuck handler or deadlock.\n */\nexport class LockTimeoutError extends SequentialThinkingError {\n\tpublic readonly sessionId: string;\n\tpublic readonly timeoutMs: number;\n\n\tconstructor(sessionId: string, timeoutMs: number) {\n\t\tsuper(\n\t\t\t`Lock timeout for session '${sessionId}' after ${timeoutMs}ms`,\n\t\t\tERROR_CODES.LOCK_TIMEOUT,\n\t\t);\n\t\tthis.name = 'LockTimeoutError';\n\t\tthis.sessionId = sessionId;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\n/**\n * Error thrown when a session is accessed by a non-owner.\n *\n * Sessions are bound to an owner identifier on first creation when accessed\n * via a multi-user transport (SSE/HTTP). Subsequent access attempts using a\n * different owner are rejected to prevent IDOR (Insecure Direct Object\n * Reference) vulnerabilities.\n *\n * The stdio transport does not set an owner, so its sessions are unaffected.\n */\nexport class SessionAccessDeniedError extends SequentialThinkingError {\n\tpublic readonly sessionId: string;\n\tpublic readonly expectedOwner: string;\n\tpublic readonly actualOwner: string | undefined;\n\n\tconstructor(sessionId: string, expectedOwner: string, actualOwner?: string) {\n\t\tsuper(\n\t\t\t`Access denied to session '${sessionId}': owned by '${expectedOwner}', accessed by '${actualOwner ?? 'anonymous'}'`,\n\t\t\tERROR_CODES.SESSION_ACCESS_DENIED,\n\t\t);\n\t\tthis.name = 'SessionAccessDeniedError';\n\t\tthis.sessionId = sessionId;\n\t\tthis.expectedOwner = expectedOwner;\n\t\tthis.actualOwner = actualOwner;\n\t}\n}\n\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C,\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","WARNING_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","SessionNotActiveError","sessionId","SessionNotFoundError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","UnknownToolError","LockTimeoutError","timeoutMs","SessionAccessDeniedError","expectedOwner","actualOwner","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,wBAAwB;IACxB,wBAAwB;IACxB,iBAAiB;IACjB,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,oBAAoB;IACpB,mBAAmB;IACnB,sBAAsB;IACtB,iBAAiB;IACjB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,sBAAsB;IACtB,oBAAoB;IACpB,mBAAmB;IACnB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;IACd,cAAc;IACd,uBAAuB;AACxB;AAQO,MAAMC,gBAAgB;IAC5B,yBAAyB;AAC1B;AA+BO,MAAMC,gCAAgCC;IAE5B,KAAgB;IAiBhC,YAAYC,OAAe,EAAEC,IAAe,CAAE;QAC7C,KAAK,CAACD;QACN,IAAI,CAAC,IAAI,GAAGC;QACZ,IAAI,CAAC,IAAI,GAAG;QACZF,MAAM,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW;IAC/C;AACD;AAEO,MAAMG,2BAA2BJ;IACvC,YAAYE,OAAe,CAAE;QAC5B,KAAK,CAACA,SAASJ,YAAY,mBAAmB;QAC9C,IAAI,CAAC,IAAI,GAAG;IACb;AACD;AAgBO,MAAMO,0BAA0BL;IAiBtC,YAAYM,QAAgB,EAAEC,MAAe,CAAE;QAC9C,MAAML,UAAUK,SACb,CAAC,MAAM,EAAED,SAAS,oBAAoB,EAAEC,QAAQ,GAChD,CAAC,MAAM,EAAED,SAAS,WAAW,CAAC;QACjC,KAAK,CAACJ,SAASJ,YAAY,cAAc;QACzC,IAAI,CAAC,IAAI,GAAG;IACb;AACD;AAgBO,MAAMU,2BAA2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mBAAmB,IAAI,OAAO,CAAC,MAAM,CAAC;IAKnD;;;OAGG;IACI,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC;IAKtC,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,wBAAwB,CAAC;IAuBzE,kBAAkB,IAAI,MAAM;IAInC;;;OAGG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAyClC;;;OAGG;IACI,KAAK,IAAI,IAAI;IAKpB;;;;OAIG;IACU,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAKrC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,YAAY,CACjC,OAAO,GAAE,aAAkB,GACzB,OAAO,CAAC,iCAAiC,CAAC,CAE5C;AAGD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,iCAAiC,CAAC,CAmBnF"}
package/dist/lib.js CHANGED
@@ -14,6 +14,7 @@ import { OutcomeRecorder } from "./core/reasoning/OutcomeRecorder.js";
14
14
  import { createReasoningStrategy } from "./core/reasoning/strategies/StrategyFactory.js";
15
15
  import { ThoughtFormatter } from "./core/ThoughtFormatter.js";
16
16
  import { ThoughtProcessor } from "./core/ThoughtProcessor.js";
17
+ import { SessionLock } from "./core/SessionLock.js";
17
18
  import { Container } from "./di/Container.js";
18
19
  import { StructuredLogger } from "./logger/StructuredLogger.js";
19
20
  import { Metrics } from "./metrics/metrics.impl.js";
@@ -83,7 +84,8 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
83
84
  maxBranchSize: options.maxBranchSize ?? fileConfig?.maxBranchSize,
84
85
  skillDirs: fileConfig?.skillDirs,
85
86
  discoveryCache: fileConfig?.discoveryCache,
86
- persistence: fileConfig?.persistence
87
+ persistence: fileConfig?.persistence,
88
+ maxSessionsPerOwner: fileConfig?.maxSessionsPerOwner
87
89
  });
88
90
  const logger = options.logger ?? new StructuredLogger({
89
91
  level: fileConfig?.logLevel ?? 'info',
@@ -135,6 +137,7 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
135
137
  });
136
138
  });
137
139
  container.register('reasoningStrategy', ()=>createReasoningStrategy(config.features.reasoningStrategy));
140
+ container.register('sessionLock', ()=>new SessionLock());
138
141
  container.register('HistoryManager', ()=>{
139
142
  const cfg = container.resolve('Config');
140
143
  const log = container.resolve('Logger');
@@ -151,7 +154,8 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
151
154
  persistenceBufferSize: cfg.persistenceBufferSize,
152
155
  persistenceFlushInterval: cfg.persistenceFlushInterval,
153
156
  persistenceMaxRetries: cfg.persistenceMaxRetries,
154
- edgeStore
157
+ edgeStore,
158
+ maxSessionsPerOwner: cfg.maxSessionsPerOwner
155
159
  });
156
160
  });
157
161
  container.registerFactory('ThoughtFormatter', ()=>new ThoughtFormatter());
@@ -168,7 +172,9 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
168
172
  const strategy = container.resolve('reasoningStrategy');
169
173
  const compressionService = config.features.compression ? container.resolve('compressionService') : void 0;
170
174
  const suspensionStore = config.features.toolInterleave ? container.resolve('suspensionStore') : void 0;
171
- return new ThoughtProcessor(history, formatter, evaluator, log, strategy, compressionService, suspensionStore, config.features);
175
+ const toolRegistry = container.resolve('ToolRegistry');
176
+ const sessionLock = container.resolve('sessionLock');
177
+ return new ThoughtProcessor(history, formatter, evaluator, log, strategy, compressionService, suspensionStore, toolRegistry, config.features, sessionLock);
172
178
  });
173
179
  return container;
174
180
  }
package/dist/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport * as v from 'valibot';\nimport { ThoughtData } from './core/thought.js';\nimport { SEQUENTIAL_THINKING_TOOL, SequentialThinkingSchema } from './schema.js';\nimport { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport type { ISummaryStore } from './contracts/summary.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport type { ISuspensionStore } from './contracts/suspension.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport type { SseTransportOptions } from './transport/SseTransport.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport type { IReasoningStrategy } from './contracts/strategy.js';\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Enable automatic skill discovery on server startup\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup)\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n\t/**\n\t * Transport type to use\n\t * @default 'stdio'\n\t */\n\ttransport?: 'stdio' | 'sse';\n\t/**\n\t * SSE transport options (used when transport: 'sse')\n\t */\n\tsseTransportOptions?: SseTransportOptions;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/**\n\t * Get all branches from the history manager.\n\t *\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/**\n\t * Clear all server state (history, tools, skills).\n\t */\n\tclear(): void;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer extends EventEmitter implements IToolAwareSequentialThinkingServer {\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\t// Create the async container first\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\n\t\t// Create a minimal server with the container\n\t\tconst server = new ToolAwareSequentialThinkingServer({\n\t\t\t...options,\n\t\t\tcontainer,\n\t\t});\n\n\t\t// Load from persistence if enabled (default: true)\n\t\tif (options.loadFromPersistence !== false) {\n\t\t\tawait server.history.loadFromPersistence();\n\t\t}\n\n\t\t// Perform async discovery if enabled (default: true)\n\t\tif (options.autoDiscover !== false) {\n\t\t\tawait server.discoverSkillsAsync();\n\t\t}\n\n\t\treturn server;\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory();\n\t * server.history.clear();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.addTool(tool);\n\t * server.tools.getTool('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.addSkill(skill);\n\t * server.skills.getSkill('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve<StructuredLogger>('Logger');\n\t\tthis._historyManager = this._container.resolve<HistoryManager>('HistoryManager');\n\t\tthis._thoughtProcessor = this._container.resolve<ThoughtProcessor>('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve<Metrics>('Metrics');\n\t\tthis._config = this._container.resolve<ServerConfig>('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve<ToolRegistry>('ToolRegistry');\n\t\tthis.skills = this._container.resolve<SkillRegistry>('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.addTool(SEQUENTIAL_THINKING_TOOL);\n\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\t// Initialize config with file defaults overridden by constructor options\n\t\tconst config = new ServerConfig({\n\t\t\tmaxHistorySize: options.maxHistorySize ?? fileConfig?.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? fileConfig?.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? fileConfig?.maxBranchSize,\n\t\t\tskillDirs: fileConfig?.skillDirs,\n\t\t\tdiscoveryCache: fileConfig?.discoveryCache,\n\t\t\tpersistence: fileConfig?.persistence,\n\t\t});\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t\t\t})\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve<HistoryManager>('HistoryManager');\n\t\t\tconst edgeStore = container.resolve<EdgeStore>('EdgeStore');\n\t\t\tconst summaryStore = container.resolve<ISummaryStore>('summaryStore');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\treturn new CompressionService({ historyManager, edgeStore, summaryStore, logger: log });\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy),\n\t\t);\n\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve<ServerConfig>('Config');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\tconst pers = container.resolve('Persistence') as PersistenceBackend | null;\n\t\t\tconst componentMetrics = container.resolve<Metrics>('Metrics');\n\t\t\tconst edgeStore = container.resolve<EdgeStore>('EdgeStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tedgeStore,\n\t\t\t});\n\t\t});\n\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false }),\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(\n\t\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\t\tconfig.features.calibration ?? false,\n\t\t\t\t),\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator')),\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve<HistoryManager>('HistoryManager');\n\t\t\tconst formatter = container.resolve<ThoughtFormatter>('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve<ThoughtEvaluator>('ThoughtEvaluator');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\tconst strategy = container.resolve<IReasoningStrategy>('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve<CompressionService>('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve<ISuspensionStore>('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\tconfig.features,\n\t\t\t);\n\t\t});\n\n\t\treturn container;\n\t}\n\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tconst configLoader = new ConfigLoader();\n\t\tconst fileConfig = configLoader.load();\n\n\t\t// Initialize persistence backend (async)\n\t\tconst persistence = await createPersistenceBackend(\n\t\t\tfileConfig?.persistence ?? { enabled: false }\n\t\t);\n\n\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(options, fileConfig, persistence);\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/**\n\t * Get all branches from the history manager\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(): Record<string, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches();\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst thoughtInput = input as ThoughtData & { register_branch_id?: string };\n\t\tif (typeof thoughtInput.register_branch_id === 'string' && thoughtInput.register_branch_id.length > 0) {\n\t\t\ttry {\n\t\t\t\tthis._historyManager.registerBranch(\n\t\t\t\t\tthoughtInput.session_id,\n\t\t\t\t\tthoughtInput.register_branch_id\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.warn('registerBranch skipped', {\n\t\t\t\t\tbranch_id: thoughtInput.register_branch_id,\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t});\n\t\t\t}\n\t\t\tdelete thoughtInput.register_branch_id;\n\t\t}\n\t\tconst result = await this._thoughtProcessor.process(thoughtInput);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tthis._skillWatcher?.stop();\n\t\tthis._toolWatcher?.stop();\n\n\t\t// Stop suspension store sweeper if registered\n\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\ttry {\n\t\t\t\tconst suspensionStore = this._container.resolve<ISuspensionStore>('suspensionStore');\n\t\t\t\tsuspensionStore.stop();\n\t\t\t} catch (error) {\n\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush any buffered writes before closing persistence\n\t\ttry {\n\t\t\tawait this._historyManager.shutdown();\n\t\t} catch (error) {\n\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Close persistence backend if available\n\t\tconst persistence = this._container.resolve<PersistenceBackend | null>('Persistence');\n\t\tif (persistence) {\n\t\t\ttry {\n\t\t\t\tawait persistence.close();\n\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t} catch (error) {\n\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t}\n\n\t/**\n\t * Clear all server state (history, tools, skills)\n\t * Useful for testing to reset state between tests\n\t */\n\tpublic clear(): void {\n\t\tthis._historyManager.clear();\n\t\tthis._logger.info('Server state cleared');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tawait this.stop();\n\t\tawait this._container.dispose();\n\t\tthis._logger.info('Server disposed, all resources released');\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n *\n * // With custom container for testing\n * const mockContainer = new Container();\n * mockContainer.registerInstance('Logger', mockLogger);\n * const server = await createServer({ container: mockContainer });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load();\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig?.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","persistence","Container","metrics","Metrics","config","ServerConfig","logger","StructuredLogger","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","createReasoningStrategy","cfg","pers","componentMetrics","HistoryManager","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","ThoughtProcessor","configLoader","ConfigLoader","createPersistenceBackend","discovered","input","startTime","Date","thoughtInput","err","String","result","durationSeconds","error","getErrorMessage","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2JO,MAAMA,0CAA0CC;IAQtD,aAAa,OAAOC,UAAyB,CAAC,CAAC,EAA8C;QAE5F,MAAMC,YAAY,MAAMH,kCAAkC,2BAA2B,CAACE;QAGtF,MAAME,SAAS,IAAIJ,kCAAkC;YACpD,GAAGE,OAAO;YACVC;QACD;QAGA,IAAID,AAAgC,UAAhCA,QAAQ,mBAAmB,EAC9B,MAAME,OAAO,OAAO,CAAC,mBAAmB;QAIzC,IAAIF,AAAyB,UAAzBA,QAAQ,YAAY,EACvB,MAAME,OAAO,mBAAmB;QAGjC,OAAOA;IACR;IAGS,KAAmCC,KAAQ,EAAEC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OAAOC,gBAAgBD;YACxB;QACD;QAGA,MAAMjD,cAAc,IAAI,CAAC,UAAU,CAAC,OAAO,CAA4B;QACvE,IAAIA,aACH,IAAI;YACH,MAAMA,YAAY,KAAK;YACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QACnB,EAAE,OAAOiD,OAAO;YACf,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,qCAAqC;gBACvD,OAAOC,gBAAgBD;YACxB;QACD;QAGD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACnB;IAMO,QAAc;QACpB,IAAI,CAAC,eAAe,CAAC,KAAK;QAC1B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACnB;IAOA,MAAa,UAAyB;QACrC,MAAM,IAAI,CAAC,IAAI;QACf,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO;QAC7B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IACnB;AACD;AA8BO,eAAeE,aACrB9D,UAAyB,CAAC,CAAC;IAE3B,OAAOF,kCAAkC,MAAM,CAACE;AACjD;AAGO,eAAe+D;IAErB,MAAMf,eAAe,IAAIC;IACzB,MAAMvC,aAAasC,aAAa,IAAI;IAEpC,MAAM/B,SAAS,IAAIC,iBAAiB;QACnC,OAAOR,YAAY,YAAY;QAC/B,SAAS;QACT,QAAQA,YAAY,aAAa;IAClC;IAGA,MAAMsD,iBAAiB,MAAMF,aAAa;QACzC7C;QACA,eAAe;IAChB;IAEAA,OAAO,IAAI,CAAC;IACZ,OAAO+C;AACR"}
1
+ {"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport * as v from 'valibot';\nimport { ThoughtData } from './core/thought.js';\nimport { SEQUENTIAL_THINKING_TOOL, SequentialThinkingSchema } from './schema.js';\nimport { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport type { ISummaryStore } from './contracts/summary.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport type { ISuspensionStore } from './contracts/suspension.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport type { ISessionLock } from './contracts/interfaces.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport type { IToolRegistry } from './contracts/interfaces.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport type { SseTransportOptions } from './transport/SseTransport.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport type { IReasoningStrategy } from './contracts/strategy.js';\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Enable automatic skill discovery on server startup\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup)\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n\t/**\n\t * Transport type to use\n\t * @default 'stdio'\n\t */\n\ttransport?: 'stdio' | 'sse';\n\t/**\n\t * SSE transport options (used when transport: 'sse')\n\t */\n\tsseTransportOptions?: SseTransportOptions;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/**\n\t * Get all branches from the history manager.\n\t *\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/**\n\t * Clear all server state (history, tools, skills).\n\t */\n\tclear(): void;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer extends EventEmitter implements IToolAwareSequentialThinkingServer {\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\t// Create the async container first\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\n\t\t// Create a minimal server with the container\n\t\tconst server = new ToolAwareSequentialThinkingServer({\n\t\t\t...options,\n\t\t\tcontainer,\n\t\t});\n\n\t\t// Load from persistence if enabled (default: true)\n\t\tif (options.loadFromPersistence !== false) {\n\t\t\tawait server.history.loadFromPersistence();\n\t\t}\n\n\t\t// Perform async discovery if enabled (default: true)\n\t\tif (options.autoDiscover !== false) {\n\t\t\tawait server.discoverSkillsAsync();\n\t\t}\n\n\t\treturn server;\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory();\n\t * server.history.clear();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.addTool(tool);\n\t * server.tools.getTool('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.addSkill(skill);\n\t * server.skills.getSkill('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve<StructuredLogger>('Logger');\n\t\tthis._historyManager = this._container.resolve<HistoryManager>('HistoryManager');\n\t\tthis._thoughtProcessor = this._container.resolve<ThoughtProcessor>('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve<Metrics>('Metrics');\n\t\tthis._config = this._container.resolve<ServerConfig>('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve<ToolRegistry>('ToolRegistry');\n\t\tthis.skills = this._container.resolve<SkillRegistry>('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.addTool(SEQUENTIAL_THINKING_TOOL);\n\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\t// Initialize config with file defaults overridden by constructor options\n\t\tconst config = new ServerConfig({\n\t\t\tmaxHistorySize: options.maxHistorySize ?? fileConfig?.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? fileConfig?.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? fileConfig?.maxBranchSize,\n\t\t\tskillDirs: fileConfig?.skillDirs,\n\t\t\tdiscoveryCache: fileConfig?.discoveryCache,\n\t\t\tpersistence: fileConfig?.persistence,\n\t\t\tmaxSessionsPerOwner: fileConfig?.maxSessionsPerOwner,\n\t\t});\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t\t\t})\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve<HistoryManager>('HistoryManager');\n\t\t\tconst edgeStore = container.resolve<EdgeStore>('EdgeStore');\n\t\t\tconst summaryStore = container.resolve<ISummaryStore>('summaryStore');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\treturn new CompressionService({ historyManager, edgeStore, summaryStore, logger: log });\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy),\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve<ServerConfig>('Config');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\tconst pers = container.resolve('Persistence') as PersistenceBackend | null;\n\t\t\tconst componentMetrics = container.resolve<Metrics>('Metrics');\n\t\t\tconst edgeStore = container.resolve<EdgeStore>('EdgeStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tedgeStore,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t});\n\t\t});\n\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false }),\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(\n\t\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\t\tconfig.features.calibration ?? false,\n\t\t\t\t),\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator')),\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve<HistoryManager>('HistoryManager');\n\t\t\tconst formatter = container.resolve<ThoughtFormatter>('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve<ThoughtEvaluator>('ThoughtEvaluator');\n\t\t\tconst log = container.resolve<StructuredLogger>('Logger');\n\t\t\tconst strategy = container.resolve<IReasoningStrategy>('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve<CompressionService>('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve<ISuspensionStore>('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve<IToolRegistry>('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve<ISessionLock>('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t);\n\t\t});\n\n\t\treturn container;\n\t}\n\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tconst configLoader = new ConfigLoader();\n\t\tconst fileConfig = configLoader.load();\n\n\t\t// Initialize persistence backend (async)\n\t\tconst persistence = await createPersistenceBackend(\n\t\t\tfileConfig?.persistence ?? { enabled: false }\n\t\t);\n\n\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(options, fileConfig, persistence);\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/**\n\t * Get all branches from the history manager\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(): Record<string, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches();\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst thoughtInput = input as ThoughtData & { register_branch_id?: string };\n\t\tif (typeof thoughtInput.register_branch_id === 'string' && thoughtInput.register_branch_id.length > 0) {\n\t\t\ttry {\n\t\t\t\tthis._historyManager.registerBranch(\n\t\t\t\t\tthoughtInput.session_id,\n\t\t\t\t\tthoughtInput.register_branch_id\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.warn('registerBranch skipped', {\n\t\t\t\t\tbranch_id: thoughtInput.register_branch_id,\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t});\n\t\t\t}\n\t\t\tdelete thoughtInput.register_branch_id;\n\t\t}\n\t\tconst result = await this._thoughtProcessor.process(thoughtInput);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tthis._skillWatcher?.stop();\n\t\tthis._toolWatcher?.stop();\n\n\t\t// Stop suspension store sweeper if registered\n\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\ttry {\n\t\t\t\tconst suspensionStore = this._container.resolve<ISuspensionStore>('suspensionStore');\n\t\t\t\tsuspensionStore.stop();\n\t\t\t} catch (error) {\n\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush any buffered writes before closing persistence\n\t\ttry {\n\t\t\tawait this._historyManager.shutdown();\n\t\t} catch (error) {\n\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Close persistence backend if available\n\t\tconst persistence = this._container.resolve<PersistenceBackend | null>('Persistence');\n\t\tif (persistence) {\n\t\t\ttry {\n\t\t\t\tawait persistence.close();\n\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t} catch (error) {\n\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t}\n\n\t/**\n\t * Clear all server state (history, tools, skills)\n\t * Useful for testing to reset state between tests\n\t */\n\tpublic clear(): void {\n\t\tthis._historyManager.clear();\n\t\tthis._logger.info('Server state cleared');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tawait this.stop();\n\t\tawait this._container.dispose();\n\t\tthis._logger.info('Server disposed, all resources released');\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n *\n * // With custom container for testing\n * const mockContainer = new Container();\n * mockContainer.registerInstance('Logger', mockLogger);\n * const server = await createServer({ container: mockContainer });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load();\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig?.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","persistence","Container","metrics","Metrics","config","ServerConfig","logger","StructuredLogger","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","createReasoningStrategy","SessionLock","cfg","pers","componentMetrics","HistoryManager","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","ConfigLoader","createPersistenceBackend","discovered","input","startTime","Date","thoughtInput","err","String","result","durationSeconds","error","getErrorMessage","createServer","initializeServer","thinking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yB,CAAC,CAAC;IAE3B,OAAOF,kCAAkC,MAAM,CAACE;AACjD;AAGO,eAAekE;IAErB,MAAMf,eAAe,IAAIC;IACzB,MAAM1C,aAAayC,aAAa,IAAI;IAEpC,MAAMlC,SAAS,IAAIC,iBAAiB;QACnC,OAAOR,YAAY,YAAY;QAC/B,SAAS;QACT,QAAQA,YAAY,aAAa;IAClC;IAGA,MAAMyD,iBAAiB,MAAMF,aAAa;QACzChD;QACA,eAAe;IAChB;IAEAA,OAAO,IAAI,CAAC;IACZ,OAAOkD;AACR"}
@@ -64,6 +64,7 @@ export declare class ToolRegistry extends BaseRegistry<Tool> {
64
64
  updateTool(name: string, updates: Partial<Tool>): void;
65
65
  hasTool(name: string): boolean;
66
66
  getTool(name: string): Tool | undefined;
67
+ list(): string[];
67
68
  setTools(tools: Tool[]): void;
68
69
  }
69
70
  //# sourceMappingURL=ToolRegistry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ToolRegistry.d.ts","sourceRoot":"","sources":["../../src/registry/ToolRegistry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,mBAAmB;IACnC,uCAAuC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,uCAAuC;IACvC,KAAK,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAE7B;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IAEpB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;;GAKG;AACH,qBAAa,YAAa,SAAQ,YAAY,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AE,MAAM,GAAG,IAAI,GAAG,SAAS;IAIvC,IAAI,IAAI,MAAM,EAAE;IAIhB,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI;CAGpC"}
@@ -84,6 +84,9 @@ class ToolRegistry extends BaseRegistry {
84
84
  getTool(name) {
85
85
  return this.get(name);
86
86
  }
87
+ list() {
88
+ return this.getNames();
89
+ }
87
90
  setTools(tools) {
88
91
  this.setAll(tools);
89
92
  }
@@ -1 +1 @@
1
- {"version":3,"file":"registry/ToolRegistry.js","sources":["../../src/registry/ToolRegistry.ts"],"sourcesContent":["/**\n * Tool registry for managing MCP tool CRUD operations.\n *\n * This module provides the `ToolRegistry` class which manages the registration,\n * retrieval, update, and removal of MCP tools. It supports optional caching\n * for improved performance, filesystem discovery, and integrates with the logging system.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateToolError, InvalidToolError, ToolNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Tool } from '../types/tool.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `ToolRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: ToolRegistryOptions = {\n * logger: new StructuredLogger({ context: 'ToolRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * toolDirs: ['./custom-tools', '~/.claude/tools'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface ToolRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for tool lookups. */\n\tcache?: DiscoveryCache<Tool>;\n\n\t/**\n\t * Directory paths to search for tools.\n\t * @default ['.claude/tools', '~/.claude/tools']\n\t */\n\ttoolDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing MCP tool operations.\n *\n * Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing\n * and backward-compatible aliases (`addTool`, `removeTool`, etc.).\n */\nexport class ToolRegistry extends BaseRegistry<Tool> {\n\tprotected override readonly _fileExtensions = ['.tool.md'];\n\tprotected override readonly _entityName = 'tool';\n\n\tconstructor(options: ToolRegistryOptions = {}) {\n\t\tsuper({\n\t\t\tlogger: options.logger,\n\t\t\tcache: options.cache,\n\t\t\tsearchDirs: options.toolDirs || ['.claude/tools', join(homedir(), '.claude/tools')],\n\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t});\n\t}\n\n\t// --- Error factories ---\n\n\tprotected override _createInvalidError(reason: string): Error {\n\t\treturn new InvalidToolError(reason);\n\t}\n\n\tprotected override _createDuplicateError(name: string): Error {\n\t\treturn new DuplicateToolError(name);\n\t}\n\n\tprotected override _createNotFoundError(name: string, action: string): Error {\n\t\treturn new ToolNotFoundError(name, action);\n\t}\n\n\t// --- Discovery ---\n\n\tprotected override _shouldSkipFile(_fileName: string): boolean {\n\t\treturn false;\n\t}\n\n\tprotected override _parseFrontmatter(content: string): Partial<Tool> & { _error?: string } {\n\t\tconst frontmatter = this._extractFrontmatter(content);\n\t\tif (!frontmatter) {\n\t\t\treturn { _error: 'No YAML frontmatter found' };\n\t\t}\n\n\t\ttry {\n\t\t\tconst result: Partial<Tool> = {\n\t\t\t\tname: typeof frontmatter.name === 'string' ? frontmatter.name : undefined,\n\t\t\t\tdescription: typeof frontmatter.description === 'string' ? frontmatter.description : '',\n\t\t\t\tinputSchema: frontmatter.inputSchema as Tool['inputSchema'],\n\t\t\t};\n\n\t\t\tif (!result.name) {\n\t\t\t\treturn { _error: 'Missing required field: name' };\n\t\t\t}\n\t\t\tif (!result.inputSchema) {\n\t\t\t\treturn { _error: 'Missing required field: inputSchema' };\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch {\n\t\t\treturn { _error: 'YAML parse error' };\n\t\t}\n\t}\n\n\tprotected override _buildItem(parsed: Partial<Tool>): Tool | null {\n\t\tif (!parsed.name || !parsed.inputSchema) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tname: parsed.name,\n\t\t\tdescription: parsed.description || '',\n\t\t\tinputSchema: parsed.inputSchema,\n\t\t};\n\t}\n\n\t// --- Tool-specific get with cache lookup ---\n\n\tpublic override get(name: string): Tool | undefined {\n\t\tif (this._cache) {\n\t\t\tconst cached = this._cache.get(`tool:${name}`);\n\t\t\tif (cached && cached.length > 0) {\n\t\t\t\treturn cached[0];\n\t\t\t}\n\t\t}\n\t\treturn this._items.get(name);\n\t}\n\n\t// --- Backward-compatible aliases ---\n\n\tpublic addTool(tool: Tool): void {\n\t\tthis.add(tool);\n\t}\n\n\tpublic removeTool(name: string): void {\n\t\tthis.remove(name);\n\t}\n\n\tpublic updateTool(name: string, updates: Partial<Tool>): void {\n\t\tthis.update(name, updates);\n\t}\n\n\tpublic hasTool(name: string): boolean {\n\t\treturn this.has(name);\n\t}\n\n\tpublic getTool(name: string): Tool | undefined {\n\t\treturn this.get(name);\n\t}\n\n\tpublic setTools(tools: Tool[]): void {\n\t\tthis.setAll(tools);\n\t}\n}\n"],"names":["ToolRegistry","BaseRegistry","options","join","homedir","reason","InvalidToolError","name","DuplicateToolError","action","ToolNotFoundError","_fileName","content","frontmatter","result","undefined","parsed","cached","tool","updates","tools"],"mappings":";;;;AAyDO,MAAMA,qBAAqBC;IACL,kBAAkB;QAAC;KAAW,CAAC;IAC/B,cAAc,OAAO;IAEjD,YAAYC,UAA+B,CAAC,CAAC,CAAE;QAC9C,KAAK,CAAC;YACL,QAAQA,QAAQ,MAAM;YACtB,OAAOA,QAAQ,KAAK;YACpB,YAAYA,QAAQ,QAAQ,IAAI;gBAAC;gBAAiBC,KAAKC,WAAW;aAAiB;YACnF,eAAeF,QAAQ,aAAa;QACrC;IACD;IAImB,oBAAoBG,MAAc,EAAS;QAC7D,OAAO,IAAIC,iBAAiBD;IAC7B;IAEmB,sBAA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C,IAAI,CAAC,GAAG,CAACA;IACV;IAEO,WAAWX,IAAY,EAAQ;QACrC,IAAI,CAAC,MAAM,CAACA;IACb;IAEO,WAAWA,IAAY,EAAEY,OAAsB,EAAQ;QAC7D,IAAI,CAAC,MAAM,CAACZ,MAAMY;IACnB;IAEO,QAAQZ,IAAY,EAAW;QACrC,OAAO,IAAI,CAAC,GAAG,CAACA;IACjB;IAEO,QAAQA,IAAY,EAAoB;QAC9C,OAAO,IAAI,CAAC,GAAG,CAACA;IACjB;IAEO,SAASa,KAAa,EAAQ;QACpC,IAAI,CAAC,MAAM,CAACA;IACb;AACD"}
1
+ {"version":3,"file":"registry/ToolRegistry.js","sources":["../../src/registry/ToolRegistry.ts"],"sourcesContent":["/**\n * Tool registry for managing MCP tool CRUD operations.\n *\n * This module provides the `ToolRegistry` class which manages the registration,\n * retrieval, update, and removal of MCP tools. It supports optional caching\n * for improved performance, filesystem discovery, and integrates with the logging system.\n *\n * @module registry\n */\n\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { DiscoveryCache } from '../cache/DiscoveryCache.js';\nimport { DuplicateToolError, InvalidToolError, ToolNotFoundError } from '../errors.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { Tool } from '../types/tool.js';\nimport { BaseRegistry } from './BaseRegistry.js';\n\n/**\n * Configuration options for creating a `ToolRegistry` instance.\n *\n * @example\n * ```typescript\n * const options: ToolRegistryOptions = {\n * logger: new StructuredLogger({ context: 'ToolRegistry' }),\n * cache: new DiscoveryCache({ ttl: 300000, maxSize: 100 }),\n * toolDirs: ['./custom-tools', '~/.claude/tools'],\n * lazyDiscovery: true\n * };\n * ```\n */\nexport interface ToolRegistryOptions {\n\t/** Optional logger for diagnostics. */\n\tlogger?: Logger;\n\n\t/** Optional cache for tool lookups. */\n\tcache?: DiscoveryCache<Tool>;\n\n\t/**\n\t * Directory paths to search for tools.\n\t * @default ['.claude/tools', '~/.claude/tools']\n\t */\n\ttoolDirs?: string[];\n\n\t/**\n\t * Enable lazy discovery (discover on first access instead of startup).\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n}\n\n/**\n * Registry for managing MCP tool operations.\n *\n * Extends `BaseRegistry<Tool>` with tool-specific frontmatter parsing\n * and backward-compatible aliases (`addTool`, `removeTool`, etc.).\n */\nexport class ToolRegistry extends BaseRegistry<Tool> {\n\tprotected override readonly _fileExtensions = ['.tool.md'];\n\tprotected override readonly _entityName = 'tool';\n\n\tconstructor(options: ToolRegistryOptions = {}) {\n\t\tsuper({\n\t\t\tlogger: options.logger,\n\t\t\tcache: options.cache,\n\t\t\tsearchDirs: options.toolDirs || ['.claude/tools', join(homedir(), '.claude/tools')],\n\t\t\tlazyDiscovery: options.lazyDiscovery,\n\t\t});\n\t}\n\n\t// --- Error factories ---\n\n\tprotected override _createInvalidError(reason: string): Error {\n\t\treturn new InvalidToolError(reason);\n\t}\n\n\tprotected override _createDuplicateError(name: string): Error {\n\t\treturn new DuplicateToolError(name);\n\t}\n\n\tprotected override _createNotFoundError(name: string, action: string): Error {\n\t\treturn new ToolNotFoundError(name, action);\n\t}\n\n\t// --- Discovery ---\n\n\tprotected override _shouldSkipFile(_fileName: string): boolean {\n\t\treturn false;\n\t}\n\n\tprotected override _parseFrontmatter(content: string): Partial<Tool> & { _error?: string } {\n\t\tconst frontmatter = this._extractFrontmatter(content);\n\t\tif (!frontmatter) {\n\t\t\treturn { _error: 'No YAML frontmatter found' };\n\t\t}\n\n\t\ttry {\n\t\t\tconst result: Partial<Tool> = {\n\t\t\t\tname: typeof frontmatter.name === 'string' ? frontmatter.name : undefined,\n\t\t\t\tdescription: typeof frontmatter.description === 'string' ? frontmatter.description : '',\n\t\t\t\tinputSchema: frontmatter.inputSchema as Tool['inputSchema'],\n\t\t\t};\n\n\t\t\tif (!result.name) {\n\t\t\t\treturn { _error: 'Missing required field: name' };\n\t\t\t}\n\t\t\tif (!result.inputSchema) {\n\t\t\t\treturn { _error: 'Missing required field: inputSchema' };\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch {\n\t\t\treturn { _error: 'YAML parse error' };\n\t\t}\n\t}\n\n\tprotected override _buildItem(parsed: Partial<Tool>): Tool | null {\n\t\tif (!parsed.name || !parsed.inputSchema) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tname: parsed.name,\n\t\t\tdescription: parsed.description || '',\n\t\t\tinputSchema: parsed.inputSchema,\n\t\t};\n\t}\n\n\t// --- Tool-specific get with cache lookup ---\n\n\tpublic override get(name: string): Tool | undefined {\n\t\tif (this._cache) {\n\t\t\tconst cached = this._cache.get(`tool:${name}`);\n\t\t\tif (cached && cached.length > 0) {\n\t\t\t\treturn cached[0];\n\t\t\t}\n\t\t}\n\t\treturn this._items.get(name);\n\t}\n\n\t// --- Backward-compatible aliases ---\n\n\tpublic addTool(tool: Tool): void {\n\t\tthis.add(tool);\n\t}\n\n\tpublic removeTool(name: string): void {\n\t\tthis.remove(name);\n\t}\n\n\tpublic updateTool(name: string, updates: Partial<Tool>): void {\n\t\tthis.update(name, updates);\n\t}\n\n\tpublic hasTool(name: string): boolean {\n\t\treturn this.has(name);\n\t}\n\n\tpublic getTool(name: string): Tool | undefined {\n\t\treturn this.get(name);\n\t}\n\n\tpublic list(): string[] {\n\t\treturn this.getNames();\n\t}\n\n\tpublic setTools(tools: Tool[]): void {\n\t\tthis.setAll(tools);\n\t}\n}\n"],"names":["ToolRegistry","BaseRegistry","options","join","homedir","reason","InvalidToolError","name","DuplicateToolError","action","ToolNotFoundError","_fileName","content","frontmatter","result","undefined","parsed","cached","tool","updates","tools"],"mappings":";;;;AAyDO,MAAMA,qBAAqBC;IACL,kBAAkB;QAAC;KAAW,CAAC;IAC/B,cAAc,OAAO;IAEjD,YAAYC,UAA+B,CAAC,CAAC,CAAE;QAC9C,KAAK,CAAC;YACL,QAAQA,QAAQ,MAAM;YACtB,OAAOA,QAAQ,KAAK;YACpB,YAAYA,QAAQ,QAAQ,IAAI;gBAAC;gBAAiBC,KAAKC,W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