@iworkforces/tracelattice 2.0.6 → 2.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +28 -1
  2. package/dist/cli.js +296 -196
  3. package/dist/contracts/summary.d.ts +0 -1
  4. package/dist/contracts/summary.d.ts.map +1 -1
  5. package/dist/core/PersistenceRestore.d.ts +1 -1
  6. package/dist/core/PersistenceRestore.d.ts.map +1 -1
  7. package/dist/core/PersistenceRestore.js.map +1 -1
  8. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  9. package/dist/core/ThoughtEvaluator.js.map +1 -1
  10. package/dist/core/ThoughtFormatter.js.map +1 -1
  11. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  12. package/dist/core/ThoughtProcessor.js.map +1 -1
  13. package/dist/core/compression/CompressionService.d.ts +6 -4
  14. package/dist/core/compression/CompressionService.d.ts.map +1 -1
  15. package/dist/core/compression/CompressionService.js +19 -10
  16. package/dist/core/compression/CompressionService.js.map +1 -1
  17. package/dist/core/compression/DehydrationPolicy.d.ts +4 -4
  18. package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -1
  19. package/dist/core/compression/DehydrationPolicy.js +3 -6
  20. package/dist/core/compression/DehydrationPolicy.js.map +1 -1
  21. package/dist/core/compression/InMemorySummaryStore.d.ts +2 -1
  22. package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -1
  23. package/dist/core/compression/InMemorySummaryStore.js.map +1 -1
  24. package/dist/core/evaluator/Calibrator.d.ts +1 -1
  25. package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
  26. package/dist/core/evaluator/Calibrator.js.map +1 -1
  27. package/dist/core/evaluator/SignalComputer.d.ts +2 -1
  28. package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
  29. package/dist/core/evaluator/SignalComputer.js.map +1 -1
  30. package/dist/core/evaluator/internals.d.ts +1 -1
  31. package/dist/core/evaluator/internals.d.ts.map +1 -1
  32. package/dist/core/evaluator/internals.js.map +1 -1
  33. package/dist/core/graph/GraphView.d.ts +13 -1
  34. package/dist/core/graph/GraphView.d.ts.map +1 -1
  35. package/dist/core/graph/GraphView.js +34 -0
  36. package/dist/core/graph/GraphView.js.map +1 -1
  37. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +6 -6
  38. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
  39. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +16 -2
  40. package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
  41. package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -1
  42. package/dist/core/reasoning/strategies/totScoring.js.map +1 -1
  43. package/dist/core/reasoning.d.ts +1 -3
  44. package/dist/core/reasoning.d.ts.map +1 -1
  45. package/dist/core/thought.d.ts +1 -1
  46. package/dist/core/thought.d.ts.map +1 -1
  47. package/dist/lib.d.ts +20 -6
  48. package/dist/lib.d.ts.map +1 -1
  49. package/dist/lib.js +52 -3
  50. package/dist/lib.js.map +1 -1
  51. package/dist/transport/HttpHelpers.d.ts +4 -1
  52. package/dist/transport/HttpHelpers.d.ts.map +1 -1
  53. package/dist/transport/HttpHelpers.js +61 -11
  54. package/dist/transport/HttpHelpers.js.map +1 -1
  55. package/dist/transport/HttpRequestLifecycle.d.ts +15 -1
  56. package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -1
  57. package/dist/transport/HttpRequestLifecycle.js +66 -4
  58. package/dist/transport/HttpRequestLifecycle.js.map +1 -1
  59. package/dist/transport/HttpTransport.d.ts +2 -0
  60. package/dist/transport/HttpTransport.d.ts.map +1 -1
  61. package/dist/transport/HttpTransport.js +75 -38
  62. package/dist/transport/HttpTransport.js.map +1 -1
  63. package/dist/transport/StreamableHttpTransport.d.ts +17 -29
  64. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
  65. package/dist/transport/StreamableHttpTransport.js +153 -124
  66. package/dist/transport/StreamableHttpTransport.js.map +1 -1
  67. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"core/graph/GraphView.js","sources":["../../../src/core/graph/GraphView.ts"],"sourcesContent":["/**\n * GraphView — read-only graph traversal queries over an {@link IEdgeStore}.\n *\n * Provides BFS / topological / ancestor / descendant queries over the\n * thought DAG. All methods return arrays of thought ids (ulid strings),\n * never `ThoughtData` objects — the view is intentionally decoupled from\n * `HistoryManager` so it can be reused by strategies that work purely in\n * terms of graph structure.\n *\n * Construction is cheap (stores a reference to the underlying store).\n * Each query reads the latest store state — no caching, no snapshots.\n *\n * @module core/graph/GraphView\n */\n\nimport type { IEdgeStore } from '../../contracts/interfaces.js';\nimport type { SessionId, ThoughtId } from '../../contracts/ids.js';\nimport { CycleDetectedError } from '../../errors.js';\nimport type { Edge } from './Edge.js';\n\n/**\n * Read-only traversal queries over an {@link IEdgeStore}.\n *\n * @example\n * ```typescript\n * const store = new EdgeStore();\n * // ... populate store ...\n * const view = new GraphView(store);\n * const order = view.topological('s1');\n * ```\n */\nexport class GraphView {\n\tprivate readonly _store: IEdgeStore;\n\n\t/**\n\t * Create a new GraphView backed by the given edge store.\n\t *\n\t * @param store - The edge store to query (held by reference, read-only access)\n\t *\n\t * @example\n\t * ```typescript\n\t * const view = new GraphView(edgeStore);\n\t * ```\n\t */\n\tconstructor(store: IEdgeStore) {\n\t\tthis._store = store;\n\t}\n\n\t/**\n\t * Return all thought ids in the session, ordered by BFS from roots.\n\t *\n\t * Roots are nodes with no incoming edges. Within a layer, neighbours\n\t * are visited in `outgoing` order (which the underlying store keeps\n\t * sorted by `createdAt` ascending).\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids in chronological BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const ids = view.chronological('s1');\n\t * ```\n\t */\n\tchronological(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst { nodes, hasIncoming } = this._collectNodes(edges);\n\t\tconst roots = this._findRoots(nodes, hasIncoming, edges);\n\t\treturn this._bfsFromRoots(sessionId, roots) as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return all thought ids reachable from `rootThoughtId` via `'branch'`\n\t * edges, including the root itself.\n\t *\n\t * Non-branch edges are ignored. Cycles (if any) do not cause infinite\n\t * loops because each node is visited at most once.\n\t *\n\t * @param sessionId - Session to query\n\t * @param rootThoughtId - The starting thought id (typically the branch root)\n\t * @returns Thought ids forming the branch (includes root)\n\t *\n\t * @example\n\t * ```typescript\n\t * const branchIds = view.branchThoughts('s1', 'thought-root');\n\t * ```\n\t */\n\tbranchThoughts(sessionId: SessionId, rootThoughtId: ThoughtId): readonly ThoughtId[] {\n\t\tconst visited = new Set<string>([rootThoughtId]);\n\t\tconst order: string[] = [rootThoughtId];\n\t\tconst queue: string[] = [rootThoughtId];\n\t\twhile (queue.length > 0) {\n\t\t\tconst current = queue.shift()!;\n\t\t\tconst out = this._store.outgoing(sessionId, current as ThoughtId);\n\t\t\tfor (const edge of out) {\n\t\t\t\tif (edge.kind !== 'branch') continue;\n\t\t\t\tif (visited.has(edge.to)) continue;\n\t\t\t\tvisited.add(edge.to);\n\t\t\t\torder.push(edge.to);\n\t\t\t\tqueue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\treturn order as ThoughtId[];\n\t}\n\n\t/**\n\t * Return a topological ordering of all thought ids in the session\n\t * using Kahn's algorithm.\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids in topological order\n\t * @throws {CycleDetectedError} If the graph contains a cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * const order = view.topological('s1');\n\t * ```\n\t */\n\ttopological(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst inDegree = this._buildInDegree(edges);\n\t\tconst queue: string[] = [];\n\t\tfor (const [node, deg] of inDegree) {\n\t\t\tif (deg === 0) queue.push(node);\n\t\t}\n\t\tconst order: string[] = [];\n\t\twhile (queue.length > 0) {\n\t\t\tconst node = queue.shift()!;\n\t\t\torder.push(node);\n\t\t\tfor (const edge of this._store.outgoing(sessionId, node as ThoughtId)) {\n\t\t\t\tconst next = (inDegree.get(edge.to) ?? 0) - 1;\n\t\t\t\tinDegree.set(edge.to, next);\n\t\t\t\tif (next === 0) queue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\tif (order.length !== inDegree.size) {\n\t\t\tthrow new CycleDetectedError(\n\t\t\t\t`Cycle detected in session '${sessionId}': topological sort incomplete (${order.length}/${inDegree.size})`\n\t\t\t);\n\t\t}\n\t\treturn order as ThoughtId[];\n\t}\n\n\t/**\n\t * Return all ancestors of `thoughtId` via incoming-edge BFS.\n\t *\n\t * The starting node is NOT included. Cycles do not cause infinite loops.\n\t *\n\t * @param sessionId - Session to query\n\t * @param thoughtId - The thought to traverse from\n\t * @param maxDepth - Optional maximum traversal depth (1 = direct parents only)\n\t * @returns Ancestor thought ids in BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const parents = view.ancestors('s1', 'thought-id', 1);\n\t * ```\n\t */\n\tancestors(sessionId: SessionId, thoughtId: ThoughtId, maxDepth?: number): readonly ThoughtId[] {\n\t\treturn this._bfsClosure(sessionId, thoughtId, maxDepth, 'incoming') as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return all descendants of `thoughtId` via outgoing-edge BFS.\n\t *\n\t * The starting node is NOT included. Cycles do not cause infinite loops.\n\t *\n\t * @param sessionId - Session to query\n\t * @param thoughtId - The thought to traverse from\n\t * @param maxDepth - Optional maximum traversal depth (1 = direct children only)\n\t * @returns Descendant thought ids in BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const children = view.descendants('s1', 'thought-id');\n\t * ```\n\t */\n\tdescendants(sessionId: SessionId, thoughtId: ThoughtId, maxDepth?: number): readonly ThoughtId[] {\n\t\treturn this._bfsClosure(sessionId, thoughtId, maxDepth, 'outgoing') as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return all thought ids in the session that have no outgoing edges.\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids that are graph leaves\n\t *\n\t * @example\n\t * ```typescript\n\t * const tips = view.leaves('s1');\n\t * ```\n\t */\n\tleaves(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst { nodes } = this._collectNodes(edges);\n\t\tconst result: string[] = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (this._store.outgoing(sessionId, node as ThoughtId).length === 0) {\n\t\t\t\tresult.push(node);\n\t\t\t}\n\t\t}\n\t\treturn result as ThoughtId[];\n\t}\n\n\t/**\n\t * Collect every node id referenced by the edges and a set of nodes\n\t * that have at least one incoming edge.\n\t */\n\tprivate _collectNodes(edges: readonly Edge[]): {\n\t\tnodes: Set<string>;\n\t\thasIncoming: Set<string>;\n\t} {\n\t\tconst nodes = new Set<string>();\n\t\tconst hasIncoming = new Set<string>();\n\t\tfor (const edge of edges) {\n\t\t\tnodes.add(edge.from);\n\t\t\tnodes.add(edge.to);\n\t\t\thasIncoming.add(edge.to);\n\t\t}\n\t\treturn { nodes, hasIncoming };\n\t}\n\n\t/**\n\t * Find roots (no incoming) ordered by the earliest outgoing edge\n\t * `createdAt`. Nodes with no outgoing edges fall back to the order\n\t * they appear among edges (already sorted by `createdAt`).\n\t */\n\tprivate _findRoots(\n\t\tnodes: Set<string>,\n\t\thasIncoming: Set<string>,\n\t\tedges: readonly Edge[]\n\t): string[] {\n\t\tconst earliest = new Map<string, number>();\n\t\tfor (const edge of edges) {\n\t\t\tif (!earliest.has(edge.from)) {\n\t\t\t\tearliest.set(edge.from, edge.createdAt);\n\t\t\t}\n\t\t}\n\t\tconst roots: string[] = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (!hasIncoming.has(node)) roots.push(node);\n\t\t}\n\t\troots.sort((a, b) => (earliest.get(a) ?? Infinity) - (earliest.get(b) ?? Infinity));\n\t\treturn roots;\n\t}\n\n\t/**\n\t * BFS from a list of root ids, visiting each node at most once.\n\t */\n\tprivate _bfsFromRoots(sessionId: SessionId, roots: readonly string[]): readonly string[] {\n\t\tconst visited = new Set<string>();\n\t\tconst order: string[] = [];\n\t\tconst queue: string[] = [];\n\t\tfor (const root of roots) {\n\t\t\tif (visited.has(root)) continue;\n\t\t\tvisited.add(root);\n\t\t\torder.push(root);\n\t\t\tqueue.push(root);\n\t\t}\n\t\twhile (queue.length > 0) {\n\t\t\tconst node = queue.shift()!;\n\t\t\tfor (const edge of this._store.outgoing(sessionId, node as ThoughtId)) {\n\t\t\t\tif (visited.has(edge.to)) continue;\n\t\t\t\tvisited.add(edge.to);\n\t\t\t\torder.push(edge.to);\n\t\t\t\tqueue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\treturn order;\n\t}\n\n\t/**\n\t * Build an in-degree map covering every node referenced by the edges.\n\t */\n\tprivate _buildInDegree(edges: readonly Edge[]): Map<string, number> {\n\t\tconst inDegree = new Map<string, number>();\n\t\tfor (const edge of edges) {\n\t\t\tif (!inDegree.has(edge.from)) inDegree.set(edge.from, 0);\n\t\t\tinDegree.set(edge.to, (inDegree.get(edge.to) ?? 0) + 1);\n\t\t}\n\t\treturn inDegree;\n\t}\n\n\t/**\n\t * Generic BFS closure in either direction. Excludes the start node\n\t * from the result and respects an optional depth cap.\n\t */\n\tprivate _bfsClosure(\n\t\tsessionId: SessionId,\n\t\tstartId: string,\n\t\tmaxDepth: number | undefined,\n\t\tdirection: 'incoming' | 'outgoing'\n\t): readonly string[] {\n\t\tconst cap = maxDepth ?? Number.POSITIVE_INFINITY;\n\t\tconst visited = new Set<string>([startId]);\n\t\tconst order: string[] = [];\n\t\tlet frontier: string[] = [startId];\n\t\tlet depth = 0;\n\t\twhile (frontier.length > 0 && depth < cap) {\n\t\t\tconst next: string[] = [];\n\t\t\tfor (const node of frontier) {\n\t\t\t\tconst edges =\n\t\t\t\t\tdirection === 'outgoing'\n\t\t\t\t\t\t? this._store.outgoing(sessionId, node as ThoughtId)\n\t\t\t\t\t\t: this._store.incoming(sessionId, node as ThoughtId);\n\t\t\t\tfor (const edge of edges) {\n\t\t\t\t\tconst neighbour = direction === 'outgoing' ? edge.to : edge.from;\n\t\t\t\t\tif (visited.has(neighbour)) continue;\n\t\t\t\t\tvisited.add(neighbour);\n\t\t\t\t\torder.push(neighbour);\n\t\t\t\t\tnext.push(neighbour);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrontier = next;\n\t\t\tdepth++;\n\t\t}\n\t\treturn order;\n\t}\n}\n"],"names":["GraphView","store","sessionId","edges","nodes","hasIncoming","roots","rootThoughtId","visited","Set","order","queue","current","out","edge","inDegree","node","deg","next","CycleDetectedError","thoughtId","maxDepth","result","earliest","Map","a","b","Infinity","root","startId","direction","cap","Number","frontier","depth","neighbour"],"mappings":";AA+BO,MAAMA;IACK,OAAmB;IAYpC,YAAYC,KAAiB,CAAE;QAC9B,IAAI,CAAC,MAAM,GAAGA;IACf;IAiBA,cAAcC,SAAoB,EAAwB;QACzD,MAAMC,QAAQ,IAAI,CAAC,MAAM,CAAC,eAAe,CAACD;QAC1C,IAAIC,AAAiB,MAAjBA,MAAM,MAAM,EACf,OAAO,EAAE;QAEV,MAAM,EAAEC,KAAK,EAAEC,WAAW,EAAE,GAAG,IAAI,CAAC,aAAa,CAACF;QAClD,MAAMG,QAAQ,IAAI,CAAC,UAAU,CAACF,OAAOC,aAAaF;QAClD,OAAO,IAAI,CAAC,aAAa,CAACD,WAAWI;IACtC;IAkBA,eAAeJ,SAAoB,EAAEK,aAAwB,EAAwB;QACpF,MAAMC,UAAU,IAAIC,IAAY;YAACF;SAAc;QAC/C,MAAMG,QAAkB;YAACH;SAAc;QACvC,MAAMI,QAAkB;YAACJ;SAAc;QACvC,MAAOI,MAAM,MAAM,GAAG,EAAG;YACxB,MAAM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AAIC,IAAY;YAACoB;SAAQ;QACzC,MAAMnB,QAAkB,EAAE;QAC1B,IAAIuB,WAAqB;YAACJ;SAAQ;QAClC,IAAIK,QAAQ;QACZ,MAAOD,SAAS,MAAM,GAAG,KAAKC,QAAQH,IAAK;YAC1C,MAAMb,OAAiB,EAAE;YACzB,KAAK,MAAMF,QAAQiB,SAAU;gBAC5B,MAAM9B,QACL2B,AAAc,eAAdA,YACG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC5B,WAAWc,QAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAACd,WAAWc;gBACpC,KAAK,MAAMF,QAAQX,MAAO;oBACzB,MAAMgC,YAAYL,AAAc,eAAdA,YAA2BhB,KAAK,EAAE,GAAGA,KAAK,IAAI;oBAChE,KAAIN,QAAQ,GAAG,CAAC2B;wBAChB3B,QAAQ,GAAG,CAAC2B;wBACZzB,MAAM,IAAI,CAACyB;wBACXjB,KAAK,IAAI,CAACiB;;gBACX;YACD;YACAF,WAAWf;YACXgB;QACD;QACA,OAAOxB;IACR;AACD"}
1
+ {"version":3,"file":"core/graph/GraphView.js","sources":["../../../src/core/graph/GraphView.ts"],"sourcesContent":["/**\n * GraphView — read-only graph traversal queries over an {@link IEdgeStore}.\n *\n * Provides BFS / topological / ancestor / descendant queries over the\n * thought DAG. Queries return thought ids or graph distances,\n * never `ThoughtData` objects — the view is intentionally decoupled from\n * `HistoryManager` so it can be reused by strategies that work purely in\n * terms of graph structure.\n *\n * Construction is cheap (stores a reference to the underlying store).\n * Each query reads the latest store state — no caching, no snapshots.\n *\n * @module core/graph/GraphView\n */\n\nimport type { IEdgeStore } from '../../contracts/interfaces.js';\nimport type { SessionId, ThoughtId } from '../../contracts/ids.js';\nimport { CycleDetectedError } from '../../errors.js';\nimport type { Edge } from './Edge.js';\n\n/**\n * Read-only traversal queries over an {@link IEdgeStore}.\n *\n * @example\n * ```typescript\n * const store = new EdgeStore();\n * // ... populate store ...\n * const view = new GraphView(store);\n * const order = view.topological('s1');\n * ```\n */\nexport class GraphView {\n\tprivate readonly _store: IEdgeStore;\n\n\t/**\n\t * Create a new GraphView backed by the given edge store.\n\t *\n\t * @param store - The edge store to query (held by reference, read-only access)\n\t *\n\t * @example\n\t * ```typescript\n\t * const view = new GraphView(edgeStore);\n\t * ```\n\t */\n\tconstructor(store: IEdgeStore) {\n\t\tthis._store = store;\n\t}\n\n\t/**\n\t * Return all thought ids in the session, ordered by BFS from roots.\n\t *\n\t * Roots are nodes with no incoming edges. Within a layer, neighbours\n\t * are visited in `outgoing` order (which the underlying store keeps\n\t * sorted by `createdAt` ascending).\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids in chronological BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const ids = view.chronological('s1');\n\t * ```\n\t */\n\tchronological(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst { nodes, hasIncoming } = this._collectNodes(edges);\n\t\tconst roots = this._findRoots(nodes, hasIncoming, edges);\n\t\treturn this._bfsFromRoots(sessionId, roots) as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return the shortest directed distance from any retained root to a thought.\n\t *\n\t * Nodes are derived from the current edge store, so isolated thoughts are\n\t * invisible and pruning can expose a retained node as a new root. Every edge\n\t * kind participates in the traversal.\n\t *\n\t * @param sessionId - Session to query\n\t * @param thoughtId - Thought whose root distance to resolve\n\t * @returns Zero for a root, or `undefined` when no root can reach the thought\n\t */\n\tdepthFromRoots(sessionId: SessionId, thoughtId: ThoughtId): number | undefined {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) return undefined;\n\n\t\tconst nodes = new Set<ThoughtId>();\n\t\tconst hasIncoming = new Set<ThoughtId>();\n\t\tconst outgoing = new Map<ThoughtId, ThoughtId[]>();\n\t\tfor (const edge of edges) {\n\t\t\tnodes.add(edge.from);\n\t\t\tnodes.add(edge.to);\n\t\t\thasIncoming.add(edge.to);\n\t\t\tconst children = outgoing.get(edge.from);\n\t\t\tif (children === undefined) outgoing.set(edge.from, [edge.to]);\n\t\t\telse children.push(edge.to);\n\t\t}\n\t\tif (!nodes.has(thoughtId)) return undefined;\n\n\t\tlet frontier: ThoughtId[] = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (!hasIncoming.has(node)) frontier.push(node);\n\t\t}\n\t\tconst visited = new Set<ThoughtId>(frontier);\n\t\tlet depth = 0;\n\t\twhile (frontier.length > 0) {\n\t\t\tconst next: ThoughtId[] = [];\n\t\t\tfor (const node of frontier) {\n\t\t\t\tif (node === thoughtId) return depth;\n\t\t\t\tfor (const child of outgoing.get(node) ?? []) {\n\t\t\t\t\tif (visited.has(child)) continue;\n\t\t\t\t\tvisited.add(child);\n\t\t\t\t\tnext.push(child);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrontier = next;\n\t\t\tdepth++;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Return all thought ids reachable from `rootThoughtId` via `'branch'`\n\t * edges, including the root itself.\n\t *\n\t * Non-branch edges are ignored. Cycles (if any) do not cause infinite\n\t * loops because each node is visited at most once.\n\t *\n\t * @param sessionId - Session to query\n\t * @param rootThoughtId - The starting thought id (typically the branch root)\n\t * @returns Thought ids forming the branch (includes root)\n\t *\n\t * @example\n\t * ```typescript\n\t * const branchIds = view.branchThoughts('s1', 'thought-root');\n\t * ```\n\t */\n\tbranchThoughts(sessionId: SessionId, rootThoughtId: ThoughtId): readonly ThoughtId[] {\n\t\tconst visited = new Set<string>([rootThoughtId]);\n\t\tconst order: string[] = [rootThoughtId];\n\t\tconst queue: string[] = [rootThoughtId];\n\t\twhile (queue.length > 0) {\n\t\t\tconst current = queue.shift()!;\n\t\t\tconst out = this._store.outgoing(sessionId, current as ThoughtId);\n\t\t\tfor (const edge of out) {\n\t\t\t\tif (edge.kind !== 'branch') continue;\n\t\t\t\tif (visited.has(edge.to)) continue;\n\t\t\t\tvisited.add(edge.to);\n\t\t\t\torder.push(edge.to);\n\t\t\t\tqueue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\treturn order as ThoughtId[];\n\t}\n\n\t/**\n\t * Return a topological ordering of all thought ids in the session\n\t * using Kahn's algorithm.\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids in topological order\n\t * @throws {CycleDetectedError} If the graph contains a cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * const order = view.topological('s1');\n\t * ```\n\t */\n\ttopological(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst inDegree = this._buildInDegree(edges);\n\t\tconst queue: string[] = [];\n\t\tfor (const [node, deg] of inDegree) {\n\t\t\tif (deg === 0) queue.push(node);\n\t\t}\n\t\tconst order: string[] = [];\n\t\twhile (queue.length > 0) {\n\t\t\tconst node = queue.shift()!;\n\t\t\torder.push(node);\n\t\t\tfor (const edge of this._store.outgoing(sessionId, node as ThoughtId)) {\n\t\t\t\tconst next = (inDegree.get(edge.to) ?? 0) - 1;\n\t\t\t\tinDegree.set(edge.to, next);\n\t\t\t\tif (next === 0) queue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\tif (order.length !== inDegree.size) {\n\t\t\tthrow new CycleDetectedError(\n\t\t\t\t`Cycle detected in session '${sessionId}': topological sort incomplete (${order.length}/${inDegree.size})`\n\t\t\t);\n\t\t}\n\t\treturn order as ThoughtId[];\n\t}\n\n\t/**\n\t * Return all ancestors of `thoughtId` via incoming-edge BFS.\n\t *\n\t * The starting node is NOT included. Cycles do not cause infinite loops.\n\t *\n\t * @param sessionId - Session to query\n\t * @param thoughtId - The thought to traverse from\n\t * @param maxDepth - Optional maximum traversal depth (1 = direct parents only)\n\t * @returns Ancestor thought ids in BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const parents = view.ancestors('s1', 'thought-id', 1);\n\t * ```\n\t */\n\tancestors(sessionId: SessionId, thoughtId: ThoughtId, maxDepth?: number): readonly ThoughtId[] {\n\t\treturn this._bfsClosure(sessionId, thoughtId, maxDepth, 'incoming') as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return all descendants of `thoughtId` via outgoing-edge BFS.\n\t *\n\t * The starting node is NOT included. Cycles do not cause infinite loops.\n\t *\n\t * @param sessionId - Session to query\n\t * @param thoughtId - The thought to traverse from\n\t * @param maxDepth - Optional maximum traversal depth (1 = direct children only)\n\t * @returns Descendant thought ids in BFS order\n\t *\n\t * @example\n\t * ```typescript\n\t * const children = view.descendants('s1', 'thought-id');\n\t * ```\n\t */\n\tdescendants(sessionId: SessionId, thoughtId: ThoughtId, maxDepth?: number): readonly ThoughtId[] {\n\t\treturn this._bfsClosure(sessionId, thoughtId, maxDepth, 'outgoing') as readonly ThoughtId[];\n\t}\n\n\t/**\n\t * Return all thought ids in the session that have no outgoing edges.\n\t *\n\t * @param sessionId - Session to query\n\t * @returns Thought ids that are graph leaves\n\t *\n\t * @example\n\t * ```typescript\n\t * const tips = view.leaves('s1');\n\t * ```\n\t */\n\tleaves(sessionId: SessionId): readonly ThoughtId[] {\n\t\tconst edges = this._store.edgesForSession(sessionId);\n\t\tif (edges.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst { nodes } = this._collectNodes(edges);\n\t\tconst result: string[] = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (this._store.outgoing(sessionId, node as ThoughtId).length === 0) {\n\t\t\t\tresult.push(node);\n\t\t\t}\n\t\t}\n\t\treturn result as ThoughtId[];\n\t}\n\n\t/**\n\t * Collect every node id referenced by the edges and a set of nodes\n\t * that have at least one incoming edge.\n\t */\n\tprivate _collectNodes(edges: readonly Edge[]): {\n\t\tnodes: Set<string>;\n\t\thasIncoming: Set<string>;\n\t} {\n\t\tconst nodes = new Set<string>();\n\t\tconst hasIncoming = new Set<string>();\n\t\tfor (const edge of edges) {\n\t\t\tnodes.add(edge.from);\n\t\t\tnodes.add(edge.to);\n\t\t\thasIncoming.add(edge.to);\n\t\t}\n\t\treturn { nodes, hasIncoming };\n\t}\n\n\t/**\n\t * Find roots (no incoming) ordered by the earliest outgoing edge\n\t * `createdAt`. Nodes with no outgoing edges fall back to the order\n\t * they appear among edges (already sorted by `createdAt`).\n\t */\n\tprivate _findRoots(\n\t\tnodes: Set<string>,\n\t\thasIncoming: Set<string>,\n\t\tedges: readonly Edge[]\n\t): string[] {\n\t\tconst earliest = new Map<string, number>();\n\t\tfor (const edge of edges) {\n\t\t\tif (!earliest.has(edge.from)) {\n\t\t\t\tearliest.set(edge.from, edge.createdAt);\n\t\t\t}\n\t\t}\n\t\tconst roots: string[] = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (!hasIncoming.has(node)) roots.push(node);\n\t\t}\n\t\troots.sort((a, b) => (earliest.get(a) ?? Infinity) - (earliest.get(b) ?? Infinity));\n\t\treturn roots;\n\t}\n\n\t/**\n\t * BFS from a list of root ids, visiting each node at most once.\n\t */\n\tprivate _bfsFromRoots(sessionId: SessionId, roots: readonly string[]): readonly string[] {\n\t\tconst visited = new Set<string>();\n\t\tconst order: string[] = [];\n\t\tconst queue: string[] = [];\n\t\tfor (const root of roots) {\n\t\t\tif (visited.has(root)) continue;\n\t\t\tvisited.add(root);\n\t\t\torder.push(root);\n\t\t\tqueue.push(root);\n\t\t}\n\t\twhile (queue.length > 0) {\n\t\t\tconst node = queue.shift()!;\n\t\t\tfor (const edge of this._store.outgoing(sessionId, node as ThoughtId)) {\n\t\t\t\tif (visited.has(edge.to)) continue;\n\t\t\t\tvisited.add(edge.to);\n\t\t\t\torder.push(edge.to);\n\t\t\t\tqueue.push(edge.to);\n\t\t\t}\n\t\t}\n\t\treturn order;\n\t}\n\n\t/**\n\t * Build an in-degree map covering every node referenced by the edges.\n\t */\n\tprivate _buildInDegree(edges: readonly Edge[]): Map<string, number> {\n\t\tconst inDegree = new Map<string, number>();\n\t\tfor (const edge of edges) {\n\t\t\tif (!inDegree.has(edge.from)) inDegree.set(edge.from, 0);\n\t\t\tinDegree.set(edge.to, (inDegree.get(edge.to) ?? 0) + 1);\n\t\t}\n\t\treturn inDegree;\n\t}\n\n\t/**\n\t * Generic BFS closure in either direction. Excludes the start node\n\t * from the result and respects an optional depth cap.\n\t */\n\tprivate _bfsClosure(\n\t\tsessionId: SessionId,\n\t\tstartId: string,\n\t\tmaxDepth: number | undefined,\n\t\tdirection: 'incoming' | 'outgoing'\n\t): readonly string[] {\n\t\tconst cap = maxDepth ?? Number.POSITIVE_INFINITY;\n\t\tconst visited = new Set<string>([startId]);\n\t\tconst order: string[] = [];\n\t\tlet frontier: string[] = [startId];\n\t\tlet depth = 0;\n\t\twhile (frontier.length > 0 && depth < cap) {\n\t\t\tconst next: string[] = [];\n\t\t\tfor (const node of frontier) {\n\t\t\t\tconst edges =\n\t\t\t\t\tdirection === 'outgoing'\n\t\t\t\t\t\t? this._store.outgoing(sessionId, node as ThoughtId)\n\t\t\t\t\t\t: this._store.incoming(sessionId, node as ThoughtId);\n\t\t\t\tfor (const edge of edges) {\n\t\t\t\t\tconst neighbour = direction === 'outgoing' ? edge.to : edge.from;\n\t\t\t\t\tif (visited.has(neighbour)) continue;\n\t\t\t\t\tvisited.add(neighbour);\n\t\t\t\t\torder.push(neighbour);\n\t\t\t\t\tnext.push(neighbour);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrontier = next;\n\t\t\tdepth++;\n\t\t}\n\t\treturn order;\n\t}\n}\n"],"names":["GraphView","store","sessionId","edges","nodes","hasIncoming","roots","thoughtId","Set","outgoing","Map","edge","children","undefined","frontier","node","visited","depth","next","child","rootThoughtId","order","queue","current","out","inDegree","deg","CycleDetectedError","maxDepth","result","earliest","a","b","Infinity","root","startId","direction","cap","Number","neighbour"],"mappings":";AA+BO,MAAMA;IACK,OAAmB;IAYpC,YAAYC,KAAiB,CAAE;QAC9B,IAAI,CAAC,MAAM,GAAGA;IACf;IAiBA,cAAcC,SAAoB,EAAwB;Q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ACrB,KAAK,MAAMC,QAAQR,MAAO;YACzB,IAAI,CAACsB,SAAS,GAAG,CAACd,KAAK,IAAI,GAAGc,SAAS,GAAG,CAACd,KAAK,IAAI,EAAE;YACtDc,SAAS,GAAG,CAACd,KAAK,EAAE,EAAGc,AAAAA,CAAAA,SAAS,GAAG,CAACd,KAAK,EAAE,KAAK,KAAK;QACtD;QACA,OAAOc;IACR;IAMQ,YACPvB,SAAoB,EACpBiC,OAAe,EACfP,QAA4B,EAC5BQ,SAAkC,EACd;QACpB,MAAMC,MAAMT,YAAYU,KAAwB;QAChD,MAAMtB,UAAU,IAAIR,IAAY;YAAC2B;SAAQ;QACzC,MAAMd,QAAkB,EAAE;QAC1B,IAAIP,WAAqB;YAACqB;SAAQ;QAClC,IAAIlB,QAAQ;QACZ,MAAOH,SAAS,MAAM,GAAG,KAAKG,QAAQoB,IAAK;YAC1C,MAAMnB,OAAiB,EAAE;YACzB,KAAK,MAAMH,QAAQD,SAAU;gBAC5B,MAAMX,QACLiC,AAAc,eAAdA,YACG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAClC,WAAWa,QAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAACb,WAAWa;gBACpC,KAAK,MAAMJ,QAAQR,MAAO;oBACzB,MAAMoC,YAAYH,AAAc,eAAdA,YAA2BzB,KAAK,EAAE,GAAGA,KAAK,IAAI;oBAChE,KAAIK,QAAQ,GAAG,CAACuB;wBAChBvB,QAAQ,GAAG,CAACuB;wBACZlB,MAAM,IAAI,CAACkB;wBACXrB,KAAK,IAAI,CAACqB;;gBACX;YACD;YACAzB,WAAWI;YACXD;QACD;QACA,OAAOI;IACR;AACD"}
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Observes the frontier (graph leaves), scores each leaf via
5
5
  * {@link scoreThought}, and decides whether to continue, branch (when the
6
- * current thought falls outside the beam), or terminate (on confidence
7
- * threshold or score plateau).
6
+ * current thought falls outside the beam), or terminate (on depth cap,
7
+ * confidence threshold, or score plateau).
8
8
  *
9
9
  * Pure policy: configuration lives in a module-level {@link WeakMap}, not
10
10
  * on the instance, so `Object.getOwnPropertyNames(strategy)` only ever
@@ -46,13 +46,13 @@ export declare class TreeOfThoughtStrategy implements IReasoningStrategy {
46
46
  /**
47
47
  * Compute the next action for the chain.
48
48
  *
49
- * Order of checks: termination by confidence → termination by plateau →
50
- * branch when the current thought is outside the beam → continue.
49
+ * Order of checks: depth cap → confidence → plateau → branch when the
50
+ * current thought is outside the beam → continue. Missing graphs continue.
51
51
  */
52
52
  decide(ctx: StrategyContext): StrategyDecision;
53
- /** True when the frontier is wider than the beam (diverse exploration). */
53
+ /** True below the depth cap when the frontier is wider than the beam. */
54
54
  shouldBranch(ctx: StrategyContext): boolean;
55
- /** True when the best frontier score crosses the threshold OR scores plateau. */
55
+ /** True at the depth cap, confidence threshold, or score plateau. */
56
56
  shouldTerminate(ctx: StrategyContext): boolean;
57
57
  }
58
58
  //# sourceMappingURL=TreeOfThoughtStrategy.d.ts.map
@@ -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,gCAAgC,CAAC;AAKxC;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,2DAA2D;IAC3D,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,kEAAkE;IAClE,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;IACxC,uDAAuD;IACvD,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,8EAA8E;IAC9E,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CACjC;AAgED;;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AAqE;IACrE,eAAe,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO;CAa9C"}
@@ -1,3 +1,4 @@
1
+ import { asThoughtId } from "../../../contracts/ids.js";
1
2
  import { scoreThought, selectBeam } from "./totScoring.js";
2
3
  import { detectPlateau } from "./plateau.js";
3
4
  const DEFAULTS = {
@@ -12,7 +13,7 @@ function configOf(s) {
12
13
  return CONFIGS.get(s) ?? DEFAULTS;
13
14
  }
14
15
  function thoughtKey(t) {
15
- return t.id ?? String(t.thought_number);
16
+ return t.id ?? asThoughtId(String(t.thought_number));
16
17
  }
17
18
  function indexHistory(history) {
18
19
  const out = new Map();
@@ -41,12 +42,19 @@ function recentScores(history, window) {
41
42
  for(let i = start; i < history.length; i++)out.push(scoreThought(history[i]));
42
43
  return out;
43
44
  }
45
+ function isAtDepthCap(ctx, depthCap) {
46
+ const depth = ctx.graph?.depthFromRoots(ctx.sessionId, thoughtKey(ctx.currentThought));
47
+ return void 0 !== depth && depth >= depthCap;
48
+ }
44
49
  class TreeOfThoughtStrategy {
45
50
  name = 'tot';
46
51
  constructor(config){
52
+ const depthCap = config?.depthCap ?? DEFAULTS.depthCap;
53
+ if (!Number.isFinite(depthCap) || !Number.isInteger(depthCap) || depthCap < 0) throw new TypeError('depthCap must be a finite nonnegative integer');
47
54
  CONFIGS.set(this, {
48
55
  ...DEFAULTS,
49
- ...config ?? {}
56
+ ...config,
57
+ depthCap
50
58
  });
51
59
  }
52
60
  decide(ctx) {
@@ -54,6 +62,10 @@ class TreeOfThoughtStrategy {
54
62
  if (!ctx.graph) return {
55
63
  action: 'continue'
56
64
  };
65
+ if (isAtDepthCap(ctx, cfg.depthCap)) return {
66
+ action: 'terminate',
67
+ reason: 'depth cap'
68
+ };
57
69
  const frontier = ctx.graph.leaves(ctx.sessionId);
58
70
  const byKey = indexHistory(ctx.history);
59
71
  const scored = scoreFrontier(frontier, byKey);
@@ -84,12 +96,14 @@ class TreeOfThoughtStrategy {
84
96
  shouldBranch(ctx) {
85
97
  const cfg = configOf(this);
86
98
  if (!ctx.graph) return false;
99
+ if (isAtDepthCap(ctx, cfg.depthCap)) return false;
87
100
  const frontier = ctx.graph.leaves(ctx.sessionId);
88
101
  return frontier.length > cfg.beamWidth;
89
102
  }
90
103
  shouldTerminate(ctx) {
91
104
  const cfg = configOf(this);
92
105
  if (!ctx.graph) return false;
106
+ if (isAtDepthCap(ctx, cfg.depthCap)) return true;
93
107
  const frontier = ctx.graph.leaves(ctx.sessionId);
94
108
  const byKey = indexHistory(ctx.history);
95
109
  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\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,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{"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 depth cap,\n * confidence 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 { asThoughtId, type ThoughtId } from '../../../contracts/ids.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): ThoughtId {\n\treturn t.id ?? asThoughtId(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/** Whether the current graph-visible thought has reached the configured depth cap. */\nfunction isAtDepthCap(ctx: StrategyContext, depthCap: number): boolean {\n\tconst depth = ctx.graph?.depthFromRoots(ctx.sessionId, thoughtKey(ctx.currentThought));\n\treturn depth !== undefined && depth >= depthCap;\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\tconst depthCap = config?.depthCap ?? DEFAULTS.depthCap;\n\t\tif (!Number.isFinite(depthCap) || !Number.isInteger(depthCap) || depthCap < 0) {\n\t\t\tthrow new TypeError('depthCap must be a finite nonnegative integer');\n\t\t}\n\t\tCONFIGS.set(this, { ...DEFAULTS, ...config, depthCap });\n\t}\n\n\t/**\n\t * Compute the next action for the chain.\n\t *\n\t * Order of checks: depth cap → confidence → plateau → branch when the\n\t * current thought is outside the beam → continue. Missing graphs 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\tif (isAtDepthCap(ctx, cfg.depthCap)) {\n\t\t\treturn { action: 'terminate', reason: 'depth cap' };\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 below the depth cap when the frontier is wider than the beam. */\n\tshouldBranch(ctx: StrategyContext): boolean {\n\t\tconst cfg = configOf(this);\n\t\tif (!ctx.graph) return false;\n\t\tif (isAtDepthCap(ctx, cfg.depthCap)) return false;\n\t\tconst frontier = ctx.graph.leaves(ctx.sessionId);\n\t\treturn frontier.length > cfg.beamWidth;\n\t}\n\n\t/** True at the depth cap, confidence threshold, or score plateau. */\n\tshouldTerminate(ctx: StrategyContext): boolean {\n\t\tconst cfg = configOf(this);\n\t\tif (!ctx.graph) return false;\n\t\tif (isAtDepthCap(ctx, cfg.depthCap)) return true;\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","asThoughtId","String","indexHistory","history","out","Map","scoreFrontier","frontier","byKey","id","undefined","scoreThought","bestScore","scored","best","Number","c","recentScores","window","start","i","isAtDepthCap","ctx","depthCap","depth","TreeOfThoughtStrategy","config","TypeError","cfg","recent","detectPlateau","beam","selectBeam","currentKey"],"mappings":";;;AA4CA,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,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DnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"core/reasoning/strategies/totScoring.js","sources":["../../../../src/core/reasoning/strategies/totScoring.ts"],"sourcesContent":["/**\n * Tree-of-Thought scoring helpers — pure functions for ranking and frontier\n * exploration over the thought DAG.\n *\n * This module exposes three primitives used by the ToT strategy:\n *\n * - {@link scoreThought}: combine confidence and quality into a [0, 1] score.\n * - {@link selectBeam}: pick the top-K candidates with deterministic tiebreaks.\n * - {@link breadthFirstFrontier}: BFS from roots, returning leaves of the\n * explored subgraph capped by depth.\n *\n * All functions are pure: no I/O, no mutable module state, no DI.\n *\n * @module core/reasoning/strategies/totScoring\n */\n\nimport type { ThoughtData } from '../../thought.js';\nimport type { ConfidenceSignals, ThoughtType } from '../../reasoning.js';\nimport type { GraphView } from '../../graph/GraphView.js';\nimport type { SessionId, ThoughtId } from '../../../contracts/ids.js';\nimport { assertNever } from '../../../utils.js';\n\n/**\n * Optional `confidence_signals` carried alongside a thought. The core\n * `ThoughtData` type does not declare this field, but evaluator output may\n * be attached by callers that want calibrated scoring.\n */\ntype ThoughtWithSignals = ThoughtData & {\n\treadonly confidence_signals?: ConfidenceSignals;\n};\n\n/**\n * A scored candidate suitable for {@link selectBeam}.\n */\nexport interface ScoredCandidate {\n\treadonly id: string;\n\treadonly score: number;\n}\n\n/**\n * Per-type score multiplier applied on top of the base confidence×quality score.\n *\n * Weights bias the ToT frontier towards productive thought kinds:\n * - `assumption` (0.5): low confidence until backed by verification.\n * - `decomposition` (1.2): encouraged for problem-splitting.\n * - `backtrack` (0.8): signals exploration but not preferred.\n * - `tool_call` / `tool_observation` (1.0): neutral exogenous information.\n * - All other types (regular, hypothesis, verification, critique, synthesis, meta): 1.0.\n *\n * Pure function: deterministic, no I/O.\n */\nfunction getTypeWeight(type: ThoughtType | undefined): number {\n\tif (type === undefined) return 1.0;\n\tswitch (type) {\n\t\tcase 'assumption':\n\t\t\treturn 0.5;\n\t\tcase 'decomposition':\n\t\t\treturn 1.2;\n\t\tcase 'backtrack':\n\t\t\treturn 0.8;\n\t\tcase 'tool_call':\n\t\t\treturn 1.0;\n\t\tcase 'tool_observation':\n\t\t\treturn 1.0;\n\t\tcase 'regular':\n\t\tcase 'hypothesis':\n\t\tcase 'verification':\n\t\tcase 'critique':\n\t\tcase 'synthesis':\n\t\tcase 'meta':\n\t\t\treturn 1.0;\n\t\tdefault:\n\t\t\treturn assertNever(type);\n\t}\n}\n\n/**\n * Score a thought by combining its (calibrated) confidence with its\n * self-assessed quality, then applying a per-type weight.\n *\n * Formula: `(calibrated_confidence ?? confidence ?? 0) * (quality_score ?? 0.5) * typeWeight(thought_type)`\n *\n * The `calibrated_confidence` (when present on `confidence_signals`) is\n * preferred over the raw `confidence` field. The result is clamped to the\n * inclusive range `[0, 1]`.\n *\n * @param t - The thought to score.\n * @returns A score in `[0, 1]`.\n *\n * @example\n * ```typescript\n * const s = scoreThought({ ...base, confidence: 0.8, quality_score: 0.5 });\n * // s === 0.4\n * ```\n */\nexport function scoreThought(t: ThoughtData): number {\n\tconst calibrated = (t as ThoughtWithSignals).confidence_signals?.calibrated_confidence;\n\tconst confidence = calibrated ?? t.confidence ?? 0;\n\tconst quality = t.quality_score ?? 0.5;\n\tconst raw = confidence * quality * getTypeWeight(t.thought_type);\n\tif (raw < 0) return 0;\n\tif (raw > 1) return 1;\n\treturn raw;\n}\n\n/**\n * Select the top-`width` candidates by score, descending.\n *\n * Sorting is stable and deterministic: ties on `score` are broken by\n * lexicographic comparison of `id` (ascending). When `width >= candidates.length`\n * all candidates are returned in sorted order. When `width <= 0` the result\n * is empty.\n *\n * @param candidates - Scored candidates (input is not mutated).\n * @param width - Beam width (top-K).\n * @returns Selected ids in descending score order.\n *\n * @example\n * ```typescript\n * const top = selectBeam([{ id: 'a', score: 0.1 }, { id: 'b', score: 0.9 }], 1);\n * // top === ['b']\n * ```\n */\nexport function selectBeam(\n\tcandidates: readonly ScoredCandidate[],\n\twidth: number\n): readonly string[] {\n\tif (width <= 0 || candidates.length === 0) {\n\t\treturn [];\n\t}\n\tconst sorted = [...candidates].sort((a, b) => {\n\t\tif (b.score !== a.score) return b.score - a.score;\n\t\treturn a.id < b.id ? -1 : 1;\n\t});\n\tconst k = width >= sorted.length ? sorted.length : width;\n\tconst result: string[] = [];\n\tfor (let i = 0; i < k; i++) {\n\t\tresult.push(sorted[i]!.id);\n\t}\n\treturn result;\n}\n\n/**\n * Compute the BFS frontier reachable from `roots` within `depthCap` levels.\n *\n * Traverses outgoing edges via `graph.descendants(sessionId, id, 1)`. The returned\n * set contains the *leaves* of the explored subgraph — nodes that either\n * (a) sit at the depth cap, or (b) have no outgoing edges within the\n * explored region.\n *\n * Special cases:\n * - `depthCap === 0` returns the unique roots in input order.\n * - empty `roots` returns an empty array.\n *\n * Each node is visited at most once, so cycles cannot cause infinite loops.\n *\n * @param graph - Read-only graph view.\n * @param sessionId - Session scoping the traversal.\n * @param roots - Starting thought ids.\n * @param depthCap - Maximum BFS depth (0 = roots only).\n * @returns Frontier (leaf) thought ids of the explored subgraph.\n *\n * @example\n * ```typescript\n * const frontier = breadthFirstFrontier(view, 's1', ['root'], 2);\n * ```\n */\nexport function breadthFirstFrontier(\n\tgraph: GraphView,\n\tsessionId: SessionId,\n\troots: readonly string[],\n\tdepthCap: number\n): readonly string[] {\n\tif (roots.length === 0) {\n\t\treturn [];\n\t}\n\tconst uniqueRoots: string[] = [];\n\tconst seenRoots = new Set<string>();\n\tfor (const r of roots) {\n\t\tif (!seenRoots.has(r)) {\n\t\t\tseenRoots.add(r);\n\t\t\tuniqueRoots.push(r);\n\t\t}\n\t}\n\tif (depthCap <= 0) {\n\t\treturn uniqueRoots;\n\t}\n\n\tconst visited = new Set<string>(uniqueRoots);\n\tlet frontier: string[] = [...uniqueRoots];\n\tlet depth = 0;\n\n\twhile (frontier.length > 0 && depth < depthCap) {\n\t\tconst next: string[] = [];\n\t\tfor (const node of frontier) {\n\t\t\tfor (const child of graph.descendants(sessionId, node as ThoughtId, 1)) {\n\t\t\t\tif (visited.has(child)) continue;\n\t\t\t\tvisited.add(child);\n\t\t\t\tnext.push(child);\n\t\t\t}\n\t\t}\n\t\tfrontier = next;\n\t\tdepth++;\n\t}\n\n\tconst explored = visited;\n\tconst leaves: string[] = [];\n\tconst seenLeaf = new Set<string>();\n\tconst collect = (id: string): void => {\n\t\tseenLeaf.add(id);\n\t\tleaves.push(id);\n\t};\n\n\tif (depth >= depthCap && frontier.length > 0) {\n\t\t// Hit the depth cap — current frontier is leaves regardless of children.\n\t\tfor (const id of frontier) collect(id);\n\t}\n\t// Any explored node with no outgoing edges inside the explored set is also\n\t// a leaf (covers nodes shallower than depthCap that terminated naturally).\n\tfor (const id of explored) {\n\t\tif (seenLeaf.has(id)) continue;\n\t\tconst children = graph.descendants(sessionId, id as ThoughtId, 1);\n\t\tif (children.length === 0) collect(id);\n\t}\n\treturn leaves;\n}\n"],"names":["getTypeWeight","type","undefined","assertNever","scoreThought","t","calibrated","confidence","quality","raw","selectBeam","candidates","width","sorted","a","b","k","result","i","breadthFirstFrontier","graph","sessionId","roots","depthCap","uniqueRoots","seenRoots","Set","r","visited","frontier","depth","next","node","child","explored","leaves","seenLeaf","collect","id","children"],"mappings":";AAmDA,SAASA,cAAcC,IAA6B;IACnD,IAAIA,AAASC,WAATD,MAAoB,OAAO;IAC/B,OAAQA;QACP,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACJ,OAAO;QACR;YACC,OAAOE,YAAYF;IACrB;AACD;AAqBO,SAASG,aAAaC,CAAc;IAC1C,MAAMC,aAAcD,EAAyB,kBAAkB,EAAE;IACjE,MAAME,aAAaD,cAAcD,EAAE,UAAU,IAAI;IACjD,MAAMG,UAAUH,EAAE,aAAa,IAAI;IACnC,MAAMI,MAAMF,aAAaC,UAAUR,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ACnE,KAAIJ,QAAQ,GAAG,CAACK;YAChBL,QAAQ,GAAG,CAACK;YACZF,KAAK,IAAI,CAACE;;QAGZJ,WAAWE;QACXD;IACD;IAEA,MAAMI,WAAWN;IACjB,MAAMO,SAAmB,EAAE;IAC3B,MAAMC,WAAW,IAAIV;IACrB,MAAMW,UAAU,CAACC;QAChBF,SAAS,GAAG,CAACE;QACbH,OAAO,IAAI,CAACG;IACb;IAEA,IAAIR,SAASP,YAAYM,SAAS,MAAM,GAAG,GAE1C,KAAK,MAAMS,MAAMT,SAAUQ,QAAQC;IAIpC,KAAK,MAAMA,MAAMJ,SAAU;QAC1B,IAAIE,SAAS,GAAG,CAACE,KAAK;QACtB,MAAMC,WAAWnB,MAAM,WAAW,CAACC,WAAWiB,IAAiB;QAC/D,IAAIC,AAAoB,MAApBA,SAAS,MAAM,EAAQF,QAAQC;IACpC;IACA,OAAOH;AACR"}
1
+ {"version":3,"file":"core/reasoning/strategies/totScoring.js","sources":["../../../../src/core/reasoning/strategies/totScoring.ts"],"sourcesContent":["/**\n * Tree-of-Thought scoring helpers — pure functions for ranking and frontier\n * exploration over the thought DAG.\n *\n * This module exposes three primitives used by the ToT strategy:\n *\n * - {@link scoreThought}: combine confidence and quality into a [0, 1] score.\n * - {@link selectBeam}: pick the top-K candidates with deterministic tiebreaks.\n * - {@link breadthFirstFrontier}: BFS from roots, returning leaves of the\n * explored subgraph capped by depth.\n *\n * All functions are pure: no I/O, no mutable module state, no DI.\n *\n * @module core/reasoning/strategies/totScoring\n */\n\nimport type { ThoughtData } from '../../thought.js';\nimport type { ThoughtType } from '../../../contracts/reasoning-types.js';\nimport type { ConfidenceSignals } from '../../reasoning.js';\nimport type { GraphView } from '../../graph/GraphView.js';\nimport type { SessionId, ThoughtId } from '../../../contracts/ids.js';\nimport { assertNever } from '../../../utils.js';\n\n/**\n * Optional `confidence_signals` carried alongside a thought. The core\n * `ThoughtData` type does not declare this field, but evaluator output may\n * be attached by callers that want calibrated scoring.\n */\ntype ThoughtWithSignals = ThoughtData & {\n\treadonly confidence_signals?: ConfidenceSignals;\n};\n\n/**\n * A scored candidate suitable for {@link selectBeam}.\n */\nexport interface ScoredCandidate {\n\treadonly id: string;\n\treadonly score: number;\n}\n\n/**\n * Per-type score multiplier applied on top of the base confidence×quality score.\n *\n * Weights bias the ToT frontier towards productive thought kinds:\n * - `assumption` (0.5): low confidence until backed by verification.\n * - `decomposition` (1.2): encouraged for problem-splitting.\n * - `backtrack` (0.8): signals exploration but not preferred.\n * - `tool_call` / `tool_observation` (1.0): neutral exogenous information.\n * - All other types (regular, hypothesis, verification, critique, synthesis, meta): 1.0.\n *\n * Pure function: deterministic, no I/O.\n */\nfunction getTypeWeight(type: ThoughtType | undefined): number {\n\tif (type === undefined) return 1.0;\n\tswitch (type) {\n\t\tcase 'assumption':\n\t\t\treturn 0.5;\n\t\tcase 'decomposition':\n\t\t\treturn 1.2;\n\t\tcase 'backtrack':\n\t\t\treturn 0.8;\n\t\tcase 'tool_call':\n\t\t\treturn 1.0;\n\t\tcase 'tool_observation':\n\t\t\treturn 1.0;\n\t\tcase 'regular':\n\t\tcase 'hypothesis':\n\t\tcase 'verification':\n\t\tcase 'critique':\n\t\tcase 'synthesis':\n\t\tcase 'meta':\n\t\t\treturn 1.0;\n\t\tdefault:\n\t\t\treturn assertNever(type);\n\t}\n}\n\n/**\n * Score a thought by combining its (calibrated) confidence with its\n * self-assessed quality, then applying a per-type weight.\n *\n * Formula: `(calibrated_confidence ?? confidence ?? 0) * (quality_score ?? 0.5) * typeWeight(thought_type)`\n *\n * The `calibrated_confidence` (when present on `confidence_signals`) is\n * preferred over the raw `confidence` field. The result is clamped to the\n * inclusive range `[0, 1]`.\n *\n * @param t - The thought to score.\n * @returns A score in `[0, 1]`.\n *\n * @example\n * ```typescript\n * const s = scoreThought({ ...base, confidence: 0.8, quality_score: 0.5 });\n * // s === 0.4\n * ```\n */\nexport function scoreThought(t: ThoughtData): number {\n\tconst calibrated = (t as ThoughtWithSignals).confidence_signals?.calibrated_confidence;\n\tconst confidence = calibrated ?? t.confidence ?? 0;\n\tconst quality = t.quality_score ?? 0.5;\n\tconst raw = confidence * quality * getTypeWeight(t.thought_type);\n\tif (raw < 0) return 0;\n\tif (raw > 1) return 1;\n\treturn raw;\n}\n\n/**\n * Select the top-`width` candidates by score, descending.\n *\n * Sorting is stable and deterministic: ties on `score` are broken by\n * lexicographic comparison of `id` (ascending). When `width >= candidates.length`\n * all candidates are returned in sorted order. When `width <= 0` the result\n * is empty.\n *\n * @param candidates - Scored candidates (input is not mutated).\n * @param width - Beam width (top-K).\n * @returns Selected ids in descending score order.\n *\n * @example\n * ```typescript\n * const top = selectBeam([{ id: 'a', score: 0.1 }, { id: 'b', score: 0.9 }], 1);\n * // top === ['b']\n * ```\n */\nexport function selectBeam(\n\tcandidates: readonly ScoredCandidate[],\n\twidth: number\n): readonly string[] {\n\tif (width <= 0 || candidates.length === 0) {\n\t\treturn [];\n\t}\n\tconst sorted = [...candidates].sort((a, b) => {\n\t\tif (b.score !== a.score) return b.score - a.score;\n\t\treturn a.id < b.id ? -1 : 1;\n\t});\n\tconst k = width >= sorted.length ? sorted.length : width;\n\tconst result: string[] = [];\n\tfor (let i = 0; i < k; i++) {\n\t\tresult.push(sorted[i]!.id);\n\t}\n\treturn result;\n}\n\n/**\n * Compute the BFS frontier reachable from `roots` within `depthCap` levels.\n *\n * Traverses outgoing edges via `graph.descendants(sessionId, id, 1)`. The returned\n * set contains the *leaves* of the explored subgraph — nodes that either\n * (a) sit at the depth cap, or (b) have no outgoing edges within the\n * explored region.\n *\n * Special cases:\n * - `depthCap === 0` returns the unique roots in input order.\n * - empty `roots` returns an empty array.\n *\n * Each node is visited at most once, so cycles cannot cause infinite loops.\n *\n * @param graph - Read-only graph view.\n * @param sessionId - Session scoping the traversal.\n * @param roots - Starting thought ids.\n * @param depthCap - Maximum BFS depth (0 = roots only).\n * @returns Frontier (leaf) thought ids of the explored subgraph.\n *\n * @example\n * ```typescript\n * const frontier = breadthFirstFrontier(view, 's1', ['root'], 2);\n * ```\n */\nexport function breadthFirstFrontier(\n\tgraph: GraphView,\n\tsessionId: SessionId,\n\troots: readonly string[],\n\tdepthCap: number\n): readonly string[] {\n\tif (roots.length === 0) {\n\t\treturn [];\n\t}\n\tconst uniqueRoots: string[] = [];\n\tconst seenRoots = new Set<string>();\n\tfor (const r of roots) {\n\t\tif (!seenRoots.has(r)) {\n\t\t\tseenRoots.add(r);\n\t\t\tuniqueRoots.push(r);\n\t\t}\n\t}\n\tif (depthCap <= 0) {\n\t\treturn uniqueRoots;\n\t}\n\n\tconst visited = new Set<string>(uniqueRoots);\n\tlet frontier: string[] = [...uniqueRoots];\n\tlet depth = 0;\n\n\twhile (frontier.length > 0 && depth < depthCap) {\n\t\tconst next: string[] = [];\n\t\tfor (const node of frontier) {\n\t\t\tfor (const child of graph.descendants(sessionId, node as ThoughtId, 1)) {\n\t\t\t\tif (visited.has(child)) continue;\n\t\t\t\tvisited.add(child);\n\t\t\t\tnext.push(child);\n\t\t\t}\n\t\t}\n\t\tfrontier = next;\n\t\tdepth++;\n\t}\n\n\tconst explored = visited;\n\tconst leaves: string[] = [];\n\tconst seenLeaf = new Set<string>();\n\tconst collect = (id: string): void => {\n\t\tseenLeaf.add(id);\n\t\tleaves.push(id);\n\t};\n\n\tif (depth >= depthCap && frontier.length > 0) {\n\t\t// Hit the depth cap — current frontier is leaves regardless of children.\n\t\tfor (const id of frontier) collect(id);\n\t}\n\t// Any explored node with no outgoing edges inside the explored set is also\n\t// a leaf (covers nodes shallower than depthCap that terminated naturally).\n\tfor (const id of explored) {\n\t\tif (seenLeaf.has(id)) continue;\n\t\tconst children = graph.descendants(sessionId, id as ThoughtId, 1);\n\t\tif (children.length === 0) collect(id);\n\t}\n\treturn leaves;\n}\n"],"names":["getTypeWeight","type","undefined","assertNever","scoreThought","t","calibrated","confidence","quality","raw","selectBeam","candidates","width","sorted","a","b","k","result","i","breadthFirstFrontier","graph","sessionId","roots","depthCap","uniqueRoots","seenRoots","Set","r","visited","frontier","depth","next","node","child","explored","leaves","seenLeaf","collect","id","children"],"mappings":";AAoDA,SAASA,cAAcC,IAA6B;IACnD,IAAIA,AAASC,WAATD,MAAoB,OAAO;IAC/B,OAAQA;QACP,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;YACJ,OAAO;QACR,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACJ,OAAO;QACR;YACC,OAAOE,YAAYF;IACrB;AACD;AAqBO,SAASG,aAAaC,CAAc;IAC1C,MAAMC,aAAcD,EAAyB,kBAAkB,EAAE;IACjE,MAAME,aAAaD,cAAcD,EAAE,UAAU,IAAI;IACjD,MAAMG,UAAUH,EAAE,aAAa,IAAI;IACnC,MAAMI,MAAMF,aAAaC,UAAUR,cAAcK,EAAE,YAAY;IAC/D,IAAII,MAAM,GAAG,OAAO;IACpB,IAAIA,MAAM,GAAG,OAAO;IACpB,OAAOA;AACR;AAoBO,SAASC,WACfC,UAAsC,EACtCC,KAAa;IAEb,IAAIA,SAAS,KAAKD,AAAsB,MAAtBA,WAAW,MAAM,EAClC,OAAO,EAAE;IAEV,MAAME,SAAS;WAAIF;KAAW,CAAC,IAAI,CAAC,CAACG,GAAGC;QACvC,IAAIA,EAAE,KAAK,KAAKD,EAAE,KAAK,EAAE,OAAOC,EAAE,KAAK,GAAGD,EAAE,KAAK;QACjD,OAAOA,EAAE,EAAE,GAAGC,EAAE,EAAE,GAAG,KAAK;IAC3B;IACA,MAAMC,IAAIJ,SAASC,OAAO,MAAM,GAAGA,OAAO,MAAM,GAAGD;IACnD,MAAMK,SAAmB,EAAE;IAC3B,IAAK,IAAIC,IAAI,GAAGA,IAAIF,GAAGE,IACtBD,OAAO,IAAI,CAACJ,MAAM,CAACK,EAAE,CAAE,EAAE;IAE1B,OAAOD;AACR;AA2BO,SAASE,qBACfC,KAAgB,EAChBC,SAAoB,EACpBC,KAAwB,EACxBC,QAAgB;IAEhB,IAAID,AAAiB,MAAjBA,MAAM,MAAM,EACf,OAAO,EAAE;IAEV,MAAME,cAAwB,EAAE;IAChC,MAAMC,YAAY,IAAIC;IACtB,KAAK,MAAMC,KAAKL,MACf,IAAI,CAACG,UAAU,GAAG,CAACE,IAAI;QACtBF,UAAU,GAAG,CAACE;QACdH,YAAY,IAAI,CAACG;IAClB;IAED,IAAIJ,YAAY,GACf,OAAOC;IAGR,MAAMI,UAAU,IAAIF,IAAYF;IAChC,IAAIK,WAAqB;WAAIL;KAAY;IACzC,IAAIM,QAAQ;IAEZ,MAAOD,SAAS,MAAM,GAAG,KAAKC,QAAQP,SAAU;QAC/C,MAAMQ,OAAiB,EAAE;QACzB,KAAK,MAAMC,QAAQH,SAClB,KAAK,MAAMI,SAASb,MAAM,WAAW,CAACC,WAAWW,MAAmB,GACnE,KAAIJ,QAAQ,GAAG,CAACK;YAChBL,QAAQ,GAAG,CAACK;YACZF,KAAK,IAAI,CAACE;;QAGZJ,WAAWE;QACXD;IACD;IAEA,MAAMI,WAAWN;IACjB,MAAMO,SAAmB,EAAE;IAC3B,MAAMC,WAAW,IAAIV;IACrB,MAAMW,UAAU,CAACC;QAChBF,SAAS,GAAG,CAACE;QACbH,OAAO,IAAI,CAACG;IACb;IAEA,IAAIR,SAASP,YAAYM,SAAS,MAAM,GAAG,GAE1C,KAAK,MAAMS,MAAMT,SAAUQ,QAAQC;IAIpC,KAAK,MAAMA,MAAMJ,SAAU;QAC1B,IAAIE,SAAS,GAAG,CAACE,KAAK;QACtB,MAAMC,WAAWnB,MAAM,WAAW,CAACC,WAAWiB,IAAiB;QAC/D,IAAIC,AAAoB,MAApBA,SAAS,MAAM,EAAQF,QAAQC;IACpC;IACA,OAAOH;AACR"}
@@ -7,9 +7,7 @@
7
7
  * @module core/reasoning
8
8
  */
9
9
  import type { CalibrationMetrics } from '../contracts/calibrator.js';
10
- import type { PatternName as ContractPatternName, ThoughtType as ContractThoughtType } from '../contracts/reasoning-types.js';
11
- export type ThoughtType = ContractThoughtType;
12
- export type PatternName = ContractPatternName;
10
+ import type { PatternName, ThoughtType } from '../contracts/reasoning-types.js';
13
11
  /**
14
12
  * A detected reasoning pattern — surfaced as metadata or a warning.
15
13
  *
@@ -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;AACrE,OAAO,KAAK,EACX,WAAW,IAAI,mBAAmB,EAClC,WAAW,IAAI,mBAAmB,EAClC,MAAM,iCAAiC,CAAC;AAEzC,MAAM,MAAM,WAAW,GAAG,mBAAmB,CAAC;AAE9C,MAAM,MAAM,WAAW,GAAG,mBAAmB,CAAC;AAE9C;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC7B,2CAA2C;IAC3C,2CAA2C;IAC3C,OAAO,EAAE,WAAW,CAAC;IAErB,uEAAuE;IACvE,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAE7B,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAC;IAEhB,wEAAwE;IACxE,aAAa,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,WAAW,iBAAiB;IACjC,6CAA6C;IAC7C,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IAEjC,wCAAwC;IACxC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,uBAAuB;IACvB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,0CAA0C;IAC1C,QAAQ,CAAC,yBAAyB,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAEhE,8CAA8C;IAC9C,QAAQ,CAAC,cAAc,EA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C;CAClD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,WAAW,cAAc;IAC9B,iCAAiC;IACjC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,8BAA8B;IAC9B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,iCAAiC;IACjC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IAEjC,6CAA6C;IAC7C,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,sCAAsC;IACtC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAE7B,kCAAkC;IAClC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAE1D,0BAA0B;IAC1B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,0CAA0C;IAC1C,QAAQ,CAAC,yBAAyB,EAAE,MAAM,CAAC;IAE3C,uCAAuC;IACvC,QAAQ,CAAC,2BAA2B,EAAE,MAAM,CAAC;IAE7C,uEAAuE;IACvE,QAAQ,CAAC,qBAAqB,EAAE,MAAM,GAAG,IAAI,CAAC;IAE9C,wEAAwE;IACxE,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3C"}
@@ -69,7 +69,7 @@ export type ThoughtData = Omit<SchemaOutput, 'id' | 'session_id' | 'continuation
69
69
  * has guaranteed per-type invariants. Allows downstream methods to consume
70
70
  * narrowed thoughts without `!` non-null assertions.
71
71
  */
72
- import type { ThoughtType } from './reasoning.js';
72
+ import type { ThoughtType } from '../contracts/reasoning-types.js';
73
73
  /** A `tool_call` thought with `tool_name` guaranteed by validation. */
74
74
  export type ToolCallThought = ThoughtData & {
75
75
  readonly thought_type: 'tool_call';
@@ -1 +1 @@
1
- {"version":3,"file":"thought.d.ts","sourceRoot":"","sources":["../../src/core/thought.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAA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IACnC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF,sEAAsE;AACtE,MAAM,MAAM,mBAAmB,GAAG,WAAW,GAAG;IAC/C,QAAQ,CAAC,YAAY,EAAE,cAAc,CAAC;IACtC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;CACrC,CAAC;AAEF,kEAAkE;AAClE,MAAM,MAAM,eAAe,GAAG,WAAW,GAAG;IAC3C,QAAQ,CAAC,YAAY,EAAE,UAAU,CAAC;IAClC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;CACrC,CAAC;AAEF,2EAA2E;AAC3E,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG;IAC5C,QAAQ,CAAC,YAAY,EAAE,WAAW,CAAC;IACnC,QAAQ,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC9C,CAAC;AAEF,qEAAqE;AACrE,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG;IACvC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAC7B,WAAW,EACX,WAAW,GAAG,kBAAkB,GAAG,WAAW,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,CAC1F,CAAC;CACF,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GACzB,eAAe,GACf,sBAAsB,GACtB,gBAAgB,GAChB,mBAAmB,GACnB,eAAe,GACf,gBAAgB,GAChB,WAAW,CAAC"}
package/dist/lib.d.ts CHANGED
@@ -12,6 +12,12 @@ import { StructuredLogger } from './logger/StructuredLogger.js';
12
12
  import { SkillRegistry } from './registry/SkillRegistry.js';
13
13
  import { ToolRegistry } from './registry/ToolRegistry.js';
14
14
  import { ServerConfig } from './ServerConfig.js';
15
+ import { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';
16
+ import type { HttpTransportOptions } from './transport/HttpTransport.js';
17
+ import type { TransportOptions } from './transport/BaseTransport.js';
18
+ import type { ITransport, TransportKind } from './contracts/transport.js';
19
+ export { HttpTransport, createHttpTransport };
20
+ export type { HttpTransportOptions, TransportOptions, ITransport, TransportKind };
15
21
  export interface ServerOptions {
16
22
  maxHistorySize?: number;
17
23
  maxBranches?: number;
@@ -80,6 +86,11 @@ export interface IToolAwareSequentialThinkingServer extends IDisposable {
80
86
  * @returns The number of skills discovered
81
87
  */
82
88
  discoverSkillsAsync(): Promise<number>;
89
+ /** Rescan configured tool and skill directories. */
90
+ refreshDiscovery(): Promise<{
91
+ tools: number;
92
+ skills: number;
93
+ }>;
83
94
  /**
84
95
  * Get all branches from the history manager.
85
96
  *
@@ -138,6 +149,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
138
149
  private _skillWatcher;
139
150
  private _toolWatcher;
140
151
  private _config;
152
+ private _acceptingDiscoveryRefreshes;
153
+ private _refreshPromise;
141
154
  private _stopPromise;
142
155
  private _disposePromise;
143
156
  /**
@@ -201,6 +214,11 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
201
214
  * @returns Promise<number> - The number of skills discovered
202
215
  */
203
216
  discoverSkillsAsync(): Promise<number>;
217
+ /** Rescan configured tool and skill directories. */
218
+ refreshDiscovery(): Promise<{
219
+ tools: number;
220
+ skills: number;
221
+ }>;
204
222
  /**
205
223
  * Get all branches from the history manager
206
224
  * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays
@@ -240,6 +258,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
240
258
  *
241
259
  * @example
242
260
  * ```typescript
261
+ * import { createServer } from '@iworkforces/tracelattice';
262
+ *
243
263
  * // Basic usage (with async discovery and persistence)
244
264
  * const server = await createServer();
245
265
  *
@@ -250,14 +270,8 @@ export declare class ToolAwareSequentialThinkingServer extends EventEmitter impl
250
270
  * maxHistorySize: 500,
251
271
  * loadFromPersistence: true
252
272
  * });
253
- *
254
- * // With custom container for testing
255
- * const mockContainer = new Container();
256
- * mockContainer.registerInstance('Logger', mockLogger);
257
- * const server = await createServer({ container: mockContainer });
258
273
  * ```
259
274
  */
260
275
  export declare function createServer(options?: ServerOptions): Promise<ToolAwareSequentialThinkingServer>;
261
276
  export declare function initializeServer(): Promise<ToolAwareSequentialThinkingServer>;
262
- export {};
263
277
  //# sourceMappingURL=lib.d.ts.map
package/dist/lib.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,KAAK,CAAC,MAAM,SAAS,CAAC;AAClC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAE5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAMzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAU1D,OAAO,EAAoB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAGnF,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAIhE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD,MAAM,WAAW,aAAa;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,aAAa,CAAC,EAAE,OAAO,CA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G;IACI,KAAK,IAAI,IAAI;IAKpB,uEAAuE;IAC1D,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3D,0EAA0E;IAC7D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAKtC;;;;OAIG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAc/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,YAAY,CACjC,OAAO,GAAE,aAAkB,GACzB,OAAO,CAAC,iCAAiC,CAAC,CAE5C;AAGD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,iCAAiC,CAAC,CAsBnF"}
package/dist/lib.js CHANGED
@@ -16,6 +16,7 @@ import { createReasoningStrategy } from "./core/reasoning/strategies/StrategyFac
16
16
  import { ThoughtFormatter } from "./core/ThoughtFormatter.js";
17
17
  import { ThoughtProcessor } from "./core/ThoughtProcessor.js";
18
18
  import { SessionLock } from "./core/SessionLock.js";
19
+ import { SessionLifecycleClosedError } from "./core/SessionErrors.js";
19
20
  import { SessionLifecycleCoordinator } from "./core/SessionLifecycleCoordinator.js";
20
21
  import { Container } from "./di/Container.js";
21
22
  import { StructuredLogger } from "./logger/StructuredLogger.js";
@@ -92,6 +93,8 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
92
93
  _skillWatcher = null;
93
94
  _toolWatcher = null;
94
95
  _config;
96
+ _acceptingDiscoveryRefreshes = true;
97
+ _refreshPromise = null;
95
98
  _stopPromise = null;
96
99
  _disposePromise = null;
97
100
  history;
@@ -290,6 +293,33 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
290
293
  const discovered = await this.skills.discoverAsync();
291
294
  return discovered;
292
295
  }
296
+ refreshDiscovery() {
297
+ if (!this._acceptingDiscoveryRefreshes) return Promise.reject(new SessionLifecycleClosedError(void 0, 'shutting_down'));
298
+ if (null !== this._refreshPromise) return this._refreshPromise;
299
+ const refreshPromise = Promise.allSettled([
300
+ this.tools.refreshAsync(),
301
+ this.skills.refreshAsync()
302
+ ]).then(([toolResult, skillResult])=>{
303
+ if ('rejected' === toolResult.status) {
304
+ if ('rejected' === skillResult.status) throw new AggregateError([
305
+ toolResult.reason,
306
+ skillResult.reason
307
+ ], 'Failed to refresh tool and skill discovery');
308
+ throw toolResult.reason;
309
+ }
310
+ if ('rejected' === skillResult.status) throw skillResult.reason;
311
+ return {
312
+ tools: toolResult.value,
313
+ skills: skillResult.value
314
+ };
315
+ });
316
+ this._refreshPromise = refreshPromise;
317
+ const clearRefreshPromise = ()=>{
318
+ if (this._refreshPromise === refreshPromise) this._refreshPromise = null;
319
+ };
320
+ refreshPromise.then(clearRefreshPromise, clearRefreshPromise);
321
+ return refreshPromise;
322
+ }
293
323
  getBranches() {
294
324
  return this._historyManager.getBranches();
295
325
  }
@@ -304,14 +334,20 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
304
334
  return this._metrics.export();
305
335
  }
306
336
  stop() {
337
+ this._acceptingDiscoveryRefreshes = false;
307
338
  if (this._stopPromise) return this._stopPromise;
339
+ const acceptedRefresh = this._refreshPromise;
308
340
  this._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async ()=>{
309
341
  const failures = [];
310
- const watcherResults = await Promise.allSettled([
342
+ const [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([
311
343
  this._skillWatcher?.stop() ?? Promise.resolve(),
312
- this._toolWatcher?.stop() ?? Promise.resolve()
344
+ this._toolWatcher?.stop() ?? Promise.resolve(),
345
+ acceptedRefresh ?? Promise.resolve()
313
346
  ]);
314
- for (const result of watcherResults)switch(result.status){
347
+ for (const result of [
348
+ skillWatcherResult,
349
+ toolWatcherResult
350
+ ])switch(result.status){
315
351
  case 'fulfilled':
316
352
  break;
317
353
  case 'rejected':
@@ -323,6 +359,18 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
323
359
  default:
324
360
  assertNever(result);
325
361
  }
362
+ switch(refreshResult.status){
363
+ case 'fulfilled':
364
+ break;
365
+ case 'rejected':
366
+ appendCleanupFailure(failures, refreshResult.reason);
367
+ this._logger.error('Error refreshing discovery during shutdown', {
368
+ error: getErrorMessage(refreshResult.reason)
369
+ });
370
+ break;
371
+ default:
372
+ assertNever(refreshResult);
373
+ }
326
374
  if (this._config.features.toolInterleave && this._container.has('suspensionStore')) try {
327
375
  const suspensionStore = this._container.resolve('suspensionStore');
328
376
  suspensionStore.stop();
@@ -404,6 +452,7 @@ async function initializeServer() {
404
452
  logger.info('Server initialized successfully');
405
453
  return thinkingServer;
406
454
  }
455
+ export { HttpTransport, createHttpTransport } from "./transport/HttpTransport.js";
407
456
  export { ToolAwareSequentialThinkingServer, createServer, initializeServer };
408
457
 
409
458
  //# sourceMappingURL=lib.js.map