tracelattice 1.3.2 → 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.
- package/README.md +25 -25
- package/dist/ServerConfig.d.ts +16 -23
- package/dist/ServerConfig.d.ts.map +1 -1
- package/dist/ServerConfig.js +12 -1
- package/dist/ServerConfig.js.map +1 -1
- package/dist/__tests__/core/HistoryManager.ownership.test.d.ts +2 -0
- package/dist/__tests__/core/HistoryManager.ownership.test.d.ts.map +1 -0
- package/dist/__tests__/core/SessionLock.test.d.ts +6 -0
- package/dist/__tests__/core/SessionLock.test.d.ts.map +1 -0
- package/dist/__tests__/core/SessionManager.test.d.ts +8 -0
- package/dist/__tests__/core/SessionManager.test.d.ts.map +1 -0
- package/dist/__tests__/core/ThoughtProcessor.toolAllowlist.test.d.ts +2 -0
- package/dist/__tests__/core/ThoughtProcessor.toolAllowlist.test.d.ts.map +1 -0
- package/dist/__tests__/eval/fixtures/scenarios.d.ts.map +1 -1
- package/dist/__tests__/helpers/factories.d.ts +20 -1
- package/dist/__tests__/helpers/factories.d.ts.map +1 -1
- package/dist/__tests__/sanitize.enforceJsonShape.test.d.ts +2 -0
- package/dist/__tests__/sanitize.enforceJsonShape.test.d.ts.map +1 -0
- package/dist/__tests__/transport-owner-context.test.d.ts +8 -0
- package/dist/__tests__/transport-owner-context.test.d.ts.map +1 -0
- package/dist/cache/DiscoveryCache.d.ts +1 -1
- package/dist/cache/DiscoveryCache.d.ts.map +1 -1
- package/dist/cache/DiscoveryCache.js.map +1 -1
- package/dist/cli.js +3602 -8
- package/dist/config/ConfigLoader.d.ts +9 -2
- package/dist/config/ConfigLoader.d.ts.map +1 -1
- package/dist/config/ConfigLoader.js +12 -5
- package/dist/config/ConfigLoader.js.map +1 -1
- package/dist/context/RequestContext.d.ts +26 -0
- package/dist/context/RequestContext.d.ts.map +1 -1
- package/dist/context/RequestContext.js +7 -1
- package/dist/context/RequestContext.js.map +1 -1
- package/dist/contracts/PersistenceBackend.d.ts.map +1 -0
- package/dist/contracts/features.d.ts +39 -0
- package/dist/contracts/features.d.ts.map +1 -0
- package/dist/contracts/features.js +15 -0
- package/dist/contracts/features.js.map +1 -0
- package/dist/contracts/ids.d.ts +58 -0
- package/dist/contracts/ids.d.ts.map +1 -0
- package/dist/contracts/ids.js +31 -0
- package/dist/contracts/ids.js.map +1 -0
- package/dist/contracts/interfaces.d.ts +48 -3
- package/dist/contracts/interfaces.d.ts.map +1 -1
- package/dist/contracts/strategy.d.ts +2 -2
- package/dist/contracts/strategy.d.ts.map +1 -1
- package/dist/contracts/suspension.d.ts +3 -2
- package/dist/contracts/suspension.d.ts.map +1 -1
- package/dist/contracts/transport.d.ts +25 -0
- package/dist/contracts/transport.d.ts.map +1 -0
- package/dist/core/HistoryManager.d.ts +15 -4
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +25 -14
- package/dist/core/HistoryManager.js.map +1 -1
- package/dist/core/IHistoryManager.d.ts +10 -0
- package/dist/core/IHistoryManager.d.ts.map +1 -1
- package/dist/core/IThoughtFormatter.d.ts +51 -0
- package/dist/core/IThoughtFormatter.d.ts.map +1 -0
- package/dist/core/IThoughtFormatter.js +1 -0
- package/dist/core/InputNormalizer.d.ts.map +1 -1
- package/dist/core/InputNormalizer.js +9 -5
- package/dist/core/InputNormalizer.js.map +1 -1
- package/dist/core/PersistenceBuffer.d.ts +1 -1
- package/dist/core/PersistenceBuffer.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.js.map +1 -1
- package/dist/core/SessionLock.d.ts +56 -0
- package/dist/core/SessionLock.d.ts.map +1 -0
- package/dist/core/SessionLock.js +43 -0
- package/dist/core/SessionLock.js.map +1 -0
- package/dist/core/SessionManager.d.ts +18 -3
- package/dist/core/SessionManager.d.ts.map +1 -1
- package/dist/core/SessionManager.js +34 -1
- package/dist/core/SessionManager.js.map +1 -1
- package/dist/core/ThoughtFormatter.d.ts +2 -1
- package/dist/core/ThoughtFormatter.d.ts.map +1 -1
- package/dist/core/ThoughtFormatter.js +3 -0
- package/dist/core/ThoughtFormatter.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts +22 -3
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +41 -16
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/compression/CompressionService.js +3 -3
- package/dist/core/compression/CompressionService.js.map +1 -1
- package/dist/core/compression/Summary.d.ts +4 -3
- package/dist/core/compression/Summary.d.ts.map +1 -1
- package/dist/core/graph/Edge.d.ts +11 -4
- package/dist/core/graph/Edge.d.ts.map +1 -1
- package/dist/core/graph/EdgeEmitter.js +5 -5
- package/dist/core/graph/EdgeEmitter.js.map +1 -1
- package/dist/core/reasoning/strategies/StrategyFactory.d.ts +1 -1
- package/dist/core/reasoning/strategies/StrategyFactory.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/StrategyFactory.js.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +5 -0
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
- package/dist/core/reasoning.d.ts +8 -1
- package/dist/core/reasoning.d.ts.map +1 -1
- package/dist/core/step.d.ts +5 -0
- package/dist/core/step.d.ts.map +1 -1
- package/dist/core/thought.d.ts +4 -3
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/core/tools/InMemorySuspensionStore.d.ts +3 -1
- package/dist/core/tools/InMemorySuspensionStore.d.ts.map +1 -1
- package/dist/core/tools/InMemorySuspensionStore.js +2 -2
- package/dist/core/tools/InMemorySuspensionStore.js.map +1 -1
- package/dist/di/Container.d.ts +6 -3
- package/dist/di/Container.d.ts.map +1 -1
- package/dist/di/Container.js.map +1 -1
- package/dist/di/ServiceRegistry.d.ts +6 -6
- package/dist/di/ServiceRegistry.d.ts.map +1 -1
- package/dist/errors.d.ts +84 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +85 -22
- package/dist/errors.js.map +1 -1
- package/dist/health/HealthChecker.d.ts +1 -1
- package/dist/health/HealthChecker.d.ts.map +1 -1
- package/dist/health/HealthChecker.js.map +1 -1
- package/dist/lib.d.ts +60 -2
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +9 -3
- package/dist/lib.js.map +1 -1
- package/dist/persistence/FilePersistence.d.ts +2 -2
- package/dist/persistence/FilePersistence.d.ts.map +1 -1
- package/dist/persistence/FilePersistence.js.map +1 -1
- package/dist/persistence/MemoryPersistence.d.ts +1 -1
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
- package/dist/persistence/MemoryPersistence.js.map +1 -1
- package/dist/persistence/PersistenceFactory.d.ts +1 -1
- package/dist/persistence/PersistenceFactory.d.ts.map +1 -1
- package/dist/persistence/PersistenceFactory.js.map +1 -1
- package/dist/persistence/SqlitePersistence.d.ts +1 -1
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
- package/dist/persistence/SqlitePersistence.js.map +1 -1
- package/dist/pool/ConnectionPool.d.ts +11 -13
- package/dist/pool/ConnectionPool.d.ts.map +1 -1
- package/dist/pool/ConnectionPool.js.map +1 -1
- package/dist/pool/IConnectionPool.d.ts +100 -0
- package/dist/pool/IConnectionPool.d.ts.map +1 -0
- package/dist/pool/IConnectionPool.js +1 -0
- package/dist/registry/BaseRegistry.d.ts +1 -1
- package/dist/registry/BaseRegistry.d.ts.map +1 -1
- package/dist/registry/BaseRegistry.js.map +1 -1
- package/dist/registry/ToolRegistry.d.ts +1 -0
- package/dist/registry/ToolRegistry.d.ts.map +1 -1
- package/dist/registry/ToolRegistry.js +3 -0
- package/dist/registry/ToolRegistry.js.map +1 -1
- package/dist/sanitize.d.ts +70 -0
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +77 -1
- package/dist/sanitize.js.map +1 -1
- package/dist/schema.d.ts +35 -35
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +15 -5
- package/dist/schema.js.map +1 -1
- package/dist/transport/BaseTransport.d.ts +3 -2
- package/dist/transport/BaseTransport.d.ts.map +1 -1
- package/dist/transport/BaseTransport.js +1 -1
- package/dist/transport/BaseTransport.js.map +1 -1
- package/dist/transport/HttpTransport.d.ts +4 -2
- package/dist/transport/HttpTransport.d.ts.map +1 -1
- package/dist/transport/HttpTransport.js +13 -4
- package/dist/transport/HttpTransport.js.map +1 -1
- package/dist/transport/SseTransport.d.ts +4 -2
- package/dist/transport/SseTransport.d.ts.map +1 -1
- package/dist/transport/SseTransport.js +13 -3
- package/dist/transport/SseTransport.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +4 -2
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +12 -4
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/dist/types/skill.d.ts +5 -0
- package/dist/types/skill.d.ts.map +1 -1
- package/dist/types/tool.d.ts +6 -1
- package/dist/types/tool.d.ts.map +1 -1
- package/package.json +12 -11
- package/dist/__tests__/helpers/index.d.ts +0 -3
- package/dist/__tests__/helpers/index.d.ts.map +0 -1
- package/dist/contracts/index.d.ts +0 -14
- package/dist/contracts/index.d.ts.map +0 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -1
- package/dist/persistence/PersistenceBackend.d.ts.map +0 -1
- /package/dist/{persistence → contracts}/PersistenceBackend.d.ts +0 -0
- /package/dist/{persistence → contracts}/PersistenceBackend.js +0 -0
- /package/dist/contracts/{index.js → transport.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TreeOfThoughtStrategy.d.ts","sourceRoot":"","sources":["../../../../src/core/reasoning/strategies/TreeOfThoughtStrategy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EACX,kBAAkB,EAClB,eAAe,EACf,gBAAgB,EAChB,MAAM,gCA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,qBAAsB,YAAW,kBAAkB;IAC/D,QAAQ,CAAC,IAAI,EAAG,KAAK,CAAU;IAE/B,6CAA6C;gBACjC,MAAM,CAAC,EAAE,SAAS;IAI9B;;;;;OAKG;IACH,MAAM,CAAC,GAAG,EAAE,eAAe,GAAG,gBAAgB;IAiC9C,2EAA2E;IAC3E,YAAY,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO;IAO3C,iFAAiF;IACjF,eAAe,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO;CAY9C"}
|
|
@@ -51,6 +51,9 @@ class TreeOfThoughtStrategy {
|
|
|
51
51
|
}
|
|
52
52
|
decide(ctx) {
|
|
53
53
|
const cfg = configOf(this);
|
|
54
|
+
if (!ctx.graph) return {
|
|
55
|
+
action: 'continue'
|
|
56
|
+
};
|
|
54
57
|
const frontier = ctx.graph.leaves(ctx.sessionId);
|
|
55
58
|
const byKey = indexHistory(ctx.history);
|
|
56
59
|
const scored = scoreFrontier(frontier, byKey);
|
|
@@ -80,11 +83,13 @@ class TreeOfThoughtStrategy {
|
|
|
80
83
|
}
|
|
81
84
|
shouldBranch(ctx) {
|
|
82
85
|
const cfg = configOf(this);
|
|
86
|
+
if (!ctx.graph) return false;
|
|
83
87
|
const frontier = ctx.graph.leaves(ctx.sessionId);
|
|
84
88
|
return frontier.length > cfg.beamWidth;
|
|
85
89
|
}
|
|
86
90
|
shouldTerminate(ctx) {
|
|
87
91
|
const cfg = configOf(this);
|
|
92
|
+
if (!ctx.graph) return false;
|
|
88
93
|
const frontier = ctx.graph.leaves(ctx.sessionId);
|
|
89
94
|
const byKey = indexHistory(ctx.history);
|
|
90
95
|
const scored = scoreFrontier(frontier, byKey);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/reasoning/strategies/TreeOfThoughtStrategy.js","sources":["../../../../src/core/reasoning/strategies/TreeOfThoughtStrategy.ts"],"sourcesContent":["/**\n * Tree-of-Thought reasoning strategy — beam search over the thought DAG.\n *\n * Observes the frontier (graph leaves), scores each leaf via\n * {@link scoreThought}, and decides whether to continue, branch (when the\n * current thought falls outside the beam), or terminate (on confidence\n * threshold or score plateau).\n *\n * Pure policy: configuration lives in a module-level {@link WeakMap}, not\n * on the instance, so `Object.getOwnPropertyNames(strategy)` only ever\n * surfaces the readonly `name` discriminator. All other state is derived\n * from the {@link StrategyContext} on every call.\n *\n * @module core/reasoning/strategies/TreeOfThoughtStrategy\n */\n\nimport type {\n\tIReasoningStrategy,\n\tStrategyContext,\n\tStrategyDecision,\n} from '../../../contracts/strategy.js';\nimport type { ThoughtData } from '../../thought.js';\nimport { scoreThought, selectBeam, type ScoredCandidate } from './totScoring.js';\nimport { detectPlateau } from './plateau.js';\n\n/**\n * Configuration knobs for {@link TreeOfThoughtStrategy}. All fields are\n * optional; defaults are applied in the constructor.\n */\nexport interface TotConfig {\n\t/** Top-K candidates kept on the frontier (default `3`). */\n\treadonly beamWidth?: number;\n\t/** Maximum exploration depth before forcing termination (default `8`). */\n\treadonly depthCap?: number;\n\t/** Score at/above which the chain terminates (default `0.85`). */\n\treadonly terminationConfidence?: number;\n\t/** Window size for plateau detection (default `3`). */\n\treadonly plateauWindow?: number;\n\t/** Minimum meaningful score change for plateau detection (default `0.02`). */\n\treadonly plateauEpsilon?: number;\n}\n\n/** Defaults applied when a {@link TotConfig} field is omitted. */\nconst DEFAULTS: Required<TotConfig> = {\n\tbeamWidth: 3,\n\tdepthCap: 8,\n\tterminationConfidence: 0.85,\n\tplateauWindow: 3,\n\tplateauEpsilon: 0.02,\n};\n\n/**\n * Module-private config storage. Keyed by strategy instance so that no\n * own-properties leak onto `this` (preserving the purity contract).\n */\nconst CONFIGS: WeakMap<TreeOfThoughtStrategy, Required<TotConfig>> = new WeakMap();\n\n/** Resolve the per-instance config (constructor always populates the map). */\nfunction configOf(s: TreeOfThoughtStrategy): Required<TotConfig> {\n\treturn CONFIGS.get(s) ?? DEFAULTS;\n}\n\n/** Stable identifier for a thought: `id` if present, else its sequence number. */\nfunction thoughtKey(t: ThoughtData): string {\n\treturn t.id ?? String(t.thought_number);\n}\n\n/** Index history by stable key for O(1) leaf-id → ThoughtData lookup. */\nfunction indexHistory(history: readonly ThoughtData[]): Map<string, ThoughtData> {\n\tconst out = new Map<string, ThoughtData>();\n\tfor (const t of history) out.set(thoughtKey(t), t);\n\treturn out;\n}\n\n/** Score the frontier (graph leaves), skipping ids absent from history. */\nfunction scoreFrontier(\n\tfrontier: readonly string[],\n\tbyKey: Map<string, ThoughtData>\n): ScoredCandidate[] {\n\tconst out: ScoredCandidate[] = [];\n\tfor (const id of frontier) {\n\t\tconst t = byKey.get(id);\n\t\tif (t !== undefined) out.push({ id, score: scoreThought(t) });\n\t}\n\treturn out;\n}\n\n/** Highest score in a candidate set, or `-Infinity` when empty. */\nfunction bestScore(scored: readonly ScoredCandidate[]): number {\n\tlet best = Number.NEGATIVE_INFINITY;\n\tfor (const c of scored) {\n\t\tif (c.score > best) best = c.score;\n\t}\n\treturn best;\n}\n\n/** Recent per-thought scores, used for plateau detection. */\nfunction recentScores(history: readonly ThoughtData[], window: number): number[] {\n\tconst start = history.length > window ? history.length - window : 0;\n\tconst out: number[] = [];\n\tfor (let i = start; i < history.length; i++) out.push(scoreThought(history[i]!));\n\treturn out;\n}\n\n/**\n * Tree-of-Thought strategy: beam search over the thought DAG. Pure policy.\n *\n * @example\n * ```typescript\n * const strategy = new TreeOfThoughtStrategy({ beamWidth: 4 });\n * const decision = strategy.decide(ctx);\n * ```\n */\nexport class TreeOfThoughtStrategy implements IReasoningStrategy {\n\treadonly name = 'tot' as const;\n\n\t/** @param config - See {@link TotConfig}. */\n\tconstructor(config?: TotConfig) {\n\t\tCONFIGS.set(this, { ...DEFAULTS, ...(config ?? {}) });\n\t}\n\n\t/**\n\t * Compute the next action for the chain.\n\t *\n\t * Order of checks: termination by confidence → termination by plateau →\n\t * branch when the current thought is outside the beam → continue.\n\t */\n\tdecide(ctx: StrategyContext): StrategyDecision {\n\t\tconst cfg = configOf(this);\n\t\tconst frontier = ctx.graph.leaves(ctx.sessionId);\n\t\tconst byKey = indexHistory(ctx.history);\n\t\tconst scored = scoreFrontier(frontier, byKey);\n\
|
|
1
|
+
{"version":3,"file":"core/reasoning/strategies/TreeOfThoughtStrategy.js","sources":["../../../../src/core/reasoning/strategies/TreeOfThoughtStrategy.ts"],"sourcesContent":["/**\n * Tree-of-Thought reasoning strategy — beam search over the thought DAG.\n *\n * Observes the frontier (graph leaves), scores each leaf via\n * {@link scoreThought}, and decides whether to continue, branch (when the\n * current thought falls outside the beam), or terminate (on confidence\n * threshold or score plateau).\n *\n * Pure policy: configuration lives in a module-level {@link WeakMap}, not\n * on the instance, so `Object.getOwnPropertyNames(strategy)` only ever\n * surfaces the readonly `name` discriminator. All other state is derived\n * from the {@link StrategyContext} on every call.\n *\n * @module core/reasoning/strategies/TreeOfThoughtStrategy\n */\n\nimport type {\n\tIReasoningStrategy,\n\tStrategyContext,\n\tStrategyDecision,\n} from '../../../contracts/strategy.js';\nimport type { ThoughtData } from '../../thought.js';\nimport { scoreThought, selectBeam, type ScoredCandidate } from './totScoring.js';\nimport { detectPlateau } from './plateau.js';\n\n/**\n * Configuration knobs for {@link TreeOfThoughtStrategy}. All fields are\n * optional; defaults are applied in the constructor.\n */\nexport interface TotConfig {\n\t/** Top-K candidates kept on the frontier (default `3`). */\n\treadonly beamWidth?: number;\n\t/** Maximum exploration depth before forcing termination (default `8`). */\n\treadonly depthCap?: number;\n\t/** Score at/above which the chain terminates (default `0.85`). */\n\treadonly terminationConfidence?: number;\n\t/** Window size for plateau detection (default `3`). */\n\treadonly plateauWindow?: number;\n\t/** Minimum meaningful score change for plateau detection (default `0.02`). */\n\treadonly plateauEpsilon?: number;\n}\n\n/** Defaults applied when a {@link TotConfig} field is omitted. */\nconst DEFAULTS: Required<TotConfig> = {\n\tbeamWidth: 3,\n\tdepthCap: 8,\n\tterminationConfidence: 0.85,\n\tplateauWindow: 3,\n\tplateauEpsilon: 0.02,\n};\n\n/**\n * Module-private config storage. Keyed by strategy instance so that no\n * own-properties leak onto `this` (preserving the purity contract).\n */\nconst CONFIGS: WeakMap<TreeOfThoughtStrategy, Required<TotConfig>> = new WeakMap();\n\n/** Resolve the per-instance config (constructor always populates the map). */\nfunction configOf(s: TreeOfThoughtStrategy): Required<TotConfig> {\n\treturn CONFIGS.get(s) ?? DEFAULTS;\n}\n\n/** Stable identifier for a thought: `id` if present, else its sequence number. */\nfunction thoughtKey(t: ThoughtData): string {\n\treturn t.id ?? String(t.thought_number);\n}\n\n/** Index history by stable key for O(1) leaf-id → ThoughtData lookup. */\nfunction indexHistory(history: readonly ThoughtData[]): Map<string, ThoughtData> {\n\tconst out = new Map<string, ThoughtData>();\n\tfor (const t of history) out.set(thoughtKey(t), t);\n\treturn out;\n}\n\n/** Score the frontier (graph leaves), skipping ids absent from history. */\nfunction scoreFrontier(\n\tfrontier: readonly string[],\n\tbyKey: Map<string, ThoughtData>\n): ScoredCandidate[] {\n\tconst out: ScoredCandidate[] = [];\n\tfor (const id of frontier) {\n\t\tconst t = byKey.get(id);\n\t\tif (t !== undefined) out.push({ id, score: scoreThought(t) });\n\t}\n\treturn out;\n}\n\n/** Highest score in a candidate set, or `-Infinity` when empty. */\nfunction bestScore(scored: readonly ScoredCandidate[]): number {\n\tlet best = Number.NEGATIVE_INFINITY;\n\tfor (const c of scored) {\n\t\tif (c.score > best) best = c.score;\n\t}\n\treturn best;\n}\n\n/** Recent per-thought scores, used for plateau detection. */\nfunction recentScores(history: readonly ThoughtData[], window: number): number[] {\n\tconst start = history.length > window ? history.length - window : 0;\n\tconst out: number[] = [];\n\tfor (let i = start; i < history.length; i++) out.push(scoreThought(history[i]!));\n\treturn out;\n}\n\n/**\n * Tree-of-Thought strategy: beam search over the thought DAG. Pure policy.\n *\n * @example\n * ```typescript\n * const strategy = new TreeOfThoughtStrategy({ beamWidth: 4 });\n * const decision = strategy.decide(ctx);\n * ```\n */\nexport class TreeOfThoughtStrategy implements IReasoningStrategy {\n\treadonly name = 'tot' as const;\n\n\t/** @param config - See {@link TotConfig}. */\n\tconstructor(config?: TotConfig) {\n\t\tCONFIGS.set(this, { ...DEFAULTS, ...(config ?? {}) });\n\t}\n\n\t/**\n\t * Compute the next action for the chain.\n\t *\n\t * Order of checks: termination by confidence → termination by plateau →\n\t * branch when the current thought is outside the beam → continue.\n\t */\n\tdecide(ctx: StrategyContext): StrategyDecision {\n\t\tconst cfg = configOf(this);\n\t\tif (!ctx.graph) {\n\t\t\treturn { action: 'continue' };\n\t\t}\n\t\tconst frontier = ctx.graph.leaves(ctx.sessionId);\n\t\tconst byKey = indexHistory(ctx.history);\n\t\tconst scored = scoreFrontier(frontier, byKey);\n\t\tif (scored.length > 0 && bestScore(scored) >= cfg.terminationConfidence) {\n\t\t\treturn { action: 'terminate', reason: 'confidence threshold' };\n\t\t}\n\n\t\tconst recent = recentScores(ctx.history, cfg.plateauWindow);\n\t\tif (detectPlateau(recent, cfg.plateauWindow, cfg.plateauEpsilon)) {\n\t\t\treturn { action: 'terminate', reason: 'plateau' };\n\t\t}\n\n\t\tif (scored.length > cfg.beamWidth) {\n\t\t\tconst beam = selectBeam(scored, cfg.beamWidth);\n\t\t\tconst currentKey = thoughtKey(ctx.currentThought);\n\t\t\tif (!beam.includes(currentKey)) {\n\t\t\t\treturn {\n\t\t\t\t\taction: 'branch',\n\t\t\t\t\tbranchId: `tot-${ctx.currentThought.thought_number}`,\n\t\t\t\t\tfromThought: ctx.currentThought.thought_number,\n\t\t\t\t\treason: 'outside beam',\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn { action: 'continue', nextHint: 'explore frontier' };\n\t}\n\n\t/** True when the frontier is wider than the beam (diverse exploration). */\n\tshouldBranch(ctx: StrategyContext): boolean {\n\t\tconst cfg = configOf(this);\n\t\tif (!ctx.graph) return false;\n\t\tconst frontier = ctx.graph.leaves(ctx.sessionId);\n\t\treturn frontier.length > cfg.beamWidth;\n\t}\n\n\t/** True when the best frontier score crosses the threshold OR scores plateau. */\n\tshouldTerminate(ctx: StrategyContext): boolean {\n\t\tconst cfg = configOf(this);\n\t\tif (!ctx.graph) return false;\n\t\tconst frontier = ctx.graph.leaves(ctx.sessionId);\n\t\tconst byKey = indexHistory(ctx.history);\n\t\tconst scored = scoreFrontier(frontier, byKey);\n\t\tif (scored.length > 0 && bestScore(scored) >= cfg.terminationConfidence) {\n\t\t\treturn true;\n\t\t}\n\t\tconst recent = recentScores(ctx.history, cfg.plateauWindow);\n\t\treturn detectPlateau(recent, cfg.plateauWindow, cfg.plateauEpsilon);\n\t}\n}\n"],"names":["DEFAULTS","CONFIGS","WeakMap","configOf","s","thoughtKey","t","String","indexHistory","history","out","Map","scoreFrontier","frontier","byKey","id","undefined","scoreThought","bestScore","scored","best","Number","c","recentScores","window","start","i","TreeOfThoughtStrategy","config","ctx","cfg","recent","detectPlateau","beam","selectBeam","currentKey"],"mappings":";;AA2CA,MAAMA,WAAgC;IACrC,WAAW;IACX,UAAU;IACV,uBAAuB;IACvB,eAAe;IACf,gBAAgB;AACjB;AAMA,MAAMC,UAA+D,IAAIC;AAGzE,SAASC,SAASC,CAAwB;IACzC,OAAOH,QAAQ,GAAG,CAACG,MAAMJ;AAC1B;AAGA,SAASK,WAAWC,CAAc;IACjC,OAAOA,EAAE,EAAE,IAAIC,OAAOD,EAAE,cAAc;AACvC;AAGA,SAASE,aAAaC,OAA+B;IACpD,MAAMC,MAAM,IAAIC;IAChB,KAAK,MAAML,KAAKG,QAASC,IAAI,GAAG,CAACL,WAAWC,IAAIA;IAChD,OAAOI;AACR;AAGA,SAASE,cACRC,QAA2B,EAC3BC,KAA+B;IAE/B,MAAMJ,MAAyB,EAAE;IACjC,KAAK,MAAMK,MAAMF,SAAU;QAC1B,MAAMP,IAAIQ,MAAM,GAAG,CAACC;QACpB,IAAIT,AAAMU,WAANV,GAAiBI,IAAI,IAAI,CAAC;YAAEK;YAAI,OAAOE,aAAaX;QAAG;IAC5D;IACA,OAAOI;AACR;AAGA,SAASQ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AAMK,aAAa9B,WAAWwB,IAAI,cAAc;YAChD,IAAI,CAACI,KAAK,QAAQ,CAACE,aAClB,OAAO;gBACN,QAAQ;gBACR,UAAU,CAAC,IAAI,EAAEN,IAAI,cAAc,CAAC,cAAc,EAAE;gBACpD,aAAaA,IAAI,cAAc,CAAC,cAAc;gBAC9C,QAAQ;YACT;QAEF;QAEA,OAAO;YAAE,QAAQ;YAAY,UAAU;QAAmB;IAC3D;IAGA,aAAaA,GAAoB,EAAW;QAC3C,MAAMC,MAAM3B,SAAS,IAAI;QACzB,IAAI,CAAC0B,IAAI,KAAK,EAAE,OAAO;QACvB,MAAMhB,WAAWgB,IAAI,KAAK,CAAC,MAAM,CAACA,IAAI,SAAS;QAC/C,OAAOhB,SAAS,MAAM,GAAGiB,IAAI,SAAS;IACvC;IAGA,gBAAgBD,GAAoB,EAAW;QAC9C,MAAMC,MAAM3B,SAAS,IAAI;QACzB,IAAI,CAAC0B,IAAI,KAAK,EAAE,OAAO;QACvB,MAAMhB,WAAWgB,IAAI,KAAK,CAAC,MAAM,CAACA,IAAI,SAAS;QAC/C,MAAMf,QAAQN,aAAaqB,IAAI,OAAO;QACtC,MAAMV,SAASP,cAAcC,UAAUC;QACvC,IAAIK,OAAO,MAAM,GAAG,KAAKD,UAAUC,WAAWW,IAAI,qBAAqB,EACtE,OAAO;QAER,MAAMC,SAASR,aAAaM,IAAI,OAAO,EAAEC,IAAI,aAAa;QAC1D,OAAOE,cAAcD,QAAQD,IAAI,aAAa,EAAEA,IAAI,cAAc;IACnE;AACD"}
|
package/dist/core/reasoning.d.ts
CHANGED
|
@@ -21,6 +21,12 @@ import type { CalibrationMetrics } from '../contracts/calibrator.js';
|
|
|
21
21
|
* ```
|
|
22
22
|
*/
|
|
23
23
|
export type ThoughtType = 'regular' | 'hypothesis' | 'verification' | 'critique' | 'synthesis' | 'meta' | 'tool_call' | 'tool_observation' | 'assumption' | 'decomposition' | 'backtrack';
|
|
24
|
+
/**
|
|
25
|
+
* Machine-readable names for the 6 detected reasoning patterns.
|
|
26
|
+
*
|
|
27
|
+
* Each name corresponds to a private detector method in PatternDetector.
|
|
28
|
+
*/
|
|
29
|
+
export type PatternName = 'consecutive_without_verification' | 'unverified_hypothesis' | 'monotonic_type' | 'no_alternatives_explored' | 'confidence_drift' | 'healthy_verification';
|
|
24
30
|
/**
|
|
25
31
|
* A detected reasoning pattern — surfaced as metadata or a warning.
|
|
26
32
|
*
|
|
@@ -36,7 +42,8 @@ export type ThoughtType = 'regular' | 'hypothesis' | 'verification' | 'critique'
|
|
|
36
42
|
*/
|
|
37
43
|
export interface PatternSignal {
|
|
38
44
|
/** Machine-readable pattern identifier. */
|
|
39
|
-
pattern
|
|
45
|
+
/** Machine-readable pattern identifier. */
|
|
46
|
+
pattern: PatternName;
|
|
40
47
|
/** Severity: 'warning' surfaces as a hint, 'info' is metadata only. */
|
|
41
48
|
severity: 'info' | 'warning';
|
|
42
49
|
/** Human-readable description of the detected pattern. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reasoning.d.ts","sourceRoot":"","sources":["../../src/core/reasoning.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAErE;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,WAAW,GACpB,SAAS,GACT,YAAY,GACZ,cAAc,GACd,UAAU,GACV,WAAW,GACX,MAAM,GACN,WAAW,GACX,kBAAkB,GAClB,YAAY,GACZ,eAAe,GACf,WAAW,CAAC;AAEf;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC7B,2CAA2C;IAC3C,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"reasoning.d.ts","sourceRoot":"","sources":["../../src/core/reasoning.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAErE;;;;;;;;;;;;GAY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
|
* next_step_conditions: ['If no results found, try broader search terms']
|
|
30
30
|
* };
|
|
31
31
|
* ```
|
|
32
|
+
*
|
|
33
|
+
* NOTE: Kept as a hand-written interface (not inferred from `StepRecommendationSchema`)
|
|
34
|
+
* because it composes `ToolRecommendation` / `SkillRecommendation`, which are themselves
|
|
35
|
+
* stricter than their schemas (required vs optional fields). An inferred type would
|
|
36
|
+
* weaken those nested guarantees.
|
|
32
37
|
*/
|
|
33
38
|
export interface StepRecommendation {
|
|
34
39
|
/** Human-readable description of what needs to be done in this step. */
|
package/dist/core/step.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"step.d.ts","sourceRoot":"","sources":["../../src/core/step.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D
|
|
1
|
+
{"version":3,"file":"step.d.ts","sourceRoot":"","sources":["../../src/core/step.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,WAAW,kBAAkB;IAClC,wEAAwE;IACxE,gBAAgB,EAAE,MAAM,CAAC;IAEzB,qEAAqE;IACrE,iBAAiB,EAAE,kBAAkB,EAAE,CAAC;IAExC,0DAA0D;IAC1D,kBAAkB,CAAC,EAAE,mBAAmB,EAAE,CAAC;IAE3C,gEAAgE;IAChE,gBAAgB,EAAE,MAAM,CAAC;IAEzB,sEAAsE;IACtE,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CAChC"}
|
package/dist/core/thought.d.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module types/thought
|
|
5
5
|
*/
|
|
6
|
+
import type { SessionId, ThoughtId, SuspensionToken } from '../contracts/ids.js';
|
|
6
7
|
import type { ThoughtType } from './reasoning.js';
|
|
7
8
|
import type { StepRecommendation } from './step.js';
|
|
8
9
|
/**
|
|
@@ -57,7 +58,7 @@ export interface ThoughtData {
|
|
|
57
58
|
* const thought: ThoughtData = { ...base, id: '01H0X0X0X0X0X0X0X0X0X0X0X0' };
|
|
58
59
|
* ```
|
|
59
60
|
*/
|
|
60
|
-
id?:
|
|
61
|
+
id?: ThoughtId;
|
|
61
62
|
/** Current thought number in the sequence (1-indexed). */
|
|
62
63
|
thought_number: number;
|
|
63
64
|
/** Estimated total number of thoughts (can be adjusted during processing). */
|
|
@@ -186,7 +187,7 @@ export interface ThoughtData {
|
|
|
186
187
|
* const thought: ThoughtData = { ...base, session_id: 'analysis-task-42' };
|
|
187
188
|
* ```
|
|
188
189
|
*/
|
|
189
|
-
session_id?:
|
|
190
|
+
session_id?: SessionId;
|
|
190
191
|
/**
|
|
191
192
|
* When true, clears all state for the target session before processing this thought.
|
|
192
193
|
* The thought is then processed as the first in a fresh session.
|
|
@@ -204,7 +205,7 @@ export interface ThoughtData {
|
|
|
204
205
|
/** Result returned by the tool (for tool_observation) */
|
|
205
206
|
tool_result?: unknown;
|
|
206
207
|
/** Continuation token linking tool_observation back to suspended tool_call */
|
|
207
|
-
continuation_token?:
|
|
208
|
+
continuation_token?: SuspensionToken;
|
|
208
209
|
/** Sub-problem labels for decomposition thoughts */
|
|
209
210
|
decomposition_children?: string[];
|
|
210
211
|
/** Thought number being backtracked from */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thought.d.ts","sourceRoot":"","sources":["../../src/core/thought.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAA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EAAE,MAAM,EAAE,CAAC;IAElC,4CAA4C;IAC5C,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* @module core/tools/InMemorySuspensionStore
|
|
9
9
|
*/
|
|
10
10
|
import type { ISuspensionStore, SuspensionRecord } from '../../contracts/suspension.js';
|
|
11
|
+
import type { Logger } from '../../logger/StructuredLogger.js';
|
|
11
12
|
/**
|
|
12
13
|
* Configuration for {@link InMemorySuspensionStore}.
|
|
13
14
|
*/
|
|
@@ -17,7 +18,8 @@ export interface InMemorySuspensionStoreConfig {
|
|
|
17
18
|
/** Sweep interval for the background expiry timer. Defaults to 60_000ms. */
|
|
18
19
|
sweepIntervalMs?: number;
|
|
19
20
|
/** Optional logger; reserved for future diagnostic output. */
|
|
20
|
-
logger
|
|
21
|
+
/** Optional logger for diagnostic output. */
|
|
22
|
+
logger?: Logger;
|
|
21
23
|
}
|
|
22
24
|
/**
|
|
23
25
|
* In-memory suspension store with TTL expiry and background sweep.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InMemorySuspensionStore.d.ts","sourceRoot":"","sources":["../../../src/core/tools/InMemorySuspensionStore.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"InMemorySuspensionStore.d.ts","sourceRoot":"","sources":["../../../src/core/tools/InMemorySuspensionStore.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAExF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAE/D;;G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,7 +12,7 @@ class InMemorySuspensionStore {
|
|
|
12
12
|
this._sweepIntervalMs = config.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
|
|
13
13
|
}
|
|
14
14
|
suspend(record) {
|
|
15
|
-
const token =
|
|
15
|
+
const token = generateSuspensionToken();
|
|
16
16
|
const createdAt = Date.now();
|
|
17
17
|
const ttlMs = record.ttlMs ?? this._ttlMs;
|
|
18
18
|
const expiresAt = createdAt + ttlMs;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/tools/InMemorySuspensionStore.js","sources":["../../../src/core/tools/InMemorySuspensionStore.ts"],"sourcesContent":["/**\n * In-memory implementation of {@link ISuspensionStore}.\n *\n * Stores suspension records in process memory with optional background\n * sweeping of expired entries. Suitable for single-process deployments;\n * cluster setups should provide a shared backend.\n *\n * @module core/tools/InMemorySuspensionStore\n */\n\nimport type { ISuspensionStore, SuspensionRecord } from '../../contracts/suspension.js';\nimport {
|
|
1
|
+
{"version":3,"file":"core/tools/InMemorySuspensionStore.js","sources":["../../../src/core/tools/InMemorySuspensionStore.ts"],"sourcesContent":["/**\n * In-memory implementation of {@link ISuspensionStore}.\n *\n * Stores suspension records in process memory with optional background\n * sweeping of expired entries. Suitable for single-process deployments;\n * cluster setups should provide a shared backend.\n *\n * @module core/tools/InMemorySuspensionStore\n */\n\nimport type { ISuspensionStore, SuspensionRecord } from '../../contracts/suspension.js';\nimport { generateSuspensionToken } from '../../contracts/ids.js';\nimport type { Logger } from '../../logger/StructuredLogger.js';\n\n/**\n * Configuration for {@link InMemorySuspensionStore}.\n */\nexport interface InMemorySuspensionStoreConfig {\n\t/** Default TTL applied to records that omit `ttlMs`. Defaults to 60_000ms. */\n\tttlMs?: number;\n\t/** Sweep interval for the background expiry timer. Defaults to 60_000ms. */\n\tsweepIntervalMs?: number;\n\t/** Optional logger; reserved for future diagnostic output. */\n\t/** Optional logger for diagnostic output. */\n\tlogger?: Logger;\n}\n\nconst DEFAULT_TTL_MS = 300_000;\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\n\n/**\n * In-memory suspension store with TTL expiry and background sweep.\n *\n * @example\n * ```typescript\n * const store = new InMemorySuspensionStore({ ttlMs: 30_000 });\n * store.start();\n * const rec = store.suspend({\n * sessionId: 's1',\n * toolCallThoughtNumber: 3,\n * toolName: 'search',\n * toolArguments: { q: 'foo' },\n * expiresAt: 0,\n * });\n * const resumed = store.resume(rec.token);\n * store.stop();\n * ```\n */\nexport class InMemorySuspensionStore implements ISuspensionStore {\n\tprivate readonly _byToken: Map<string, SuspensionRecord> = new Map();\n\tprivate readonly _bySession: Map<string, Set<string>> = new Map();\n\tprivate readonly _ttlMs: number;\n\tprivate readonly _sweepIntervalMs: number;\n\tprivate _timer: ReturnType<typeof setInterval> | null = null;\n\n\tconstructor(config: InMemorySuspensionStoreConfig = {}) {\n\t\tthis._ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;\n\t\tthis._sweepIntervalMs = config.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;\n\t}\n\n\tsuspend(\n\t\trecord: Omit<SuspensionRecord, 'token' | 'createdAt'> & { ttlMs?: number },\n\t): SuspensionRecord {\n\t\tconst token = generateSuspensionToken();\n\t\tconst createdAt = Date.now();\n\t\tconst ttlMs = record.ttlMs ?? this._ttlMs;\n\t\tconst expiresAt = createdAt + ttlMs;\n\n\t\tconst full: SuspensionRecord = {\n\t\t\ttoken,\n\t\t\tsessionId: record.sessionId,\n\t\t\ttoolCallThoughtNumber: record.toolCallThoughtNumber,\n\t\t\ttoolName: record.toolName,\n\t\t\ttoolArguments: record.toolArguments,\n\t\t\tcreatedAt,\n\t\t\texpiresAt,\n\t\t};\n\n\t\tthis._byToken.set(token, full);\n\t\tlet bucket = this._bySession.get(full.sessionId);\n\t\tif (!bucket) {\n\t\t\tbucket = new Set();\n\t\t\tthis._bySession.set(full.sessionId, bucket);\n\t\t}\n\t\tbucket.add(token);\n\n\t\treturn full;\n\t}\n\n\tresume(token: string): SuspensionRecord | null {\n\t\tconst rec = this._byToken.get(token);\n\t\tif (!rec) return null;\n\t\tif (rec.expiresAt <= Date.now()) {\n\t\t\tthis._delete(token, rec.sessionId);\n\t\t\treturn null;\n\t\t}\n\t\tthis._delete(token, rec.sessionId);\n\t\treturn rec;\n\t}\n\n\tpeek(token: string): SuspensionRecord | null {\n\t\treturn this._byToken.get(token) ?? null;\n\t}\n\n\texpireOlderThan(now: number): number {\n\t\tlet removed = 0;\n\t\tfor (const [token, rec] of this._byToken) {\n\t\t\tif (rec.expiresAt <= now) {\n\t\t\t\tthis._delete(token, rec.sessionId);\n\t\t\t\tremoved++;\n\t\t\t}\n\t\t}\n\t\treturn removed;\n\t}\n\n\tclearSession(sessionId: string): void {\n\t\tconst bucket = this._bySession.get(sessionId);\n\t\tif (!bucket) return;\n\t\tfor (const token of bucket) {\n\t\t\tthis._byToken.delete(token);\n\t\t}\n\t\tthis._bySession.delete(sessionId);\n\t}\n\n\tsize(sessionId?: string): number {\n\t\tif (sessionId === undefined) return this._byToken.size;\n\t\treturn this._bySession.get(sessionId)?.size ?? 0;\n\t}\n\n\tstart(): void {\n\t\tif (this._timer !== null) return;\n\t\tthis._timer = setInterval(() => {\n\t\t\tthis.expireOlderThan(Date.now());\n\t\t}, this._sweepIntervalMs);\n\t\tthis._timer.unref?.();\n\t}\n\n\tstop(): void {\n\t\tif (this._timer === null) return;\n\t\tclearInterval(this._timer);\n\t\tthis._timer = null;\n\t}\n\n\tprivate _delete(token: string, sessionId: string): void {\n\t\tthis._byToken.delete(token);\n\t\tconst bucket = this._bySession.get(sessionId);\n\t\tif (bucket) {\n\t\t\tbucket.delete(token);\n\t\t\tif (bucket.size === 0) this._bySession.delete(sessionId);\n\t\t}\n\t}\n}\n"],"names":["DEFAULT_TTL_MS","DEFAULT_SWEEP_INTERVAL_MS","InMemorySuspensionStore","Map","config","record","token","generateSuspensionToken","createdAt","Date","ttlMs","expiresAt","full","bucket","Set","rec","now","removed","session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,IAAIO,AAAgB,MAAhBA,OAAO,IAAI,EAAQ,IAAI,CAAC,UAAU,CAAC,MAAM,CAACK;QAC/C;IACD;AACD"}
|
package/dist/di/Container.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import type { Logger } from '../logger/StructuredLogger.js';
|
|
2
|
+
import type { ServerConfig } from '../ServerConfig.js';
|
|
3
|
+
import type { ConfigFileOptions } from '../config/ConfigLoader.js';
|
|
1
4
|
import type { IDisposable } from '../types/disposable.js';
|
|
2
5
|
import type { ServiceKey, ServiceRegistry } from './ServiceRegistry.js';
|
|
3
6
|
/**
|
|
@@ -218,9 +221,9 @@ export declare class Container {
|
|
|
218
221
|
* ```
|
|
219
222
|
*/
|
|
220
223
|
export interface CreateContainerOptions {
|
|
221
|
-
logger?:
|
|
222
|
-
config?:
|
|
223
|
-
fileConfig?:
|
|
224
|
+
logger?: Logger;
|
|
225
|
+
config?: ServerConfig;
|
|
226
|
+
fileConfig?: ConfigFileOptions;
|
|
224
227
|
}
|
|
225
228
|
export declare function createDefaultContainer(options?: CreateContainerOptions): Container;
|
|
226
229
|
//# sourceMappingURL=Container.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Container.d.ts","sourceRoot":"","sources":["../../src/di/Container.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,SAAS;IACrB,OAAO,CAAC,SAAS,CAAmC;IACpD,OAAO,CAAC,UAAU,CAAyC;IAC3D,OAAO,CAAC,mBAAmB,CAAyC;IACpE,OAAO,CAAC,UAAU,CAA0B;IAC5C,OAAO,CAAC,YAAY,CAAuC;IAE3D;;;;;;;;;;OAUG;IACH,gBAAgB,CAAC,CAAC,SAAS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container.js","sources":["../../src/di/Container.ts"],"sourcesContent":["import type { IDisposable } from '../types/disposable.js';\nimport type { ServiceKey, ServiceRegistry } from './ServiceRegistry.js';\n\n/**\n * Lightweight dependency injection container for managing service dependencies.\n *\n * This container supports:\n * - Instance registration (singleton-like behavior)\n * - Factory registration (lazy instantiation with caching)\n * - Transient factory registration (new instance each time)\n *\n * The container is type-safe when using ServiceKey from ServiceRegistry.\n * For dynamic/unknown services, use string keys with generic type parameters.\n *\n * @example\n * ```typescript\n * const container = new Container();\n *\n * // Type-safe registration with ServiceKey (recommended)\n * container.registerInstance('Logger', new StructuredLogger());\n *\n * // Type inference works automatically\n * const logger = container.resolve('Logger'); // Type: StructuredLogger\n *\n * // Register a factory with caching (singleton per container)\n * container.register('HistoryManager', () =>\n * new HistoryManager({ logger: container.resolve('Logger') })\n * );\n *\n * // Register a transient factory (new instance each time)\n * container.registerFactory('RequestContext', () =>\n * new RequestContext()\n * );\n *\n * // For dynamic services not in ServiceRegistry\n * container.registerInstance<MyService>('MyService', myService);\n * const service = container.resolve<MyService>('MyService');\n * ```\n */\nexport class Container {\n\tprivate _services: Map<string, unknown> = new Map();\n\tprivate _factories: Map<string, () => unknown> = new Map();\n\tprivate _transientFactories: Map<string, () => unknown> = new Map();\n\tprivate _resolving: Set<string> = new Set();\n\tprivate _disposables: Map<string, IDisposable> = new Map();\n\n\t/**\n\t * Register a singleton instance that will be returned for all resolutions.\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param instance - The instance to register\n\t *\n\t * @example\n\t * ```typescript\n\t * container.registerInstance('Config', new ServerConfig({ ... }));\n\t * ```\n\t */\n\tregisterInstance<K extends ServiceKey>(name: K, instance: ServiceRegistry[K]): void;\n\tregisterInstance<T>(name: string, instance: T): void;\n\tregisterInstance(name: string, instance: unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._services.set(name, instance);\n\t}\n\n\t/**\n\t * Register a factory function that will be called once and cached.\n\t * The first call to `resolve` will invoke the factory and cache the result.\n\t * Subsequent calls will return the cached instance (singleton behavior).\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param factory - A factory function that creates the service\n\t *\n\t * @example\n\t * ```typescript\n\t * container.register('HistoryManager', () =>\n\t * new HistoryManager({ logger: container.resolve('Logger') })\n\t * );\n\t * ```\n\t */\n\tregister<K extends ServiceKey>(name: K, factory: () => ServiceRegistry[K]): void;\n\tregister<T>(name: string, factory: () => T): void;\n\tregister(name: string, factory: () => unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._factories.set(name, factory);\n\t}\n\n\t/**\n\t * Register a transient factory function that will be called on every resolution.\n\t * Each call to `resolve` will invoke the factory and return a new instance.\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param factory - A factory function that creates the service\n\t *\n\t * @example\n\t * ```typescript\n\t * container.registerFactory('RequestContext', () =>\n\t * new RequestContext()\n\t * );\n\t * ```\n\t */\n\tregisterFactory<K extends ServiceKey>(name: K, factory: () => ServiceRegistry[K]): void;\n\tregisterFactory<T>(name: string, factory: () => T): void;\n\tregisterFactory(name: string, factory: () => unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._transientFactories.set(name, factory);\n\t}\n\n\t/**\n\t * Resolve a service by name.\n\t *\n\t * Resolution order:\n\t * 1. If a registered instance exists, return it\n\t * 2. If a cached factory exists, return it\n\t * 3. If a factory exists, invoke it, cache the result, and return it\n\t * 4. If a transient factory exists, invoke it and return a new instance\n\t * 5. Throw an error if the service is not found\n\t *\n\t * @param name - The name/identifier of service to resolve\n\t * @returns The resolved service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * // Type-safe: ServiceRegistry provides autocomplete\n\t * const logger = container.resolve('Logger'); // Type: StructuredLogger\n\t * const config = container.resolve('Config'); // Type: ServerConfig\n\t *\n\t * // Dynamic: For services not in ServiceRegistry\n\t * const service = container.resolve<MyService>('MyService');\n\t * ```\n\t */\n\tresolve<K extends ServiceKey>(name: K): ServiceRegistry[K];\n\tresolve<T>(name: string): T;\n\tresolve(name: string): unknown {\n\t\tif (this._resolving.has(name)) {\n\t\t\tthrow new Error(`Circular dependency detected while resolving service: ${name}`);\n\t\t}\n\n\t\tthis._resolving.add(name);\n\n\t\ttry {\n\t\t\t// Check for registered instance first\n\t\t\tif (this._services.has(name)) {\n\t\t\t\treturn this._services.get(name);\n\t\t\t}\n\n\t\t\t// Check for cached factory result\n\t\t\tif (this._factories.has(name)) {\n\t\t\t\tconst factory = this._factories.get(name)!;\n\t\t\t\tconst instance = factory();\n\t\t\t\t// Cache the result for future calls (singleton behavior)\n\t\t\t\tthis._services.set(name, instance);\n\t\t\t\tthis._factories.delete(name);\n\t\t\t\treturn instance;\n\t\t\t}\n\n\t\t\t// Check for transient factory (call every time)\n\t\t\tif (this._transientFactories.has(name)) {\n\t\t\t\tconst factory = this._transientFactories.get(name)!;\n\t\t\t\treturn factory();\n\t\t\t}\n\n\t\t\tthrow new Error(`Service not found: ${name}. Did you forget to register it?`);\n\t\t} finally {\n\t\t\tthis._resolving.delete(name);\n\t\t}\n\t}\n\n\t/**\n\t * Check if a service is registered (either as instance or factory).\n\t *\n\t * @param name - The name/identifier of the service to check\n\t * @returns `true` if the service is registered, `false` otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (!container.has('Logger')) {\n\t * container.registerInstance('Logger', new StructuredLogger());\n\t * }\n\t * ```\n\t */\n\thas(name: string): boolean {\n\t\treturn (\n\t\t\tthis._services.has(name) || this._factories.has(name) || this._transientFactories.has(name)\n\t\t);\n\t}\n\n\t/**\n\t * Remove a registered service from the container.\n\t *\n\t * @param name - The name/identifier of the service to unregister\n\t * @returns `true` if the service was found and removed, `false` otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * container.unregister('HistoryManager');\n\t * ```\n\t */\n\tunregister(name: string): boolean {\n\t\tconst hadInstance = this._services.delete(name);\n\t\tconst hadFactory = this._factories.delete(name);\n\t\tconst hadTransient = this._transientFactories.delete(name);\n\t\tthis._disposables.delete(name);\n\t\treturn hadInstance || hadFactory || hadTransient;\n\t}\n\n\t/**\n\t * Clear all registered services and factories from the container.\n\t *\n\t * @example\n\t * ```typescript\n\t * container.clear();\n\t * ```\n\t */\n\tclear(): void {\n\t\tthis._services.clear();\n\t\tthis._factories.clear();\n\t\tthis._transientFactories.clear();\n\t\tthis._resolving.clear();\n\t\tthis._disposables.clear();\n\t}\n\n\t/**\n\t * Get the number of registered services (including instances, factories, and transient factories).\n\t *\n\t * @returns The total count of registered services\n\t *\n\t * @example\n\t * ```typescript\n\t * console.log(`Registered services: ${container.size}`);\n\t * ```\n\t */\n\tget size(): number {\n\t\treturn this._services.size + this._factories.size + this._transientFactories.size;\n\t}\n\n\t/**\n\t * Get an array of all registered service names.\n\t *\n\t * @returns An array of service names\n\t *\n\t * @example\n\t * ```typescript\n\t * const names = container.registeredServices();\n\t * console.log('Registered:', names.join(', '));\n\t * ```\n\t */\n\tregisteredServices(): string[] {\n\t\tconst names = new Set<string>();\n\t\tfor (const name of this._services.keys()) names.add(name);\n\t\tfor (const name of this._factories.keys()) names.add(name);\n\t\tfor (const name of this._transientFactories.keys()) names.add(name);\n\t\treturn Array.from(names);\n\t}\n\n\t/**\n\t * Register an instance as disposable for lifecycle management.\n\t * The instance will have its `dispose()` method called when the container is disposed.\n\t *\n\t * @param name - The service name (must already be registered)\n\t * @param instance - The disposable instance to track\n\t *\n\t * @example\n\t * ```typescript\n\t * const pool = new ConnectionPool();\n\t * container.registerInstance('ConnectionPool', pool);\n\t * container.registerDisposable('ConnectionPool', pool);\n\t * ```\n\t */\n\tregisterDisposable(name: string, instance: IDisposable): void {\n\t\tthis._disposables.set(name, instance);\n\t}\n\n\t/**\n\t * Dispose of all registered disposable services.\n\t * Calls `dispose()` on each registered disposable in reverse registration order.\n\t * Errors during individual disposal are caught and logged to prevent cascading failures.\n\t *\n\t * @example\n\t * ```typescript\n\t * await container.dispose();\n\t * ```\n\t */\n\tasync dispose(): Promise<void> {\n\t\tconst entries = Array.from(this._disposables.entries()).reverse();\n\t\tconst errors: Array<{ name: string; error: unknown }> = [];\n\n\t\tfor (const [name, disposable] of entries) {\n\t\t\ttry {\n\t\t\t\tawait disposable.dispose();\n\t\t\t} catch (error) {\n\t\t\t\terrors.push({ name, error });\n\t\t\t}\n\t\t}\n\n\t\tthis._disposables.clear();\n\n\t\tif (errors.length > 0) {\n\t\t\tconst messages = errors.map(\n\t\t\t\t(e) => `${e.name}: ${e.error instanceof Error ? e.error.message : String(e.error)}`\n\t\t\t);\n\t\t\tthrow new Error(`Failed to dispose services: ${messages.join(', ')}`);\n\t\t}\n\t}\n}\n\n/**\n * Create a pre-configured container with all default services registered.\n *\n * This factory function creates a container with all standard services\n * for the ToolAwareSequentialThinkingServer.\n *\n * @param options - Configuration options for the container\n * @returns A configured container ready to use\n *\n * @example\n * ```typescript\n * const container = createDefaultContainer({\n * logger: customLogger,\n * config: customConfig\n * });\n * const server = new ToolAwareSequentialThinkingServer({ container });\n * ```\n */\nexport interface CreateContainerOptions {\n\tlogger?: unknown;\n\tconfig?: unknown;\n\tfileConfig?: Record<string, unknown>;\n}\n\nexport function createDefaultContainer(options: CreateContainerOptions = {}): Container {\n\tconst container = new Container();\n\n\t// Register logger if provided\n\tif (options.logger) {\n\t\tcontainer.registerInstance('Logger', options.logger);\n\t}\n\n\t// Register config if provided\n\tif (options.config) {\n\t\tcontainer.registerInstance('Config', options.config);\n\t}\n\n\treturn container;\n}\n"],"names":["Container","Map","Set","name","instance","Error","factory","hadInstance","hadFactory","hadTransient","names","Array","entries","errors","disposable","error","messages","e","String","createDefaultContainer","options","container"],"mappings":"AAuCO,MAAMA;IACJ,YAAkC,IAAIC,MAAM;IAC5C,aAAyC,IAAIA,MAAM;IACnD,sBAAkD,IAAIA,MAAM;IAC5D,aAA0B,IAAIC,MAAM;IACpC,eAAyC,IAAID,MAAM;IAe3D,iBAAiBE,IAAY,EAAEC,QAAiB,EAAQ;QACvD,IACC,IAAI,CAAC,SAAS,CAAC,GAAG,CAACD,SACnB,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,SACpB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,OAE7B,MAAM,IAAIE,MAAM,CAAC,SAAS,EAAEF,KAAK,uBAAuB,CAAC;QAE1D,IAAI,CAAC,SAAS,CAAC,GAAG,CAACA,MAAMC;IAC1B;IAmBA,SAASD,IAAY,EAAEG,OAAsB,EAAQ;QACpD,IACC,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH,SACnB,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,SACpB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,OAE7B,MAAM,IAAIE,MAAM,CAAC,SAAS,EAAEF,KAAK,uBAAuB,CAAC;QAE1D,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,MAAMG;IAC3B;IAkBA,gBAAgBH,IAAY,EAAEG,OAAsB,EAAQ;QAC3D,IACC,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH,SACnB,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,SACpB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,OAE7B,MAAM,IAAIE,MAAM,CAAC,SAAS,EAAEF,KAAK,uBAAuB,CAAC;QAE1D,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,MAAMG;IACpC;IA4BA,QAAQH,IAAY,EAAW;QAC9B,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,OAC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,GAAG;YAEpF,MAAM,IAAIZ,MAAM,CAAC,4BAA4B,EAAEW,SAAS,IAAI,CAAC,OAAO;QACrE;IACD;AACD;AA0BO,SAASG,uBAAuBC,UAAkC,CAAC,CAAC;IAC1E,MAAMC,YAAY,IAAIrB;IAGtB,IAAIoB,QAAQ,MAAM,EACjBC,UAAU,gBAAgB,CAAC,UAAUD,QAAQ,MAAM;IAIpD,IAAIA,QAAQ,MAAM,EACjBC,UAAU,gBAAgB,CAAC,UAAUD,QAAQ,MAAM;IAGpD,OAAOC;AACR"}
|
|
1
|
+
{"version":3,"file":"di/Container.js","sources":["../../src/di/Container.ts"],"sourcesContent":["import type { Logger } from '../logger/StructuredLogger.js';\nimport type { ServerConfig } from '../ServerConfig.js';\nimport type { ConfigFileOptions } from '../config/ConfigLoader.js';\n\nimport type { IDisposable } from '../types/disposable.js';\nimport type { ServiceKey, ServiceRegistry } from './ServiceRegistry.js';\n\n/**\n * Lightweight dependency injection container for managing service dependencies.\n *\n * This container supports:\n * - Instance registration (singleton-like behavior)\n * - Factory registration (lazy instantiation with caching)\n * - Transient factory registration (new instance each time)\n *\n * The container is type-safe when using ServiceKey from ServiceRegistry.\n * For dynamic/unknown services, use string keys with generic type parameters.\n *\n * @example\n * ```typescript\n * const container = new Container();\n *\n * // Type-safe registration with ServiceKey (recommended)\n * container.registerInstance('Logger', new StructuredLogger());\n *\n * // Type inference works automatically\n * const logger = container.resolve('Logger'); // Type: StructuredLogger\n *\n * // Register a factory with caching (singleton per container)\n * container.register('HistoryManager', () =>\n * new HistoryManager({ logger: container.resolve('Logger') })\n * );\n *\n * // Register a transient factory (new instance each time)\n * container.registerFactory('RequestContext', () =>\n * new RequestContext()\n * );\n *\n * // For dynamic services not in ServiceRegistry\n * container.registerInstance<MyService>('MyService', myService);\n * const service = container.resolve<MyService>('MyService');\n * ```\n */\nexport class Container {\n\tprivate _services: Map<string, unknown> = new Map();\n\tprivate _factories: Map<string, () => unknown> = new Map();\n\tprivate _transientFactories: Map<string, () => unknown> = new Map();\n\tprivate _resolving: Set<string> = new Set();\n\tprivate _disposables: Map<string, IDisposable> = new Map();\n\n\t/**\n\t * Register a singleton instance that will be returned for all resolutions.\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param instance - The instance to register\n\t *\n\t * @example\n\t * ```typescript\n\t * container.registerInstance('Config', new ServerConfig({ ... }));\n\t * ```\n\t */\n\tregisterInstance<K extends ServiceKey>(name: K, instance: ServiceRegistry[K]): void;\n\tregisterInstance<T>(name: string, instance: T): void;\n\tregisterInstance(name: string, instance: unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._services.set(name, instance);\n\t}\n\n\t/**\n\t * Register a factory function that will be called once and cached.\n\t * The first call to `resolve` will invoke the factory and cache the result.\n\t * Subsequent calls will return the cached instance (singleton behavior).\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param factory - A factory function that creates the service\n\t *\n\t * @example\n\t * ```typescript\n\t * container.register('HistoryManager', () =>\n\t * new HistoryManager({ logger: container.resolve('Logger') })\n\t * );\n\t * ```\n\t */\n\tregister<K extends ServiceKey>(name: K, factory: () => ServiceRegistry[K]): void;\n\tregister<T>(name: string, factory: () => T): void;\n\tregister(name: string, factory: () => unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._factories.set(name, factory);\n\t}\n\n\t/**\n\t * Register a transient factory function that will be called on every resolution.\n\t * Each call to `resolve` will invoke the factory and return a new instance.\n\t *\n\t * @param name - The unique name/identifier for the service\n\t * @param factory - A factory function that creates the service\n\t *\n\t * @example\n\t * ```typescript\n\t * container.registerFactory('RequestContext', () =>\n\t * new RequestContext()\n\t * );\n\t * ```\n\t */\n\tregisterFactory<K extends ServiceKey>(name: K, factory: () => ServiceRegistry[K]): void;\n\tregisterFactory<T>(name: string, factory: () => T): void;\n\tregisterFactory(name: string, factory: () => unknown): void {\n\t\tif (\n\t\t\tthis._services.has(name) ||\n\t\t\tthis._factories.has(name) ||\n\t\t\tthis._transientFactories.has(name)\n\t\t) {\n\t\t\tthrow new Error(`Service '${name}' is already registered`);\n\t\t}\n\t\tthis._transientFactories.set(name, factory);\n\t}\n\n\t/**\n\t * Resolve a service by name.\n\t *\n\t * Resolution order:\n\t * 1. If a registered instance exists, return it\n\t * 2. If a cached factory exists, return it\n\t * 3. If a factory exists, invoke it, cache the result, and return it\n\t * 4. If a transient factory exists, invoke it and return a new instance\n\t * 5. Throw an error if the service is not found\n\t *\n\t * @param name - The name/identifier of service to resolve\n\t * @returns The resolved service instance\n\t * @throws {Error} If the service is not registered\n\t *\n\t * @example\n\t * ```typescript\n\t * // Type-safe: ServiceRegistry provides autocomplete\n\t * const logger = container.resolve('Logger'); // Type: StructuredLogger\n\t * const config = container.resolve('Config'); // Type: ServerConfig\n\t *\n\t * // Dynamic: For services not in ServiceRegistry\n\t * const service = container.resolve<MyService>('MyService');\n\t * ```\n\t */\n\tresolve<K extends ServiceKey>(name: K): ServiceRegistry[K];\n\tresolve<T>(name: string): T;\n\tresolve(name: string): unknown {\n\t\tif (this._resolving.has(name)) {\n\t\t\tthrow new Error(`Circular dependency detected while resolving service: ${name}`);\n\t\t}\n\n\t\tthis._resolving.add(name);\n\n\t\ttry {\n\t\t\t// Check for registered instance first\n\t\t\tif (this._services.has(name)) {\n\t\t\t\treturn this._services.get(name);\n\t\t\t}\n\n\t\t\t// Check for cached factory result\n\t\t\tif (this._factories.has(name)) {\n\t\t\t\tconst factory = this._factories.get(name)!;\n\t\t\t\tconst instance = factory();\n\t\t\t\t// Cache the result for future calls (singleton behavior)\n\t\t\t\tthis._services.set(name, instance);\n\t\t\t\tthis._factories.delete(name);\n\t\t\t\treturn instance;\n\t\t\t}\n\n\t\t\t// Check for transient factory (call every time)\n\t\t\tif (this._transientFactories.has(name)) {\n\t\t\t\tconst factory = this._transientFactories.get(name)!;\n\t\t\t\treturn factory();\n\t\t\t}\n\n\t\t\tthrow new Error(`Service not found: ${name}. Did you forget to register it?`);\n\t\t} finally {\n\t\t\tthis._resolving.delete(name);\n\t\t}\n\t}\n\n\t/**\n\t * Check if a service is registered (either as instance or factory).\n\t *\n\t * @param name - The name/identifier of the service to check\n\t * @returns `true` if the service is registered, `false` otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * if (!container.has('Logger')) {\n\t * container.registerInstance('Logger', new StructuredLogger());\n\t * }\n\t * ```\n\t */\n\thas(name: string): boolean {\n\t\treturn (\n\t\t\tthis._services.has(name) || this._factories.has(name) || this._transientFactories.has(name)\n\t\t);\n\t}\n\n\t/**\n\t * Remove a registered service from the container.\n\t *\n\t * @param name - The name/identifier of the service to unregister\n\t * @returns `true` if the service was found and removed, `false` otherwise\n\t *\n\t * @example\n\t * ```typescript\n\t * container.unregister('HistoryManager');\n\t * ```\n\t */\n\tunregister(name: string): boolean {\n\t\tconst hadInstance = this._services.delete(name);\n\t\tconst hadFactory = this._factories.delete(name);\n\t\tconst hadTransient = this._transientFactories.delete(name);\n\t\tthis._disposables.delete(name);\n\t\treturn hadInstance || hadFactory || hadTransient;\n\t}\n\n\t/**\n\t * Clear all registered services and factories from the container.\n\t *\n\t * @example\n\t * ```typescript\n\t * container.clear();\n\t * ```\n\t */\n\tclear(): void {\n\t\tthis._services.clear();\n\t\tthis._factories.clear();\n\t\tthis._transientFactories.clear();\n\t\tthis._resolving.clear();\n\t\tthis._disposables.clear();\n\t}\n\n\t/**\n\t * Get the number of registered services (including instances, factories, and transient factories).\n\t *\n\t * @returns The total count of registered services\n\t *\n\t * @example\n\t * ```typescript\n\t * console.log(`Registered services: ${container.size}`);\n\t * ```\n\t */\n\tget size(): number {\n\t\treturn this._services.size + this._factories.size + this._transientFactories.size;\n\t}\n\n\t/**\n\t * Get an array of all registered service names.\n\t *\n\t * @returns An array of service names\n\t *\n\t * @example\n\t * ```typescript\n\t * const names = container.registeredServices();\n\t * console.log('Registered:', names.join(', '));\n\t * ```\n\t */\n\tregisteredServices(): string[] {\n\t\tconst names = new Set<string>();\n\t\tfor (const name of this._services.keys()) names.add(name);\n\t\tfor (const name of this._factories.keys()) names.add(name);\n\t\tfor (const name of this._transientFactories.keys()) names.add(name);\n\t\treturn Array.from(names);\n\t}\n\n\t/**\n\t * Register an instance as disposable for lifecycle management.\n\t * The instance will have its `dispose()` method called when the container is disposed.\n\t *\n\t * @param name - The service name (must already be registered)\n\t * @param instance - The disposable instance to track\n\t *\n\t * @example\n\t * ```typescript\n\t * const pool = new ConnectionPool();\n\t * container.registerInstance('ConnectionPool', pool);\n\t * container.registerDisposable('ConnectionPool', pool);\n\t * ```\n\t */\n\tregisterDisposable(name: string, instance: IDisposable): void {\n\t\tthis._disposables.set(name, instance);\n\t}\n\n\t/**\n\t * Dispose of all registered disposable services.\n\t * Calls `dispose()` on each registered disposable in reverse registration order.\n\t * Errors during individual disposal are caught and logged to prevent cascading failures.\n\t *\n\t * @example\n\t * ```typescript\n\t * await container.dispose();\n\t * ```\n\t */\n\tasync dispose(): Promise<void> {\n\t\tconst entries = Array.from(this._disposables.entries()).reverse();\n\t\tconst errors: Array<{ name: string; error: unknown }> = [];\n\n\t\tfor (const [name, disposable] of entries) {\n\t\t\ttry {\n\t\t\t\tawait disposable.dispose();\n\t\t\t} catch (error) {\n\t\t\t\terrors.push({ name, error });\n\t\t\t}\n\t\t}\n\n\t\tthis._disposables.clear();\n\n\t\tif (errors.length > 0) {\n\t\t\tconst messages = errors.map(\n\t\t\t\t(e) => `${e.name}: ${e.error instanceof Error ? e.error.message : String(e.error)}`\n\t\t\t);\n\t\t\tthrow new Error(`Failed to dispose services: ${messages.join(', ')}`);\n\t\t}\n\t}\n}\n\n/**\n * Create a pre-configured container with all default services registered.\n *\n * This factory function creates a container with all standard services\n * for the ToolAwareSequentialThinkingServer.\n *\n * @param options - Configuration options for the container\n * @returns A configured container ready to use\n *\n * @example\n * ```typescript\n * const container = createDefaultContainer({\n * logger: customLogger,\n * config: customConfig\n * });\n * const server = new ToolAwareSequentialThinkingServer({ container });\n * ```\n */\nexport interface CreateContainerOptions {\n\tlogger?: Logger;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n}\n\nexport function createDefaultContainer(options: CreateContainerOptions = {}): Container {\n\tconst container = new Container();\n\n\t// Register logger if provided\n\tif (options.logger) {\n\t\tcontainer.registerInstance('Logger', options.logger);\n\t}\n\n\t// Register config if provided\n\tif (options.config) {\n\t\tcontainer.registerInstance('Config', options.config);\n\t}\n\n\treturn container;\n}\n"],"names":["Container","Map","Set","name","instance","Error","factory","hadInstance","hadFactory","hadTransient","names","Array","entries","errors","disposable","error","messages","e","String","createDefaultContainer","options","container"],"mappings":"AA2CO,MAAMA;IACJ,YAAkC,IAAIC,MAAM;IAC5C,aAAyC,IAAIA,MAAM;IACnD,sBAAkD,IAAIA,MAAM;IAC5D,aAA0B,IAAIC,MAAM;IACpC,eAAyC,IAAID,MAAM;IAe3D,iBAAiBE,IAAY,EAAEC,QAAiB,EAAQ;QACvD,IACC,IAAI,CAAC,SAAS,CAAC,GAAG,CAACD,SACnB,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,SACpB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,OAE7B,MAAM,IAAIE,MAAM,CAAC,SAAS,EAAEF,KAAK,uBAAuB,CAAC;QAE1D,IAAI,CAAC,SAAS,CAAC,GAAG,CAACA,MAAMC;IAC1B;IAmBA,SAASD,IAAY,EAAEG,OAAsB,EAAQ;QACpD,IACC,IAAI,CAAC,SAAS,CAAC,GAAG,CAACH,SACnB,IAAI,CAAC,UAAU,CAAC,GAAG,CAACA,SACpB,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAACA,OAE7B,MAAM,IAAIE,MAAM,CAAC,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AC,IAAI,CAAC,YAAY,CAAC,OAAO,IAAI,OAAO;QAC/D,MAAME,SAAkD,EAAE;QAE1D,KAAK,MAAM,CAACV,MAAMW,WAAW,IAAIF,QAChC,IAAI;YACH,MAAME,WAAW,OAAO;QACzB,EAAE,OAAOC,OAAO;YACfF,OAAO,IAAI,CAAC;gBAAEV;gBAAMY;YAAM;QAC3B;QAGD,IAAI,CAAC,YAAY,CAAC,KAAK;QAEvB,IAAIF,OAAO,MAAM,GAAG,GAAG;YACtB,MAAMG,WAAWH,OAAO,GAAG,CAC1B,CAACI,IAAM,GAAGA,EAAE,IAAI,CAAC,EAAE,EAAEA,EAAE,KAAK,YAAYZ,QAAQY,EAAE,KAAK,CAAC,OAAO,GAAGC,OAAOD,EAAE,KAAK,GAAG;YAEpF,MAAM,IAAIZ,MAAM,CAAC,4BAA4B,EAAEW,SAAS,IAAI,CAAC,OAAO;QACrE;IACD;AACD;AA0BO,SAASG,uBAAuBC,UAAkC,CAAC,CAAC;IAC1E,MAAMC,YAAY,IAAIrB;IAGtB,IAAIoB,QAAQ,MAAM,EACjBC,UAAU,gBAAgB,CAAC,UAAUD,QAAQ,MAAM;IAIpD,IAAIA,QAAQ,MAAM,EACjBC,UAAU,gBAAgB,CAAC,UAAUD,QAAQ,MAAM;IAGpD,OAAOC;AACR"}
|
|
@@ -5,19 +5,18 @@
|
|
|
5
5
|
* Interface types are imported from contracts/ to reduce coupling.
|
|
6
6
|
* Concrete types are imported only where needed for DI resolution.
|
|
7
7
|
*/
|
|
8
|
-
import type { PersistenceBackend } from '../
|
|
8
|
+
import type { PersistenceBackend } from '../contracts/PersistenceBackend.js';
|
|
9
9
|
import type { HistoryManager } from '../core/HistoryManager.js';
|
|
10
10
|
import type { EdgeStore } from '../core/graph/EdgeStore.js';
|
|
11
11
|
import type { ICalibrator } from '../contracts/calibrator.js';
|
|
12
|
-
import type { IOutcomeRecorder } from '../contracts/interfaces.js';
|
|
12
|
+
import type { IOutcomeRecorder, ISessionLock, IToolRegistry } from '../contracts/interfaces.js';
|
|
13
13
|
import type { IReasoningStrategy } from '../contracts/strategy.js';
|
|
14
14
|
import type { ThoughtEvaluator } from '../core/ThoughtEvaluator.js';
|
|
15
|
-
import type {
|
|
15
|
+
import type { IThoughtFormatter } from '../core/IThoughtFormatter.js';
|
|
16
16
|
import type { ThoughtProcessor } from '../core/ThoughtProcessor.js';
|
|
17
17
|
import type { StructuredLogger } from '../logger/StructuredLogger.js';
|
|
18
18
|
import type { Metrics } from '../metrics/metrics.impl.js';
|
|
19
19
|
import type { SkillRegistry } from '../registry/SkillRegistry.js';
|
|
20
|
-
import type { ToolRegistry } from '../registry/ToolRegistry.js';
|
|
21
20
|
import type { ServerConfig } from '../ServerConfig.js';
|
|
22
21
|
import type { ISummaryStore } from '../contracts/summary.js';
|
|
23
22
|
import type { CompressionService } from '../core/compression/CompressionService.js';
|
|
@@ -28,10 +27,10 @@ export interface ServiceRegistry {
|
|
|
28
27
|
FileConfig: Record<string, unknown>;
|
|
29
28
|
HistoryManager: HistoryManager;
|
|
30
29
|
ThoughtProcessor: ThoughtProcessor;
|
|
31
|
-
ThoughtFormatter:
|
|
30
|
+
ThoughtFormatter: IThoughtFormatter;
|
|
32
31
|
ThoughtEvaluator: ThoughtEvaluator;
|
|
33
32
|
Persistence: PersistenceBackend | null;
|
|
34
|
-
ToolRegistry:
|
|
33
|
+
ToolRegistry: IToolRegistry;
|
|
35
34
|
SkillRegistry: SkillRegistry;
|
|
36
35
|
Metrics: Metrics;
|
|
37
36
|
EdgeStore: EdgeStore;
|
|
@@ -41,6 +40,7 @@ export interface ServiceRegistry {
|
|
|
41
40
|
summaryStore: ISummaryStore;
|
|
42
41
|
compressionService: CompressionService;
|
|
43
42
|
suspensionStore: ISuspensionStore;
|
|
43
|
+
sessionLock: ISessionLock;
|
|
44
44
|
}
|
|
45
45
|
export type ServiceKey = keyof ServiceRegistry;
|
|
46
46
|
//# sourceMappingURL=ServiceRegistry.d.ts.map
|
|
@@ -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,
|
|
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,YAAY,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChG,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,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AACpF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,MAAM,WAAW,eAAe;IAC/B,MAAM,EAAE,gBAAgB,CAAC;IACzB,MAAM,EAAE,YAAY,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,cAAc,EAAE,cAAc,CAAC;IAC/B,gBAAgB,EAAE,gBAAgB,CAAC;IACnC,gBAAgB,EAAE,iBAAiB,CAAC;IACpC,gBAAgB,EAAE,gBAAgB,CAAC;IACnC,WAAW,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACvC,YAAY,EAAE,aAAa,CAAC;IAC5B,aAAa,EAAE,aAAa,CAAC;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,SAAS,CAAC;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
|
@@ -25,6 +25,45 @@
|
|
|
25
25
|
* ```
|
|
26
26
|
* @module errors
|
|
27
27
|
*/
|
|
28
|
+
/**
|
|
29
|
+
* All known error codes as a const object for exhaustive switching.
|
|
30
|
+
*/
|
|
31
|
+
export declare const ERROR_CODES: {
|
|
32
|
+
readonly CONFIGURATION_ERROR: "CONFIGURATION_ERROR";
|
|
33
|
+
readonly TOOL_NOT_FOUND: "TOOL_NOT_FOUND";
|
|
34
|
+
readonly SKILL_NOT_FOUND: "SKILL_NOT_FOUND";
|
|
35
|
+
readonly INVALID_THOUGHT: "INVALID_THOUGHT";
|
|
36
|
+
readonly SKILL_DISCOVERY_FAILED: "SKILL_DISCOVERY_FAILED";
|
|
37
|
+
readonly HISTORY_LIMIT_EXCEEDED: "HISTORY_LIMIT_EXCEEDED";
|
|
38
|
+
readonly DUPLICATE_SKILL: "DUPLICATE_SKILL";
|
|
39
|
+
readonly INVALID_SKILL: "INVALID_SKILL";
|
|
40
|
+
readonly DUPLICATE_TOOL: "DUPLICATE_TOOL";
|
|
41
|
+
readonly INVALID_TOOL: "INVALID_TOOL";
|
|
42
|
+
readonly SESSION_NOT_ACTIVE: "SESSION_NOT_ACTIVE";
|
|
43
|
+
readonly SESSION_NOT_FOUND: "SESSION_NOT_FOUND";
|
|
44
|
+
readonly MAX_SESSIONS_REACHED: "MAX_SESSIONS_REACHED";
|
|
45
|
+
readonly POOL_TERMINATED: "POOL_TERMINATED";
|
|
46
|
+
readonly VALIDATION_ERROR: "VALIDATION_ERROR";
|
|
47
|
+
readonly INVALID_EDGE: "INVALID_EDGE";
|
|
48
|
+
readonly CYCLE_DETECTED: "CYCLE_DETECTED";
|
|
49
|
+
readonly SUSPENSION_NOT_FOUND: "SUSPENSION_NOT_FOUND";
|
|
50
|
+
readonly SUSPENSION_EXPIRED: "SUSPENSION_EXPIRED";
|
|
51
|
+
readonly INVALID_TOOL_CALL: "INVALID_TOOL_CALL";
|
|
52
|
+
readonly INVALID_BACKTRACK: "INVALID_BACKTRACK";
|
|
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";
|
|
57
|
+
};
|
|
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];
|
|
28
67
|
/**
|
|
29
68
|
* Base error class for all Sequential Thinking server errors.
|
|
30
69
|
*
|
|
@@ -54,7 +93,7 @@
|
|
|
54
93
|
*/
|
|
55
94
|
export declare class SequentialThinkingError extends Error {
|
|
56
95
|
/** The error code for programmatic identification. */
|
|
57
|
-
readonly code:
|
|
96
|
+
readonly code: ErrorCode;
|
|
58
97
|
/**
|
|
59
98
|
* Creates a new SequentialThinkingError.
|
|
60
99
|
*
|
|
@@ -70,7 +109,7 @@ export declare class SequentialThinkingError extends Error {
|
|
|
70
109
|
* console.log(error.code); // 'CUSTOM_ERROR'
|
|
71
110
|
* ```
|
|
72
111
|
*/
|
|
73
|
-
constructor(message: string, code:
|
|
112
|
+
constructor(message: string, code: ErrorCode);
|
|
74
113
|
}
|
|
75
114
|
export declare class ConfigurationError extends SequentialThinkingError {
|
|
76
115
|
constructor(message: string);
|
|
@@ -577,6 +616,49 @@ export declare class InvalidToolCallError extends SequentialThinkingError {
|
|
|
577
616
|
export declare class InvalidBacktrackError extends SequentialThinkingError {
|
|
578
617
|
constructor(message: string);
|
|
579
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
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Type guard to check if an error has a specific error code.
|
|
658
|
+
*/
|
|
659
|
+
export declare function isErrorCode<C extends ErrorCode>(err: unknown, code: C): err is SequentialThinkingError & {
|
|
660
|
+
readonly code: C;
|
|
661
|
+
};
|
|
580
662
|
/**
|
|
581
663
|
* Extract a human-readable message from an unknown error value.
|
|
582
664
|
*
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,sDAAsD;IACtD,SAAgB,IAAI,EAAE,
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],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