@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,195 @@
1
+ /**
2
+ * JWT Validator with hardened security
3
+ */
4
+ export class JWTValidator extends EventEmitter<[never]> {
5
+ constructor(options?: {});
6
+ config: {
7
+ algorithm: any;
8
+ allowedAlgorithms: any;
9
+ secret: any;
10
+ publicKey: any;
11
+ privateKey: any;
12
+ issuer: any;
13
+ audience: any;
14
+ clockTolerance: any;
15
+ maxTokenAge: any;
16
+ notBeforeTolerance: any;
17
+ requireJti: boolean;
18
+ requireSub: boolean;
19
+ allowNoneAlgorithm: boolean;
20
+ strictValidation: boolean;
21
+ enableJtiTracking: boolean;
22
+ jtiExpirationMs: any;
23
+ singleUseTokens: boolean;
24
+ maxTrackedJtis: any;
25
+ validateClaims: any;
26
+ enableAuditLog: boolean;
27
+ };
28
+ usedJtis: Map<any, any>;
29
+ selfSignedJtis: Set<any>;
30
+ stats: {
31
+ tokensGenerated: number;
32
+ tokensValidated: number;
33
+ validationFailures: number;
34
+ algorithmMismatch: number;
35
+ expiredTokens: number;
36
+ invalidSignature: number;
37
+ replayAttempts: number;
38
+ };
39
+ /**
40
+ * Validate configuration on initialization
41
+ * @private
42
+ */
43
+ private _validateConfig;
44
+ /**
45
+ * Generate a secure JWT token
46
+ *
47
+ * @param {Object} payload - Token payload
48
+ * @param {Object} options - Additional signing options
49
+ * @returns {string} Signed JWT token
50
+ *
51
+ * @example
52
+ * const token = validator.sign({
53
+ * sub: 'user-123',
54
+ * roles: ['admin'],
55
+ * tenant: 'acme-corp'
56
+ * });
57
+ */
58
+ sign(payload: any, options?: any): string;
59
+ /**
60
+ * Verify and decode a JWT token with hardened validation
61
+ *
62
+ * @param {string} token - JWT token to verify
63
+ * @param {Object} options - Verification options
64
+ * @returns {Object} Decoded and validated payload
65
+ *
66
+ * @example
67
+ * try {
68
+ * const payload = validator.verify(token);
69
+ * console.log('Valid token for user:', payload.sub);
70
+ * } catch (error) {
71
+ * console.error('Invalid token:', error.message);
72
+ * }
73
+ */
74
+ verify(token: string, options?: any): any;
75
+ /**
76
+ * Decode token header without verification (for algorithm checking)
77
+ * @private
78
+ */
79
+ private _decodeTokenHeader;
80
+ /**
81
+ * Validate required claims are present
82
+ * @private
83
+ */
84
+ private _validateRequiredClaims;
85
+ /**
86
+ * Validate custom claims
87
+ * @private
88
+ */
89
+ private _validateCustomClaims;
90
+ /**
91
+ * Expiry time (ms) of a JTI store entry, including clock tolerance.
92
+ * @private
93
+ */
94
+ private _jtiExpiry;
95
+ /**
96
+ * Remove a JTI from both tracking structures.
97
+ * @private
98
+ */
99
+ private _forgetJti;
100
+ /**
101
+ * Look up a JTI, dropping it if it has expired and refreshing its LRU
102
+ * position otherwise.
103
+ * @private
104
+ */
105
+ private _getJtiEntry;
106
+ /**
107
+ * Record a JTI in the bounded store. When the store is full, expired
108
+ * entries are purged first; if it is still full the least-recently-used
109
+ * entry is evicted.
110
+ * @private
111
+ */
112
+ private _trackJti;
113
+ /**
114
+ * Drop every expired JTI from the store.
115
+ * @private
116
+ * @returns {number} Number of entries removed
117
+ */
118
+ private _purgeExpiredJtis;
119
+ /**
120
+ * Start periodic cleanup of expired JTIs
121
+ * @private
122
+ */
123
+ private _startJtiCleanup;
124
+ jtiCleanupInterval: NodeJS.Timeout;
125
+ /**
126
+ * Decode token without verification (use with caution)
127
+ *
128
+ * @param {string} token - JWT token to decode
129
+ * @returns {Object} Decoded payload (unverified)
130
+ */
131
+ decode(token: string): any;
132
+ /**
133
+ * Get validator statistics
134
+ *
135
+ * @returns {Object} Statistics object
136
+ */
137
+ getStats(): any;
138
+ /**
139
+ * Reset statistics
140
+ */
141
+ resetStats(): void;
142
+ /**
143
+ * Clear JTI tracking
144
+ */
145
+ clearJtiTracking(): void;
146
+ /**
147
+ * Destroy validator and cleanup resources
148
+ */
149
+ destroy(): void;
150
+ }
151
+ export namespace SECURE_ALGORITHMS {
152
+ let HS256: string;
153
+ let HS384: string;
154
+ let HS512: string;
155
+ let RS256: string;
156
+ let RS384: string;
157
+ let RS512: string;
158
+ let ES256: string;
159
+ let ES384: string;
160
+ let ES512: string;
161
+ let PS256: string;
162
+ let PS384: string;
163
+ let PS512: string;
164
+ }
165
+ export namespace MIN_KEY_SIZES {
166
+ let HS256_1: number;
167
+ export { HS256_1 as HS256 };
168
+ let HS384_1: number;
169
+ export { HS384_1 as HS384 };
170
+ let HS512_1: number;
171
+ export { HS512_1 as HS512 };
172
+ let RS256_1: number;
173
+ export { RS256_1 as RS256 };
174
+ let RS384_1: number;
175
+ export { RS384_1 as RS384 };
176
+ let RS512_1: number;
177
+ export { RS512_1 as RS512 };
178
+ let ES256_1: number;
179
+ export { ES256_1 as ES256 };
180
+ let ES384_1: number;
181
+ export { ES384_1 as ES384 };
182
+ let ES512_1: number;
183
+ export { ES512_1 as ES512 };
184
+ let PS256_1: number;
185
+ export { PS256_1 as PS256 };
186
+ let PS384_1: number;
187
+ export { PS384_1 as PS384 };
188
+ let PS512_1: number;
189
+ export { PS512_1 as PS512 };
190
+ }
191
+ /**
192
+ * Required JWT claims for validation
193
+ */
194
+ export const REQUIRED_CLAIMS: string[];
195
+ import { EventEmitter } from "events";
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Secure plugin sandbox for executing third-party plugins with strict isolation.
3
+ *
4
+ * Features:
5
+ * - VM-based execution isolation
6
+ * - Resource limits (memory, CPU time, I/O)
7
+ * - Permission-based access control
8
+ * - Audit logging for security compliance
9
+ * - Plugin signature verification
10
+ * - Fail-closed security model
11
+ *
12
+ * @class PluginSandbox
13
+ * @extends EventEmitter
14
+ */
15
+ export class PluginSandbox extends EventEmitter<[never]> {
16
+ constructor(options?: {});
17
+ config: {
18
+ timeout: any;
19
+ memoryLimit: any;
20
+ allowEval: boolean;
21
+ allowWasm: boolean;
22
+ allowAsync: any;
23
+ permissions: any;
24
+ maxFileSize: any;
25
+ maxNetworkRequests: any;
26
+ maxCpuTime: any;
27
+ auditEnabled: boolean;
28
+ logLevel: any;
29
+ };
30
+ signatureVerifier: any;
31
+ activeSandboxes: Map<any, any>;
32
+ executionMetrics: Map<any, any>;
33
+ /**
34
+ * Execute a plugin within the secure sandbox environment.
35
+ *
36
+ * @param {Object} plugin - Plugin configuration and code
37
+ * @param {Object} context - Execution context and input data
38
+ * @param {Object} options - Override options for this execution
39
+ * @returns {Promise<any>} Plugin execution result
40
+ * @throws {SecurityError} On security policy violations
41
+ * @throws {ResourceError} On resource limit exceeded
42
+ * @throws {ValidationError} On plugin validation failure
43
+ */
44
+ execute(plugin: any, context?: any, options?: any): Promise<any>;
45
+ /**
46
+ * Enforce rate limiting
47
+ */
48
+ _enforceRateLimit(customRateLimit?: {}): void;
49
+ /**
50
+ * Validate plugin structure and security
51
+ */
52
+ _validatePlugin(plugin: any): void;
53
+ /**
54
+ * Execute plugin in isolated VM context using isolated-vm
55
+ */
56
+ _executeInSandbox(plugin: any, prompt: any, executionId: any): Promise<any>;
57
+ /**
58
+ * Create secure globals for isolated-vm
59
+ */
60
+ _createSecureGlobals(executionId: any): {
61
+ console: {
62
+ log: () => void;
63
+ error: () => void;
64
+ warn: () => void;
65
+ info: () => void;
66
+ };
67
+ setTimeout: (fn: any, delay: any) => NodeJS.Timeout;
68
+ clearTimeout: typeof clearTimeout;
69
+ Math: Math;
70
+ JSON: JSON;
71
+ Date: DateConstructor;
72
+ __SANDBOX_ID__: any;
73
+ };
74
+ /**
75
+ * Create secure sandbox context (legacy method for compatibility)
76
+ */
77
+ _createSandboxContext(executionId: any): {
78
+ console: {
79
+ log: () => void;
80
+ error: () => void;
81
+ warn: () => void;
82
+ info: () => void;
83
+ };
84
+ setTimeout: (fn: any, delay: any) => NodeJS.Timeout;
85
+ clearTimeout: typeof clearTimeout;
86
+ setImmediate: typeof setImmediate;
87
+ process: {
88
+ env: {};
89
+ memoryUsage: any;
90
+ hrtime: any;
91
+ };
92
+ Buffer: {
93
+ from: any;
94
+ alloc: (size: any) => Buffer<ArrayBuffer>;
95
+ };
96
+ Math: Math;
97
+ JSON: JSON;
98
+ Date: DateConstructor;
99
+ require: () => never;
100
+ import: () => never;
101
+ eval: () => never;
102
+ Function: () => never;
103
+ fetch: typeof fetch;
104
+ fs: typeof fs;
105
+ global: any;
106
+ globalThis: any;
107
+ window: any;
108
+ __SANDBOX_ID__: any;
109
+ };
110
+ /**
111
+ * Sanitize execution result
112
+ */
113
+ _sanitizeResult(result: any): any;
114
+ /**
115
+ * Get sandbox statistics
116
+ */
117
+ getStats(): {
118
+ activeExecutions: any;
119
+ rateLimitEntries: any;
120
+ options: any;
121
+ };
122
+ /**
123
+ * Clean up rate limit entries
124
+ */
125
+ cleanup(): void;
126
+ }
127
+ /**
128
+ * Legacy sanitizer for backward compatibility
129
+ */
130
+ export function sanitizeOutput(obj: any): any;
131
+ /**
132
+ * Input sanitizer for security validation
133
+ */
134
+ export class InputSanitizer {
135
+ static sanitizeInput(input: any): string;
136
+ static validateInput(input: any): boolean;
137
+ }
138
+ /**
139
+ * Output sanitizer for data protection
140
+ */
141
+ export class OutputSanitizer {
142
+ static sanitizeOutput(output: any): any;
143
+ static sanitizeText(text: any): any;
144
+ }
145
+ /**
146
+ * Simple sandbox runner with timeout and abort support
147
+ * @param {Function} fn - Function to execute
148
+ * @param {Object} options - Options object
149
+ * @param {number} options.timeoutMs - Timeout in milliseconds (default: 5000)
150
+ * @param {AbortSignal} options.signal - AbortSignal for cancellation
151
+ * @returns {Promise<Object>} Result object with success/error
152
+ */
153
+ export function run(fn: Function, { timeoutMs, signal }?: {
154
+ timeoutMs: number;
155
+ signal: AbortSignal;
156
+ }): Promise<any>;
157
+ import { EventEmitter } from "events";
158
+ import fs = require("fs");
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Plugin signature verification with Ed25519
3
+ */
4
+ export class PluginSignatureVerifier {
5
+ constructor(options?: {});
6
+ enabled: boolean;
7
+ trustStore: any;
8
+ auditLogger: any;
9
+ failClosed: boolean;
10
+ requireContentDigest: boolean;
11
+ /**
12
+ * Load trusted public keys from configuration.
13
+ * Without a keys file the trust store stays empty (no built-in keys).
14
+ * @param {string} keysPath - Path to trusted keys file
15
+ */
16
+ _loadTrustedKeys(keysPath: string): void;
17
+ /**
18
+ * Verify plugin signature
19
+ * @param {object} manifest - Plugin manifest
20
+ * @param {string} signature - Base64 encoded signature
21
+ * @param {string} signerId - Signer identifier
22
+ * @param {object} [content] - Plugin content to check against
23
+ * manifest.contentDigest: `{ files, baseDir, contents }` (see
24
+ * computeContentDigest)
25
+ * @returns {Promise<object>} Verification result
26
+ */
27
+ verifyPluginSignature(manifest: object, signature: string, signerId: string, content?: object): Promise<object>;
28
+ /**
29
+ * Check the supplied plugin content against the signed contentDigest.
30
+ * @param {object} canonicalManifest - Signed manifest
31
+ * @param {object|null} content - `{ files, baseDir, contents }`
32
+ * @returns {boolean} true when the content digest was checked and matched
33
+ * @private
34
+ */
35
+ private _verifyContentDigest;
36
+ /**
37
+ * Verify Ed25519 signature
38
+ * @param {Buffer} data - Data that was signed
39
+ * @param {Buffer} signature - Signature bytes
40
+ * @param {crypto.KeyObject|Buffer|string} publicKey - Ed25519 public key
41
+ * (raw hex, PEM, DER or KeyObject)
42
+ * @returns {Promise<boolean>} Verification result
43
+ */
44
+ _verifyEd25519Signature(data: Buffer, signature: Buffer, publicKey: crypto.KeyObject | Buffer | string): Promise<boolean>;
45
+ /**
46
+ * Canonicalize manifest for consistent signing
47
+ * @param {object} manifest - Plugin manifest
48
+ * @returns {object} Canonicalized manifest
49
+ */
50
+ _canonicalizeManifest(manifest: object): object;
51
+ /**
52
+ * Bytes that a signer must sign for a manifest (canonical JSON).
53
+ * @param {object} manifest - Plugin manifest
54
+ * @returns {Buffer}
55
+ */
56
+ getSigningPayload(manifest: object): Buffer;
57
+ /**
58
+ * Sort object keys recursively
59
+ * @param {any} obj - Object to sort
60
+ * @returns {any} Object with sorted keys
61
+ */
62
+ _sortObjectKeys(obj: any): any;
63
+ /**
64
+ * Hash manifest for audit trail
65
+ * @param {object} manifest - Canonicalized manifest
66
+ * @returns {string} SHA-256 hash
67
+ */
68
+ _hashManifest(manifest: object): string;
69
+ /**
70
+ * Default audit logger
71
+ * @param {object} result - Verification result
72
+ * @param {object} manifest - Plugin manifest
73
+ */
74
+ _defaultAuditLogger(result: object, manifest: object): void;
75
+ /**
76
+ * Audit verification attempt
77
+ * @param {object} result - Verification result
78
+ * @param {object} manifest - Plugin manifest
79
+ */
80
+ _auditVerification(result: object, manifest: object): void;
81
+ /**
82
+ * Add trusted signer
83
+ * @param {string} signerId - Signer identifier
84
+ * @param {string|Buffer|crypto.KeyObject} publicKey - Ed25519 public key:
85
+ * 64 hex characters (raw 32 bytes), PEM, DER (SPKI) or a KeyObject
86
+ * @param {string} name - Human-readable name
87
+ * @param {object} metadata - Additional metadata
88
+ */
89
+ addTrustedSigner(signerId: string, publicKey: string | Buffer | crypto.KeyObject, name: string, metadata?: object): void;
90
+ /**
91
+ * Remove trusted signer
92
+ * @param {string} signerId - Signer identifier
93
+ */
94
+ removeTrustedSigner(signerId: string): any;
95
+ /**
96
+ * List trusted signers
97
+ * @returns {Array} List of trusted signers
98
+ */
99
+ listTrustedSigners(): any[];
100
+ }
101
+ /**
102
+ * Create plugin signature verifier instance
103
+ * @param {object} options - Configuration options
104
+ * @returns {PluginSignatureVerifier} Verifier instance
105
+ */
106
+ export function createPluginVerifier(options?: object): PluginSignatureVerifier;
107
+ /**
108
+ * Compute the content digest of a plugin.
109
+ *
110
+ * The digest is `sha256-<hex>` of the lines `<relativePath>\0<sha256 of
111
+ * file>\n`, sorted by relative path. Paths are relative to `baseDir` and use
112
+ * forward slashes, so the digest is identical on Windows and POSIX.
113
+ *
114
+ * @param {Object} options
115
+ * @param {string[]} [options.files] - File paths (absolute or relative to baseDir)
116
+ * @param {string} [options.baseDir] - Plugin root; files must be inside it
117
+ * @param {Object<string, Buffer|string>} [options.contents] - In-memory
118
+ * files keyed by relative path (alternative or addition to `files`)
119
+ * @returns {string} `sha256-<hex>`
120
+ */
121
+ export function computeContentDigest({ files, baseDir, contents }?: {
122
+ files?: string[];
123
+ baseDir?: string;
124
+ contents?: {
125
+ [x: string]: Buffer | string;
126
+ };
127
+ }): string;
128
+ /**
129
+ * Convert supported public key encodings to an Ed25519 KeyObject.
130
+ *
131
+ * Accepted: a KeyObject; a 64-character hex string or 32-byte Buffer (raw
132
+ * key); a PEM string ("-----BEGIN PUBLIC KEY-----"); a DER (SPKI) Buffer or
133
+ * base64 string.
134
+ *
135
+ * @param {crypto.KeyObject|Buffer|string} publicKey
136
+ * @returns {crypto.KeyObject}
137
+ */
138
+ export function toEd25519PublicKey(publicKey: crypto.KeyObject | Buffer | string): crypto.KeyObject;
139
+ import crypto = require("crypto");
@@ -0,0 +1,5 @@
1
+ export function validateInput(input: any, opts?: {}): {
2
+ valid: boolean;
3
+ reasons: string[];
4
+ sanitized: string;
5
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Async generator that streams embedding results for a collection of documents.
3
+ *
4
+ * Documents are processed in batches of `batchSize`. Before each batch the
5
+ * generator checks heap memory; when usage exceeds
6
+ * `backpressureThreshold * maxMemoryMB` it pauses briefly and retries,
7
+ * giving the GC time to reclaim memory.
8
+ *
9
+ * Each yielded value is an object containing the document id, the computed
10
+ * vector, the document index, and a progress fraction (0-1).
11
+ *
12
+ * Errors within a batch are caught and yielded as objects with an `error`
13
+ * property so that consumers can decide how to handle partial failures
14
+ * without losing the rest of the stream.
15
+ *
16
+ * @param {Array<{id: string, content: string}>} documents - Documents to embed
17
+ * @param {Object} embedder - Embedder with `.embed()` or `.embedQuery()`
18
+ * @param {Object} [options] - Override any key from {@link DEFAULT_CONFIG}
19
+ * @yields {{ id: string, vector: number[], index: number, progress: number }
20
+ * | { id: string, error: Error, index: number, progress: number }}
21
+ *
22
+ * @example
23
+ * const docs = [{ id: '1', content: 'hello' }, { id: '2', content: 'world' }];
24
+ * for await (const emb of createEmbeddingStream(docs, myEmbedder)) {
25
+ * console.log(emb.id, emb.vector.length);
26
+ * }
27
+ */
28
+ export function createEmbeddingStream(documents: Array<{
29
+ id: string;
30
+ content: string;
31
+ }>, embedder: any, options?: any): AsyncGenerator<{
32
+ backpressure?: boolean;
33
+ id: string;
34
+ vector: any;
35
+ index: number;
36
+ progress: number;
37
+ error?: undefined;
38
+ } | {
39
+ id: string;
40
+ error: any;
41
+ index: number;
42
+ progress: number;
43
+ }, void, unknown>;
44
+ /**
45
+ * Streaming Embeddings Generator
46
+ *
47
+ * Async generator that yields embeddings chunk by chunk with backpressure
48
+ * support. Processes documents in configurable batches while monitoring
49
+ * memory usage to prevent OOM conditions in large-scale pipelines.
50
+ *
51
+ * Features:
52
+ * - Batch-based document embedding with configurable size
53
+ * - Memory-aware backpressure (pauses when heap exceeds threshold)
54
+ * - Per-batch error isolation (failures don't abort the stream)
55
+ * - Progress tracking via yielded metadata
56
+ * - Support for both `.embed()` and `.embedQuery()` embedder APIs
57
+ *
58
+ * @module streaming/embedding-stream
59
+ * @since 2.5.0
60
+ */
61
+ /**
62
+ * Default configuration for the embedding stream
63
+ * @type {Object}
64
+ */
65
+ export const DEFAULT_CONFIG: any;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Adapts an AsyncGenerator to the Server-Sent Events protocol.
3
+ *
4
+ * Writes well-formed SSE frames to an HTTP response, manages heartbeat
5
+ * keep-alive comments, and handles client disconnects gracefully.
6
+ *
7
+ * @extends EventEmitter
8
+ *
9
+ * @example
10
+ * const adapter = new SSEAdapter({ heartbeatIntervalMs: 10000 });
11
+ * adapter.on('token', (t) => console.log('sent', t));
12
+ * await adapter.stream(asyncTokenGenerator, res);
13
+ */
14
+ export class SSEAdapter extends EventEmitter<[never]> {
15
+ /**
16
+ * @param {Object} [options] - Configuration overrides
17
+ * @param {string} [options.eventName='token'] - SSE event name for token frames
18
+ * @param {string} [options.doneEvent='[DONE]'] - Sentinel value for the final data frame
19
+ * @param {number} [options.heartbeatIntervalMs=15000] - Heartbeat interval in milliseconds
20
+ */
21
+ constructor(options?: {
22
+ eventName?: string;
23
+ doneEvent?: string;
24
+ heartbeatIntervalMs?: number;
25
+ });
26
+ config: any;
27
+ /**
28
+ * Stream tokens from an AsyncGenerator to an HTTP response as SSE.
29
+ *
30
+ * Sets the required SSE headers, starts a heartbeat timer, and iterates
31
+ * over the generator. Each yielded value should be an object with at least
32
+ * a `token` property and an optional `done` boolean.
33
+ *
34
+ * @param {AsyncGenerator<{token: string, done?: boolean}>} asyncGenerator - Token source
35
+ * @param {import('http').ServerResponse} httpResponse - Writable HTTP response
36
+ * @returns {Promise<void>} Resolves when the stream ends or the client disconnects
37
+ */
38
+ stream(asyncGenerator: AsyncGenerator<{
39
+ token: string;
40
+ done?: boolean;
41
+ }>, httpResponse: import("http").ServerResponse): Promise<void>;
42
+ /**
43
+ * Format a single SSE event string.
44
+ *
45
+ * Multi-line data is split so each line is prefixed with `data: ` as
46
+ * required by the SSE specification.
47
+ *
48
+ * @param {string} eventName - The SSE event type
49
+ * @param {*} data - Payload (will be JSON-stringified)
50
+ * @returns {string} Fully formatted SSE frame including trailing blank line
51
+ */
52
+ formatEvent(eventName: string, data: any): string;
53
+ }
54
+ /**
55
+ * Default configuration for SSE streaming
56
+ * @type {Object}
57
+ */
58
+ export const DEFAULT_CONFIG: any;
59
+ import { EventEmitter } from "events";