@devilsdev/rag-pipeline-utils 2.4.4 → 2.5.0

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 (225) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +345 -0
  3. package/README.md +418 -117
  4. package/SECURITY.md +5 -5
  5. package/dist/experimental.cjs +2 -0
  6. package/dist/experimental.d.ts +1 -0
  7. package/dist/experimental.mjs +5 -0
  8. package/dist/index.cjs +4992 -1242
  9. package/dist/index.d.ts +80 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  12. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  13. package/dist/types/agentic/query-planner.d.ts +145 -0
  14. package/dist/types/agentic/self-critique.d.ts +45 -0
  15. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  16. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  17. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  18. package/dist/types/ai/multimodal.d.ts +39 -0
  19. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  20. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  21. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  22. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  23. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  24. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  25. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  26. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  27. package/dist/types/citation/citation-tracker.d.ts +64 -0
  28. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  29. package/dist/types/citation/source-mapper.d.ts +37 -0
  30. package/dist/types/connectors/anthropic-connector.d.ts +92 -0
  31. package/dist/types/connectors/base-connector.d.ts +87 -0
  32. package/dist/types/connectors/cohere-connector.d.ts +89 -0
  33. package/dist/types/connectors/connector-utils.d.ts +110 -0
  34. package/dist/types/connectors/local-embedder.d.ts +86 -0
  35. package/dist/types/connectors/memory-retriever.d.ts +91 -0
  36. package/dist/types/connectors/ollama-connector.d.ts +110 -0
  37. package/dist/types/connectors/openai-connector.d.ts +114 -0
  38. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  39. package/dist/types/cost/cost-calculator.d.ts +152 -0
  40. package/dist/types/cost/cost-tracker.d.ts +126 -0
  41. package/dist/types/cost/token-budget.d.ts +110 -0
  42. package/dist/types/dag/core/error-context.d.ts +239 -0
  43. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  44. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  45. package/dist/types/dag/dag-engine.d.ts +156 -0
  46. package/dist/types/dag/dag-node.d.ts +37 -0
  47. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  48. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  49. package/dist/types/debug/execution-tracer.d.ts +57 -0
  50. package/dist/types/debug/trace-inspector.d.ts +31 -0
  51. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  52. package/dist/types/enterprise/data-governance.d.ts +203 -0
  53. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  54. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  55. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  56. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  57. package/dist/types/evaluate/groundedness.d.ts +60 -0
  58. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  59. package/dist/types/evaluate/relevance.d.ts +21 -0
  60. package/dist/types/evaluate/scoring.d.ts +123 -0
  61. package/dist/types/experimental.d.ts +15 -0
  62. package/dist/types/graph/entity-extractor.d.ts +84 -0
  63. package/dist/types/graph/graph-index.d.ts +49 -0
  64. package/dist/types/graph/graph-retriever.d.ts +81 -0
  65. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  66. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  67. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  68. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  69. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  70. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  71. package/dist/types/mcp/mcp-server.d.ts +85 -0
  72. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  73. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  74. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  75. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  76. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  77. package/dist/types/retrieval/file-vector-store.d.ts +87 -0
  78. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  79. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  80. package/dist/types/security/jwt-config.d.ts +80 -0
  81. package/dist/types/security/jwt-validator.d.ts +195 -0
  82. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  83. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  84. package/dist/types/security/validator.d.ts +5 -0
  85. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  86. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  87. package/dist/types/streaming/stream-router.d.ts +88 -0
  88. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  89. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  90. package/dist/types/templates/scaffold.d.ts +55 -0
  91. package/dist/types/templates/template-registry.d.ts +63 -0
  92. package/dist/types/utils/embed-query.d.ts +20 -0
  93. package/dist/types/utils/logger.d.ts +50 -0
  94. package/dist/types/utils/rate-limiter.d.ts +66 -0
  95. package/dist/types/utils/retry.d.ts +27 -0
  96. package/dist/types/utils/run-abort.d.ts +34 -0
  97. package/dist/types/utils/secure-logging.d.ts +51 -0
  98. package/dist/types/utils/structured-logger.d.ts +126 -0
  99. package/package.json +53 -29
  100. package/src/agentic/agentic-pipeline.js +75 -7
  101. package/src/agentic/iterative-retriever.js +47 -10
  102. package/src/agentic/query-planner.js +329 -78
  103. package/src/citation/citation-tracker.js +6 -4
  104. package/src/citation/hallucination-detector.js +2 -2
  105. package/src/citation/source-mapper.js +15 -28
  106. package/src/cli/commands/ai.js +101 -0
  107. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  108. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  109. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  110. package/src/cli/commands/plugin-hub.js +96 -36
  111. package/src/cli/diagnostics/config-checker.js +76 -63
  112. package/src/cli/diagnostics/environment-checker.js +62 -31
  113. package/src/cli/diagnostics/plugin-checker.js +36 -89
  114. package/src/cli/doctor-command.js +39 -5
  115. package/src/cli/enhanced-cli-commands.js +72 -217
  116. package/src/cli/handlers/ai-handler.js +364 -0
  117. package/src/cli/handlers/diagnostics-handler.js +78 -31
  118. package/src/cli/handlers/ingest-handler.js +28 -22
  119. package/src/cli/handlers/init-handler.js +148 -25
  120. package/src/cli/handlers/query-handler.js +41 -26
  121. package/src/cli/handlers/run-handler.js +16 -167
  122. package/src/cli/handlers/serve-handler.js +60 -0
  123. package/src/cli/services/bench-stats.js +54 -0
  124. package/src/cli/services/benchmark.js +161 -0
  125. package/src/cli/services/feedback.js +155 -0
  126. package/src/cli/services/rag-service.js +322 -0
  127. package/src/cli/shared/cli-utils.js +24 -7
  128. package/src/cli/shared/config-context.js +21 -0
  129. package/src/cli/wizard/config-builder.js +81 -0
  130. package/src/cli/wizard/init-wizard.js +617 -0
  131. package/src/config/component-factory.js +125 -0
  132. package/src/config/load-config.js +29 -10
  133. package/src/config/load-plugin-config.js +46 -2
  134. package/src/connectors/anthropic-connector.js +93 -55
  135. package/src/connectors/base-connector.js +74 -19
  136. package/src/connectors/cohere-connector.js +88 -32
  137. package/src/connectors/connector-utils.js +302 -0
  138. package/src/connectors/local-embedder.js +43 -5
  139. package/src/connectors/memory-retriever.js +108 -15
  140. package/src/connectors/ollama-connector.js +83 -49
  141. package/src/connectors/openai-connector.js +108 -44
  142. package/src/connectors/rag-prompt.js +88 -0
  143. package/src/core/create-pipeline.js +209 -60
  144. package/src/core/plugin-registry.js +87 -11
  145. package/src/cost/cost-calculator.js +205 -32
  146. package/src/dev/dev-server.js +166 -11
  147. package/src/dev/hot-reload.js +40 -1
  148. package/src/ecosystem/plugin-checks.js +181 -0
  149. package/src/ecosystem/plugin-hub.js +50 -125
  150. package/src/ecosystem/plugin-installer.js +298 -0
  151. package/src/ecosystem/plugin-probe.js +127 -0
  152. package/src/ecosystem/plugin-scanner.js +185 -0
  153. package/src/ecosystem/tar-extract.js +114 -0
  154. package/src/enterprise/audit-logging.js +158 -29
  155. package/src/enterprise/sso-integration.js +715 -228
  156. package/src/evaluate/context-metrics.js +28 -16
  157. package/src/evaluate/evaluator.js +3 -3
  158. package/src/evaluate/faithfulness.js +18 -14
  159. package/src/evaluate/groundedness.js +43 -12
  160. package/src/evaluate/pipeline-evaluator.js +35 -8
  161. package/src/evaluate/scoring.js +251 -3
  162. package/src/experimental.js +71 -0
  163. package/src/guardrails/guardrails-pipeline.js +69 -7
  164. package/src/guardrails/injection-detector.js +283 -0
  165. package/src/guardrails/post-generation-guard.js +19 -0
  166. package/src/guardrails/pre-retrieval-guard.js +36 -36
  167. package/src/guardrails/retrieval-guard.js +58 -8
  168. package/src/index.js +36 -1
  169. package/src/loader/document-reader.js +91 -0
  170. package/src/reranker/cascade-reranker.js +3 -0
  171. package/src/reranker/embedding-reranker.js +136 -21
  172. package/src/reranker/llm-reranker.js +79 -12
  173. package/src/reranker/scoring-reranker.js +3 -0
  174. package/src/retrieval/bm25-search.js +12 -6
  175. package/src/retrieval/file-vector-store.js +212 -0
  176. package/src/retrieval/hybrid-retriever.js +22 -19
  177. package/src/security/jwt-config.js +13 -2
  178. package/src/security/jwt-validator.js +134 -30
  179. package/src/security/plugin-sandbox.js +18 -1
  180. package/src/security/plugin-signature-verifier.js +245 -70
  181. package/src/utils/deprecate.js +69 -0
  182. package/src/utils/embed-query.js +33 -0
  183. package/src/utils/input-sanitizer.js +19 -4
  184. package/src/utils/logger.js +34 -4
  185. package/src/utils/run-abort.js +102 -0
  186. package/src/ai/federated-learning.js +0 -211
  187. package/src/ai/federation.js +0 -71
  188. package/src/ai/index.js +0 -22
  189. package/src/ai/model-trainer.js +0 -217
  190. package/src/ai/model-training.js +0 -202
  191. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  192. package/src/ai/orchestrator.js +0 -65
  193. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  194. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  195. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  196. package/src/cli/commands/ai-ml/index.js +0 -17
  197. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  198. package/src/cli/commands/ai-ml/shared.js +0 -51
  199. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  200. package/src/cli/commands/ai-ml.js +0 -386
  201. package/src/cli/commands/docs.js +0 -228
  202. package/src/cli/commands/dx.js +0 -538
  203. package/src/cli/commands/wizard.js +0 -627
  204. package/src/cli/input-sanitization-middleware.js +0 -356
  205. package/src/cli/interactive-wizard.js +0 -373
  206. package/src/cli/templates/development.template.json +0 -64
  207. package/src/cli/templates/minimal.template.json +0 -33
  208. package/src/cli/templates/production.template.json +0 -104
  209. package/src/cli/templates/testing.template.json +0 -45
  210. package/src/cli/wizard/configuration.js +0 -148
  211. package/src/cli/wizard/observability.js +0 -79
  212. package/src/cli/wizard/performance.js +0 -76
  213. package/src/cli/wizard/plugin-selection.js +0 -297
  214. package/src/cli/wizard/preview-save.js +0 -172
  215. package/src/cli/wizard/project-setup.js +0 -66
  216. package/src/core/pipeline-factory.js +0 -59
  217. package/src/dag/enhanced-dag-engine.js +0 -894
  218. package/src/dx/index.js +0 -40
  219. package/src/dx/integration-templates.js +0 -662
  220. package/src/dx/performance-profiler.js +0 -968
  221. package/src/dx/realtime-debugger.js +0 -755
  222. package/src/dx/visual-pipeline-builder.js +0 -578
  223. package/src/ingest.js +0 -59
  224. package/src/pipeline/pipeline.js +0 -18
  225. package/src/query.js +0 -117
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Maps token counts to cost estimates by provider and model.
3
+ *
4
+ * @example
5
+ * const calc = new CostCalculator();
6
+ * const cost = calc.estimate('gpt-4o', 1500, 500);
7
+ * console.log(cost.totalCost); // 0.015
8
+ */
9
+ export class CostCalculator extends EventEmitter<[never]> {
10
+ /**
11
+ * Provenance of the built-in pricing table.
12
+ * @returns {typeof PRICING_METADATA}
13
+ */
14
+ static getPricingMetadata(): typeof PRICING_METADATA;
15
+ /**
16
+ * @param {object} [options]
17
+ * @param {Record<string, {input: number, output: number, unit?: number, source?: string, asOf?: string}>} [options.pricing]
18
+ * Replaces the built-in pricing table entirely (only these models are known).
19
+ * @param {Record<string, {input: number, output: number, unit: number}>} [options.customPricing]
20
+ * Additional or override model pricing entries, merged over the base table.
21
+ */
22
+ constructor(options?: {
23
+ pricing?: Record<string, {
24
+ input: number;
25
+ output: number;
26
+ unit?: number;
27
+ source?: string;
28
+ asOf?: string;
29
+ }>;
30
+ customPricing?: Record<string, {
31
+ input: number;
32
+ output: number;
33
+ unit: number;
34
+ }>;
35
+ });
36
+ pricing: {
37
+ [x: string]: {
38
+ input: number;
39
+ output: number;
40
+ unit: number;
41
+ source: string;
42
+ asOf: string;
43
+ };
44
+ };
45
+ /** @private Models already warned about as unknown */
46
+ private _warnedModels;
47
+ /**
48
+ * Resolve a model key from the pricing table.
49
+ * Tries an exact match (case-insensitive, '.' and '-' equivalent), then the
50
+ * longest known key contained in the model name (so dated snapshots such
51
+ * as "gpt-4o-mini-2024-07-18" resolve to "gpt-4o-mini", not "gpt-4"), then
52
+ * a known key that contains the model name.
53
+ * @param {string} model
54
+ * @returns {string|null} The matched pricing key or null.
55
+ * @private
56
+ */
57
+ private _resolveModel;
58
+ /**
59
+ * Emit a one-time warning for a model with no known price.
60
+ * Listeners on 'warning' receive `{ type: 'unknown-model', model, message }`;
61
+ * without a listener the warning goes to process.emitWarning.
62
+ * @param {string} model
63
+ * @private
64
+ */
65
+ private _warnUnknownModel;
66
+ /**
67
+ * Estimate the cost for a given token count.
68
+ *
69
+ * @param {string} model - Model identifier (case-insensitive, partial match supported).
70
+ * @param {number} inputTokens - Number of input / prompt tokens.
71
+ * @param {number} [outputTokens=0] - Number of output / completion tokens.
72
+ * @returns {{inputCost: number, outputCost: number, totalCost: number, model: string,
73
+ * inputTokens: number, outputTokens: number, currency: string,
74
+ * pricingSource?: string, pricingAsOf?: string|null, warning?: string}}
75
+ */
76
+ estimate(model: string, inputTokens: number, outputTokens?: number): {
77
+ inputCost: number;
78
+ outputCost: number;
79
+ totalCost: number;
80
+ model: string;
81
+ inputTokens: number;
82
+ outputTokens: number;
83
+ currency: string;
84
+ pricingSource?: string;
85
+ pricingAsOf?: string | null;
86
+ warning?: string;
87
+ };
88
+ /**
89
+ * Register custom model pricing.
90
+ *
91
+ * @param {string} model - Model identifier.
92
+ * @param {{input: number, output: number, unit?: number, source?: string, asOf?: string}} pricing - Pricing definition.
93
+ */
94
+ addModel(model: string, pricing: {
95
+ input: number;
96
+ output: number;
97
+ unit?: number;
98
+ source?: string;
99
+ asOf?: string;
100
+ }): void;
101
+ /**
102
+ * List all known model names.
103
+ * @returns {string[]}
104
+ */
105
+ listModels(): string[];
106
+ /**
107
+ * Retrieve pricing for a specific model.
108
+ *
109
+ * @param {string} model - Model identifier (supports fuzzy resolution).
110
+ * @returns {{input: number, output: number, unit: number, source?: string, asOf?: string|null}|null}
111
+ */
112
+ getModelPricing(model: string): {
113
+ input: number;
114
+ output: number;
115
+ unit: number;
116
+ source?: string;
117
+ asOf?: string | null;
118
+ } | null;
119
+ }
120
+ /**
121
+ * Built-in pricing table for common LLM and embedding models.
122
+ * Prices are in USD per `unit` tokens. Each entry records its `source`
123
+ * (provider pricing page) and `asOf` date.
124
+ * @type {Record<string, {input: number, output: number, unit: number, source: string, asOf: string}>}
125
+ */
126
+ export const PRICING: Record<string, {
127
+ input: number;
128
+ output: number;
129
+ unit: number;
130
+ source: string;
131
+ asOf: string;
132
+ }>;
133
+ /**
134
+ * Where the built-in prices come from and when they were recorded.
135
+ *
136
+ * The values are the providers' published list prices as copied into this
137
+ * library on `asOf`; they have not been re-verified since and providers
138
+ * change prices often. Pass `pricing` or `customPricing` to CostCalculator
139
+ * to use current or negotiated prices.
140
+ */
141
+ export const PRICING_METADATA: Readonly<{
142
+ asOf: "2026-04-07";
143
+ verified: false;
144
+ currency: "USD";
145
+ sources: Readonly<{
146
+ openai: "https://openai.com/api/pricing/";
147
+ anthropic: "https://www.anthropic.com/pricing#api";
148
+ cohere: "https://cohere.com/pricing";
149
+ }>;
150
+ note: "Built-in list prices, not re-verified since asOf. Override with the `pricing` or `customPricing` option.";
151
+ }>;
152
+ import { EventEmitter } from "events";
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Wraps pipeline execution to automatically track token usage and costs.
3
+ *
4
+ * @example
5
+ * const tracker = new CostTracker({ model: 'gpt-4o', enableBudget: true, budgetOptions: { maxCost: 10 } });
6
+ * const wrapped = tracker.wrap(pipeline);
7
+ * const result = await wrapped.run(input);
8
+ * console.log(result.cost); // { inputTokens, outputTokens, estimatedCost, model }
9
+ * console.log(tracker.getSummary());
10
+ */
11
+ export class CostTracker extends EventEmitter<[never]> {
12
+ /**
13
+ * @param {object} [options]
14
+ * @param {string} [options.model='gpt-3.5-turbo'] - Default LLM model for cost estimation.
15
+ * @param {string} [options.embeddingModel='text-embedding-3-small'] - Default embedding model.
16
+ * @param {boolean} [options.enableBudget=false] - Whether to enforce a token/cost budget.
17
+ * @param {object} [options.budgetOptions] - Options forwarded to {@link TokenBudget}.
18
+ * @param {object} [options.calculatorOptions] - Options forwarded to {@link CostCalculator}.
19
+ */
20
+ constructor(options?: {
21
+ model?: string;
22
+ embeddingModel?: string;
23
+ enableBudget?: boolean;
24
+ budgetOptions?: object;
25
+ calculatorOptions?: object;
26
+ });
27
+ config: {
28
+ model: string;
29
+ embeddingModel: string;
30
+ enableBudget: boolean;
31
+ budgetOptions: object;
32
+ calculatorOptions?: object;
33
+ };
34
+ calculator: CostCalculator;
35
+ budget: TokenBudget;
36
+ sessions: any[];
37
+ currentSession: {
38
+ id: string;
39
+ startTime: number;
40
+ endTime: any;
41
+ metadata: any;
42
+ entries: any[];
43
+ totalTokens: number;
44
+ totalCost: number;
45
+ };
46
+ /**
47
+ * Extract token usage from a pipeline result.
48
+ * Checks common locations: result.usage, result.evaluation, or estimates from content length.
49
+ * @param {object} result
50
+ * @returns {{inputTokens: number, outputTokens: number}}
51
+ * @private
52
+ */
53
+ private _extractUsage;
54
+ /**
55
+ * Wrap a pipeline so that every `.run()` call is cost-tracked.
56
+ *
57
+ * @param {object} pipeline - Object with a `.run()` method.
58
+ * @returns {object} A proxy pipeline whose `.run()` enriches results with cost data.
59
+ */
60
+ wrap(pipeline: object): object;
61
+ /**
62
+ * Start a new tracking session.
63
+ *
64
+ * @param {object} [metadata={}] - Arbitrary metadata to attach to the session.
65
+ * @returns {{id: string, startTime: number, metadata: object, entries: Array,
66
+ * totalTokens: number, totalCost: number}}
67
+ */
68
+ startSession(metadata?: object): {
69
+ id: string;
70
+ startTime: number;
71
+ metadata: object;
72
+ entries: any[];
73
+ totalTokens: number;
74
+ totalCost: number;
75
+ };
76
+ /**
77
+ * End the current tracking session and compute totals.
78
+ *
79
+ * @returns {object|null} The closed session, or null if no session was active.
80
+ */
81
+ endSession(): object | null;
82
+ /**
83
+ * Return an aggregate summary across all sessions.
84
+ *
85
+ * @returns {{totalTokens: number, totalCost: number, sessionCount: number,
86
+ * avgCostPerQuery: number, breakdown: Record<string, {tokens: number, cost: number, count: number}>}}
87
+ */
88
+ getSummary(): {
89
+ totalTokens: number;
90
+ totalCost: number;
91
+ sessionCount: number;
92
+ avgCostPerQuery: number;
93
+ breakdown: Record<string, {
94
+ tokens: number;
95
+ cost: number;
96
+ count: number;
97
+ }>;
98
+ };
99
+ /**
100
+ * Return the full history of tracked operations across all sessions.
101
+ *
102
+ * @returns {Array<{timestamp: number, inputTokens: number, outputTokens: number,
103
+ * cost: number, model: string, sessionId: string}>}
104
+ */
105
+ getHistory(): Array<{
106
+ timestamp: number;
107
+ inputTokens: number;
108
+ outputTokens: number;
109
+ cost: number;
110
+ model: string;
111
+ sessionId: string;
112
+ }>;
113
+ }
114
+ /**
115
+ * Default tracker configuration.
116
+ * @type {{model: string, embeddingModel: string, enableBudget: boolean, budgetOptions: object}}
117
+ */
118
+ export const DEFAULT_CONFIG: {
119
+ model: string;
120
+ embeddingModel: string;
121
+ enableBudget: boolean;
122
+ budgetOptions: object;
123
+ };
124
+ import { EventEmitter } from "events";
125
+ import { CostCalculator } from "./cost-calculator";
126
+ import { TokenBudget } from "./token-budget";
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Configurable token and cost budgets with hard and soft limits.
3
+ *
4
+ * Emits:
5
+ * - `usage` — after every {@link record} call with the recorded entry.
6
+ * - `warning` — when usage crosses the soft limit threshold.
7
+ * - `exceeded` — when usage crosses a hard limit.
8
+ *
9
+ * @example
10
+ * const budget = new TokenBudget({ maxTokens: 100000, maxCost: 5.0 });
11
+ * budget.on('warning', (msg) => console.warn(msg));
12
+ * const status = budget.check(2000, 0.10);
13
+ * if (status.allowed) budget.record(2000, 0.10);
14
+ */
15
+ export class TokenBudget extends EventEmitter<[never]> {
16
+ /**
17
+ * @param {object} [options]
18
+ * @param {number} [options.maxTokens=Infinity] - Hard token limit.
19
+ * @param {number} [options.maxCost=Infinity] - Hard cost limit (USD).
20
+ * @param {number} [options.softLimitPercent=0.8] - Fraction (0-1) at which soft-limit warnings fire.
21
+ * @param {number} [options.trackingWindow=0] - Sliding window in ms (0 disables).
22
+ */
23
+ constructor(options?: {
24
+ maxTokens?: number;
25
+ maxCost?: number;
26
+ softLimitPercent?: number;
27
+ trackingWindow?: number;
28
+ });
29
+ config: {
30
+ maxTokens: number;
31
+ maxCost: number;
32
+ softLimitPercent: number;
33
+ trackingWindow: number;
34
+ };
35
+ usage: {
36
+ tokens: number;
37
+ cost: number;
38
+ operations: number;
39
+ history: any[];
40
+ };
41
+ /**
42
+ * Prune history entries outside the sliding window.
43
+ * @private
44
+ */
45
+ private _pruneWindow;
46
+ /**
47
+ * Check whether a prospective usage fits within the budget.
48
+ *
49
+ * @param {number} [tokens=0] - Tokens about to be consumed.
50
+ * @param {number} [cost=0] - Cost about to be incurred.
51
+ * @returns {{allowed: boolean, reason?: string, remaining: {tokens: number, cost: number},
52
+ * warnings: string[], usage: {tokens: number, cost: number, operations: number}}}
53
+ */
54
+ check(tokens?: number, cost?: number): {
55
+ allowed: boolean;
56
+ reason?: string;
57
+ remaining: {
58
+ tokens: number;
59
+ cost: number;
60
+ };
61
+ warnings: string[];
62
+ usage: {
63
+ tokens: number;
64
+ cost: number;
65
+ operations: number;
66
+ };
67
+ };
68
+ /**
69
+ * Record actual token and cost usage.
70
+ *
71
+ * @param {number} tokens - Tokens consumed.
72
+ * @param {number} [cost=0] - Cost incurred (USD).
73
+ */
74
+ record(tokens: number, cost?: number): void;
75
+ /**
76
+ * Reset all usage counters to zero.
77
+ */
78
+ reset(): void;
79
+ /**
80
+ * Return current usage summary.
81
+ *
82
+ * @returns {{tokens: number, cost: number, operations: number,
83
+ * limits: {maxTokens: number, maxCost: number},
84
+ * remaining: {tokens: number, cost: number}}}
85
+ */
86
+ getUsage(): {
87
+ tokens: number;
88
+ cost: number;
89
+ operations: number;
90
+ limits: {
91
+ maxTokens: number;
92
+ maxCost: number;
93
+ };
94
+ remaining: {
95
+ tokens: number;
96
+ cost: number;
97
+ };
98
+ };
99
+ }
100
+ /**
101
+ * Default budget configuration.
102
+ * @type {{maxTokens: number, maxCost: number, softLimitPercent: number, trackingWindow: number}}
103
+ */
104
+ export const DEFAULT_CONFIG: {
105
+ maxTokens: number;
106
+ maxCost: number;
107
+ softLimitPercent: number;
108
+ trackingWindow: number;
109
+ };
110
+ import { EventEmitter } from "events";
@@ -0,0 +1,239 @@
1
+ export = ErrorContext;
2
+ /**
3
+ * ErrorContext class for managing DAG execution errors
4
+ *
5
+ * Provides comprehensive error management with:
6
+ * - Rich error context creation with node metadata
7
+ * - Error aggregation for multiple failures
8
+ * - Property preservation across error transformations
9
+ * - Error serialization for logging and monitoring
10
+ * - Cycle path tracking and reporting
11
+ * - Downstream impact analysis
12
+ *
13
+ * @class
14
+ * @since 2.2.4
15
+ *
16
+ * @example
17
+ * const errorContext = new ErrorContext();
18
+ *
19
+ * // Create error with context
20
+ * const nodeError = errorContext.createErrorContext('nodeA', new Error('Failed'), {
21
+ * downstream: ['nodeB', 'nodeC'],
22
+ * timestamp: Date.now()
23
+ * });
24
+ *
25
+ * // Aggregate multiple errors
26
+ * const errorsMap = new Map([['nodeA', error1], ['nodeB', error2]]);
27
+ * const aggregated = errorContext.aggregateErrors(errorsMap);
28
+ *
29
+ * // Serialize for logging
30
+ * console.log(errorContext.serializeError(nodeError));
31
+ */
32
+ declare class ErrorContext {
33
+ /**
34
+ * Create error context with node information and downstream impact
35
+ *
36
+ * Creates a new Error object enriched with:
37
+ * - Node ID for tracing execution path
38
+ * - Timestamp for temporal analysis
39
+ * - Original error as cause (for stack trace preservation)
40
+ * - Downstream node impact message
41
+ *
42
+ * @param {string} nodeId - ID of the node that failed
43
+ * @param {Error} error - Original error that occurred
44
+ * @param {Object} [options={}] - Additional context options
45
+ * @param {string[]} [options.downstream=[]] - Array of downstream node IDs affected
46
+ * @param {number} [options.timestamp=Date.now()] - Error timestamp
47
+ * @returns {Error} Enhanced error object with context
48
+ *
49
+ * @example
50
+ * const error = errorContext.createErrorContext(
51
+ * 'processData',
52
+ * new Error('Invalid input'),
53
+ * {
54
+ * downstream: ['saveResults', 'sendNotification'],
55
+ * timestamp: Date.now()
56
+ * }
57
+ * );
58
+ * // Error message: "Node processData execution failed: Invalid input.
59
+ * // This affects downstream nodes: saveResults, sendNotification"
60
+ * // error.nodeId === 'processData'
61
+ * // error.cause === original Error object
62
+ *
63
+ * @since 2.2.4
64
+ */
65
+ createErrorContext(nodeId: string, error: Error, options?: {
66
+ downstream?: string[];
67
+ timestamp?: number;
68
+ }): Error;
69
+ /**
70
+ * Aggregate multiple errors into a single error object
71
+ *
72
+ * Creates a consolidated error when multiple nodes fail during execution.
73
+ * The aggregated error maintains references to all original errors for
74
+ * comprehensive debugging.
75
+ *
76
+ * @param {Map<string, Error>} errorsMap - Map of node ID to error object
77
+ * @returns {Error|null} Aggregated error, single error, or null if no errors
78
+ *
79
+ * @example
80
+ * const errors = new Map([
81
+ * ['nodeA', new Error('A failed')],
82
+ * ['nodeB', new Error('B failed')]
83
+ * ]);
84
+ * const aggregated = errorContext.aggregateErrors(errors);
85
+ * // aggregated.message === 'Multiple execution errors'
86
+ * // aggregated.errors === [Error('A failed'), Error('B failed')]
87
+ *
88
+ * @since 2.2.4
89
+ */
90
+ aggregateErrors(errorsMap: Map<string, Error>): Error | null;
91
+ /**
92
+ * Preserve node context when wrapping or transforming errors
93
+ *
94
+ * Ensures all error metadata (nodeId, timestamp, cause, cycle, errors)
95
+ * is preserved when creating wrapped errors. This is critical for
96
+ * maintaining debugging information through error propagation.
97
+ *
98
+ * @param {Error} error - Original error to preserve
99
+ * @param {Object} [context={}] - Additional context to add
100
+ * @returns {Error} New error with preserved properties
101
+ *
102
+ * @example
103
+ * const originalError = new Error('Original');
104
+ * originalError.nodeId = 'nodeA';
105
+ * originalError.timestamp = Date.now();
106
+ *
107
+ * const wrapped = errorContext.preserveNodeContext(originalError, {
108
+ * retryCount: 3
109
+ * });
110
+ * // wrapped.nodeId === 'nodeA'
111
+ * // wrapped.timestamp === original timestamp
112
+ * // wrapped.retryCount === 3
113
+ *
114
+ * @since 2.2.4
115
+ */
116
+ preserveNodeContext(error: Error, context?: any): Error;
117
+ /**
118
+ * Format error report for debugging and monitoring
119
+ *
120
+ * Creates a structured representation of an error suitable for logging,
121
+ * monitoring systems, or debugging tools. Includes all metadata and
122
+ * nested error information.
123
+ *
124
+ * @param {Error} error - Error to format
125
+ * @returns {Object} Structured error report
126
+ *
127
+ * @example
128
+ * const report = errorContext.formatErrorReport(nodeError);
129
+ * // {
130
+ * // message: "Node A execution failed: ...",
131
+ * // nodeId: "A",
132
+ * // timestamp: 1234567890,
133
+ * // cause: { message: "...", stack: "..." },
134
+ * // cycle: null,
135
+ * // errors: null
136
+ * // }
137
+ *
138
+ * @since 2.2.4
139
+ */
140
+ formatErrorReport(error: Error): any;
141
+ /**
142
+ * Serialize error for logging and monitoring systems
143
+ *
144
+ * Converts error to JSON string with formatting for readability.
145
+ * Safe for logging systems that require string representation.
146
+ *
147
+ * @param {Error} error - Error to serialize
148
+ * @param {number} [indent=2] - JSON indentation spaces
149
+ * @returns {string} JSON string representation of error
150
+ *
151
+ * @example
152
+ * const json = errorContext.serializeError(nodeError);
153
+ * console.log(json);
154
+ * // {
155
+ * // "message": "Node A execution failed: ...",
156
+ * // "nodeId": "A",
157
+ * // "timestamp": 1234567890,
158
+ * // ...
159
+ * // }
160
+ *
161
+ * @since 2.2.4
162
+ */
163
+ serializeError(error: Error, indent?: number): string;
164
+ /**
165
+ * Wrap execution errors with appropriate context
166
+ *
167
+ * Implements error wrapping policy:
168
+ * - Node errors (with nodeId or starting with "Node ") are rethrown unchanged
169
+ * - Validation/cycle errors are wrapped once with "DAG execution failed"
170
+ * - Timeout and "no sink nodes" errors are not wrapped
171
+ * - All other errors are wrapped with "DAG execution failed"
172
+ *
173
+ * All error properties are preserved during wrapping.
174
+ *
175
+ * @param {Error} error - Error to wrap
176
+ * @returns {Error} Appropriately wrapped error
177
+ *
178
+ * @example
179
+ * const nodeError = new Error('Node A failed');
180
+ * nodeError.nodeId = 'A';
181
+ * const wrapped = errorContext.wrapExecutionError(nodeError);
182
+ * // Returns same error unchanged (node error policy)
183
+ *
184
+ * @example
185
+ * const validationError = new Error('DAG validation failed: cycle detected');
186
+ * validationError.cycle = ['A', 'B', 'A'];
187
+ * const wrapped = errorContext.wrapExecutionError(validationError);
188
+ * // Returns: Error('DAG execution failed: DAG validation failed: cycle detected')
189
+ * // with cycle property preserved
190
+ *
191
+ * @since 2.2.4
192
+ */
193
+ wrapExecutionError(error: Error): Error;
194
+ /**
195
+ * Create cycle error with path information
196
+ *
197
+ * Creates a specialized error for cycle detection with the cycle path
198
+ * embedded for debugging and error reporting.
199
+ *
200
+ * @param {string[]} cyclePath - Array of node IDs forming the cycle
201
+ * @returns {Error} Cycle error with path information
202
+ *
203
+ * @example
204
+ * const cycleError = errorContext.createCycleError(['A', 'B', 'C', 'A']);
205
+ * // cycleError.message === 'Cycle detected involving node: A -> B -> C -> A'
206
+ * // cycleError.cycle === ['A', 'B', 'C', 'A']
207
+ *
208
+ * @since 2.2.4
209
+ */
210
+ createCycleError(cyclePath: string[]): Error;
211
+ /**
212
+ * Check if error should halt execution
213
+ *
214
+ * Determines if an error is critical enough to stop DAG execution
215
+ * based on error type and execution options.
216
+ *
217
+ * @param {Error} error - Error to evaluate
218
+ * @param {Object} options - Execution options
219
+ * @param {boolean} [options.continueOnError=false] - Continue on non-critical errors
220
+ * @param {boolean} [options.isNonCritical=false] - Whether node is non-critical
221
+ * @returns {boolean} True if execution should halt
222
+ *
223
+ * @example
224
+ * const shouldHalt = errorContext.shouldHaltExecution(error, {
225
+ * continueOnError: true,
226
+ * isNonCritical: true
227
+ * });
228
+ * // Returns false - execution continues
229
+ *
230
+ * @since 2.2.4
231
+ */
232
+ shouldHaltExecution(error: Error, options?: {
233
+ continueOnError?: boolean;
234
+ isNonCritical?: boolean;
235
+ }): boolean;
236
+ }
237
+ declare namespace ErrorContext {
238
+ export { ErrorContext as default };
239
+ }