tracelattice 1.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +112 -0
- package/dist/ServerConfig.d.ts +229 -0
- package/dist/ServerConfig.d.ts.map +1 -0
- package/dist/ServerConfig.js +121 -0
- package/dist/ServerConfig.js.map +1 -0
- package/dist/__tests__/base-registry.test.d.ts +2 -0
- package/dist/__tests__/base-registry.test.d.ts.map +1 -0
- package/dist/__tests__/base-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/base-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/base-transport.test.d.ts +2 -0
- package/dist/__tests__/base-transport.test.d.ts.map +1 -0
- package/dist/__tests__/config-loader.test.d.ts +2 -0
- package/dist/__tests__/config-loader.test.d.ts.map +1 -0
- package/dist/__tests__/connection-pool-cov.test.d.ts +2 -0
- package/dist/__tests__/connection-pool-cov.test.d.ts.map +1 -0
- package/dist/__tests__/connection-pool.test.d.ts +2 -0
- package/dist/__tests__/connection-pool.test.d.ts.map +1 -0
- package/dist/__tests__/container.test.d.ts +2 -0
- package/dist/__tests__/container.test.d.ts.map +1 -0
- package/dist/__tests__/crud.test.d.ts +2 -0
- package/dist/__tests__/crud.test.d.ts.map +1 -0
- package/dist/__tests__/discovery-cache.test.d.ts +2 -0
- package/dist/__tests__/discovery-cache.test.d.ts.map +1 -0
- package/dist/__tests__/errors.test.d.ts +2 -0
- package/dist/__tests__/errors.test.d.ts.map +1 -0
- package/dist/__tests__/factories.test.d.ts +2 -0
- package/dist/__tests__/factories.test.d.ts.map +1 -0
- package/dist/__tests__/health-checker-cov.test.d.ts +2 -0
- package/dist/__tests__/health-checker-cov.test.d.ts.map +1 -0
- package/dist/__tests__/health-checker.test.d.ts +2 -0
- package/dist/__tests__/health-checker.test.d.ts.map +1 -0
- package/dist/__tests__/helpers/factories.d.ts +36 -0
- package/dist/__tests__/helpers/factories.d.ts.map +1 -0
- package/dist/__tests__/helpers/index.d.ts +3 -0
- package/dist/__tests__/helpers/index.d.ts.map +1 -0
- package/dist/__tests__/helpers/timers.d.ts +4 -0
- package/dist/__tests__/helpers/timers.d.ts.map +1 -0
- package/dist/__tests__/history-manager.test.d.ts +2 -0
- package/dist/__tests__/history-manager.test.d.ts.map +1 -0
- package/dist/__tests__/http-helpers-cov.test.d.ts +2 -0
- package/dist/__tests__/http-helpers-cov.test.d.ts.map +1 -0
- package/dist/__tests__/http-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/http-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/http-transport.test.d.ts +2 -0
- package/dist/__tests__/http-transport.test.d.ts.map +1 -0
- package/dist/__tests__/input-normalizer.test.d.ts +8 -0
- package/dist/__tests__/input-normalizer.test.d.ts.map +1 -0
- package/dist/__tests__/integration.test.d.ts +2 -0
- package/dist/__tests__/integration.test.d.ts.map +1 -0
- package/dist/__tests__/lib-server.test.d.ts +2 -0
- package/dist/__tests__/lib-server.test.d.ts.map +1 -0
- package/dist/__tests__/memory-persistence.test.d.ts +2 -0
- package/dist/__tests__/memory-persistence.test.d.ts.map +1 -0
- package/dist/__tests__/metrics-integration.test.d.ts +2 -0
- package/dist/__tests__/metrics-integration.test.d.ts.map +1 -0
- package/dist/__tests__/persistence.test.d.ts +2 -0
- package/dist/__tests__/persistence.test.d.ts.map +1 -0
- package/dist/__tests__/reasoning-integration.test.d.ts +11 -0
- package/dist/__tests__/reasoning-integration.test.d.ts.map +1 -0
- package/dist/__tests__/reasoning-types.test.d.ts +2 -0
- package/dist/__tests__/reasoning-types.test.d.ts.map +1 -0
- package/dist/__tests__/request-context.test.d.ts +2 -0
- package/dist/__tests__/request-context.test.d.ts.map +1 -0
- package/dist/__tests__/sanitize.test.d.ts +2 -0
- package/dist/__tests__/sanitize.test.d.ts.map +1 -0
- package/dist/__tests__/schema.test.d.ts +2 -0
- package/dist/__tests__/schema.test.d.ts.map +1 -0
- package/dist/__tests__/sequentialthinking-tools.test.d.ts +2 -0
- package/dist/__tests__/sequentialthinking-tools.test.d.ts.map +1 -0
- package/dist/__tests__/server-config.test.d.ts +2 -0
- package/dist/__tests__/server-config.test.d.ts.map +1 -0
- package/dist/__tests__/skill-discovery.test.d.ts +2 -0
- package/dist/__tests__/skill-discovery.test.d.ts.map +1 -0
- package/dist/__tests__/skill-registry.test.d.ts +2 -0
- package/dist/__tests__/skill-registry.test.d.ts.map +1 -0
- package/dist/__tests__/skill-watcher.test.d.ts +2 -0
- package/dist/__tests__/skill-watcher.test.d.ts.map +1 -0
- package/dist/__tests__/sqlite-persistence.test.d.ts +2 -0
- package/dist/__tests__/sqlite-persistence.test.d.ts.map +1 -0
- package/dist/__tests__/sse-transport-cov.test.d.ts +2 -0
- package/dist/__tests__/sse-transport-cov.test.d.ts.map +1 -0
- package/dist/__tests__/sse-transport.test.d.ts +2 -0
- package/dist/__tests__/sse-transport.test.d.ts.map +1 -0
- package/dist/__tests__/streamable-http-cov.test.d.ts +2 -0
- package/dist/__tests__/streamable-http-cov.test.d.ts.map +1 -0
- package/dist/__tests__/streamable-http-transport.test.d.ts +2 -0
- package/dist/__tests__/streamable-http-transport.test.d.ts.map +1 -0
- package/dist/__tests__/structured-logger.test.d.ts +2 -0
- package/dist/__tests__/structured-logger.test.d.ts.map +1 -0
- package/dist/__tests__/thought-evaluator.test.d.ts +2 -0
- package/dist/__tests__/thought-evaluator.test.d.ts.map +1 -0
- package/dist/__tests__/thought-formatter.test.d.ts +2 -0
- package/dist/__tests__/thought-formatter.test.d.ts.map +1 -0
- package/dist/__tests__/thought-processor.test.d.ts +8 -0
- package/dist/__tests__/thought-processor.test.d.ts.map +1 -0
- package/dist/__tests__/tool-registry-cov.test.d.ts +2 -0
- package/dist/__tests__/tool-registry-cov.test.d.ts.map +1 -0
- package/dist/__tests__/tool-registry.test.d.ts +2 -0
- package/dist/__tests__/tool-registry.test.d.ts.map +1 -0
- package/dist/__tests__/tool-watcher.test.d.ts +2 -0
- package/dist/__tests__/tool-watcher.test.d.ts.map +1 -0
- package/dist/__tests__/worker-manager-cov.test.d.ts +2 -0
- package/dist/__tests__/worker-manager-cov.test.d.ts.map +1 -0
- package/dist/__tests__/worker-manager.test.d.ts +2 -0
- package/dist/__tests__/worker-manager.test.d.ts.map +1 -0
- package/dist/cache/DiscoveryCache.d.ts +269 -0
- package/dist/cache/DiscoveryCache.d.ts.map +1 -0
- package/dist/cache/DiscoveryCache.js +100 -0
- package/dist/cache/DiscoveryCache.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +114 -0
- package/dist/cli.js.map +1 -0
- package/dist/cluster/WorkerManager.d.ts +166 -0
- package/dist/cluster/WorkerManager.d.ts.map +1 -0
- package/dist/cluster/WorkerManager.js +202 -0
- package/dist/cluster/WorkerManager.js.map +1 -0
- package/dist/cluster/worker.d.ts +11 -0
- package/dist/cluster/worker.d.ts.map +1 -0
- package/dist/cluster/worker.js +36 -0
- package/dist/cluster/worker.js.map +1 -0
- package/dist/config/ConfigLoader.d.ts +224 -0
- package/dist/config/ConfigLoader.d.ts.map +1 -0
- package/dist/config/ConfigLoader.js +85 -0
- package/dist/config/ConfigLoader.js.map +1 -0
- package/dist/context/RequestContext.d.ts +61 -0
- package/dist/context/RequestContext.d.ts.map +1 -0
- package/dist/context/RequestContext.js +17 -0
- package/dist/context/RequestContext.js.map +1 -0
- package/dist/contracts/index.d.ts +10 -0
- package/dist/contracts/index.d.ts.map +1 -0
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/interfaces.d.ts +107 -0
- package/dist/contracts/interfaces.d.ts.map +1 -0
- package/dist/contracts/interfaces.js +1 -0
- package/dist/core/HistoryManager.d.ts +514 -0
- package/dist/core/HistoryManager.d.ts.map +1 -0
- package/dist/core/HistoryManager.js +331 -0
- package/dist/core/HistoryManager.js.map +1 -0
- package/dist/core/IHistoryManager.d.ts +100 -0
- package/dist/core/IHistoryManager.d.ts.map +1 -0
- package/dist/core/IHistoryManager.js +1 -0
- package/dist/core/InputNormalizer.d.ts +139 -0
- package/dist/core/InputNormalizer.d.ts.map +1 -0
- package/dist/core/InputNormalizer.js +101 -0
- package/dist/core/InputNormalizer.js.map +1 -0
- package/dist/core/ThoughtEvaluator.d.ts +127 -0
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -0
- package/dist/core/ThoughtEvaluator.js +346 -0
- package/dist/core/ThoughtEvaluator.js.map +1 -0
- package/dist/core/ThoughtFormatter.d.ts +133 -0
- package/dist/core/ThoughtFormatter.d.ts.map +1 -0
- package/dist/core/ThoughtFormatter.js +70 -0
- package/dist/core/ThoughtFormatter.js.map +1 -0
- package/dist/core/ThoughtProcessor.d.ts +218 -0
- package/dist/core/ThoughtProcessor.d.ts.map +1 -0
- package/dist/core/ThoughtProcessor.js +205 -0
- package/dist/core/ThoughtProcessor.js.map +1 -0
- package/dist/core/reasoning.d.ts +169 -0
- package/dist/core/reasoning.d.ts.map +1 -0
- package/dist/core/reasoning.js +1 -0
- package/dist/core/step.d.ts +45 -0
- package/dist/core/step.d.ts.map +1 -0
- package/dist/core/step.js +1 -0
- package/dist/core/thought.d.ts +190 -0
- package/dist/core/thought.d.ts.map +1 -0
- package/dist/core/thought.js +1 -0
- package/dist/di/Container.d.ts +226 -0
- package/dist/di/Container.d.ts.map +1 -0
- package/dist/di/Container.js +96 -0
- package/dist/di/Container.js.map +1 -0
- package/dist/di/ServiceRegistry.d.ts +32 -0
- package/dist/di/ServiceRegistry.d.ts.map +1 -0
- package/dist/di/ServiceRegistry.js +1 -0
- package/dist/errors.d.ts +482 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +108 -0
- package/dist/errors.js.map +1 -0
- package/dist/health/HealthChecker.d.ts +73 -0
- package/dist/health/HealthChecker.d.ts.map +1 -0
- package/dist/health/HealthChecker.js +69 -0
- package/dist/health/HealthChecker.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1 -0
- package/dist/lib.d.ts +205 -0
- package/dist/lib.d.ts.map +1 -0
- package/dist/lib.js +219 -0
- package/dist/lib.js.map +1 -0
- package/dist/logger/NullLogger.d.ts +154 -0
- package/dist/logger/NullLogger.d.ts.map +1 -0
- package/dist/logger/NullLogger.js +24 -0
- package/dist/logger/NullLogger.js.map +1 -0
- package/dist/logger/StructuredLogger.d.ts +327 -0
- package/dist/logger/StructuredLogger.d.ts.map +1 -0
- package/dist/logger/StructuredLogger.js +72 -0
- package/dist/logger/StructuredLogger.js.map +1 -0
- package/dist/metrics/__tests__/metrics.test.d.ts +2 -0
- package/dist/metrics/__tests__/metrics.test.d.ts.map +1 -0
- package/dist/metrics/metrics.impl.d.ts +252 -0
- package/dist/metrics/metrics.impl.d.ts.map +1 -0
- package/dist/metrics/metrics.impl.js +197 -0
- package/dist/metrics/metrics.impl.js.map +1 -0
- package/dist/persistence/FilePersistence.d.ts +66 -0
- package/dist/persistence/FilePersistence.d.ts.map +1 -0
- package/dist/persistence/FilePersistence.js +132 -0
- package/dist/persistence/FilePersistence.js.map +1 -0
- package/dist/persistence/MemoryPersistence.d.ts +68 -0
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -0
- package/dist/persistence/MemoryPersistence.js +51 -0
- package/dist/persistence/MemoryPersistence.js.map +1 -0
- package/dist/persistence/PersistenceBackend.d.ts +69 -0
- package/dist/persistence/PersistenceBackend.d.ts.map +1 -0
- package/dist/persistence/PersistenceBackend.js +1 -0
- package/dist/persistence/PersistenceFactory.d.ts +21 -0
- package/dist/persistence/PersistenceFactory.d.ts.map +1 -0
- package/dist/persistence/PersistenceFactory.js +25 -0
- package/dist/persistence/PersistenceFactory.js.map +1 -0
- package/dist/persistence/SqlitePersistence.d.ts +60 -0
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -0
- package/dist/persistence/SqlitePersistence.js +136 -0
- package/dist/persistence/SqlitePersistence.js.map +1 -0
- package/dist/pool/ConnectionPool.d.ts +215 -0
- package/dist/pool/ConnectionPool.d.ts.map +1 -0
- package/dist/pool/ConnectionPool.js +187 -0
- package/dist/pool/ConnectionPool.js.map +1 -0
- package/dist/registry/BaseRegistry.d.ts +203 -0
- package/dist/registry/BaseRegistry.d.ts.map +1 -0
- package/dist/registry/BaseRegistry.js +165 -0
- package/dist/registry/BaseRegistry.js.map +1 -0
- package/dist/registry/SkillRegistry.d.ts +69 -0
- package/dist/registry/SkillRegistry.d.ts.map +1 -0
- package/dist/registry/SkillRegistry.js +88 -0
- package/dist/registry/SkillRegistry.js.map +1 -0
- package/dist/registry/ToolRegistry.d.ts +69 -0
- package/dist/registry/ToolRegistry.d.ts.map +1 -0
- package/dist/registry/ToolRegistry.js +93 -0
- package/dist/registry/ToolRegistry.js.map +1 -0
- package/dist/sanitize.d.ts +63 -0
- package/dist/sanitize.d.ts.map +1 -0
- package/dist/sanitize.js +14 -0
- package/dist/sanitize.js.map +1 -0
- package/dist/schema.d.ts +531 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +204 -0
- package/dist/schema.js.map +1 -0
- package/dist/telemetry/Telemetry.d.ts +36 -0
- package/dist/telemetry/Telemetry.d.ts.map +1 -0
- package/dist/telemetry/Telemetry.js +68 -0
- package/dist/telemetry/Telemetry.js.map +1 -0
- package/dist/telemetry/__tests__/Telemetry.test.d.ts +2 -0
- package/dist/telemetry/__tests__/Telemetry.test.d.ts.map +1 -0
- package/dist/transport/BaseTransport.d.ts +184 -0
- package/dist/transport/BaseTransport.d.ts.map +1 -0
- package/dist/transport/BaseTransport.js +200 -0
- package/dist/transport/BaseTransport.js.map +1 -0
- package/dist/transport/HttpHelpers.d.ts +60 -0
- package/dist/transport/HttpHelpers.d.ts.map +1 -0
- package/dist/transport/HttpHelpers.js +50 -0
- package/dist/transport/HttpHelpers.js.map +1 -0
- package/dist/transport/HttpTransport.d.ts +134 -0
- package/dist/transport/HttpTransport.d.ts.map +1 -0
- package/dist/transport/HttpTransport.js +175 -0
- package/dist/transport/HttpTransport.js.map +1 -0
- package/dist/transport/SseTransport.d.ts +133 -0
- package/dist/transport/SseTransport.d.ts.map +1 -0
- package/dist/transport/SseTransport.js +318 -0
- package/dist/transport/SseTransport.js.map +1 -0
- package/dist/transport/StreamableHttpTransport.d.ts +224 -0
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -0
- package/dist/transport/StreamableHttpTransport.js +407 -0
- package/dist/transport/StreamableHttpTransport.js.map +1 -0
- package/dist/types/disposable.d.ts +22 -0
- package/dist/types/disposable.d.ts.map +1 -0
- package/dist/types/disposable.js +1 -0
- package/dist/types/server-config.d.ts +32 -0
- package/dist/types/server-config.d.ts.map +1 -0
- package/dist/types/server-config.js +1 -0
- package/dist/types/skill.d.ts +69 -0
- package/dist/types/skill.d.ts.map +1 -0
- package/dist/types/skill.js +1 -0
- package/dist/types/tool.d.ts +68 -0
- package/dist/types/tool.d.ts.map +1 -0
- package/dist/types/tool.js +1 -0
- package/dist/watchers/SkillWatcher.d.ts +132 -0
- package/dist/watchers/SkillWatcher.d.ts.map +1 -0
- package/dist/watchers/SkillWatcher.js +73 -0
- package/dist/watchers/SkillWatcher.js.map +1 -0
- package/dist/watchers/ToolWatcher.d.ts +109 -0
- package/dist/watchers/ToolWatcher.d.ts.map +1 -0
- package/dist/watchers/ToolWatcher.js +71 -0
- package/dist/watchers/ToolWatcher.js.map +1 -0
- package/package.json +95 -0
package/dist/schema.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import * as __rspack_external_valibot from "valibot";
|
|
2
|
+
const TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.
|
|
3
|
+
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
|
|
4
|
+
Each thought can build on, question, or revise previous insights as understanding deepens.
|
|
5
|
+
|
|
6
|
+
IMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.
|
|
7
|
+
|
|
8
|
+
When to use this tool:
|
|
9
|
+
- Breaking down complex problems into steps
|
|
10
|
+
- Planning and design with room for revision
|
|
11
|
+
- Analysis that might need course correction
|
|
12
|
+
- Problems where the full scope might not be clear initially
|
|
13
|
+
- Problems that require a multi-step solution
|
|
14
|
+
- Tasks that need to maintain context over multiple steps
|
|
15
|
+
- Situations where irrelevant information needs to be filtered out
|
|
16
|
+
- When you need guidance on which tools to use and in what order
|
|
17
|
+
- When you need guidance on which skills to invoke for specific workflows
|
|
18
|
+
|
|
19
|
+
Key features:
|
|
20
|
+
- You can adjust total_thoughts up or down as you progress
|
|
21
|
+
- You can question or revise previous thoughts
|
|
22
|
+
- You can add more thoughts even after reaching what seemed like the end
|
|
23
|
+
- You can express uncertainty and explore alternative approaches
|
|
24
|
+
- Not every thought needs to build linearly - you can branch or backtrack
|
|
25
|
+
- Generates a solution hypothesis
|
|
26
|
+
- Verifies the hypothesis based on the Chain of Thought steps
|
|
27
|
+
- Recommends appropriate tools for each step
|
|
28
|
+
- Recommends appropriate skills alongside tools
|
|
29
|
+
- Provides rationale for tool recommendations
|
|
30
|
+
- Suggests tool execution order and parameters
|
|
31
|
+
- Tracks previous recommendations and remaining steps
|
|
32
|
+
|
|
33
|
+
Parameters explained:
|
|
34
|
+
- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., ["mcp-omnisearch", "mcp-turso-cloud"])
|
|
35
|
+
- available_skills: (Optional) Array of skill names that are available for use (e.g., ["commit", "review-pr", "pdf"])
|
|
36
|
+
- thought: Your current thinking step, which can include:
|
|
37
|
+
* Regular analytical steps
|
|
38
|
+
* Revisions of previous thoughts
|
|
39
|
+
* Questions about previous decisions
|
|
40
|
+
* Realizations about needing more analysis
|
|
41
|
+
* Changes in approach
|
|
42
|
+
* Hypothesis generation
|
|
43
|
+
* Hypothesis verification
|
|
44
|
+
* Tool recommendations and rationale
|
|
45
|
+
- next_thought_needed: True if you need more thinking, even if at what seemed like the end
|
|
46
|
+
- thought_number: Current number in sequence (can go beyond initial total if needed)
|
|
47
|
+
- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)
|
|
48
|
+
- is_revision: A boolean indicating if this thought revises previous thinking
|
|
49
|
+
- revises_thought: If is_revision is true, which thought number is being reconsidered
|
|
50
|
+
- branch_from_thought: If branching, which thought number is the branching point
|
|
51
|
+
- branch_id: Identifier for the current branch (if any)
|
|
52
|
+
- needs_more_thoughts: If reaching end but realizing more thoughts needed
|
|
53
|
+
- current_step: Current step recommendation, including:
|
|
54
|
+
* step_description: What needs to be done
|
|
55
|
+
* recommended_tools: (CRITICAL: PLURAL - "recommended_tools" with an 's') Tools recommended for this step - MUST be an array.
|
|
56
|
+
* recommended_skills: (CRITICAL: PLURAL - "recommended_skills" with an 's') Skills recommended for this step (optional) - MUST be an array.
|
|
57
|
+
* expected_outcome: What to expect from this step
|
|
58
|
+
* next_step_conditions: Conditions to consider for the next step
|
|
59
|
+
- previous_steps: Steps already recommended (each step MUST use "recommended_tools" PLURAL)
|
|
60
|
+
- remaining_steps: High-level descriptions of upcoming steps
|
|
61
|
+
|
|
62
|
+
Reasoning Enhancement Parameters:
|
|
63
|
+
- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta'
|
|
64
|
+
- quality_score: Self-assessed quality of this thought (0-1)
|
|
65
|
+
- confidence: Confidence in this thought's correctness (0-1)
|
|
66
|
+
- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)
|
|
67
|
+
- verification_target: For 'verification'/'critique' types, the thought_number being evaluated
|
|
68
|
+
- synthesis_sources: For 'synthesis' type, the thought_numbers being combined
|
|
69
|
+
- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)
|
|
70
|
+
- merge_branch_ids: Branch IDs merged into current context
|
|
71
|
+
- meta_observation: Observation about reasoning process (with thought_type 'meta')
|
|
72
|
+
- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)
|
|
73
|
+
- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.
|
|
74
|
+
- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.
|
|
75
|
+
|
|
76
|
+
Response Enrichment:
|
|
77
|
+
- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)
|
|
78
|
+
- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). All components floored at 0.01 to prevent collapse.
|
|
79
|
+
- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5)
|
|
80
|
+
- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Present only when warnings are detected.
|
|
81
|
+
- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (4+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)
|
|
82
|
+
You should:
|
|
83
|
+
1. Start with an initial estimate of needed thoughts, but be ready to adjust
|
|
84
|
+
2. Feel free to question or revise previous thoughts
|
|
85
|
+
3. Don't hesitate to add more thoughts if needed, even at the "end"
|
|
86
|
+
4. Express uncertainty when present
|
|
87
|
+
5. Mark thoughts that revise previous thinking or branch into new paths
|
|
88
|
+
6. Ignore information that is irrelevant to the current step
|
|
89
|
+
7. Generate a solution hypothesis when appropriate
|
|
90
|
+
8. Verify the hypothesis based on the Chain of Thought steps
|
|
91
|
+
9. Consider available tools that could help with the current step
|
|
92
|
+
10. Provide clear rationale for tool recommendations
|
|
93
|
+
11. Suggest specific tool parameters when appropriate
|
|
94
|
+
12. Consider alternative tools for each step
|
|
95
|
+
13. Track progress through the recommended steps
|
|
96
|
+
14. Consider available skills that provide workflows for complex tasks
|
|
97
|
+
15. Coordinate skill invocation with tool recommendations (skills may call tools)
|
|
98
|
+
16. Provide a single, ideally correct answer as the final output
|
|
99
|
+
17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached
|
|
100
|
+
18. Classify your reasoning steps using thought_type for better analytics and self-awareness
|
|
101
|
+
19. Use hypothesis → verification chains to test solutions before committing
|
|
102
|
+
20. Self-assess quality and confidence to track reasoning reliability
|
|
103
|
+
21. Use merge_from_thoughts to combine insights from multiple reasoning branches
|
|
104
|
+
22. Use session_id to isolate independent reasoning chains from each other
|
|
105
|
+
23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;
|
|
106
|
+
const ToolRecommendationSchema = __rspack_external_valibot.object({
|
|
107
|
+
tool_name: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Name of the tool being recommended')),
|
|
108
|
+
confidence: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(0), __rspack_external_valibot.maxValue(1), __rspack_external_valibot.description('0-1 indicating confidence in recommendation')),
|
|
109
|
+
rationale: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Why this tool is recommended')),
|
|
110
|
+
priority: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.description('Order in the recommendation sequence (default: 999)'))),
|
|
111
|
+
suggested_inputs: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.record(__rspack_external_valibot.string(), __rspack_external_valibot.unknown()), __rspack_external_valibot.description('Optional suggested parameters'))),
|
|
112
|
+
alternatives: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Alternative tools that could be used')))
|
|
113
|
+
});
|
|
114
|
+
const SkillRecommendationSchema = __rspack_external_valibot.object({
|
|
115
|
+
skill_name: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Name of the skill being recommended')),
|
|
116
|
+
confidence: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(0), __rspack_external_valibot.maxValue(1), __rspack_external_valibot.description('0-1 indicating confidence in recommendation (default: 0.5)'))),
|
|
117
|
+
rationale: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Why this skill is recommended (default: empty string)'))),
|
|
118
|
+
priority: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.description('Order in the recommendation sequence (default: 999)'))),
|
|
119
|
+
alternatives: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Alternative skills that could be used'))),
|
|
120
|
+
allowed_tools: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Tools this skill is allowed to use (from skill frontmatter)'))),
|
|
121
|
+
user_invocable: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether this skill can be user-invoked')))
|
|
122
|
+
});
|
|
123
|
+
const StepRecommendationSchema = __rspack_external_valibot.object({
|
|
124
|
+
step_description: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('What needs to be done')),
|
|
125
|
+
recommended_tools: __rspack_external_valibot.pipe(__rspack_external_valibot.array(ToolRecommendationSchema), __rspack_external_valibot.description('Tools recommended for this step')),
|
|
126
|
+
recommended_skills: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(SkillRecommendationSchema), __rspack_external_valibot.description('Skills recommended for this step'))),
|
|
127
|
+
expected_outcome: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('What to expect from this step')),
|
|
128
|
+
next_step_conditions: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Conditions to consider for the next step')))
|
|
129
|
+
});
|
|
130
|
+
const PartialToolRecommendationSchema = __rspack_external_valibot.object({
|
|
131
|
+
tool_name: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Name of the tool being recommended')),
|
|
132
|
+
rationale: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Why this tool is recommended (default: empty string)'))),
|
|
133
|
+
confidence: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(0), __rspack_external_valibot.maxValue(1), __rspack_external_valibot.description('0-1 indicating confidence in recommendation (default: 0.5)'))),
|
|
134
|
+
priority: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.description('Order in the recommendation sequence (default: 999)'))),
|
|
135
|
+
suggested_inputs: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.record(__rspack_external_valibot.string(), __rspack_external_valibot.unknown()), __rspack_external_valibot.description('Optional suggested parameters'))),
|
|
136
|
+
alternatives: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Alternative tools that could be used')))
|
|
137
|
+
});
|
|
138
|
+
const PartialStepRecommendationSchema = __rspack_external_valibot.object({
|
|
139
|
+
step_description: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('What needs to be done')),
|
|
140
|
+
recommended_tools: __rspack_external_valibot.pipe(__rspack_external_valibot.array(PartialToolRecommendationSchema), __rspack_external_valibot.description('Tools recommended for this step')),
|
|
141
|
+
recommended_skills: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(SkillRecommendationSchema), __rspack_external_valibot.description('Skills recommended for this step'))),
|
|
142
|
+
expected_outcome: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('What to expect from this step (default: empty string)'))),
|
|
143
|
+
next_step_conditions: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Conditions to consider for the next step')))
|
|
144
|
+
});
|
|
145
|
+
const SequentialThinkingSchema = __rspack_external_valibot.object({
|
|
146
|
+
available_mcp_tools: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Array of MCP tool names available for use (e.g., ["mcp-omnisearch", "mcp-turso-cloud"])'))),
|
|
147
|
+
available_skills: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description('Array of skill names available for use (e.g., ["commit", "review-pr", "pdf"])'))),
|
|
148
|
+
thought: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Your current thinking step')),
|
|
149
|
+
next_thought_needed: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether another thought step is needed (defaults to true if not provided)'))),
|
|
150
|
+
thought_number: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Current thought number')),
|
|
151
|
+
total_thoughts: __rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Estimated total thoughts needed')),
|
|
152
|
+
is_revision: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('Whether this revises previous thinking'))),
|
|
153
|
+
revises_thought: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Which thought is being reconsidered'))),
|
|
154
|
+
branch_from_thought: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Branching point thought number'))),
|
|
155
|
+
branch_id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.regex(/^[a-zA-Z0-9_-]+$/, 'Branch ID must contain only letters, numbers, hyphens, and underscores'), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(50), __rspack_external_valibot.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)'))),
|
|
156
|
+
needs_more_thoughts: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('If more thoughts are needed'))),
|
|
157
|
+
current_step: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(StepRecommendationSchema, __rspack_external_valibot.description('Current step recommendation'))),
|
|
158
|
+
previous_steps: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(PartialStepRecommendationSchema), __rspack_external_valibot.description('Steps already recommended (lenient schema - allows partial data with defaults)'))),
|
|
159
|
+
remaining_steps: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.string()), __rspack_external_valibot.description("High-level descriptions of upcoming steps"))),
|
|
160
|
+
thought_type: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.picklist([
|
|
161
|
+
'regular',
|
|
162
|
+
'hypothesis',
|
|
163
|
+
'verification',
|
|
164
|
+
'critique',
|
|
165
|
+
'synthesis',
|
|
166
|
+
'meta'
|
|
167
|
+
]), __rspack_external_valibot.description('Classified purpose: regular, hypothesis, verification, critique, synthesis, meta'))),
|
|
168
|
+
quality_score: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(0), __rspack_external_valibot.maxValue(1), __rspack_external_valibot.description('Self-assessed quality score (0-1)'))),
|
|
169
|
+
confidence: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(0), __rspack_external_valibot.maxValue(1), __rspack_external_valibot.description('Explicit confidence in correctness (0-1)'))),
|
|
170
|
+
hypothesis_id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.regex(/^[a-zA-Z0-9_-]+$/, 'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(50), __rspack_external_valibot.description('Identifier linking hypothesis to verification thoughts'))),
|
|
171
|
+
verification_target: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1), __rspack_external_valibot.description('Thought number being verified or critiqued'))),
|
|
172
|
+
synthesis_sources: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1))), __rspack_external_valibot.description('Thought numbers being synthesized'))),
|
|
173
|
+
merge_from_thoughts: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.pipe(__rspack_external_valibot.number(), __rspack_external_valibot.minValue(1))), __rspack_external_valibot.description('Thought numbers from other branches being merged (DAG)'))),
|
|
174
|
+
merge_branch_ids: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.array(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.regex(/^[a-zA-Z0-9_-]+$/), __rspack_external_valibot.maxLength(50))), __rspack_external_valibot.description('Branch IDs being merged into current context'))),
|
|
175
|
+
meta_observation: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.description('Metacognitive observation about reasoning process'))),
|
|
176
|
+
reasoning_depth: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.picklist([
|
|
177
|
+
'shallow',
|
|
178
|
+
'moderate',
|
|
179
|
+
'deep'
|
|
180
|
+
]), __rspack_external_valibot.description('Effort signal: how deep reasoning should go'))),
|
|
181
|
+
session_id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.regex(/^[a-zA-Z0-9_-]+$/, 'Session ID must contain only letters, numbers, hyphens, and underscores'), __rspack_external_valibot.minLength(1), __rspack_external_valibot.maxLength(100), __rspack_external_valibot.description('Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'))),
|
|
182
|
+
reset_state: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.boolean(), __rspack_external_valibot.description('When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.')))
|
|
183
|
+
});
|
|
184
|
+
const SEQUENTIAL_THINKING_TOOL = {
|
|
185
|
+
name: 'sequentialthinking_tools',
|
|
186
|
+
description: TOOL_DESCRIPTION,
|
|
187
|
+
inputSchema: {}
|
|
188
|
+
};
|
|
189
|
+
const JsonRpcRequestSchema = __rspack_external_valibot.object({
|
|
190
|
+
jsonrpc: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.literal('2.0'), __rspack_external_valibot.description('JSON-RPC protocol version (must be "2.0")')),
|
|
191
|
+
method: __rspack_external_valibot.pipe(__rspack_external_valibot.string(), __rspack_external_valibot.minLength(1), __rspack_external_valibot.description('Method name to invoke')),
|
|
192
|
+
params: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.union([
|
|
193
|
+
__rspack_external_valibot.object({}),
|
|
194
|
+
__rspack_external_valibot.array(__rspack_external_valibot.unknown())
|
|
195
|
+
]), __rspack_external_valibot.description('Method parameters (object or array)'))),
|
|
196
|
+
id: __rspack_external_valibot.optional(__rspack_external_valibot.pipe(__rspack_external_valibot.union([
|
|
197
|
+
__rspack_external_valibot.string(),
|
|
198
|
+
__rspack_external_valibot.number(),
|
|
199
|
+
__rspack_external_valibot["null"]()
|
|
200
|
+
]), __rspack_external_valibot.description('Request ID (omit for notifications)')))
|
|
201
|
+
});
|
|
202
|
+
export { JsonRpcRequestSchema, PartialStepRecommendationSchema, PartialToolRecommendationSchema, SEQUENTIAL_THINKING_TOOL, SequentialThinkingSchema, SkillRecommendationSchema, StepRecommendationSchema, ToolRecommendationSchema };
|
|
203
|
+
|
|
204
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","sources":["../src/schema.ts"],"sourcesContent":["/**\n * Valibot validation schemas for the sequential thinking MCP tool.\n *\n * This module defines the validation schemas used for the sequential thinking tool,\n * including schemas for tool recommendations, skill recommendations, step recommendations,\n * and the main sequential thinking input. All schemas use Valibot for runtime validation\n * and provide detailed descriptions for MCP protocol compatibility.\n *\n * @remarks\n * **Schema Overview:**\n * - `ToolRecommendationSchema` - Validates tool recommendation objects with confidence scores\n * - `SkillRecommendationSchema` - Validates skill recommendation objects\n * - `StepRecommendationSchema` - Validates step coordination structures\n * - `SequentialThinkingSchema` - Main schema for thought input validation\n * - Reasoning enhancement fields: thought_type, quality_score, confidence, hypothesis_id, etc.\n *\n * @example\n * ```typescript\n * import { SequentialThinkingSchema } from './schema.js';\n * import { safeParse } from 'valibot';\n *\n * const result = safeParse(SequentialThinkingSchema, inputData);\n * if (result.success) {\n * const thought = result.output;\n * // Process the valid thought\n * } else {\n * console.error('Validation failed:', result.issues);\n * }\n * ```\n * @module schema\n */\n\nimport * as v from 'valibot';\nimport type { Tool } from './types/tool.js';\n/**\n * Detailed description for the sequential thinking tool.\n *\n * This description is shown to LLMs when they consider using this tool.\n * It explains when to use the tool, its features, parameters, and best practices.\n */\nconst TOOL_DESCRIPTION = `A detailed tool for dynamic and reflective problem-solving through thoughts.\nThis tool helps analyze problems through a flexible thinking process that can adapt and evolve.\nEach thought can build on, question, or revise previous insights as understanding deepens.\n\nIMPORTANT: This server facilitates sequential thinking with MCP tool coordination and skill recommendations. The LLM analyzes available tools and skills to make intelligent recommendations, which are then tracked and organized by this server.\n\nWhen to use this tool:\n- Breaking down complex problems into steps\n- Planning and design with room for revision\n- Analysis that might need course correction\n- Problems where the full scope might not be clear initially\n- Problems that require a multi-step solution\n- Tasks that need to maintain context over multiple steps\n- Situations where irrelevant information needs to be filtered out\n- When you need guidance on which tools to use and in what order\n- When you need guidance on which skills to invoke for specific workflows\n\nKey features:\n- You can adjust total_thoughts up or down as you progress\n- You can question or revise previous thoughts\n- You can add more thoughts even after reaching what seemed like the end\n- You can express uncertainty and explore alternative approaches\n- Not every thought needs to build linearly - you can branch or backtrack\n- Generates a solution hypothesis\n- Verifies the hypothesis based on the Chain of Thought steps\n- Recommends appropriate tools for each step\n- Recommends appropriate skills alongside tools\n- Provides rationale for tool recommendations\n- Suggests tool execution order and parameters\n- Tracks previous recommendations and remaining steps\n\nParameters explained:\n- available_mcp_tools: (Optional) Array of MCP tool names that are available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])\n- available_skills: (Optional) Array of skill names that are available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])\n- thought: Your current thinking step, which can include:\n* Regular analytical steps\n* Revisions of previous thoughts\n* Questions about previous decisions\n* Realizations about needing more analysis\n* Changes in approach\n* Hypothesis generation\n* Hypothesis verification\n* Tool recommendations and rationale\n- next_thought_needed: True if you need more thinking, even if at what seemed like the end\n- thought_number: Current number in sequence (can go beyond initial total if needed)\n- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)\n- is_revision: A boolean indicating if this thought revises previous thinking\n- revises_thought: If is_revision is true, which thought number is being reconsidered\n- branch_from_thought: If branching, which thought number is the branching point\n- branch_id: Identifier for the current branch (if any)\n- needs_more_thoughts: If reaching end but realizing more thoughts needed\n- current_step: Current step recommendation, including:\n* step_description: What needs to be done\n* recommended_tools: (CRITICAL: PLURAL - \"recommended_tools\" with an 's') Tools recommended for this step - MUST be an array.\n* recommended_skills: (CRITICAL: PLURAL - \"recommended_skills\" with an 's') Skills recommended for this step (optional) - MUST be an array.\n* expected_outcome: What to expect from this step\n* next_step_conditions: Conditions to consider for the next step\n- previous_steps: Steps already recommended (each step MUST use \"recommended_tools\" PLURAL)\n- remaining_steps: High-level descriptions of upcoming steps\n\nReasoning Enhancement Parameters:\n- thought_type: Thought purpose: 'regular' (default), 'hypothesis', 'verification', 'critique', 'synthesis', 'meta'\n- quality_score: Self-assessed quality of this thought (0-1)\n- confidence: Confidence in this thought's correctness (0-1)\n- hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)\n- verification_target: For 'verification'/'critique' types, the thought_number being evaluated\n- synthesis_sources: For 'synthesis' type, the thought_numbers being combined\n- merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)\n- merge_branch_ids: Branch IDs merged into current context\n- meta_observation: Observation about reasoning process (with thought_type 'meta')\n- reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)\n- session_id: (Optional) Unique identifier to scope thought history, branches, and statistics to an isolated session. When provided, all state is scoped to this session ID. When omitted, uses shared global state (backward compatible). Format: alphanumeric, hyphens, underscores, 1-100 chars.\n- reset_state: (Optional) When true, clears all state for the target session (or global state if no session_id) before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.\n\nResponse Enrichment:\n- When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)\n- confidence_signals.structural_quality: Composite 0-1 score — weighted geometric mean of type_diversity (0.3), verification_coverage (0.3), depth_efficiency (0.2), confidence_stability (0.2). All components floored at 0.01 to prevent collapse.\n- confidence_signals.quality_components: Individual metrics — type_diversity (Shannon entropy/log₂(6)), verification_coverage (verified/total hypotheses, 1.0 if none), depth_efficiency (max(chain_depth, branch_count+1)/total, branching rewarded), confidence_stability (1 - stddev(confidence), default 0.5)\n- reasoning_hints: (Conditional) Array of actionable hint strings from cross-thought pattern analysis. Only warning-severity patterns produce hints. Max 3 hints per response, with 3-thought cooldown per pattern per session. Present only when warnings are detected.\n- Detected patterns (internal, not in response): consecutive_without_verification (3+ regular thoughts without verification), unverified_hypothesis (hypothesis without verification within 3 thoughts), no_alternatives_explored (5+ thoughts with no critique/branches), monotonic_type (4+ consecutive same type), confidence_drift (3+ consecutive decreasing confidence), healthy_verification (hypothesis verified within 3 thoughts — info only)\nYou should:\n1. Start with an initial estimate of needed thoughts, but be ready to adjust\n2. Feel free to question or revise previous thoughts\n3. Don't hesitate to add more thoughts if needed, even at the \"end\"\n4. Express uncertainty when present\n5. Mark thoughts that revise previous thinking or branch into new paths\n6. Ignore information that is irrelevant to the current step\n7. Generate a solution hypothesis when appropriate\n8. Verify the hypothesis based on the Chain of Thought steps\n9. Consider available tools that could help with the current step\n10. Provide clear rationale for tool recommendations\n11. Suggest specific tool parameters when appropriate\n12. Consider alternative tools for each step\n13. Track progress through the recommended steps\n14. Consider available skills that provide workflows for complex tasks\n15. Coordinate skill invocation with tool recommendations (skills may call tools)\n16. Provide a single, ideally correct answer as the final output\n17. Only set next_thought_needed to false when truly done and a satisfactory answer is reached\n18. Classify your reasoning steps using thought_type for better analytics and self-awareness\n19. Use hypothesis → verification chains to test solutions before committing\n20. Self-assess quality and confidence to track reasoning reliability\n21. Use merge_from_thoughts to combine insights from multiple reasoning branches\n22. Use session_id to isolate independent reasoning chains from each other\n23. Use reset_state: true when starting a completely new analysis to avoid statistical contamination from previous chains`;\n\n/**\n * Valibot schema for validating tool recommendation objects.\n *\n * Validates that a tool recommendation has:\n * - A tool name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { ToolRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(ToolRecommendationSchema, {\n * tool_name: 'mcp__tavily-mcp__tavily-search',\n * confidence: 0.9,\n * rationale: 'Best for web search',\n * priority: 1\n * });\n * ```\n */\nexport const ToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\tconfidence: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(0),\n\t\tv.maxValue(1),\n\t\tv.description('0-1 indicating confidence in recommendation')\n\t),\n\trationale: v.pipe(v.string(), v.description('Why this tool is recommended')),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(v.record(v.string(), v.unknown()), v.description('Optional suggested parameters'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating skill recommendation objects.\n *\n * Validates that a skill recommendation has:\n * - A skill name (string)\n * - A confidence score between 0 and 1\n * - A rationale explaining the recommendation\n * - A priority number for ordering\n * - Optional alternative skills\n * - Optional allowed tools list\n * - Optional user invocable flag\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SkillRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(SkillRecommendationSchema, {\n * skill_name: 'commit',\n * confidence: 0.95,\n * rationale: 'Handles git commit workflow',\n * priority: 1,\n * user_invocable: true\n * });\n * ```\n */\nexport const SkillRecommendationSchema = v.object({\n\tskill_name: v.pipe(v.string(), v.description('Name of the skill being recommended')),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.description('Why this skill is recommended (default: empty string)'))\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative skills that could be used'))\n\t),\n\tallowed_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Tools this skill is allowed to use (from skill frontmatter)')\n\t\t)\n\t),\n\tuser_invocable: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this skill can be user-invoked'))\n\t),\n});\n\n/**\n * Valibot schema for validating step recommendation objects.\n *\n * Validates that a step recommendation has:\n * - A step description\n * - An array of recommended tools\n * - An optional array of recommended skills\n * - An expected outcome\n * - Optional conditions for the next step\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { StepRecommendationSchema } from './schema.js';\n *\n * const result = safeParse(StepRecommendationSchema, {\n * step_description: 'Search for TypeScript files',\n * recommended_tools: [{ ... }],\n * expected_outcome: 'List of all TypeScript files'\n * });\n * ```\n */\nexport const StepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(ToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.pipe(v.string(), v.description('What to expect from this step')),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial tool recommendation objects.\n *\n * This is a lenient version of ToolRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only tool_name and rationale\n * are required, while confidence and priority are optional with default values.\n *\n * Validates that a partial tool recommendation has:\n * - A tool name (required)\n * - A rationale explaining the recommendation (required)\n * - An optional confidence score (defaults to 0.5)\n * - An optional priority number (defaults to 999)\n * - Optional suggested input parameters\n * - Optional alternative tools\n *\n * @remarks\n * **Design Rationale:**\n * LLMs tend to provide complete data for current_step but only partial data\n * for previous_steps (historical context). This schema accommodates that natural\n * LLM behavior while maintaining data integrity through sensible defaults.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialToolRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialToolRecommendationSchema, {\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * });\n * // confidence and priority will be filled in by the normalizer\n * ```\n */\nexport const PartialToolRecommendationSchema = v.object({\n\ttool_name: v.pipe(v.string(), v.description('Name of the tool being recommended')),\n\trationale: v.optional(\n\t\tv.pipe(v.string(), v.description('Why this tool is recommended (default: empty string)'))\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('0-1 indicating confidence in recommendation (default: 0.5)')\n\t\t)\n\t),\n\tpriority: v.optional(\n\t\tv.pipe(v.number(), v.description('Order in the recommendation sequence (default: 999)'))\n\t),\n\tsuggested_inputs: v.optional(\n\t\tv.pipe(v.record(v.string(), v.unknown()), v.description('Optional suggested parameters'))\n\t),\n\talternatives: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Alternative tools that could be used'))\n\t),\n});\n\n/**\n * Valibot schema for validating partial step recommendation objects.\n *\n * This is a lenient version of StepRecommendationSchema used for previous_steps,\n * where LLMs naturally provide partial/skeletal data. Only step_description is\n * strictly required, while expected_outcome and tool recommendation fields are\n * optional with default values.\n *\n * Validates that a partial step recommendation has:\n * - A step description (required)\n * - An array of recommended tools (with optional confidence/priority)\n * - An optional array of recommended skills\n * - An optional expected outcome (defaults to empty string)\n * - Optional conditions for the next step\n *\n * @remarks\n * **Design Rationale:**\n * LLMs provide complete, detailed data for current_step but only brief summaries\n * for previous_steps. This schema allows the natural LLM behavior while the\n * InputNormalizer fills in sensible defaults for missing fields.\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { PartialStepRecommendationSchema } from './schema.js';\n *\n * // Minimal valid input (LLM often generates this for previous_steps)\n * const result = safeParse(PartialStepRecommendationSchema, {\n * step_description: 'Read the file',\n * recommended_tools: [{\n * tool_name: 'Read',\n * rationale: 'Read the file'\n * }]\n * });\n * // confidence, priority, and expected_outcome will be filled in by normalizer\n * ```\n */\nexport const PartialStepRecommendationSchema = v.object({\n\tstep_description: v.pipe(v.string(), v.description('What needs to be done')),\n\trecommended_tools: v.pipe(\n\t\tv.array(PartialToolRecommendationSchema),\n\t\tv.description('Tools recommended for this step')\n\t),\n\trecommended_skills: v.optional(\n\t\tv.pipe(v.array(SkillRecommendationSchema), v.description('Skills recommended for this step'))\n\t),\n\texpected_outcome: v.optional(\n\t\tv.pipe(v.string(), v.description('What to expect from this step (default: empty string)'))\n\t),\n\tnext_step_conditions: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('Conditions to consider for the next step'))\n\t),\n});\n\n/**\n * Main Valibot schema for validating sequential thinking tool input.\n *\n * This is the primary schema used for the sequential thinking MCP tool.\n * It validates all thought data including:\n * - Optional available tools and skills arrays\n * - The thought content (required)\n * - Thought numbering (thought_number, total_thoughts)\n * - Revision and branching metadata\n * - Current, previous, and remaining step recommendations\n *\n * @remarks\n * **Validation Rules:**\n * - `thought_number` must be >= 1\n * - `total_thoughts` must be >= 1\n * - `branch_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n * - `confidence` values must be between 0 and 1\n * - `thought_type` must be one of: regular, hypothesis, verification, critique, synthesis, meta\n * - `quality_score` and `confidence` must be between 0 and 1\n * - `hypothesis_id` must be 1-50 characters, alphanumeric/hyphens/underscores only\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { SequentialThinkingSchema } from './schema.js';\n *\n * const result = safeParse(SequentialThinkingSchema, {\n * thought: 'I need to analyze the problem',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * available_mcp_tools: ['Read', 'Write', 'Grep']\n * });\n *\n * if (result.success) {\n * console.log('Valid thought:', result.output);\n * } else {\n * console.error('Validation errors:', result.issues);\n * }\n * ```\n */\nexport const SequentialThinkingSchema = v.object({\n\tavailable_mcp_tools: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description(\n\t\t\t\t'Array of MCP tool names available for use (e.g., [\"mcp-omnisearch\", \"mcp-turso-cloud\"])'\n\t\t\t)\n\t\t)\n\t),\n\tavailable_skills: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.string()),\n\t\t\tv.description('Array of skill names available for use (e.g., [\"commit\", \"review-pr\", \"pdf\"])')\n\t\t)\n\t),\n\tthought: v.pipe(v.string(), v.description('Your current thinking step')),\n\tnext_thought_needed: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description('Whether another thought step is needed (defaults to true if not provided)')\n\t\t)\n\t),\n\tthought_number: v.pipe(v.number(), v.minValue(1), v.description('Current thought number')),\n\ttotal_thoughts: v.pipe(\n\t\tv.number(),\n\t\tv.minValue(1),\n\t\tv.description('Estimated total thoughts needed')\n\t),\n\tis_revision: v.optional(\n\t\tv.pipe(v.boolean(), v.description('Whether this revises previous thinking'))\n\t),\n\trevises_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Which thought is being reconsidered'))\n\t),\n\tbranch_from_thought: v.optional(\n\t\tv.pipe(v.number(), v.minValue(1), v.description('Branching point thought number'))\n\t),\n\tbranch_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Branch ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Branch identifier (alphanumeric, hyphens, underscores only, max 50 chars)')\n\t\t)\n\t),\n\tneeds_more_thoughts: v.optional(\n\t\tv.pipe(v.boolean(), v.description('If more thoughts are needed'))\n\t),\n\tcurrent_step: v.optional(\n\t\tv.pipe(StepRecommendationSchema, v.description('Current step recommendation'))\n\t),\n\tprevious_steps: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(PartialStepRecommendationSchema),\n\t\t\tv.description(\n\t\t\t\t'Steps already recommended (lenient schema - allows partial data with defaults)'\n\t\t\t)\n\t\t)\n\t),\n\tremaining_steps: v.optional(\n\t\tv.pipe(v.array(v.string()), v.description('High-level descriptions of upcoming steps'))\n\t),\n\tthought_type: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['regular', 'hypothesis', 'verification', 'critique', 'synthesis', 'meta']),\n\t\t\tv.description(\n\t\t\t\t'Classified purpose: regular, hypothesis, verification, critique, synthesis, meta'\n\t\t\t)\n\t\t)\n\t),\n\tquality_score: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Self-assessed quality score (0-1)')\n\t\t)\n\t),\n\tconfidence: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(0),\n\t\t\tv.maxValue(1),\n\t\t\tv.description('Explicit confidence in correctness (0-1)')\n\t\t)\n\t),\n\thypothesis_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(50),\n\t\t\tv.description('Identifier linking hypothesis to verification thoughts')\n\t\t)\n\t),\n\tverification_target: v.optional(\n\t\tv.pipe(\n\t\t\tv.number(),\n\t\t\tv.minValue(1),\n\t\t\tv.description('Thought number being verified or critiqued')\n\t\t)\n\t),\n\tsynthesis_sources: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers being synthesized')\n\t\t)\n\t),\n\tmerge_from_thoughts: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.number(), v.minValue(1))),\n\t\t\tv.description('Thought numbers from other branches being merged (DAG)')\n\t\t)\n\t),\n\tmerge_branch_ids: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+$/), v.maxLength(50))),\n\t\t\tv.description('Branch IDs being merged into current context')\n\t\t)\n\t),\n\tmeta_observation: v.optional(\n\t\tv.pipe(v.string(), v.description('Metacognitive observation about reasoning process'))\n\t),\n\treasoning_depth: v.optional(\n\t\tv.pipe(\n\t\t\tv.picklist(['shallow', 'moderate', 'deep']),\n\t\t\tv.description('Effort signal: how deep reasoning should go')\n\t\t)\n\t),\n\tsession_id: v.optional(\n\t\tv.pipe(\n\t\t\tv.string(),\n\t\t\tv.regex(\n\t\t\t\t/^[a-zA-Z0-9_-]+$/,\n\t\t\t\t'Session ID must contain only letters, numbers, hyphens, and underscores'\n\t\t\t),\n\t\t\tv.minLength(1),\n\t\t\tv.maxLength(100),\n\t\t\tv.description(\n\t\t\t\t'Optional session identifier for state isolation. When provided, thought history, branches, and statistics are scoped to this session. Omitting preserves global behavior.'\n\t\t\t)\n\t\t)\n\t),\n\treset_state: v.optional(\n\t\tv.pipe(\n\t\t\tv.boolean(),\n\t\t\tv.description(\n\t\t\t\t'When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'\n\t\t\t)\n\t\t)\n\t),\n});\n\n/**\n * The sequential thinking tool definition for MCP registration.\n *\n * This object defines the tool that is registered with the MCP server.\n * The inputSchema is left empty as the schema is handled by tmcp\n * when registering the tool using the Valibot adapter.\n *\n * @example\n * ```typescript\n * import { SEQUENTIAL_THINKING_TOOL } from './schema.js';\n * import { McpServer } from 'tmcp';\n *\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * server.tool({\n * name: SEQUENTIAL_THINKING_TOOL.name,\n * description: SEQUENTIAL_THINKING_TOOL.description,\n * schema: SequentialThinkingSchema\n * }, handler);\n * ```\n */\nexport const SEQUENTIAL_THINKING_TOOL: Tool = {\n\tname: 'sequentialthinking_tools',\n\tdescription: TOOL_DESCRIPTION,\n\tinputSchema: {}, // Schema is handled by tmcp when registering the tool\n};\n\n/**\n * Valibot schema for validating JSON-RPC 2.0 request messages.\n *\n * Validates that a JSON-RPC request has:\n * - A jsonrpc version (must be \"2.0\")\n * - A method name (string)\n * - Optional params (object or array)\n * - Optional id (string, number, or null for notifications)\n *\n * @example\n * ```typescript\n * import { safeParse } from 'valibot';\n * import { JsonRpcRequestSchema } from './schema.js';\n *\n * const result = safeParse(JsonRpcRequestSchema, {\n * jsonrpc: '2.0',\n * method: 'tools/list',\n * id: 1\n * });\n * ```\n */\nexport const JsonRpcRequestSchema = v.object({\n\tjsonrpc: v.pipe(\n\t\tv.string(),\n\t\tv.literal('2.0'),\n\t\tv.description('JSON-RPC protocol version (must be \"2.0\")')\n\t),\n\tmethod: v.pipe(v.string(), v.minLength(1), v.description('Method name to invoke')),\n\tparams: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.object({}), v.array(v.unknown())]),\n\t\t\tv.description('Method parameters (object or array)')\n\t\t)\n\t),\n\tid: v.optional(\n\t\tv.pipe(\n\t\t\tv.union([v.string(), v.number(), v.null()]),\n\t\t\tv.description('Request ID (omit for notifications)')\n\t\t)\n\t),\n});\n"],"names":["TOOL_DESCRIPTION","ToolRecommendationSchema","v","SkillRecommendationSchema","StepRecommendationSchema","PartialToolRecommendationSchema","PartialStepRecommendationSchema","SequentialThinkingSchema","SEQUENTIAL_THINKING_TOOL","JsonRpcRequestSchema"],"mappings":";AAwCA,MAAMA,mBAAmB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAIA,0BAAAA,QAAU,CACbA,0BAAAA,IAAM,CACLA,0BAAAA,KAAO,CAAC;QAACA,0BAAAA,MAAQ;QAAIA,0BAAAA,MAAQ;QAAIA,yBAAAA,CAAAA,OAAM;KAAG,GAC1CA,0BAAAA,WAAa,CAAC;AAGjB"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Logger } from '../logger/StructuredLogger.js';
|
|
2
|
+
export interface TelemetrySpan {
|
|
3
|
+
name: string;
|
|
4
|
+
kind: 'server' | 'client' | 'consumer' | 'producer' | 'internal';
|
|
5
|
+
startTime: number;
|
|
6
|
+
endTime?: number;
|
|
7
|
+
durationMs?: number;
|
|
8
|
+
attributes: Record<string, string | number | boolean>;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface TelemetryOptions {
|
|
12
|
+
enabled?: boolean;
|
|
13
|
+
serviceName?: string;
|
|
14
|
+
maxSpans?: number;
|
|
15
|
+
logger?: Logger;
|
|
16
|
+
}
|
|
17
|
+
type SpanContext = {
|
|
18
|
+
span: TelemetrySpan;
|
|
19
|
+
end: (error?: unknown) => TelemetrySpan;
|
|
20
|
+
};
|
|
21
|
+
export declare class Telemetry {
|
|
22
|
+
private _enabled;
|
|
23
|
+
private _serviceName;
|
|
24
|
+
private _maxSpans;
|
|
25
|
+
private _spans;
|
|
26
|
+
private _logger?;
|
|
27
|
+
constructor(options?: TelemetryOptions);
|
|
28
|
+
get isEnabled(): boolean;
|
|
29
|
+
startSpan(name: string, kind: TelemetrySpan['kind'], attributes?: Record<string, string | number | boolean>): SpanContext;
|
|
30
|
+
getSpans(): ReadonlyArray<TelemetrySpan>;
|
|
31
|
+
exportToJSON(): string;
|
|
32
|
+
exportToFile(filePath: string): Promise<void>;
|
|
33
|
+
clear(): void;
|
|
34
|
+
}
|
|
35
|
+
export {};
|
|
36
|
+
//# sourceMappingURL=Telemetry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Tel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CAAC,aAAa,CAAC;IAIxC,YAAY,IAAI,MAAM;IAIhB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOnD,KAAK,IAAI,IAAI;CAGb"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
class Telemetry {
|
|
2
|
+
_enabled;
|
|
3
|
+
_serviceName;
|
|
4
|
+
_maxSpans;
|
|
5
|
+
_spans = [];
|
|
6
|
+
_logger;
|
|
7
|
+
constructor(options = {}){
|
|
8
|
+
this._enabled = options.enabled ?? false;
|
|
9
|
+
this._serviceName = options.serviceName ?? 'trace-lattice';
|
|
10
|
+
this._maxSpans = options.maxSpans ?? 1000;
|
|
11
|
+
this._logger = options.logger;
|
|
12
|
+
}
|
|
13
|
+
get isEnabled() {
|
|
14
|
+
return this._enabled;
|
|
15
|
+
}
|
|
16
|
+
startSpan(name, kind, attributes = {}) {
|
|
17
|
+
const now = Date.now();
|
|
18
|
+
const span = {
|
|
19
|
+
name,
|
|
20
|
+
kind,
|
|
21
|
+
startTime: now,
|
|
22
|
+
attributes: {
|
|
23
|
+
service: this._serviceName,
|
|
24
|
+
...attributes
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
span,
|
|
29
|
+
end: (error)=>{
|
|
30
|
+
span.endTime = Date.now();
|
|
31
|
+
span.durationMs = span.endTime - span.startTime;
|
|
32
|
+
if (error instanceof Error) span.error = error.message;
|
|
33
|
+
else if ('string' == typeof error) span.error = error;
|
|
34
|
+
if (this._enabled) {
|
|
35
|
+
this._spans.push(span);
|
|
36
|
+
if (this._spans.length > this._maxSpans) this._spans = this._spans.slice(this._spans.length - this._maxSpans);
|
|
37
|
+
this._logger?.debug('Telemetry span recorded', {
|
|
38
|
+
name: span.name,
|
|
39
|
+
kind: span.kind,
|
|
40
|
+
durationMs: span.durationMs,
|
|
41
|
+
hasError: Boolean(span.error)
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return span;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
getSpans() {
|
|
49
|
+
return this._spans;
|
|
50
|
+
}
|
|
51
|
+
exportToJSON() {
|
|
52
|
+
return JSON.stringify(this._spans, null, 2);
|
|
53
|
+
}
|
|
54
|
+
async exportToFile(filePath) {
|
|
55
|
+
const { writeFile, mkdir } = await import("node:fs/promises");
|
|
56
|
+
const { dirname } = await import("node:path");
|
|
57
|
+
await mkdir(dirname(filePath), {
|
|
58
|
+
recursive: true
|
|
59
|
+
});
|
|
60
|
+
await writeFile(filePath, this.exportToJSON(), 'utf-8');
|
|
61
|
+
}
|
|
62
|
+
clear() {
|
|
63
|
+
this._spans = [];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export { Telemetry };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=Telemetry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry/Telemetry.js","sources":["../../src/telemetry/Telemetry.ts"],"sourcesContent":["import type { Logger } from '../logger/StructuredLogger.js';\n\nexport interface TelemetrySpan {\n\tname: string;\n\tkind: 'server' | 'client' | 'consumer' | 'producer' | 'internal';\n\tstartTime: number;\n\tendTime?: number;\n\tdurationMs?: number;\n\tattributes: Record<string, string | number | boolean>;\n\terror?: string;\n}\n\nexport interface TelemetryOptions {\n\tenabled?: boolean;\n\tserviceName?: string;\n\tmaxSpans?: number;\n\tlogger?: Logger;\n}\n\ntype SpanContext = {\n\tspan: TelemetrySpan;\n\tend: (error?: unknown) => TelemetrySpan;\n};\n\nexport class Telemetry {\n\tprivate _enabled: boolean;\n\tprivate _serviceName: string;\n\tprivate _maxSpans: number;\n\tprivate _spans: TelemetrySpan[] = [];\n\tprivate _logger?: Logger;\n\n\tconstructor(options: TelemetryOptions = {}) {\n\t\tthis._enabled = options.enabled ?? false;\n\t\tthis._serviceName = options.serviceName ?? 'trace-lattice';\n\t\tthis._maxSpans = options.maxSpans ?? 1000;\n\t\tthis._logger = options.logger;\n\t}\n\n\tget isEnabled(): boolean {\n\t\treturn this._enabled;\n\t}\n\n\tstartSpan(\n\t\tname: string,\n\t\tkind: TelemetrySpan['kind'],\n\t\tattributes: Record<string, string | number | boolean> = {}\n\t): SpanContext {\n\t\tconst now = Date.now();\n\t\tconst span: TelemetrySpan = {\n\t\t\tname,\n\t\t\tkind,\n\t\t\tstartTime: now,\n\t\t\tattributes: {\n\t\t\t\tservice: this._serviceName,\n\t\t\t\t...attributes,\n\t\t\t},\n\t\t};\n\n\t\treturn {\n\t\t\tspan,\n\t\t\tend: (error?: unknown): TelemetrySpan => {\n\t\t\t\tspan.endTime = Date.now();\n\t\t\t\tspan.durationMs = span.endTime - span.startTime;\n\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\tspan.error = error.message;\n\t\t\t\t} else if (typeof error === 'string') {\n\t\t\t\t\tspan.error = error;\n\t\t\t\t}\n\n\t\t\t\tif (this._enabled) {\n\t\t\t\t\tthis._spans.push(span);\n\t\t\t\t\tif (this._spans.length > this._maxSpans) {\n\t\t\t\t\t\tthis._spans = this._spans.slice(this._spans.length - this._maxSpans);\n\t\t\t\t\t}\n\t\t\t\t\tthis._logger?.debug('Telemetry span recorded', {\n\t\t\t\t\t\tname: span.name,\n\t\t\t\t\t\tkind: span.kind,\n\t\t\t\t\t\tdurationMs: span.durationMs,\n\t\t\t\t\t\thasError: Boolean(span.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn span;\n\t\t\t},\n\t\t};\n\t}\n\n\tgetSpans(): ReadonlyArray<TelemetrySpan> {\n\t\treturn this._spans;\n\t}\n\n\texportToJSON(): string {\n\t\treturn JSON.stringify(this._spans, null, 2);\n\t}\n\n\tasync exportToFile(filePath: string): Promise<void> {\n\t\tconst { writeFile, mkdir } = await import('node:fs/promises');\n\t\tconst { dirname } = await import('node:path');\n\t\tawait mkdir(dirname(filePath), { recursive: true });\n\t\tawait writeFile(filePath, this.exportToJSON(), 'utf-8');\n\t}\n\n\tclear(): void {\n\t\tthis._spans = [];\n\t}\n}\n"],"names":["Telemetry","options","name","kind","attributes","now","Date","span","error","Error","Boolean","JSON","filePath","writeFile","mkdir","dirname"],"mappings":"AAwBO,MAAMA;IACJ,SAAkB;IAClB,aAAqB;IACrB,UAAkB;IAClB,SAA0B,EAAE,CAAC;IAC7B,QAAiB;IAEzB,YAAYC,UAA4B,CAAC,CAAC,CAAE;QAC3C,IAAI,CAAC,QAAQ,GAAGA,QAAQ,OAAO,IAAI;QACnC,IAAI,CAAC,YAAY,GAAGA,QAAQ,WAAW,IAAI;QAC3C,IAAI,CAAC,SAAS,GAAGA,QAAQ,QAAQ,IAAI;QACrC,IAAI,CAAC,OAAO,GAAGA,QAAQ,MAAM;IAC9B;IAEA,IAAI,YAAqB;QACxB,OAAO,IAAI,CAAC,QAAQ;IACrB;IAEA,UACCC,IAAY,EACZC,IAA2B,EAC3BC,aAAwD,CAAC,CAAC,EAC5C;QACd,MAAMC,MAAMC,KAAK,GAAG;QACpB,MAAMC,OAAsB;YAC3BL;YACAC;YACA,WAAWE;YACX,YAAY;gBACX,SAAS,IAAI,CAAC,YAAY;gBAC1B,GAAGD,UAAU;YACd;QACD;QAEA,OAAO;YACNG;YACA,KAAK,CAACC;gBACLD,KAAK,OAAO,GAAGD,KAAK,GAAG;gBACvBC,KAAK,UAAU,GAAGA,KAAK,OAAO,GAAGA,KAAK,SAAS;gBAC/C,IAAIC,iBAAiBC,OACpBF,KAAK,KAAK,GAAGC,MAAM,OAAO;qBACpB,IAAI,AAAiB,YAAjB,OAAOA,OACjBD,KAAK,KAAK,GAAGC;gBAGd,IAAI,IAAI,CAAC,QAAQ,EAAE;oBAClB,IAAI,CAAC,MAAM,CAAC,IAAI,CAACD;oBACjB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,SAAS,EACtC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,SAAS;oBAEpE,IAAI,CAAC,OAAO,EAAE,MAAM,2BAA2B;wBAC9C,MAAMA,KAAK,IAAI;wBACf,MAAMA,KAAK,IAAI;wBACf,YAAYA,KAAK,UAAU;wBAC3B,UAAUG,QAAQH,KAAK,KAAK;oBAC7B;gBACD;gBAEA,OAAOA;YACR;QACD;IACD;IAEA,WAAyC;QACxC,OAAO,IAAI,CAAC,MAAM;IACnB;IAEA,eAAuB;QACtB,OAAOI,KAAK,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM;IAC1C;IAEA,MAAM,aAAaC,QAAgB,EAAiB;QACnD,MAAM,EAAEC,SAAS,EAAEC,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,MAAM,EAAEC,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC;QACjC,MAAMD,MAAMC,QAAQH,WAAW;YAAE,WAAW;QAAK;QACjD,MAAMC,UAAUD,UAAU,IAAI,CAAC,YAAY,IAAI;IAChD;IAEA,QAAc;QACb,IAAI,CAAC,MAAM,GAAG,EAAE;IACjB;AACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Telemetry.test.d.ts","sourceRoot":"","sources":["../../../src/telemetry/__tests__/Telemetry.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base transport implementation.
|
|
3
|
+
*
|
|
4
|
+
* This class provides shared functionality for all transport implementations,
|
|
5
|
+
* including session validation, rate limiting, CORS handling, and IP extraction.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* **Security Features:**
|
|
9
|
+
* - Session ID validation (alphanumeric, max 64 chars)
|
|
10
|
+
* - Query parameter sanitization (whitelist allowed keys)
|
|
11
|
+
* - Rate limiting per IP (configurable, default 100 req/min)
|
|
12
|
+
* - CORS origin validation
|
|
13
|
+
*
|
|
14
|
+
* **Rate Limiting:**
|
|
15
|
+
* - Tracks requests per IP address within a time window
|
|
16
|
+
* - Returns 429 Too Many Requests when limit exceeded
|
|
17
|
+
* - Can be disabled via `enableRateLimit: false`
|
|
18
|
+
*/
|
|
19
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
20
|
+
import { URL } from 'node:url';
|
|
21
|
+
import type { HealthChecker } from '../health/HealthChecker.js';
|
|
22
|
+
import type { Logger } from '../logger/StructuredLogger.js';
|
|
23
|
+
/**
|
|
24
|
+
* Transport interface contract for MCP server communication.
|
|
25
|
+
* All transport implementations must implement this interface.
|
|
26
|
+
*/
|
|
27
|
+
export interface ITransport {
|
|
28
|
+
/**
|
|
29
|
+
* Connect the transport to an MCP server.
|
|
30
|
+
*/
|
|
31
|
+
connect(mcpServer: unknown): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Stop the transport with graceful shutdown.
|
|
34
|
+
* @param timeout - Maximum time to wait for in-flight requests (default: 30s)
|
|
35
|
+
*/
|
|
36
|
+
stop(timeout?: number): Promise<void>;
|
|
37
|
+
/**
|
|
38
|
+
* Number of currently connected clients.
|
|
39
|
+
*/
|
|
40
|
+
readonly clientCount: number;
|
|
41
|
+
}
|
|
42
|
+
export interface TransportOptions {
|
|
43
|
+
port?: number;
|
|
44
|
+
host?: string;
|
|
45
|
+
allowedHosts?: string[];
|
|
46
|
+
corsOrigin?: string;
|
|
47
|
+
enableCors?: boolean;
|
|
48
|
+
enableRateLimit?: boolean;
|
|
49
|
+
maxRequestsPerMinute?: number;
|
|
50
|
+
logger?: Logger;
|
|
51
|
+
healthChecker?: HealthChecker;
|
|
52
|
+
}
|
|
53
|
+
export declare abstract class BaseTransport implements ITransport {
|
|
54
|
+
protected _port: number;
|
|
55
|
+
protected _host: string;
|
|
56
|
+
protected _corsOrigin: string;
|
|
57
|
+
protected _enableCors: boolean;
|
|
58
|
+
protected _rateLimitEnabled: boolean;
|
|
59
|
+
protected _maxRequestsPerMinute: number;
|
|
60
|
+
protected _allowedHosts: Set<string>;
|
|
61
|
+
protected _rateLimitMap: Map<string, {
|
|
62
|
+
count: number;
|
|
63
|
+
resetTime: number;
|
|
64
|
+
}>;
|
|
65
|
+
protected _rateLimitCleanupIntervalId: NodeJS.Timeout | null;
|
|
66
|
+
protected _wasHostExplicitlySet: boolean;
|
|
67
|
+
/** Shutdown state for graceful shutdown. */
|
|
68
|
+
protected _isShuttingDown: boolean;
|
|
69
|
+
private _logger;
|
|
70
|
+
protected _healthChecker: HealthChecker | null;
|
|
71
|
+
constructor(options?: TransportOptions);
|
|
72
|
+
/**
|
|
73
|
+
* Get the server URL with localhost substitution for default host.
|
|
74
|
+
*/
|
|
75
|
+
get serverUrl(): string;
|
|
76
|
+
/**
|
|
77
|
+
* Validate session ID format.
|
|
78
|
+
*
|
|
79
|
+
* @param sessionId - The session ID to validate
|
|
80
|
+
* @returns true if valid, false otherwise
|
|
81
|
+
*/
|
|
82
|
+
protected validateSessionId(sessionId: string): boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Sanitize query parameters by removing any not in whitelist.
|
|
85
|
+
*
|
|
86
|
+
* @param url - The URL object containing query parameters
|
|
87
|
+
* @returns A sanitized record of allowed query parameters
|
|
88
|
+
*/
|
|
89
|
+
protected sanitizeQueryParams(url: URL): Record<string, string>;
|
|
90
|
+
/**
|
|
91
|
+
* Check rate limit for a given IP address.
|
|
92
|
+
*
|
|
93
|
+
* @param ip - The IP address to check
|
|
94
|
+
* @returns true if rate limit exceeded, false otherwise
|
|
95
|
+
*/
|
|
96
|
+
protected checkRateLimit(ip: string): boolean;
|
|
97
|
+
protected _cleanupExpiredRateLimitEntries(now?: number): void;
|
|
98
|
+
protected _startRateLimitCleanup(): void;
|
|
99
|
+
protected _stopRateLimitCleanup(): void;
|
|
100
|
+
/**
|
|
101
|
+
* Get client IP address from request.
|
|
102
|
+
*
|
|
103
|
+
* @param req - The incoming request
|
|
104
|
+
* @returns The client IP address
|
|
105
|
+
*/
|
|
106
|
+
protected getClientIp(req: IncomingMessage): string;
|
|
107
|
+
/**
|
|
108
|
+
* Validate CORS origin from request headers.
|
|
109
|
+
*
|
|
110
|
+
* @param req - The incoming request
|
|
111
|
+
* @returns true if origin is valid, false otherwise
|
|
112
|
+
*/
|
|
113
|
+
protected validateCorsOrigin(req: IncomingMessage): boolean;
|
|
114
|
+
/**
|
|
115
|
+
* Set CORS headers on response.
|
|
116
|
+
*
|
|
117
|
+
* @param res - The server response
|
|
118
|
+
*/
|
|
119
|
+
protected setCorsHeaders(res: ServerResponse): void;
|
|
120
|
+
protected validateHostHeader(req: IncomingMessage): boolean;
|
|
121
|
+
private _buildAllowedHosts;
|
|
122
|
+
/**
|
|
123
|
+
* Log a message using the configured logger.
|
|
124
|
+
*
|
|
125
|
+
* @param level - Log level
|
|
126
|
+
* @param message - Message to log
|
|
127
|
+
* @param meta - Optional metadata
|
|
128
|
+
*/
|
|
129
|
+
protected log(level: 'info' | 'warn' | 'error', message: string, meta?: Record<string, unknown>): void;
|
|
130
|
+
/**
|
|
131
|
+
* Check if transport is shutting down.
|
|
132
|
+
* @returns true if in shutdown phase
|
|
133
|
+
*/
|
|
134
|
+
protected isShuttingDown(): boolean;
|
|
135
|
+
/**
|
|
136
|
+
* Handle GET /health endpoint — liveness check.
|
|
137
|
+
*
|
|
138
|
+
* Builds a standard health response with optional liveness data from the health checker.
|
|
139
|
+
* Transports can pass extra data (e.g. client counts, session info).
|
|
140
|
+
*
|
|
141
|
+
* @param res - The server response
|
|
142
|
+
* @param extraData - Optional additional health metadata
|
|
143
|
+
*/
|
|
144
|
+
protected handleHealthEndpoint(res: ServerResponse, extraData?: Record<string, unknown>): void;
|
|
145
|
+
/**
|
|
146
|
+
* Handle GET /ready endpoint — readiness check.
|
|
147
|
+
*
|
|
148
|
+
* Delegates to the health checker if available, otherwise returns a default OK response.
|
|
149
|
+
*
|
|
150
|
+
* @param res - The server response
|
|
151
|
+
*/
|
|
152
|
+
protected handleReadinessEndpoint(res: ServerResponse): Promise<void>;
|
|
153
|
+
/**
|
|
154
|
+
* Handle GET /metrics endpoint — Prometheus metrics.
|
|
155
|
+
*
|
|
156
|
+
* Returns 404 if no metrics provider is configured.
|
|
157
|
+
*
|
|
158
|
+
* @param res - The server response
|
|
159
|
+
* @param metricsProvider - Function that returns Prometheus-format metrics text
|
|
160
|
+
*/
|
|
161
|
+
protected handleMetricsEndpoint(res: ServerResponse, metricsProvider: (() => string) | null): void;
|
|
162
|
+
/**
|
|
163
|
+
* Connect to MCP server.
|
|
164
|
+
*/
|
|
165
|
+
abstract connect(mcpServer: unknown): Promise<void>;
|
|
166
|
+
/**
|
|
167
|
+
* Stop transport server with graceful shutdown.
|
|
168
|
+
*
|
|
169
|
+
* This method should:
|
|
170
|
+
* 1. Set shutdown flag to prevent new connections
|
|
171
|
+
* 2. Wait for in-flight requests to complete (configurable timeout)
|
|
172
|
+
* 3. Close server connections
|
|
173
|
+
* 4. Release resources
|
|
174
|
+
*
|
|
175
|
+
* @param timeout - Maximum time to wait for requests to drain (default: 30 seconds)
|
|
176
|
+
* @returns Promise that resolves when shutdown is complete
|
|
177
|
+
*/
|
|
178
|
+
abstract stop(timeout?: number): Promise<void>;
|
|
179
|
+
/**
|
|
180
|
+
* Get number of clients connected.
|
|
181
|
+
*/
|
|
182
|
+
abstract get clientCount(): number;
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=BaseTransport.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseTransport.d.ts","sourceRoot":"","sources":["../../src/transport/BaseTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,MAAM,EAAY,MAAM,+BAA+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