nexus-ai-pro 0.2.0 → 0.6.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 (193) hide show
  1. package/EXPLANATION.md +389 -0
  2. package/LICENSE +0 -0
  3. package/NEXUS.md +346 -0
  4. package/README.md +301 -1015
  5. package/assets/nexus-ai-pro-presentation.jpg +0 -0
  6. package/dist/agent/loop.d.ts +0 -0
  7. package/dist/agent/loop.js +0 -0
  8. package/dist/agent/tool.d.ts +0 -0
  9. package/dist/agent/tool.js +0 -0
  10. package/dist/cache/adapters.d.ts +0 -0
  11. package/dist/cache/adapters.js +0 -0
  12. package/dist/cache/memory-cache.d.ts +0 -0
  13. package/dist/cache/memory-cache.js +39 -1
  14. package/dist/cache/semantic-cache.d.ts +0 -0
  15. package/dist/cache/semantic-cache.js +0 -0
  16. package/dist/connectors/web.d.ts +0 -0
  17. package/dist/connectors/web.js +0 -0
  18. package/dist/context/index.d.ts +2 -0
  19. package/dist/context/index.js +1 -0
  20. package/dist/context/window.d.ts +34 -0
  21. package/dist/context/window.js +285 -0
  22. package/dist/core/nexus.d.ts +14 -0
  23. package/dist/core/nexus.js +169 -1
  24. package/dist/core/response-format.d.ts +0 -0
  25. package/dist/core/response-format.js +0 -0
  26. package/dist/core/secure-stream.d.ts +0 -0
  27. package/dist/core/secure-stream.js +0 -0
  28. package/dist/core/streaming.d.ts +0 -0
  29. package/dist/core/streaming.js +0 -0
  30. package/dist/embeddings/providers.d.ts +0 -0
  31. package/dist/embeddings/providers.js +0 -0
  32. package/dist/evals/metrics.d.ts +0 -0
  33. package/dist/evals/metrics.js +0 -0
  34. package/dist/evals/runner.d.ts +0 -0
  35. package/dist/evals/runner.js +0 -0
  36. package/dist/hallucination/consistency.d.ts +1 -0
  37. package/dist/hallucination/consistency.js +35 -4
  38. package/dist/hallucination/factual.d.ts +0 -0
  39. package/dist/hallucination/factual.js +0 -0
  40. package/dist/hallucination/knowledge-graph.d.ts +5 -1
  41. package/dist/hallucination/knowledge-graph.js +4 -2
  42. package/dist/hallucination/rag.d.ts +0 -0
  43. package/dist/hallucination/rag.js +0 -0
  44. package/dist/hallucination/retrieval.d.ts +0 -0
  45. package/dist/hallucination/retrieval.js +0 -0
  46. package/dist/hallucination/verification.d.ts +0 -0
  47. package/dist/hallucination/verification.js +0 -0
  48. package/dist/index.d.ts +6 -2
  49. package/dist/index.js +3 -1
  50. package/dist/jobs/batch.d.ts +0 -0
  51. package/dist/jobs/batch.js +0 -0
  52. package/dist/jobs/durable-adapters.d.ts +0 -0
  53. package/dist/jobs/durable-adapters.js +0 -0
  54. package/dist/jobs/queue.d.ts +0 -0
  55. package/dist/jobs/queue.js +0 -0
  56. package/dist/models/registry.d.ts +0 -0
  57. package/dist/models/registry.js +0 -0
  58. package/dist/next/route-handler.d.ts +0 -0
  59. package/dist/next/route-handler.js +0 -0
  60. package/dist/ops/audit-logger.d.ts +0 -0
  61. package/dist/ops/audit-logger.js +0 -0
  62. package/dist/ops/health.d.ts +0 -0
  63. package/dist/ops/health.js +0 -0
  64. package/dist/ops/metrics.d.ts +0 -0
  65. package/dist/ops/metrics.js +0 -0
  66. package/dist/ops/otel-tracing.d.ts +0 -0
  67. package/dist/ops/otel-tracing.js +0 -0
  68. package/dist/ops/rate-limiter.d.ts +0 -0
  69. package/dist/ops/rate-limiter.js +0 -0
  70. package/dist/optimizer/budget.d.ts +0 -0
  71. package/dist/optimizer/budget.js +0 -0
  72. package/dist/optimizer/cost.d.ts +0 -0
  73. package/dist/optimizer/cost.js +0 -0
  74. package/dist/optimizer/densifier.d.ts +0 -0
  75. package/dist/optimizer/densifier.js +0 -0
  76. package/dist/optimizer/index.d.ts +0 -0
  77. package/dist/optimizer/index.js +0 -0
  78. package/dist/pipeline/pipeline.d.ts +0 -0
  79. package/dist/pipeline/pipeline.js +0 -0
  80. package/dist/pipeline/types.d.ts +3 -1
  81. package/dist/pipeline/types.js +0 -0
  82. package/dist/providers/anthropic.d.ts +4 -1
  83. package/dist/providers/anthropic.js +106 -96
  84. package/dist/providers/base.d.ts +5 -1
  85. package/dist/providers/base.js +37 -3
  86. package/dist/providers/cohere.d.ts +0 -0
  87. package/dist/providers/cohere.js +59 -44
  88. package/dist/providers/errors.d.ts +26 -0
  89. package/dist/providers/errors.js +132 -0
  90. package/dist/providers/google.d.ts +0 -0
  91. package/dist/providers/google.js +96 -77
  92. package/dist/providers/groq.d.ts +0 -0
  93. package/dist/providers/groq.js +0 -0
  94. package/dist/providers/mistral.d.ts +0 -0
  95. package/dist/providers/mistral.js +0 -0
  96. package/dist/providers/ollama.d.ts +2 -1
  97. package/dist/providers/ollama.js +82 -64
  98. package/dist/providers/openai.d.ts +11 -1
  99. package/dist/providers/openai.js +255 -155
  100. package/dist/providers/openrouter.d.ts +0 -0
  101. package/dist/providers/openrouter.js +0 -0
  102. package/dist/providers/type-guards.d.ts +8 -0
  103. package/dist/providers/type-guards.js +33 -0
  104. package/dist/rag/file-ingestion.d.ts +0 -0
  105. package/dist/rag/file-ingestion.js +0 -0
  106. package/dist/rag/ingestion.d.ts +0 -0
  107. package/dist/rag/ingestion.js +0 -0
  108. package/dist/router/auto-router.d.ts +0 -0
  109. package/dist/router/auto-router.js +0 -0
  110. package/dist/router/failover.d.ts +3 -0
  111. package/dist/router/failover.js +75 -23
  112. package/dist/router/index.d.ts +0 -0
  113. package/dist/router/index.js +0 -0
  114. package/dist/router/rules-router.d.ts +0 -0
  115. package/dist/router/rules-router.js +0 -0
  116. package/dist/router/types.d.ts +0 -0
  117. package/dist/router/types.js +0 -0
  118. package/dist/security/index.d.ts +0 -0
  119. package/dist/security/index.js +0 -0
  120. package/dist/security/injection-calibration.d.ts +0 -0
  121. package/dist/security/injection-calibration.js +0 -0
  122. package/dist/security/injection-detector.d.ts +0 -0
  123. package/dist/security/injection-detector.js +0 -0
  124. package/dist/security/input-guard.d.ts +0 -0
  125. package/dist/security/input-guard.js +0 -0
  126. package/dist/security/output-guard.d.ts +0 -0
  127. package/dist/security/output-guard.js +0 -0
  128. package/dist/security/pii-detector.d.ts +0 -0
  129. package/dist/security/pii-detector.js +0 -0
  130. package/dist/security/policies.d.ts +0 -0
  131. package/dist/security/policies.js +0 -0
  132. package/dist/security/prompt-hardening.d.ts +0 -0
  133. package/dist/security/prompt-hardening.js +0 -0
  134. package/dist/security/schema-validator.d.ts +8 -8
  135. package/dist/security/schema-validator.js +0 -0
  136. package/dist/security/semantic-injection-classifier.d.ts +0 -0
  137. package/dist/security/semantic-injection-classifier.js +0 -0
  138. package/dist/security/upload-scanner.d.ts +0 -0
  139. package/dist/security/upload-scanner.js +0 -0
  140. package/dist/testing/provider-conformance.d.ts +6 -3
  141. package/dist/testing/provider-conformance.js +68 -11
  142. package/dist/types/agent.d.ts +0 -0
  143. package/dist/types/agent.js +0 -0
  144. package/dist/types/config.d.ts +4 -0
  145. package/dist/types/config.js +0 -0
  146. package/dist/types/context-window.d.ts +55 -0
  147. package/dist/types/context-window.js +1 -0
  148. package/dist/types/messages.d.ts +1 -0
  149. package/dist/types/messages.js +0 -0
  150. package/dist/types/optimizer.d.ts +0 -0
  151. package/dist/types/optimizer.js +0 -0
  152. package/dist/types/planning.d.ts +2 -0
  153. package/dist/types/planning.js +0 -0
  154. package/dist/types/providers.d.ts +0 -0
  155. package/dist/types/providers.js +0 -0
  156. package/dist/types/response.d.ts +2 -0
  157. package/dist/types/response.js +0 -0
  158. package/dist/types/security.d.ts +0 -0
  159. package/dist/types/security.js +0 -0
  160. package/dist/types/voice.d.ts +121 -0
  161. package/dist/types/voice.js +1 -0
  162. package/dist/utils/ids.d.ts +0 -0
  163. package/dist/utils/ids.js +0 -0
  164. package/dist/utils/logger.d.ts +0 -0
  165. package/dist/utils/logger.js +0 -0
  166. package/dist/utils/tokenizer.d.ts +0 -0
  167. package/dist/utils/tokenizer.js +0 -0
  168. package/dist/voice/errors.d.ts +8 -0
  169. package/dist/voice/errors.js +16 -0
  170. package/dist/voice/index.d.ts +3 -0
  171. package/dist/voice/index.js +2 -0
  172. package/dist/voice/manager.d.ts +21 -0
  173. package/dist/voice/manager.js +104 -0
  174. package/dist/voice/providers/openai.d.ts +29 -0
  175. package/dist/voice/providers/openai.js +248 -0
  176. package/dist/workflow/chains.d.ts +0 -0
  177. package/dist/workflow/chains.js +0 -0
  178. package/dist/workflow/domain.d.ts +0 -0
  179. package/dist/workflow/domain.js +0 -0
  180. package/examples/agent.ts +0 -0
  181. package/examples/basic.ts +0 -0
  182. package/examples/bullmq-worker.ts +0 -0
  183. package/examples/classifier-calibration.ts +0 -0
  184. package/examples/domain-workflows.ts +0 -0
  185. package/examples/feature-flags.ts +0 -0
  186. package/examples/minimal.ts +0 -0
  187. package/examples/ocr-pdf-ingestion.ts +0 -0
  188. package/examples/optimizer.ts +0 -0
  189. package/examples/otel-express.ts +0 -0
  190. package/examples/otel-node-http.ts +0 -0
  191. package/examples/persisted-vector-store.ts +0 -0
  192. package/examples/security.ts +0 -0
  193. package/package.json +25 -6
package/EXPLANATION.md ADDED
@@ -0,0 +1,389 @@
1
+ # nexus-ai-pro Explanation
2
+
3
+ `nexus-ai-pro` is a TypeScript library for building AI features without rebuilding the same provider, routing, security, cache, context, and tool plumbing in every app.
4
+
5
+ For a quick start, read [README.md](./README.md). For testing and operational checks, read [NEXUS.md](./NEXUS.md).
6
+
7
+ ## Plain-English Summary
8
+
9
+ Most AI apps begin with one provider call. Then the app grows:
10
+
11
+ - users want streaming
12
+ - teams want fallback models
13
+ - prompts need guardrails
14
+ - long chats exceed context windows
15
+ - model costs need planning
16
+ - tools need safe execution loops
17
+ - documents need RAG
18
+ - production needs metrics, retries, health checks, and test fixtures
19
+
20
+ `nexus-ai-pro` puts those pieces behind one main class: `NexusAI`.
21
+
22
+ You can use it lightly:
23
+
24
+ ```ts
25
+ const ai = new NexusAI({
26
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
27
+ routing: { mode: 'direct' },
28
+ defaultModel: 'openai/fast',
29
+ security: 'off',
30
+ tokenOptimizer: { enabled: false },
31
+ });
32
+ ```
33
+
34
+ Or you can enable the production layers you need:
35
+
36
+ ```ts
37
+ const ai = new NexusAI({
38
+ providers: {
39
+ openai: { apiKey: process.env.OPENAI_API_KEY! },
40
+ anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
41
+ google: { apiKey: process.env.GOOGLE_API_KEY! },
42
+ },
43
+ routing: { mode: 'auto', strategy: 'quality' },
44
+ security: 'standard',
45
+ contextWindow: {
46
+ strategy: 'last-messages-with-summary',
47
+ lastMessages: 10,
48
+ summary: { model: 'openai/fast', maxTokens: 600 },
49
+ },
50
+ cache: { enabled: true, strategy: 'hybrid' },
51
+ metrics: { enabled: true },
52
+ });
53
+ ```
54
+
55
+ ## Request Lifecycle
56
+
57
+ A normal `ai.complete(...)` request moves through these steps:
58
+
59
+ ```txt
60
+ request
61
+ -> pipeline hooks/custom steps
62
+ -> response-format prompt shaping
63
+ -> context-window compaction
64
+ -> token optimization
65
+ -> input security
66
+ -> routing
67
+ -> cost budget check
68
+ -> cache lookup
69
+ -> provider call with retry/failover
70
+ -> output security
71
+ -> response-format validation
72
+ -> cache write
73
+ -> final response
74
+ ```
75
+
76
+ Most layers are optional. The user chooses the tradeoff between latency, safety, cost, and observability.
77
+
78
+ ## Main Concepts
79
+
80
+ ### Providers
81
+
82
+ Provider adapters normalize request and response shapes.
83
+
84
+ Supported adapters:
85
+
86
+ - OpenAI
87
+ - Anthropic
88
+ - Google Gemini
89
+ - Ollama
90
+ - OpenRouter
91
+ - Groq
92
+ - Mistral
93
+ - Cohere
94
+
95
+ Provider SDKs are optional peer dependencies. Install only the SDKs your app uses.
96
+
97
+ ### Routing
98
+
99
+ Routing chooses a model and provider.
100
+
101
+ Modes:
102
+
103
+ - `direct`
104
+ - `auto`
105
+ - `rules`
106
+ - `hybrid`
107
+
108
+ Strategies:
109
+
110
+ - `quality`
111
+ - `cost`
112
+ - `speed`
113
+ - `privacy`
114
+
115
+ Routing can also use:
116
+
117
+ - candidate model lists
118
+ - allow and deny patterns
119
+ - required capabilities
120
+ - weighted preferences
121
+ - provider health scores
122
+
123
+ ### Context Windows
124
+
125
+ Context-window management compacts long conversations before the prompt goes to the model.
126
+
127
+ It solves the "10+ prompts and growing chat history" problem without forcing every app to write its own memory logic.
128
+
129
+ Strategies:
130
+
131
+ - keep the last N messages
132
+ - keep recent messages up to a token budget
133
+ - summarize older messages and keep recent messages
134
+ - automatically compact only when thresholds are exceeded
135
+
136
+ Example:
137
+
138
+ ```ts
139
+ contextWindow: {
140
+ strategy: 'last-messages-with-summary',
141
+ lastMessages: 8,
142
+ summary: {
143
+ model: 'openai/fast',
144
+ maxTokens: 500,
145
+ fallbackToLocal: true,
146
+ },
147
+ }
148
+ ```
149
+
150
+ Summaries can be:
151
+
152
+ - local
153
+ - generated by a configured model
154
+ - custom through a user-provided summarizer function
155
+
156
+ Metadata is exposed at:
157
+
158
+ - `response.meta.contextWindow`
159
+ - `stream done.meta.contextWindow`
160
+ - `ai.plan(...).contextWindow`
161
+
162
+ ### Token Optimizer
163
+
164
+ The token optimizer is separate from context windows.
165
+
166
+ Context windows decide which conversation history to keep. Token optimization then estimates, densifies, truncates, warns, blocks, or allows the final request.
167
+
168
+ Budget actions:
169
+
170
+ - `error`
171
+ - `truncate`
172
+ - `densify`
173
+ - `allow`
174
+
175
+ ### Security
176
+
177
+ Security runs before provider calls and after provider responses.
178
+
179
+ Input protections include:
180
+
181
+ - schema validation
182
+ - prompt-injection detection
183
+ - optional prompt-injection neutralization
184
+ - PII detection
185
+ - secret detection
186
+ - URL checks
187
+ - tool allowlists
188
+ - max input length
189
+
190
+ Output protections include:
191
+
192
+ - PII redaction
193
+ - secret redaction
194
+ - max output length
195
+ - moderation term checks
196
+ - data leakage checks
197
+ - grounding overlap checks
198
+
199
+ Security levels:
200
+
201
+ - `off`
202
+ - `basic`
203
+ - `standard`
204
+ - `strict`
205
+ - `paranoid`
206
+
207
+ These are guardrails, not a complete security boundary. Apps still need authorization, least-privilege tools, provider-side moderation where appropriate, and human review for high-risk workflows.
208
+
209
+ ### Streaming
210
+
211
+ `ai.stream(...)` normalizes provider streaming into one shape:
212
+
213
+ - `text`
214
+ - `tool_call`
215
+ - `done`
216
+ - `error`
217
+
218
+ Streaming failover can retry before any chunks have been emitted. After partial output is emitted, the stream reports an error instead of silently switching models mid-answer.
219
+
220
+ ### RAG and Verification
221
+
222
+ RAG helpers attach retrieved context to a request.
223
+
224
+ Verification helpers can check generated claims against supplied context and optionally repair unsupported answers.
225
+
226
+ Main helpers:
227
+
228
+ - `withRagContext(...)`
229
+ - `MemoryVectorStore`
230
+ - `completeVerified(...)`
231
+ - `withKnowledgeGraphContext(...)`
232
+ - `completeConsistent(...)`
233
+
234
+ The default vector store can run without an external embedding service, but production semantic search should use a real embedding provider.
235
+
236
+ ### Tools and Agents
237
+
238
+ Tools are declared with `tool(...)`.
239
+
240
+ `ai.agent(...)` can:
241
+
242
+ - choose tools
243
+ - execute tool calls
244
+ - inject tool results back into the conversation
245
+ - stop at a max iteration count
246
+ - call step callbacks
247
+
248
+ The agent loop is intentionally small. Complex agent products should still keep their own authorization and business rules outside model output.
249
+
250
+ ### Cache, Jobs, and Evals
251
+
252
+ Cache:
253
+
254
+ - exact memory cache
255
+ - semantic cache
256
+ - hybrid exact/semantic strategy
257
+ - Redis and SQLite adapter wrappers
258
+
259
+ Jobs:
260
+
261
+ - concurrency-limited batch completion
262
+ - in-memory queue
263
+ - Redis and BullMQ adapter wrappers
264
+
265
+ Evals:
266
+
267
+ - built-in eval runner
268
+ - quality metrics
269
+ - operational metrics
270
+ - RAG metrics
271
+ - safety heuristics
272
+
273
+ ## Voice Integrations
274
+
275
+ Voice is now an optional provider-neutral layer. It is deliberately split from the main runtime so text-only users do not pay for voice code.
276
+
277
+ Import choices:
278
+
279
+ - `nexus-ai-pro/voice` gives `VoiceManager`, types, and errors.
280
+ - `nexus-ai-pro/voice/openai` gives the OpenAI voice adapter.
281
+ - Custom providers can be registered without importing hosted provider adapters.
282
+
283
+ The basic operations are:
284
+
285
+ - `ai.transcribe(...)` for speech-to-text
286
+ - `ai.speak(...)` for text-to-speech
287
+ - `ai.voice(...)` for the full voice pipeline
288
+ - `registerVoiceProvider(...)` for private, local, or hosted services
289
+
290
+ The full voice turn is:
291
+
292
+ ```txt
293
+ audio/transcript
294
+ -> transcribe if needed
295
+ -> append transcript to completion messages
296
+ -> normal Nexus complete pipeline
297
+ -> speak if requested
298
+ ```
299
+
300
+ Because the completion step calls `ai.complete(...)`, it reuses routing, security, context-window compaction, token optimization, cache, retries, metrics, and tracing.
301
+
302
+ Realtime sessions are still future work. That should be added as a separate `VoiceSession` abstraction instead of forcing realtime state into normal completion streams.
303
+
304
+ ## Choosing a Setup
305
+
306
+ For a small app:
307
+
308
+ ```ts
309
+ const ai = new NexusAI({
310
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
311
+ routing: { mode: 'direct' },
312
+ defaultModel: 'openai/fast',
313
+ security: 'standard',
314
+ });
315
+ ```
316
+
317
+ For a latency-sensitive route:
318
+
319
+ ```ts
320
+ const ai = new NexusAI({
321
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
322
+ routing: { mode: 'direct' },
323
+ defaultModel: 'openai/fast',
324
+ security: 'off',
325
+ tokenOptimizer: { enabled: false },
326
+ cache: { enabled: false },
327
+ pipeline: { trace: false, includeTraceInResponse: false },
328
+ });
329
+ ```
330
+
331
+ For a production assistant:
332
+
333
+ ```ts
334
+ const ai = new NexusAI({
335
+ providers: {
336
+ openai: { apiKey: process.env.OPENAI_API_KEY! },
337
+ anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
338
+ },
339
+ routing: {
340
+ mode: 'auto',
341
+ strategy: 'quality',
342
+ fallback: { onError: ['openai/fast'] },
343
+ },
344
+ security: 'strict',
345
+ contextWindow: {
346
+ strategy: 'auto',
347
+ lastMessages: 12,
348
+ maxInputTokens: 12000,
349
+ summary: { model: 'openai/fast', maxTokens: 600 },
350
+ },
351
+ retry: { enabled: true, maxRetries: 2 },
352
+ health: { enabled: true },
353
+ metrics: { enabled: true },
354
+ });
355
+ ```
356
+
357
+ ## Important Files
358
+
359
+ - `src/core/nexus.ts` - main runtime
360
+ - `src/providers/*` - provider adapters
361
+ - `src/router/*` - routing and failover
362
+ - `src/security/*` - guardrails
363
+ - `src/context/*` - context-window management
364
+ - `src/optimizer/*` - token and cost optimization
365
+ - `src/hallucination/*` - RAG, verification, vector search, knowledge graph context
366
+ - `src/agent/*` - tools and agent loop
367
+ - `src/cache/*` - exact and semantic cache
368
+ - `src/jobs/*` - batch and queue support
369
+ - `src/evals/*` - eval runner and metrics
370
+ - `src/workflow/*` - reusable workflow templates
371
+ - `src/types/*` - public TypeScript types
372
+ - `tests/*` - unit, smoke, API, type, and conformance tests
373
+
374
+ ## Known Limitations
375
+
376
+ - Voice is documented as a roadmap, not a finished runtime.
377
+ - Audio/video preprocessing is limited.
378
+ - Provider modality support differs and may require preprocessing.
379
+ - Built-in model metadata is a routing convenience, not a pricing contract.
380
+ - Process-memory cache and queues are not enough for distributed production systems.
381
+ - Default hash embeddings are useful for tests and demos, not strong semantic search.
382
+ - NLI verification needs a specialized verifier for high-confidence entailment.
383
+ - Guardrails reduce risk but do not replace application authorization or review.
384
+
385
+ ## How To Read The Docs
386
+
387
+ - Start with `README.md` if you are using the package.
388
+ - Read this file if you want the design explained.
389
+ - Read `NEXUS.md` if you are testing, publishing, or maintaining the package.
package/LICENSE CHANGED
File without changes