nexus-ai-pro 1.6.0 → 1.7.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 (101) hide show
  1. package/API_STABILITY.md +67 -0
  2. package/CHANGELOG.md +78 -1
  3. package/README.md +225 -3
  4. package/SECURITY.md +1 -1
  5. package/dist/batch/anthropic.d.ts +26 -0
  6. package/dist/batch/anthropic.js +179 -0
  7. package/dist/batch/errors.d.ts +24 -0
  8. package/dist/batch/errors.js +46 -0
  9. package/dist/batch/index.d.ts +7 -0
  10. package/dist/batch/index.js +6 -0
  11. package/dist/batch/manager.d.ts +59 -0
  12. package/dist/batch/manager.js +275 -0
  13. package/dist/batch/mock.d.ts +41 -0
  14. package/dist/batch/mock.js +93 -0
  15. package/dist/batch/openai.d.ts +31 -0
  16. package/dist/batch/openai.js +169 -0
  17. package/dist/core/nexus.d.ts +5 -0
  18. package/dist/core/nexus.js +56 -14
  19. package/dist/embeddings/manager.js +6 -1
  20. package/dist/images/asset-stores.d.ts +127 -0
  21. package/dist/images/asset-stores.js +377 -0
  22. package/dist/images/asset-support.d.ts +107 -0
  23. package/dist/images/asset-support.js +166 -0
  24. package/dist/images/assets.d.ts +5 -85
  25. package/dist/images/assets.js +7 -166
  26. package/dist/images/index.d.ts +1 -0
  27. package/dist/images/index.js +1 -0
  28. package/dist/images/manager.d.ts +4 -1
  29. package/dist/images/manager.js +14 -2
  30. package/dist/index.d.ts +7 -0
  31. package/dist/index.js +6 -0
  32. package/dist/ops/circuit-breaker.d.ts +89 -0
  33. package/dist/ops/circuit-breaker.js +207 -0
  34. package/dist/ops/family-telemetry.d.ts +52 -0
  35. package/dist/ops/family-telemetry.js +74 -0
  36. package/dist/ops/rate-limit-adapters.d.ts +62 -0
  37. package/dist/ops/rate-limit-adapters.js +81 -0
  38. package/dist/ops/rate-limiter.d.ts +15 -1
  39. package/dist/ops/rate-limiter.js +33 -2
  40. package/dist/router/auto-router.d.ts +8 -0
  41. package/dist/router/auto-router.js +15 -1
  42. package/dist/router/index.d.ts +1 -1
  43. package/dist/router/index.js +2 -2
  44. package/dist/router/types.d.ts +7 -0
  45. package/dist/telephony/manager.d.ts +5 -1
  46. package/dist/telephony/manager.js +18 -7
  47. package/dist/types/batch.d.ts +134 -0
  48. package/dist/types/batch.js +4 -0
  49. package/dist/types/config.d.ts +9 -0
  50. package/dist/voice/manager.d.ts +5 -1
  51. package/dist/voice/manager.js +18 -7
  52. package/dist-cjs/batch/anthropic.d.ts +26 -0
  53. package/dist-cjs/batch/anthropic.js +183 -0
  54. package/dist-cjs/batch/errors.d.ts +24 -0
  55. package/dist-cjs/batch/errors.js +55 -0
  56. package/dist-cjs/batch/index.d.ts +7 -0
  57. package/dist-cjs/batch/index.js +21 -0
  58. package/dist-cjs/batch/manager.d.ts +59 -0
  59. package/dist-cjs/batch/manager.js +279 -0
  60. package/dist-cjs/batch/mock.d.ts +41 -0
  61. package/dist-cjs/batch/mock.js +97 -0
  62. package/dist-cjs/batch/openai.d.ts +31 -0
  63. package/dist-cjs/batch/openai.js +173 -0
  64. package/dist-cjs/core/nexus.d.ts +5 -0
  65. package/dist-cjs/core/nexus.js +56 -14
  66. package/dist-cjs/embeddings/manager.js +6 -1
  67. package/dist-cjs/images/asset-stores.d.ts +127 -0
  68. package/dist-cjs/images/asset-stores.js +385 -0
  69. package/dist-cjs/images/asset-support.d.ts +107 -0
  70. package/dist-cjs/images/asset-support.js +185 -0
  71. package/dist-cjs/images/assets.d.ts +5 -85
  72. package/dist-cjs/images/assets.js +40 -199
  73. package/dist-cjs/images/index.d.ts +1 -0
  74. package/dist-cjs/images/index.js +4 -1
  75. package/dist-cjs/images/manager.d.ts +4 -1
  76. package/dist-cjs/images/manager.js +14 -2
  77. package/dist-cjs/index.d.ts +7 -0
  78. package/dist-cjs/index.js +46 -27
  79. package/dist-cjs/ops/circuit-breaker.d.ts +89 -0
  80. package/dist-cjs/ops/circuit-breaker.js +211 -0
  81. package/dist-cjs/ops/family-telemetry.d.ts +52 -0
  82. package/dist-cjs/ops/family-telemetry.js +78 -0
  83. package/dist-cjs/ops/rate-limit-adapters.d.ts +62 -0
  84. package/dist-cjs/ops/rate-limit-adapters.js +86 -0
  85. package/dist-cjs/ops/rate-limiter.d.ts +15 -1
  86. package/dist-cjs/ops/rate-limiter.js +33 -2
  87. package/dist-cjs/router/auto-router.d.ts +8 -0
  88. package/dist-cjs/router/auto-router.js +15 -1
  89. package/dist-cjs/router/index.d.ts +1 -1
  90. package/dist-cjs/router/index.js +2 -2
  91. package/dist-cjs/router/types.d.ts +7 -0
  92. package/dist-cjs/telephony/manager.d.ts +5 -1
  93. package/dist-cjs/telephony/manager.js +18 -7
  94. package/dist-cjs/types/batch.d.ts +134 -0
  95. package/dist-cjs/types/batch.js +8 -0
  96. package/dist-cjs/types/config.d.ts +9 -0
  97. package/dist-cjs/voice/manager.d.ts +5 -1
  98. package/dist-cjs/voice/manager.js +18 -7
  99. package/package.json +96 -5
  100. package/NEXUS.md +0 -387
  101. package/ROADMAP.md +0 -444
package/API_STABILITY.md CHANGED
@@ -158,6 +158,73 @@ only when the client exposes `eval`; without it the compare-and-set degrades to
158
158
  that narrows but does not close the race, and that limitation is documented rather than hidden.
159
159
  Webhook delivery is best-effort and never fails the operation it describes.
160
160
 
161
+ ## Resilience API stage
162
+
163
+ `CircuitBreaker`, the `RateLimitStore` contract, `MemoryRateLimitStore`, `RedisRateLimitStore`, and
164
+ the `ops/circuit-breaker` and `ops/rate-limit-adapters` subpaths are public and follow the 1.x rules,
165
+ together with `circuitBreaker` and `rateLimit.store` in `NexusAIConfig`.
166
+
167
+ `RateLimiter.check()` keeps its synchronous signature and in-memory behavior; `checkAsync()` is the
168
+ additive store-aware path. `NexusRateLimitError` gained an optional `resetAt` and a
169
+ `retryAfterSeconds` accessor. `RouterContext` gained an optional `openCircuits`, and `Router.route()`
170
+ an optional trailing parameter, both additive.
171
+
172
+ Which provider a breaker excludes at a given moment is a runtime decision, not a compatibility
173
+ guarantee: thresholds, scoring, and the exact ordering of candidates can change in a minor release.
174
+ What is guaranteed is the state machine — closed, open after a threshold is crossed, half-open after
175
+ the cooldown, closed again only after the configured probe successes — and that routing still selects
176
+ a provider when every circuit is open rather than failing the request untried.
177
+
178
+ Breaker state is per process by design. Two workers can disagree about a provider, and neither the
179
+ breaker nor its snapshot promises cluster-wide consensus. Rate-limit counters are the opposite: they
180
+ are only shared when a store is configured, and the default in-memory counter gives each worker its
181
+ own budget.
182
+
183
+ ## Batch API stage
184
+
185
+ `BatchManager`, the `BatchProvider` contract, the OpenAI and Anthropic adapters, the deterministic
186
+ mock, and the `nexus-ai-pro/batch`, `batch/openai`, `batch/anthropic`, and `batch/mock` subpaths are
187
+ public and follow the 1.x rules, as are the normalized request, ref, state, and result shapes.
188
+
189
+ `BatchJobRef` is guaranteed to stay JSON-serializable and sufficient on its own to poll, collect, or
190
+ cancel a batch. That is what makes a persisted ref survive a restart, and narrowing it would break
191
+ every stored ref, so it requires a major release.
192
+
193
+ Two behaviors are guaranteed. Results are matched by `customId`, never by position, and a duplicate
194
+ `customId` is refused before submission. And a failed batch returns no items rather than fabricated
195
+ ones.
196
+
197
+ Provider vocabulary is not normalized beyond `BatchJobStatus`. Anthropic reports only `in_progress`
198
+ and `ended`, with the real outcome on the per-item results; that adapter maps `ended` to `completed`
199
+ and lets item errors carry the detail rather than inventing a batch-level failure. Payloads under
200
+ `raw`, provider quotas, completion windows, and the discount rate itself are provider-controlled and
201
+ may change without a major release.
202
+
203
+ ## Asset store stage
204
+
205
+ `FilesystemAssetStore`, `S3AssetStore`, the `S3LikeClient` contract, and the
206
+ `nexus-ai-pro/images/stores` subpath are public under the 1.x rules and implement the existing
207
+ `AssetStore` contract unchanged. The shared contract, errors, and validation moved to an internal
208
+ `asset-support` module and are re-exported from `images/assets`, so every existing import resolves
209
+ as before.
210
+
211
+ All three stores guarantee that a missing asset and one owned by another tenant are
212
+ indistinguishable, that stored bytes carry a SHA-256 checksum, and that a lapsed asset is unreadable
213
+ before it is purged. `S3AssetStore.purgeExpired()` lists the record prefix on every call; on a large
214
+ bucket prefer the provider lifecycle rules. Neither durable store coordinates concurrent deletes
215
+ across processes.
216
+
217
+ ## Model registry generation stage
218
+
219
+ `data/models/*.json` is the versioned source of truth in the repository, and
220
+ `scripts/generate-model-registry.mjs` emits `src/models/generated.ts` from it.
221
+
222
+ Neither is published, and neither is public API. They duplicate `KNOWN_MODELS` exactly, so shipping
223
+ them would add roughly 310KB to every install for data nothing reads. Generation is a build-time
224
+ guarantee about how the registry is maintained, not a runtime surface: the resolver continues to read
225
+ `KNOWN_MODELS`, and a test asserts the two match. Switching the resolver over is a later change, so
226
+ that introducing generation cannot alter pricing behavior in the same release.
227
+
161
228
  ## Deprecation process
162
229
 
163
230
  Deprecated APIs are marked with `@deprecated` in declarations and described in the changelog. Removals
package/CHANGELOG.md CHANGED
@@ -4,6 +4,82 @@ Notable changes to this project are recorded here. The format follows [Keep a Ch
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.7.0] - 2026-09-08
8
+
9
+ Batch economics, distributed limits, and durable assets: the rest of the theme *work that
10
+ outlives a process*. The half-price asynchronous tier is reachable, one rate-limit budget covers
11
+ every worker, a failing provider leaves routing until it recovers, generated media persists
12
+ outside the process, and every operation family reports into the same metrics and audit log.
13
+
14
+ ### Added
15
+
16
+ - **Circuit breaking.** `CircuitBreaker` consumes the same attempt signals as `ProviderHealthMonitor`
17
+ and trips routing away from a failing provider entirely, rather than merely ranking it lower. Two
18
+ independent triggers: consecutive failures, and a failure rate over a rolling window that catches a
19
+ provider failing half its calls without ever failing several in a row. After a cooldown the circuit
20
+ admits a limited number of probes; a success closes it, a failure reopens it and restarts the
21
+ cooldown. Exposed through `circuitBreaker` config, `ai.getCircuitBreakerStatus()`,
22
+ `ai.resetCircuitBreaker()`, and the `nexus-ai-pro/ops/circuit-breaker` subpath.
23
+ - **Distributed rate limiting.** A `RateLimitStore` contract with `MemoryRateLimitStore` and
24
+ `RedisRateLimitStore`, set through `rateLimit.store`, so one budget covers every worker instead of
25
+ each process getting the full limit. The Redis store does the increment and the expiry in one
26
+ atomic Lua call when the client exposes `eval`, and re-arms a missing TTL on the fallback path so a
27
+ crash between `INCR` and `PEXPIRE` cannot block a key forever. Completions and embeddings share the
28
+ limiter, so they share the budget.
29
+ - `NexusRateLimitError` now carries `resetAt` and a `retryAfterSeconds` accessor, so a gateway can
30
+ answer with a real `Retry-After` header.
31
+ - New subpaths `nexus-ai-pro/ops/circuit-breaker` and `nexus-ai-pro/ops/rate-limit-adapters`.
32
+ - **Provider batch tiers.** `BatchManager` puts OpenAI Batch and Anthropic Message Batches behind one
33
+ operation handle, reaching the roughly half-price asynchronous tier that local `runBatch()`
34
+ concurrency cannot. Results are matched by a required `customId` rather than by position, since a
35
+ batch provider does not guarantee output order; a duplicate id is refused before submission.
36
+ Polling backs off up to a configurable ceiling, an idempotency key replays instead of submitting
37
+ twice, and `resume()` collects a batch from its `BatchJobRef` alone so a restarted worker can
38
+ finish what another submitted. Ships with a deterministic `MockBatchProvider`.
39
+ - **Filesystem and S3 asset stores.** `FilesystemAssetStore` and `S3AssetStore` implement the
40
+ existing `AssetStore` contract, with tenant isolation, retention, SHA-256 checksums, and signing.
41
+ A missing asset and one owned by another tenant are indistinguishable, because a distinguishable
42
+ error leaks the existence of another tenant asset. Both write bytes and a JSON sidecar per asset
43
+ rather than a shared index, so concurrent writers do not contend and a torn write loses at most
44
+ one record. `S3LikeClient` is structural, so S3, R2, and MinIO all work without an SDK dependency.
45
+ - **Generated model registry.** `data/models/*.json` is now the versioned source of truth, and
46
+ `scripts/generate-model-registry.mjs` emits `src/models/generated.ts` from it. The generator
47
+ validates required fields, price signs, context bounds, status values, and dangling aliases;
48
+ `npm run registry:check` runs inside `npm run check` so committed data and output cannot drift.
49
+ The runtime still reads `KNOWN_MODELS`, and a test asserts the two match exactly. The generated
50
+ module and its data are build-time artifacts and are not published: they duplicate `KNOWN_MODELS`
51
+ exactly, so shipping them would add roughly 310KB to every install for data nothing reads.
52
+ - New subpaths `nexus-ai-pro/batch`, `batch/openai`, `batch/anthropic`, `batch/mock`, and
53
+ `nexus-ai-pro/images/stores`.
54
+ - **Cross-family observability.** Image, voice, and telephony operations now report into the same
55
+ metrics collector, audit log, and rate limiter as completions and embeddings, closing the gap where
56
+ an application running phone agents and image generation had observability for only part of its
57
+ spend. Metrics carry `family` and `operation` labels, and one rate-limit budget now covers every
58
+ family. `FamilyTelemetry` is exported for a family an application adds itself.
59
+
60
+ ### Changed
61
+
62
+ - `RateLimiter` gained `checkAsync()` for the store-aware path. `check()` keeps its synchronous
63
+ signature and behavior, and the runtime only awaits when a store is configured, so a request
64
+ without one pays no extra microtask.
65
+ - `ImageManager`, `VoiceManager`, and `TelephonyManager` accept an optional second constructor
66
+ argument carrying the shared observability objects. It defaults to empty, so constructing one
67
+ standalone is unchanged and simply records nothing.
68
+ - The shared asset contract, errors, and validation moved from `images/assets` to an internal
69
+ `asset-support` module so the filesystem, S3, and memory stores cannot drift on what a valid asset
70
+ is. `images/assets` re-exports all of it, so existing imports are unchanged.
71
+ - Documentation consolidated from nine files to seven. `NEXUS.md` and `EXPLANATION.md` were four
72
+ releases stale and largely restated the README; their unique content moved to `CONTRIBUTING.md`
73
+ (real-provider test setup, the public-feature checklist, the manual smoke checklist) and to a new
74
+ README "Known Limitations" section. The published package now carries only `README.md`,
75
+ `API_STABILITY.md`, `CHANGELOG.md`, `SECURITY.md`, and `LICENSE`; `ROADMAP.md` is a design proposal
76
+ and stays on GitHub.
77
+ - `SECURITY.md` no longer names a specific supported version line. It claimed `0.9.x` while 1.6.0 was
78
+ the published release, so the wording is now version-independent and cannot go stale again.
79
+ - `RouterContext` gained an optional `openCircuits`, and `Router.route()` an optional trailing
80
+ parameter. When every candidate's circuit is open the router routes anyway: that usually means a
81
+ shared dependency is down, and one attempt beats a certain failure with no attempt at all.
82
+
7
83
  ## [1.6.0] - 2026-09-03
8
84
 
9
85
  Durable operations, the first half of the theme *work that outlives a process*. Long-running work now
@@ -321,7 +397,8 @@ shared policy vocabulary is in place for a future release that revisits this.
321
397
  - URL fetching rejects unsafe private-network targets and limits response reads.
322
398
  - CLI and audit findings no longer disclose detected secret values.
323
399
 
324
- [Unreleased]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.6.0...HEAD
400
+ [Unreleased]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.7.0...HEAD
401
+ [1.7.0]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.6.0...v1.7.0
325
402
  [1.6.0]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.5.0...v1.6.0
326
403
  [1.5.0]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.4.0...v1.5.0
327
404
  [1.4.0]: https://github.com/mkhitar-abrahamyan/nexus-ai/compare/v1.3.0...v1.4.0
package/README.md CHANGED
@@ -6,8 +6,8 @@ Use the whole pipeline for production AI features, or turn pieces off when you o
6
6
 
7
7
  - NPM: https://www.npmjs.com/package/nexus-ai-pro
8
8
  - GitHub: https://github.com/mkhitar-abrahamyan/nexus-ai
9
- - Full technical notes and manual test cases: [NEXUS.md](./NEXUS.md)
10
- - Image generation status and remaining infrastructure work: [ROADMAP.md](./ROADMAP.md)
9
+ - Contributing, testing, and release procedure: [CONTRIBUTING.md](https://github.com/mkhitar-abrahamyan/nexus-ai/blob/main/CONTRIBUTING.md)
10
+ - Delivered work and what is planned next: [ROADMAP.md](https://github.com/mkhitar-abrahamyan/nexus-ai/blob/main/ROADMAP.md)
11
11
 
12
12
  ## Install
13
13
 
@@ -85,6 +85,9 @@ You can still pass a plain `NexusAIConfig` to `new NexusAI(...)` when you want f
85
85
  - add tools, agents, RAG context, evals, batch jobs, and queues
86
86
  - embed text through the same routing, caching, batching, budget, retry, and metrics as a completion
87
87
  - run long operations that survive a restart, with leases, retries, dead-lettering, and signed webhooks
88
+ - trip routing away from a failing provider, and share one rate-limit budget across workers
89
+ - reach the providers' half-price asynchronous batch tier behind one operation handle
90
+ - persist generated media to disk or S3 with tenant isolation, retention, and checksums
88
91
  - build persistent realtime voice agents with interruption, live tools, and normalized conversation state
89
92
  - keep TypeScript types around every request and response
90
93
 
@@ -418,6 +421,199 @@ const response = await ai.completeVerified(
418
421
  );
419
422
  ```
420
423
 
424
+ ## Provider Batch Tiers
425
+
426
+ Both OpenAI and Anthropic sell an asynchronous tier at roughly half price, in exchange for a
427
+ completion window measured in hours. Local `runBatch()` concurrency cannot reach it — it is a
428
+ different API. `BatchManager` puts both behind one operation handle.
429
+
430
+ ```ts
431
+ import { BatchManager } from 'nexus-ai-pro/batch';
432
+ import { OpenAIBatchProvider } from 'nexus-ai-pro/batch/openai';
433
+
434
+ const batch = new BatchManager({
435
+ providers: { openai: new OpenAIBatchProvider({ apiKey: process.env.OPENAI_API_KEY! }) },
436
+ defaultProvider: 'openai',
437
+ });
438
+
439
+ const handle = await batch.submit({
440
+ model: 'gpt-5.4-mini',
441
+ idempotencyKey: `nightly-${date}`,
442
+ items: documents.map((document) => ({
443
+ customId: document.id,
444
+ request: { model: 'gpt-5.4-mini', messages: [{ role: 'user', content: document.text }] },
445
+ })),
446
+ });
447
+
448
+ console.log(handle.id); // persist this, do not block a request on the result
449
+ ```
450
+
451
+ `customId` is required, not optional. A batch provider does not guarantee output order, and matching
452
+ results by position is exactly the bug that silently mislabels every row. Duplicates are refused
453
+ before submission for the same reason.
454
+
455
+ The handle settles when the provider finishes, which can be hours later, so treat it as a background
456
+ operation:
457
+
458
+ ```ts
459
+ const result = await handle.result();
460
+
461
+ result.status; // completed | failed | expired | cancelled
462
+ result.counts; // { total, completed, failed }
463
+ result.items; // one entry per customId, with response or error
464
+ result.cost.amount; // priced per item, then discounted at the provider's batch rate
465
+ ```
466
+
467
+ A mixed batch is normal: individual items carry their own `error` while the batch still reports
468
+ `completed`. Nothing is invented for a failed batch — `items` comes back empty rather than padded.
469
+
470
+ **Surviving a restart.** Everything after `submit` takes only a `BatchJobRef`, which is
471
+ JSON-serializable. A worker that never submitted the batch can collect it:
472
+
473
+ ```ts
474
+ const ref = { id: savedBatchId, provider: 'openai' };
475
+
476
+ await batch.status(ref); // provider-side state, without waiting
477
+ const result = await batch.resume(ref);
478
+ await batch.cancel(ref);
479
+ ```
480
+
481
+ Polling backs off from the configured interval up to `maxPollIntervalMs`, so a 24-hour batch does
482
+ not generate 2,880 polls while a fast one is still caught by the first few short intervals.
483
+
484
+ ## Asset Stores
485
+
486
+ `AssetStore` has three implementations. They share one contract, so retention, tenant isolation, and
487
+ checksums behave identically:
488
+
489
+ ```ts
490
+ import { MemoryAssetStore } from 'nexus-ai-pro/images/assets';
491
+ import { FilesystemAssetStore, S3AssetStore } from 'nexus-ai-pro/images/stores';
492
+
493
+ const store = new FilesystemAssetStore({ directory: '/var/lib/app/assets', defaultTtlSeconds: 86_400 });
494
+
495
+ const s3 = new S3AssetStore({
496
+ client, // structural: S3, R2, MinIO, or a test double
497
+ bucket: 'generated-media',
498
+ prefix: 'nexus-assets/',
499
+ });
500
+ ```
501
+
502
+ A missing asset and one owned by another tenant are **indistinguishable** — both return `undefined`
503
+ rather than a permission error, because a distinguishable error leaks the existence of another
504
+ tenant's asset.
505
+
506
+ Both durable stores write two objects per asset: the bytes, and a JSON sidecar holding the
507
+ descriptor, tenant, and expiry. A single shared index would be a write-contention point and a
508
+ corruption blast radius; per-asset sidecars let concurrent writers proceed and lose at most one
509
+ record. `purgeExpired()` is exact but costs a directory listing, so on a large S3 bucket prefer the
510
+ provider's own lifecycle rules and keep this as the fallback.
511
+
512
+ ## Model Registry Generation
513
+
514
+ The registry is generated from versioned provider data in `data/models/`, not hand-edited. The
515
+ Claude 5 reasoning bug fixed in 1.4.0 was exactly the kind of error a hand-written literal of 100+
516
+ models invites.
517
+
518
+ ```bash
519
+ npm run registry:generate # data/models/*.json -> src/models/generated.ts
520
+ npm run registry:check # fails if the committed output is stale
521
+ ```
522
+
523
+ `registry:check` runs as part of `npm run check`, so committed data and committed output cannot
524
+ drift apart. The generator validates required fields, price signs, context bounds, status values,
525
+ and that every alias points at a model that exists — a dangling alias otherwise fails only when a
526
+ request happens to use it.
527
+
528
+ The runtime still reads the hand-written `KNOWN_MODELS`; a test asserts the generated registry
529
+ matches it exactly. Swapping the runtime over is deliberately a separate change, so introducing the
530
+ generator cannot quietly alter pricing data in the same release.
531
+
532
+ `src/models/generated.ts` and `data/` are build-time artifacts and are **not** published. They
533
+ duplicate `KNOWN_MODELS` exactly, and shipping them in both builds would add roughly 310KB to every
534
+ install for data nothing reads. Both live in the repository, where a diff is what you actually want.
535
+
536
+ ## Resilience: Circuit Breaking and Distributed Limits
537
+
538
+ Health monitoring ranks a struggling provider lower. A circuit breaker is the stronger step: while a
539
+ circuit is open the provider is removed from routing entirely, so a hard-down provider stops
540
+ absorbing one failed attempt per request.
541
+
542
+ ```ts
543
+ const ai = new NexusAI({
544
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! }, anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! } },
545
+ health: { enabled: true },
546
+ circuitBreaker: {
547
+ enabled: true,
548
+ failureThreshold: 5, // consecutive failures that open the circuit
549
+ failureRateThreshold: 0.5, // or half the calls failing in the window
550
+ minimumThroughput: 10,
551
+ resetTimeoutMs: 30_000, // cooldown before a probe
552
+ halfOpenMaxCalls: 1,
553
+ onStateChange: (event) => logger.warn('circuit', event),
554
+ },
555
+ });
556
+
557
+ ai.getCircuitBreakerStatus(); // state, failure rate, retryAt per provider
558
+ ai.resetCircuitBreaker('openai');
559
+ ```
560
+
561
+ Two independent triggers, because they catch different failures. A consecutive count catches a
562
+ provider that is hard down. A failure *rate* catches one that fails half its calls without ever
563
+ failing several in a row — invisible to a consecutive counter. The rate is only considered once
564
+ `minimumThroughput` calls have been seen, since one failure out of two is not evidence of anything.
565
+
566
+ After the cooldown the circuit goes half-open and admits a limited number of probes. A successful
567
+ probe closes it; a failed probe reopens it and restarts the cooldown. If *every* circuit is open the
568
+ router routes anyway — that usually means a shared dependency is down, and one attempt beats a
569
+ certain failure with no attempt at all.
570
+
571
+ `isFailure` keeps errors that are not the provider's fault out of the calculation:
572
+
573
+ ```ts
574
+ circuitBreaker: {
575
+ enabled: true,
576
+ isFailure: (error) => !(error instanceof Error && error.name === 'AbortError'),
577
+ }
578
+ ```
579
+
580
+ **Distributed rate limiting.** The built-in limiter is process-local, which multiplies the real
581
+ limit by the number of workers. Pointing it at a shared store fixes that, and the same budget then
582
+ covers completions and embeddings alike:
583
+
584
+ ```ts
585
+ import { RedisRateLimitStore } from 'nexus-ai-pro/ops/rate-limit-adapters';
586
+
587
+ const ai = new NexusAI({
588
+ providers: { openai: { apiKey: process.env.OPENAI_API_KEY! } },
589
+ rateLimit: {
590
+ enabled: true,
591
+ maxRequests: 100,
592
+ windowMs: 60_000,
593
+ key: 'userId',
594
+ store: new RedisRateLimitStore(redis),
595
+ },
596
+ });
597
+ ```
598
+
599
+ Prefer a client exposing `eval`: the increment and the expiry then happen in one atomic round trip.
600
+ Without it the store falls back to `INCR` plus `PEXPIRE` and re-arms any missing TTL it sees, so a
601
+ crash between the two calls cannot block a key forever.
602
+
603
+ `NexusRateLimitError` carries `resetAt` and `retryAfterSeconds`, so a gateway can answer with a
604
+ real `Retry-After` header:
605
+
606
+ ```ts
607
+ catch (error) {
608
+ if (error instanceof NexusRateLimitError) {
609
+ response.setHeader('Retry-After', String(error.retryAfterSeconds ?? 60));
610
+ }
611
+ }
612
+ ```
613
+
614
+ Omitting `store` keeps the original synchronous in-memory path, which costs no extra microtask per
615
+ request.
616
+
421
617
  ## Durable Operations
422
618
 
423
619
  Long-running work — an image render, a batch, anything asynchronous — runs through one lifecycle:
@@ -427,6 +623,11 @@ covering the rest. `OperationRunner` owns it end to end, so a crashed worker doe
427
623
  The default store is in-process, so the small case needs no infrastructure:
428
624
 
429
625
  ```ts
626
+ import { BatchManager } from 'nexus-ai-pro/batch';
627
+ import { OpenAIBatchProvider } from 'nexus-ai-pro/batch/openai';
628
+ import { FilesystemAssetStore, S3AssetStore } from 'nexus-ai-pro/images/stores';
629
+ import { CircuitBreaker } from 'nexus-ai-pro/ops/circuit-breaker';
630
+ import { RedisRateLimitStore } from 'nexus-ai-pro/ops/rate-limit-adapters';
430
631
  import { OperationRunner } from 'nexus-ai-pro/operations';
431
632
 
432
633
  const runner = new OperationRunner<string>({ retry: { maxAttempts: 3, baseDelayMs: 500 } });
@@ -1385,12 +1586,33 @@ npm run test:conformance:real
1385
1586
 
1386
1587
  ## Roadmap
1387
1588
 
1589
+ See [ROADMAP.md](https://github.com/mkhitar-abrahamyan/nexus-ai/blob/main/ROADMAP.md) for what has
1590
+ shipped and what is planned. It is a design proposal, not a compatibility promise; the guarantees
1591
+ live in [API_STABILITY.md](./API_STABILITY.md).
1592
+
1388
1593
  1.4.0 closed the completion-request gap: prompt caching, reasoning controls, tool and sampling
1389
1594
  controls, structured usage with numeric cost, and capability negotiation with registry provenance.
1390
1595
 
1391
1596
  Next is durable execution — an operation state machine, provider batch APIs, distributed rate
1392
1597
  limiting and circuit breaking, first-class embeddings, and filesystem/S3 asset stores — followed by
1393
- image portability and promotion out of experimental. See [ROADMAP.md](./ROADMAP.md).
1598
+ image portability and promotion out of experimental. See
1599
+ [ROADMAP.md](https://github.com/mkhitar-abrahamyan/nexus-ai/blob/main/ROADMAP.md).
1600
+
1601
+ ## Known Limitations
1602
+
1603
+ - Voice, telephony, images, local models, and custom providers are optional layers; enable only what
1604
+ you use.
1605
+ - Audio and video preprocessing is limited, and provider modality support differs.
1606
+ - Bundled model metadata is a routing and estimation convenience, not a pricing contract.
1607
+ - Process-memory cache, queues, and asset storage are not enough for a distributed deployment; use
1608
+ the Redis, BullMQ, filesystem, or S3 adapters instead.
1609
+ - Default hash embeddings suit tests and demos, not strong semantic search. Register a real
1610
+ embedding provider for production retrieval.
1611
+ - NLI verification is an interface; bring a specialized verifier for high-confidence entailment.
1612
+ - Guardrails reduce risk but do not replace application authorization, provider-side moderation, or
1613
+ human review of high-impact actions.
1614
+ - Circuit-breaker state is per process, and realtime sessions are not yet routed through the metrics,
1615
+ audit, and rate-limit path that every other family uses.
1394
1616
 
1395
1617
  ## Production Notes
1396
1618
 
package/SECURITY.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Supported versions
4
4
 
5
- Security fixes are provided for the latest published minor release. Users should upgrade to the newest `0.9.x` patch as fixes become available.
5
+ Security fixes are provided for the latest published minor release. Upgrade to the newest patch of that line as fixes become available; older minor releases do not receive backports.
6
6
 
7
7
  ## Reporting a vulnerability
8
8
 
@@ -0,0 +1,26 @@
1
+ import type { BatchJobRef, BatchJobState, BatchOutputItem, BatchProvider, BatchProviderCallContext, BatchProviderInfo, BatchSubmitRequest } from '../types/batch.js';
2
+ export interface AnthropicBatchProviderOptions {
3
+ apiKey: string;
4
+ baseUrl?: string;
5
+ version?: string;
6
+ headers?: Record<string, string>;
7
+ fetch?: typeof fetch;
8
+ /** Applied to any item that names no model. */
9
+ defaultModel?: string;
10
+ maxTokens?: number;
11
+ }
12
+ /** Anthropic Message Batches: half price, 24-hour window. */
13
+ export declare class AnthropicBatchProvider implements BatchProvider {
14
+ private readonly options;
15
+ readonly info: BatchProviderInfo;
16
+ constructor(options: AnthropicBatchProviderOptions);
17
+ submit(request: BatchSubmitRequest, context: BatchProviderCallContext): Promise<BatchJobRef>;
18
+ poll(ref: BatchJobRef, context: BatchProviderCallContext): Promise<BatchJobState>;
19
+ results(ref: BatchJobRef, context: BatchProviderCallContext): Promise<BatchOutputItem[]>;
20
+ cancel(ref: BatchJobRef, context: BatchProviderCallContext): Promise<BatchJobState>;
21
+ private toState;
22
+ private toOutputItem;
23
+ private request;
24
+ private requestText;
25
+ private send;
26
+ }
@@ -0,0 +1,179 @@
1
+ import { buildMeta } from '../core/usage.js';
2
+ import { BatchProviderResponseError } from './errors.js';
3
+ /**
4
+ * Anthropic reports only `in_progress` and `ended` for the batch itself.
5
+ *
6
+ * `ended` covers success, cancellation, and expiry alike, so the real outcome only appears on the
7
+ * per-item results. This adapter reports `completed` on `ended` and lets the item errors carry the
8
+ * detail, rather than inventing a batch-level failure the API never stated.
9
+ */
10
+ const STATUS_MAP = {
11
+ in_progress: 'in_progress',
12
+ canceling: 'cancelling',
13
+ cancelling: 'cancelling',
14
+ ended: 'completed',
15
+ };
16
+ /** Anthropic Message Batches: half price, 24-hour window. */
17
+ export class AnthropicBatchProvider {
18
+ options;
19
+ info = {
20
+ name: 'anthropic',
21
+ capabilities: {
22
+ maxItems: 100_000,
23
+ maxBytes: 256 * 1024 * 1024,
24
+ completionWindows: ['24h'],
25
+ supportsCancel: true,
26
+ discount: 0.5,
27
+ },
28
+ };
29
+ constructor(options) {
30
+ this.options = options;
31
+ }
32
+ async submit(request, context) {
33
+ const requests = request.items.map((item) => {
34
+ const { system, messages } = splitSystem(item.request.messages);
35
+ return {
36
+ custom_id: item.customId,
37
+ params: {
38
+ model: item.request.model || request.model || this.options.defaultModel,
39
+ max_tokens: item.request.maxTokens ?? this.options.maxTokens ?? 1024,
40
+ temperature: item.request.temperature,
41
+ system,
42
+ messages,
43
+ },
44
+ };
45
+ });
46
+ const batch = (await this.request('/messages/batches', { method: 'POST', body: JSON.stringify({ requests }) }, context));
47
+ if (!batch.id)
48
+ throw new BatchProviderResponseError('anthropic', 'the batch response returned no id');
49
+ return { id: batch.id, provider: 'anthropic' };
50
+ }
51
+ async poll(ref, context) {
52
+ const batch = (await this.request(`/messages/batches/${encodeURIComponent(ref.id)}`, {}, context));
53
+ return this.toState(ref, batch);
54
+ }
55
+ async results(ref, context) {
56
+ const body = await this.requestText(`/messages/batches/${encodeURIComponent(ref.id)}/results`, context);
57
+ return body
58
+ .split('\n')
59
+ .filter((line) => line.trim().length > 0)
60
+ .map((line) => this.toOutputItem(line));
61
+ }
62
+ async cancel(ref, context) {
63
+ const batch = (await this.request(`/messages/batches/${encodeURIComponent(ref.id)}/cancel`, { method: 'POST' }, context));
64
+ return this.toState(ref, batch);
65
+ }
66
+ toState(ref, batch) {
67
+ const counts = batch.request_counts;
68
+ return {
69
+ ref,
70
+ status: STATUS_MAP[batch.processing_status ?? ''] ?? 'in_progress',
71
+ counts: counts
72
+ ? {
73
+ total: (counts.processing ?? 0) +
74
+ (counts.succeeded ?? 0) +
75
+ (counts.errored ?? 0) +
76
+ (counts.canceled ?? 0) +
77
+ (counts.expired ?? 0),
78
+ completed: counts.succeeded ?? 0,
79
+ failed: (counts.errored ?? 0) + (counts.canceled ?? 0) + (counts.expired ?? 0),
80
+ }
81
+ : undefined,
82
+ createdAt: batch.created_at,
83
+ completedAt: batch.ended_at,
84
+ expiresAt: batch.expires_at,
85
+ raw: batch,
86
+ };
87
+ }
88
+ toOutputItem(line) {
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(line);
92
+ }
93
+ catch (error) {
94
+ throw new BatchProviderResponseError('anthropic', 'a result line was not valid JSON', error);
95
+ }
96
+ const customId = parsed.custom_id ?? '';
97
+ const result = parsed.result;
98
+ if (result?.type !== 'succeeded' || !result.message) {
99
+ return {
100
+ customId,
101
+ error: {
102
+ message: result?.error?.message ?? `batch item ${result?.type ?? 'failed'}`,
103
+ code: result?.error?.type ?? result?.type,
104
+ },
105
+ };
106
+ }
107
+ const message = result.message;
108
+ const content = (message.content ?? [])
109
+ .filter((part) => part.type === 'text')
110
+ .map((part) => part.text ?? '')
111
+ .join('');
112
+ const response = {
113
+ content,
114
+ role: 'assistant',
115
+ finishReason: message.stop_reason === 'max_tokens' ? 'length' : 'stop',
116
+ meta: buildMeta({
117
+ provider: 'anthropic',
118
+ model: message.model ?? '',
119
+ latencyMs: 0,
120
+ inputTokens: message.usage?.input_tokens,
121
+ outputTokens: message.usage?.output_tokens,
122
+ cachedReadTokens: message.usage?.cache_read_input_tokens,
123
+ }),
124
+ };
125
+ return { customId, response };
126
+ }
127
+ async request(path, init, context) {
128
+ const response = await this.send(path, init, context);
129
+ return response.json();
130
+ }
131
+ async requestText(path, context) {
132
+ const response = await this.send(path, {}, context);
133
+ return response.text();
134
+ }
135
+ async send(path, init, context) {
136
+ const fetchImpl = this.options.fetch ?? fetch;
137
+ const baseUrl = (this.options.baseUrl || 'https://api.anthropic.com/v1').replace(/\/$/, '');
138
+ const response = await fetchImpl(`${baseUrl}${path}`, {
139
+ ...init,
140
+ headers: {
141
+ 'x-api-key': this.options.apiKey,
142
+ 'anthropic-version': this.options.version ?? '2023-06-01',
143
+ 'content-type': 'application/json',
144
+ ...this.options.headers,
145
+ ...(init.headers ?? {}),
146
+ },
147
+ signal: context.signal,
148
+ });
149
+ if (!response.ok) {
150
+ throw new BatchProviderResponseError('anthropic', `${path} failed: ${response.status} ${await safeText(response)}`);
151
+ }
152
+ return response;
153
+ }
154
+ }
155
+ /**
156
+ * Anthropic takes the system prompt as a top-level field rather than a message.
157
+ *
158
+ * Splitting it here keeps the neutral request shape unchanged for callers, who write a system
159
+ * message like every other provider.
160
+ */
161
+ function splitSystem(messages) {
162
+ const system = messages
163
+ .filter((message) => message.role === 'system')
164
+ .map((message) => (typeof message.content === 'string' ? message.content : ''))
165
+ .join('\n')
166
+ .trim();
167
+ return {
168
+ system: system || undefined,
169
+ messages: messages.filter((message) => message.role !== 'system'),
170
+ };
171
+ }
172
+ async function safeText(response) {
173
+ try {
174
+ return (await response.text()).slice(0, 500);
175
+ }
176
+ catch {
177
+ return '';
178
+ }
179
+ }