@rudderjs/ai 1.5.0 → 1.6.1

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 (163) hide show
  1. package/README.md +482 -4
  2. package/boost/guidelines.md +60 -0
  3. package/boost/skills/ai-agents/SKILL.md +7 -0
  4. package/boost/skills/ai-tools/SKILL.md +7 -0
  5. package/dist/agent.d.ts +35 -1
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +118 -16
  8. package/dist/agent.js.map +1 -1
  9. package/dist/budget/pricing.d.ts +124 -0
  10. package/dist/budget/pricing.d.ts.map +1 -0
  11. package/dist/budget/pricing.js +175 -0
  12. package/dist/budget/pricing.js.map +1 -0
  13. package/dist/budget/storage.d.ts +104 -0
  14. package/dist/budget/storage.d.ts.map +1 -0
  15. package/dist/budget/storage.js +0 -0
  16. package/dist/budget/storage.js.map +1 -0
  17. package/dist/budget/with-budget.d.ts +119 -0
  18. package/dist/budget/with-budget.d.ts.map +1 -0
  19. package/dist/budget/with-budget.js +175 -0
  20. package/dist/budget/with-budget.js.map +1 -0
  21. package/dist/budget-orm/index.d.ts +96 -0
  22. package/dist/budget-orm/index.d.ts.map +1 -0
  23. package/dist/budget-orm/index.js +177 -0
  24. package/dist/budget-orm/index.js.map +1 -0
  25. package/dist/commands/ai-eval.d.ts +93 -0
  26. package/dist/commands/ai-eval.d.ts.map +1 -0
  27. package/dist/commands/ai-eval.js +378 -0
  28. package/dist/commands/ai-eval.js.map +1 -0
  29. package/dist/computer-use/actions.d.ts +214 -0
  30. package/dist/computer-use/actions.d.ts.map +1 -0
  31. package/dist/computer-use/actions.js +48 -0
  32. package/dist/computer-use/actions.js.map +1 -0
  33. package/dist/computer-use/errors.d.ts +57 -0
  34. package/dist/computer-use/errors.d.ts.map +1 -0
  35. package/dist/computer-use/errors.js +76 -0
  36. package/dist/computer-use/errors.js.map +1 -0
  37. package/dist/computer-use/index.d.ts +53 -0
  38. package/dist/computer-use/index.d.ts.map +1 -0
  39. package/dist/computer-use/index.js +51 -0
  40. package/dist/computer-use/index.js.map +1 -0
  41. package/dist/computer-use/playwright.d.ts +76 -0
  42. package/dist/computer-use/playwright.d.ts.map +1 -0
  43. package/dist/computer-use/playwright.js +270 -0
  44. package/dist/computer-use/playwright.js.map +1 -0
  45. package/dist/computer-use/tool.d.ts +154 -0
  46. package/dist/computer-use/tool.d.ts.map +1 -0
  47. package/dist/computer-use/tool.js +210 -0
  48. package/dist/computer-use/tool.js.map +1 -0
  49. package/dist/eval/fixtures.d.ts +65 -0
  50. package/dist/eval/fixtures.d.ts.map +1 -0
  51. package/dist/eval/fixtures.js +110 -0
  52. package/dist/eval/fixtures.js.map +1 -0
  53. package/dist/eval/html-reporter.d.ts +25 -0
  54. package/dist/eval/html-reporter.d.ts.map +1 -0
  55. package/dist/eval/html-reporter.js +209 -0
  56. package/dist/eval/html-reporter.js.map +1 -0
  57. package/dist/eval/index.d.ts +271 -0
  58. package/dist/eval/index.d.ts.map +1 -0
  59. package/dist/eval/index.js +510 -0
  60. package/dist/eval/index.js.map +1 -0
  61. package/dist/eval/json-reporter.d.ts +43 -0
  62. package/dist/eval/json-reporter.d.ts.map +1 -0
  63. package/dist/eval/json-reporter.js +40 -0
  64. package/dist/eval/json-reporter.js.map +1 -0
  65. package/dist/fake.d.ts +36 -1
  66. package/dist/fake.d.ts.map +1 -1
  67. package/dist/fake.js +49 -2
  68. package/dist/fake.js.map +1 -1
  69. package/dist/file-search.d.ts +168 -0
  70. package/dist/file-search.d.ts.map +1 -0
  71. package/dist/file-search.js +158 -0
  72. package/dist/file-search.js.map +1 -0
  73. package/dist/index.d.ts +22 -2
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +17 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/mcp/client-tools.d.ts +39 -0
  78. package/dist/mcp/client-tools.d.ts.map +1 -0
  79. package/dist/mcp/client-tools.js +147 -0
  80. package/dist/mcp/client-tools.js.map +1 -0
  81. package/dist/mcp/index.d.ts +16 -0
  82. package/dist/mcp/index.d.ts.map +1 -0
  83. package/dist/mcp/index.js +15 -0
  84. package/dist/mcp/index.js.map +1 -0
  85. package/dist/mcp/server-from-agent.d.ts +24 -0
  86. package/dist/mcp/server-from-agent.d.ts.map +1 -0
  87. package/dist/mcp/server-from-agent.js +113 -0
  88. package/dist/mcp/server-from-agent.js.map +1 -0
  89. package/dist/mcp/types.d.ts +64 -0
  90. package/dist/mcp/types.d.ts.map +1 -0
  91. package/dist/mcp/types.js +6 -0
  92. package/dist/mcp/types.js.map +1 -0
  93. package/dist/memory-embedding/index.d.ts +121 -0
  94. package/dist/memory-embedding/index.d.ts.map +1 -0
  95. package/dist/memory-embedding/index.js +229 -0
  96. package/dist/memory-embedding/index.js.map +1 -0
  97. package/dist/memory-extract.d.ts +60 -0
  98. package/dist/memory-extract.d.ts.map +1 -0
  99. package/dist/memory-extract.js +163 -0
  100. package/dist/memory-extract.js.map +1 -0
  101. package/dist/memory-inject.d.ts +39 -0
  102. package/dist/memory-inject.d.ts.map +1 -0
  103. package/dist/memory-inject.js +135 -0
  104. package/dist/memory-inject.js.map +1 -0
  105. package/dist/memory-orm/index.d.ts +118 -0
  106. package/dist/memory-orm/index.d.ts.map +1 -0
  107. package/dist/memory-orm/index.js +187 -0
  108. package/dist/memory-orm/index.js.map +1 -0
  109. package/dist/memory.d.ts +55 -0
  110. package/dist/memory.d.ts.map +1 -0
  111. package/dist/memory.js +132 -0
  112. package/dist/memory.js.map +1 -0
  113. package/dist/observers.d.ts +22 -0
  114. package/dist/observers.d.ts.map +1 -1
  115. package/dist/observers.js.map +1 -1
  116. package/dist/provider-tools.d.ts +15 -1
  117. package/dist/provider-tools.d.ts.map +1 -1
  118. package/dist/provider-tools.js +21 -1
  119. package/dist/provider-tools.js.map +1 -1
  120. package/dist/providers/anthropic.d.ts.map +1 -1
  121. package/dist/providers/anthropic.js +61 -6
  122. package/dist/providers/anthropic.js.map +1 -1
  123. package/dist/providers/elevenlabs.d.ts +98 -0
  124. package/dist/providers/elevenlabs.d.ts.map +1 -0
  125. package/dist/providers/elevenlabs.js +229 -0
  126. package/dist/providers/elevenlabs.js.map +1 -0
  127. package/dist/providers/google.d.ts +83 -1
  128. package/dist/providers/google.d.ts.map +1 -1
  129. package/dist/providers/google.js +491 -8
  130. package/dist/providers/google.js.map +1 -1
  131. package/dist/providers/openai.d.ts +3 -1
  132. package/dist/providers/openai.d.ts.map +1 -1
  133. package/dist/providers/openai.js +209 -5
  134. package/dist/providers/openai.js.map +1 -1
  135. package/dist/providers/voyage.d.ts +91 -0
  136. package/dist/providers/voyage.d.ts.map +1 -0
  137. package/dist/providers/voyage.js +166 -0
  138. package/dist/providers/voyage.js.map +1 -0
  139. package/dist/queue-job.d.ts +69 -4
  140. package/dist/queue-job.d.ts.map +1 -1
  141. package/dist/queue-job.js +114 -11
  142. package/dist/queue-job.js.map +1 -1
  143. package/dist/registry.d.ts +3 -1
  144. package/dist/registry.d.ts.map +1 -1
  145. package/dist/registry.js +10 -0
  146. package/dist/registry.js.map +1 -1
  147. package/dist/server/provider.d.ts.map +1 -1
  148. package/dist/server/provider.js +23 -1
  149. package/dist/server/provider.js.map +1 -1
  150. package/dist/similarity-search.d.ts +163 -0
  151. package/dist/similarity-search.d.ts.map +1 -0
  152. package/dist/similarity-search.js +147 -0
  153. package/dist/similarity-search.js.map +1 -0
  154. package/dist/tool.d.ts.map +1 -1
  155. package/dist/tool.js +13 -4
  156. package/dist/tool.js.map +1 -1
  157. package/dist/types.d.ts +246 -0
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/vector-stores/index.d.ts +96 -0
  160. package/dist/vector-stores/index.d.ts.map +1 -0
  161. package/dist/vector-stores/index.js +153 -0
  162. package/dist/vector-stores/index.js.map +1 -0
  163. package/package.json +41 -3
package/README.md CHANGED
@@ -16,7 +16,9 @@ pnpm add openai # OpenAI (GPT) — also used for OpenRou
16
16
  pnpm add @google/genai # Google (Gemini)
17
17
  pnpm add cohere-ai # Cohere (reranking + embeddings)
18
18
  pnpm add @aws-sdk/client-bedrock-runtime # AWS Bedrock
19
- # Jina — no extra package needed
19
+ # ElevenLabs (premium TTS + STT) — no extra package needed (direct HTTP)
20
+ # VoyageAI (embeddings + reranking) — no extra package needed (direct HTTP)
21
+ # Jina — no extra package needed (direct HTTP)
20
22
  ```
21
23
 
22
24
  ## Runtime Compatibility
@@ -28,6 +30,12 @@ pnpm add @aws-sdk/client-bedrock-runtime # AWS Bedrock
28
30
  | `@rudderjs/ai` | Node, browser, Electron main+renderer, React Native | Agents, tools, streaming, providers — any `fetch`-capable JS runtime |
29
31
  | `@rudderjs/ai/node` | Node only | `documentFromPath()`, `imageFromPath()`, `transcribeFromPath()` (filesystem helpers) |
30
32
  | `@rudderjs/ai/server` | Node only | `AiProvider` (the RudderJS `ServiceProvider` — auto-discovered, you rarely import it) |
33
+ | `@rudderjs/ai/mcp` | Node only (in practice) | `mcpClientTools()` + `mcpServerFromAgent()` — requires `@modelcontextprotocol/sdk` |
34
+ | `@rudderjs/ai/memory-orm` | Node only | `OrmUserMemory` + `UserMemoryRecord` — ORM-backed `UserMemory` |
35
+ | `@rudderjs/ai/memory-embedding` | Node only | `EmbeddingUserMemory` — semantic recall via the registered embedding model |
36
+ | `@rudderjs/ai/budget-orm` | Node only | `OrmBudgetStorage` + `BudgetUsageRecord` — ORM-backed `BudgetStorage` |
37
+ | `@rudderjs/ai/eval` | Any `fetch`-capable runtime | `evalSuite()` + `runSuite()` + metrics for testing agents against real models |
38
+ | `@rudderjs/ai/computer-use` | Node only (in practice) | `executeComputerAction(page, action, state)` — lower-level Playwright dispatcher |
31
39
 
32
40
  The main entry has zero `node:*` static imports, so you can call agents and tools directly from a React Native screen, an Electron renderer, or a browser. `@rudderjs/core` is an optional peer — only `/server` consumers pull it in.
33
41
 
@@ -46,6 +54,8 @@ export default {
46
54
  ollama: { driver: 'ollama', baseUrl: 'http://localhost:11434' },
47
55
  cohere: { driver: 'cohere', apiKey: process.env.COHERE_API_KEY! },
48
56
  jina: { driver: 'jina', apiKey: process.env.JINA_API_KEY! },
57
+ voyage: { driver: 'voyage', apiKey: process.env.VOYAGE_API_KEY! }, // embeddings + reranking
58
+ elevenlabs:{ driver: 'elevenlabs', apiKey: process.env.ELEVENLABS_API_KEY! }, // premium TTS + STT
49
59
  openrouter: {
50
60
  driver: 'openrouter',
51
61
  apiKey: process.env.OPENROUTER_API_KEY!,
@@ -60,11 +70,10 @@ export default {
60
70
  },
61
71
  }
62
72
 
63
- // bootstrap/providers.ts
64
- import { AiProvider } from '@rudderjs/ai/server'
65
- export default [AiProvider]
66
73
  ```
67
74
 
75
+ `AiProvider` is picked up by [auto-discovery](https://github.com/rudderjs/rudder/blob/main/docs/guide/service-providers.md#auto-discovery) — `pnpm rudder providers:discover` is all that's needed. The class lives at `@rudderjs/ai/server` (the main entry is runtime-agnostic); auto-discovery reads `rudderjs.providerSubpath` and loads it for you.
76
+
68
77
  ## Usage
69
78
 
70
79
  ### Agent Class
@@ -573,6 +582,68 @@ const agent = AI.agent({
573
582
  })
574
583
  ```
575
584
 
585
+ ### Computer Use (Anthropic)
586
+
587
+ `computerUseTool({ page })` exposes a Playwright `Page` to an Anthropic Claude model via the native `computer_20250124` tool block — the model takes screenshots, moves the cursor, clicks, types, scrolls, presses keys. Anthropic-only (`anthropic/*` and `bedrock/anthropic.*`); OpenRouter-routed Anthropic models throw `ComputerUseProviderError`.
588
+
589
+ ```ts
590
+ import { chromium } from 'playwright'
591
+ import { Agent, computerUseTool } from '@rudderjs/ai'
592
+
593
+ const browser = await chromium.launch()
594
+ const page = await browser.newPage({ viewport: { width: 1280, height: 800 } })
595
+
596
+ class BrowserAgent extends Agent {
597
+ model() { return 'anthropic/claude-sonnet-4-5' }
598
+ tools() {
599
+ return [
600
+ computerUseTool({
601
+ page,
602
+ viewport: { width: 1280, height: 800 },
603
+ needsApproval: true, // default — pauses the loop before every action
604
+ maxActions: 50, // per-instance safety cap; throws ComputerUseLimitError when exceeded
605
+ }),
606
+ ]
607
+ }
608
+ }
609
+
610
+ await new BrowserAgent().prompt('Find the cheapest flight from SFO to JFK next Tuesday.')
611
+ ```
612
+
613
+ Playwright is **not** a dep of `@rudderjs/ai` — install it in your app. The tool accepts a structural `PageLike` subset so types check without the 300MB Playwright bundle. Action failures surface as `is_error: true` tool-results so the model can retry. `needsApproval: true` (the default) routes every action through the standard approval gate — review what the model wants to click before it clicks it.
614
+
615
+ ### Hosted vector stores + `fileSearch`
616
+
617
+ `VectorStores` is a CRUD façade over the provider's hosted vector store; `fileSearch({ stores })` is the agent tool that queries them. The provider runs ingestion, chunking, embedding, and retrieval server-side — no embedding pipeline, no pgvector setup, no `execute` to write. Supported on **OpenAI** (`vectorStores.*`) and **Gemini** (`fileSearchStores`). Same façade, same agent surface.
618
+
619
+ ```ts
620
+ import { Agent, VectorStores, fileSearch } from '@rudderjs/ai'
621
+
622
+ // 1. Manage the store
623
+ const kb = await VectorStores.create('Knowledge Base') // OpenAI default
624
+ await kb.add({ filePath: './report.pdf', attributes: { author: 'Alice', year: 2026 } })
625
+
626
+ // 2. Use it as an agent tool
627
+ class SupportAgent extends Agent {
628
+ model() { return 'openai/gpt-4o' } // or 'google/gemini-2.5-flash'
629
+ tools() {
630
+ return [
631
+ fileSearch({
632
+ stores: [kb.id],
633
+ where: { author: 'Alice', year: 2026 }, // server-side metadata filter
634
+ maxResults: 10,
635
+ }),
636
+ ]
637
+ }
638
+ }
639
+ ```
640
+
641
+ **Provider override:** pass `{ provider: 'google' }` to `VectorStores.create(...)` for Gemini. Store ids are full resource paths (`fileSearchStores/foo-bar`) on Gemini, opaque (`vs_abc123`) on OpenAI — apps pass them back verbatim through the same `VectorStores` API.
642
+
643
+ **Self-hosted RAG fallback.** `fileSearch({ ..., fallback: { model, column, embedWith } })` lifts a `similaritySearch` `execute` onto the tool. Providers that recognize the file-search hint (OpenAI, Gemini) still emit their native block; other providers serialize the tool as a function-call and run the fallback against a local pgvector model. Same agent prompt across hosted and self-hosted RAG.
644
+
645
+ Full surface (provider-differences table, `where`/filter shapes, testing with `AiFake`): the framework's [Vector Stores guide](https://github.com/rudderjs/rudder/blob/main/docs/guide/vector-stores.md).
646
+
576
647
  ### Reranking
577
648
 
578
649
  Reorder documents by relevance to a query — useful for RAG pipelines:
@@ -664,6 +735,54 @@ for await (const chunk of stream) {
664
735
  const final = await response // full AgentResponse when stream completes
665
736
  ```
666
737
 
738
+ ### Queued prompts (`agent.queue()`)
739
+
740
+ Push the agent run onto the queue for background execution. Returns a builder so you can configure the queue, attach success/failure callbacks, and (optionally) stream progress to a broadcast channel as it runs.
741
+
742
+ Requires `@rudderjs/queue` (and `@rudderjs/broadcast` if you call `.broadcast()`).
743
+
744
+ ```ts
745
+ // Fire-and-forget background run
746
+ await new SupportAgent()
747
+ .queue('Help with refund request')
748
+ .onQueue('ai')
749
+ .send()
750
+
751
+ // With success/failure callbacks
752
+ await new ResearchAgent()
753
+ .queue('Research GPT-5 architecture')
754
+ .then(response => console.log('Done:', response.text))
755
+ .catch(error => console.error('Failed:', error))
756
+ .send()
757
+ ```
758
+
759
+ #### Stream progress to a broadcast channel — `.broadcast(channel)`
760
+
761
+ Background AI work + live UI without polling. Each stream chunk is broadcast to the channel as the job runs; the final response is broadcast as a `done` event:
762
+
763
+ ```ts
764
+ await new SupportAgent()
765
+ .queue('Help with refund request')
766
+ .broadcast(`user.${userId}.support`)
767
+ .send()
768
+
769
+ // Subscribers on `user.${userId}.support` receive:
770
+ // { event: 'chunk', data: <StreamChunk> } // one per stream chunk (text-delta, tool-call, ...)
771
+ // { event: 'done', data: <AgentResponse> } // final result, after the loop ends
772
+ // { event: 'error', data: { message } } // on failure
773
+ ```
774
+
775
+ The wire shape matches the framework's normal `StreamChunk` types — the same `text-delta` / `tool-call` / `tool-result` shapes you'd iterate from `agent.stream()`. Frontends can subscribe to the channel and reuse their existing chunk-handling code.
776
+
777
+ Pass `eventPrefix` to namespace events when the channel carries other unrelated messages:
778
+
779
+ ```ts
780
+ .broadcast('shared-channel', { eventPrefix: 'agent.' })
781
+ // emits 'agent.chunk', 'agent.done', 'agent.error'
782
+ ```
783
+
784
+ **Process model:** `@rudderjs/broadcast`'s `broadcast()` writes to the WS server in the same process. In the typical RudderJS dev setup (single process running both web + `queue:work`) this works out of the box. Production deployments that run the queue worker as a separate process from the broadcast WS server will need a pub/sub bridge (Redis, Reverb, etc.) — outside the scope of v1.
785
+
667
786
  ### Conversation History
668
787
 
669
788
  Pass message history to maintain context across turns:
@@ -694,6 +813,152 @@ await new ChatAgent().prompt('Continue?') // resumes same thread (per user + cl
694
813
 
695
814
  Returning `false` (the default) keeps the agent stateless. Async returns are awaited; an optional `historyLimit` caps loaded messages. Per-call escape hatches: `prompt(input, { conversation: false })` or `agent.forUser(id).prompt()` / `agent.continue(id).prompt()` — explicit always wins. See `docs/guide/ai.md` for the full precedence chain.
696
815
 
816
+ ### User memory beyond conversation history (Mem0-style)
817
+
818
+ Conversation history persists messages; user memory persists **facts** that should travel across conversations. Useful when the agent needs to remember "Alice's project is named Foo" in a brand-new thread without replaying the entire prior session.
819
+
820
+ ```ts
821
+ import type { UserMemory } from '@rudderjs/ai'
822
+ import { MemoryUserMemory } from '@rudderjs/ai'
823
+
824
+ // config/ai.ts — wire a backend
825
+ export default {
826
+ default: 'anthropic/claude-sonnet-4-5',
827
+ providers: { /* ... */ },
828
+ memory: new MemoryUserMemory(), // in-process; swap for an ORM- or embedding-backed store in production
829
+ } satisfies AiConfig
830
+
831
+ // Use it directly
832
+ const memory = app().make<UserMemory>('ai.memory')
833
+ await memory.remember('user_123', 'Project name is Foo', { tags: ['project'] })
834
+ const facts = await memory.recall('user_123', 'project')
835
+ //=> [{ fact: 'Project name is Foo', tags: ['project'], ... }]
836
+ ```
837
+
838
+ Or declare on an agent class to opt into auto-inject — relevant facts get prepended to the system prompt before each turn, with no plumbing on the caller's side:
839
+
840
+ ```ts
841
+ class SupportAgent extends Agent {
842
+ remembers() {
843
+ return {
844
+ user: ctx.user.id,
845
+ inject: 'auto', // recall + prepend matching facts before each model call
846
+ tags: ['support'], // recall scope
847
+ injectLimit: 5, // cap facts per turn
848
+ injectTokenBudget: 400, // hard token cap; lowest-score facts drop first
849
+ }
850
+ }
851
+ }
852
+
853
+ await new SupportAgent().prompt('Where is my project deployed?')
854
+ // system prompt sent to the model:
855
+ // "You are a support agent.\n\n
856
+ // <user-memory>\n
857
+ // - Project Foo deploys to fly.io us-east\n
858
+ // - …\n
859
+ // </user-memory>"
860
+ ```
861
+
862
+ The auto-cascade runs in `Agent.prompt` / `Agent.stream`, before conversation persistence. `withMemoryInject(spec)` is also exported so you can drop it into `agent.middleware()` manually if you want full control.
863
+
864
+ **Continuation note:** when you pass `options.messages` (e.g. resuming after a client-tool round-trip), both auto-inject and auto-extract are skipped — the system prompt was already augmented on the original turn, and re-extracting would write the same facts twice.
865
+
866
+ #### Auto-extract — distill facts from each turn
867
+
868
+ Set `extract: 'auto'` (and an `extractWith` model) and a small model is asked to pull durable facts from each successful turn:
869
+
870
+ ```ts
871
+ class SupportAgent extends Agent {
872
+ remembers() {
873
+ return {
874
+ user: ctx.user.id,
875
+ inject: 'auto',
876
+ extract: 'auto',
877
+ extractWith: 'anthropic/claude-haiku-4-5', // small model for fact distillation
878
+ tags: ['support'],
879
+ }
880
+ }
881
+ }
882
+
883
+ await new SupportAgent().prompt('hey, my project is named Foo and lives at /var/www/foo')
884
+ // On success, the small model is asked to distill durable facts. Survivors above
885
+ // the confidence threshold (default 0.7) get written via `mem.remember()`:
886
+ // - "Project name is Foo" (score ~0.95, tags: ['support', 'project'])
887
+ ```
888
+
889
+ Failures (network, JSON parse, schema mismatch, store write) route through `MemoryExtractOptions.onError` and never break the parent run. Failed parent runs do NOT trigger extract.
890
+
891
+ **Poisoning mitigation** — auto-extraction trusts the user's own conversation as input. The default 0.7 confidence threshold is the v1 defense against adversarial "facts." Pair with `MemoryExtractOptions.onExtracted` for an audit log when shipping to production, and tighten the threshold for high-risk domains.
892
+
893
+ #### Production backend — `OrmUserMemory`
894
+
895
+ For production, swap `MemoryUserMemory` for `OrmUserMemory` (subpath `@rudderjs/ai/memory-orm`) — persists rows via your registered `@rudderjs/orm` adapter (Prisma today; Drizzle once you wire the tables):
896
+
897
+ ```ts
898
+ // config/ai.ts
899
+ import type { AiConfig } from '@rudderjs/ai'
900
+ import { OrmUserMemory } from '@rudderjs/ai/memory-orm'
901
+
902
+ export default {
903
+ default: 'anthropic/claude-sonnet-4-5',
904
+ providers: { /* ... */ },
905
+ memory: new OrmUserMemory(),
906
+ } satisfies AiConfig
907
+ ```
908
+
909
+ Add the schema to your Prisma file (or import the reference string `userMemoryPrismaSchema` from `@rudderjs/ai/memory-orm`):
910
+
911
+ ```prisma
912
+ model UserMemory {
913
+ id String @id @default(cuid())
914
+ userId String
915
+ fact String
916
+ /// JSON-encoded `string[]` of tags, or null
917
+ tags String?
918
+ /// Confidence score in [0, 1] — extract sets this from the model's self-rating
919
+ score Float?
920
+ /// Phase 5 — vector embedding for cosine recall (nullable so Phase 4 ignores it)
921
+ embedding Bytes?
922
+ createdAt DateTime @default(now())
923
+ updatedAt DateTime @updatedAt
924
+
925
+ @@index([userId])
926
+ }
927
+ ```
928
+
929
+ Then run `pnpm exec prisma db push` (dev) or `pnpm exec prisma migrate dev` (prod). The `embedding Bytes?` column is intentionally nullable — Phase 5's `EmbeddingUserMemory` populates it without forcing a follow-up migration.
930
+
931
+ `OrmUserMemory.recall()` uses **OR-of-LIKE token overlap** on the `fact` column — same semantic as `MemoryUserMemory`. Tag-array filtering happens JS-side after fetch (pushing tags into the WHERE is adapter-specific; that lands in a follow-up).
932
+
933
+ #### Embedding backend — `EmbeddingUserMemory` (Phase 5)
934
+
935
+ For semantic recall ("Where do I deploy?" matching "Project Foo lives at fly.io"), wrap `OrmUserMemory` with `EmbeddingUserMemory` from `@rudderjs/ai/memory-embedding`:
936
+
937
+ ```ts
938
+ import { OrmUserMemory } from '@rudderjs/ai/memory-orm'
939
+ import { EmbeddingUserMemory } from '@rudderjs/ai/memory-embedding'
940
+
941
+ export default {
942
+ default: 'anthropic/claude-sonnet-4-5',
943
+ providers: { /* ... */ },
944
+ memory: new EmbeddingUserMemory({
945
+ inner: new OrmUserMemory(),
946
+ model: 'openai/text-embedding-3-small',
947
+ threshold: 0.5, // cosine floor; matches below get dropped
948
+ }),
949
+ } satisfies AiConfig
950
+ ```
951
+
952
+ `remember()` embeds the fact via `AI.embed()` and writes the Float32-packed vector into the row's `embedding` column. `recall()` embeds the query and ranks all of the user's facts by **pure-JS cosine similarity** (acceptable up to a few thousand facts/user; for larger workloads, B7 lands a pgvector-backed variant).
953
+
954
+ **GDPR right-to-be-forgotten cascades automatically** — the embedding lives in the same row as the fact, so `forget()` / `forgetAll()` delete both. No second store to keep in sync.
955
+
956
+ **Backward compat with Phase 4:** rows persisted before `EmbeddingUserMemory` was wired in have `embedding === null`. The default `nullEmbeddingFallback: 'token-overlap'` falls back to the same token-overlap matching `MemoryUserMemory` uses, so upgrading from `OrmUserMemory` doesn't lose recall on existing rows. New `remember()` calls populate the embedding column going forward. Set `nullEmbeddingFallback: 'skip'` to drop pre-embedding rows entirely.
957
+
958
+ `embed()` failures (network down, missing peer SDK) are swallowed: `remember()` still persists the entry with `embedding === null`, and `recall()` falls back to token-overlap. The parent prompt never breaks because of memory work.
959
+
960
+ **A4 status (all phases shipped):** interface, in-process backend, per-call/class declaration, auto-inject, auto-extract, ORM-backed `OrmUserMemory`, and embedding-backed `EmbeddingUserMemory` all ship today. The roadmap item is complete.
961
+
697
962
  ### Model Selection
698
963
 
699
964
  Configure available models for user selection (used by `@rudderjs/panels` chat UI):
@@ -729,6 +994,44 @@ const loggingMiddleware: AiMiddleware = {
729
994
  }
730
995
  ```
731
996
 
997
+ ### Per-user budgets — `withBudget(...)`
998
+
999
+ Cap daily or monthly spend per user. The middleware pre-debits the estimated input cost on every iteration (refusing with `BudgetExceededError` when the cap would be exceeded) and trues up the actual delta after each step's usage report:
1000
+
1001
+ ```ts
1002
+ import { withBudget, memoryBudgetStorage, BudgetExceededError } from '@rudderjs/ai'
1003
+
1004
+ class ChatAgent extends Agent {
1005
+ model() { return 'anthropic/claude-sonnet-4-5' }
1006
+ middleware() {
1007
+ return [
1008
+ withBudget({
1009
+ user: () => req.user?.id ?? null, // null bypasses enforcement (unauth)
1010
+ budget: { period: 'monthly', cap: 5.00 }, // USD; also 'daily'
1011
+ storage: memoryBudgetStorage(), // swap for ormBudgetStorage in production
1012
+ // timezone: 'America/Los_Angeles', // optional — period rollover boundary
1013
+ // onExceeded: ({ spent, cap }) => log.warn({ spent, cap }, 'budget hit'),
1014
+ // pricing: { ...ModelPricing, 'custom/model': { ... } }, // overrides
1015
+ }),
1016
+ ]
1017
+ }
1018
+ }
1019
+ ```
1020
+
1021
+ **Production storage — `OrmBudgetStorage`** persists spend rows via your registered ORM adapter:
1022
+
1023
+ ```ts
1024
+ import { OrmBudgetStorage, BudgetUsageRecord } from '@rudderjs/ai/budget-orm'
1025
+
1026
+ withBudget({
1027
+ user: () => req.user.id,
1028
+ budget: { period: 'monthly', cap: 25 },
1029
+ storage: new OrmBudgetStorage(),
1030
+ })
1031
+ ```
1032
+
1033
+ Schema reference is exported as `budgetUsagePrismaSchema` from `@rudderjs/ai/budget-orm` (also lives at `playground/prisma/schema/ai.prisma`). The `@@unique([userId, period, periodKey])` index is load-bearing — it provides first-write race protection. Caveats: refunds on errors are **not** issued; cache token deltas (Anthropic ephemeral, OpenAI prefix) aren't yet exposed on `TokenUsage`, so cached requests bill at full input rate; default token estimator is `text.length / 4` (override via `estimateTokens` for `tiktoken`). Under high single-user concurrency, total spend can briefly exceed `cap` by up to `costUsd × concurrency` (R-M-W race in the cap-check). The `BudgetExceededError` bubbles up — catch it at the route boundary to return a friendly 402.
1034
+
732
1035
  ### Testing
733
1036
 
734
1037
  ```ts
@@ -778,6 +1081,179 @@ await new ChatAgent().prompt('again') // throws "Stray prompt: no scripted res
778
1081
 
779
1082
  Under strict mode, only `respondWithSequence` entries count as valid responses; ambient `respondWith` is ignored. Force a single-step script via `respondWithSequence([{ text: '...' }])` if you want exact-one-prompt tests with content.
780
1083
 
1084
+ ### Evals — `@rudderjs/ai/eval`
1085
+
1086
+ `AiFake` proves the agent's wiring works; **evals** prove the agent does the right thing on real models. Define a suite of input cases + assertions, run them against any `Agent`, get a console report with pass/fail + cost + tokens:
1087
+
1088
+ ```ts
1089
+ // evals/support-agent.eval.ts
1090
+ import { evalSuite, llmJudge, exactMatch, regex } from '@rudderjs/ai/eval'
1091
+ import { SupportAgent } from '../app/Agents/SupportAgent.js'
1092
+
1093
+ export default evalSuite('SupportAgent', {
1094
+ agent: () => new SupportAgent(),
1095
+ cases: [
1096
+ { name: 'password reset',
1097
+ input: 'How do I reset my password?',
1098
+ assert: llmJudge('mentions a password reset link') },
1099
+ { name: 'price',
1100
+ input: 'How much does this cost?',
1101
+ assert: exactMatch('$99/month') },
1102
+ { name: 'support email',
1103
+ input: 'How do I contact support?',
1104
+ assert: regex(/support@example\.com/) },
1105
+ ],
1106
+ })
1107
+ ```
1108
+
1109
+ Run via the CLI (Phase 2):
1110
+
1111
+ ```bash
1112
+ pnpm rudder ai:eval # all suites under evals/**/*.eval.ts
1113
+ pnpm rudder ai:eval support # only suites whose name includes "support"
1114
+ pnpm rudder ai:eval --bail # stop on first failing suite
1115
+ pnpm rudder ai:eval --json # machine-readable envelope to stdout
1116
+ ```
1117
+
1118
+ ```text
1119
+ SupportAgent (3 cases, 2.3s, $0.014)
1120
+ ✓ password reset 1.2s $0.003 tokens: 487
1121
+ ✓ price 0.8s $0.002 tokens: 312
1122
+ ✗ support email 1.1s $0.002 tokens: 425
1123
+ pattern /support@example\.com/ did not match "Reach us at hello@…"
1124
+
1125
+ 2 passed, 1 failed
1126
+ total: $0.007 • cumulative tokens: 1,224
1127
+ ```
1128
+
1129
+ Exits 0 when every case passes, 1 on any failure. `--json` emits `{ suites: [{ suite, passed, failed, cases: [{ name, status, pass, score?, reason?, tokens, cost, duration }] }] }` to stdout — pipe directly into `jq` for CI gates.
1130
+
1131
+ Override the discovery pattern via `config('ai').eval.pattern` (`'evals/**/*.eval.ts'` by default; supports `<dir>/**/*<suffix>` and `*<suffix>` shapes).
1132
+
1133
+ Or run programmatically:
1134
+
1135
+ ```ts
1136
+ import { runSuite, reportConsole, reportJson } from '@rudderjs/ai/eval'
1137
+ import suite from './evals/support-agent.eval.ts'
1138
+
1139
+ reportConsole(await runSuite(suite))
1140
+ // reportJson(await runSuite(suite)) // structured envelope for CI scripts
1141
+ ```
1142
+
1143
+ **Built-in metrics:**
1144
+
1145
+ | Metric | Behavior |
1146
+ |---|---|
1147
+ | `exactMatch(string)` | `response.text === expected` |
1148
+ | `regex(RegExp)` | `pattern.test(response.text)` |
1149
+ | `llmJudge(criterion, opts?)` | Asks a small model whether the response satisfies a natural-language criterion. Returns the judge's reasoning in `reason` so failures are debuggable. |
1150
+ | `jsonShape(zodSchema)` | Strips ```` ``` ```` fences, parses, runs zod `safeParse`. Surfaces the zod issue path on failure. Pairs with `Output.object({ schema })` on the agent. |
1151
+ | `semanticMatch(reference, opts?)` | Embeds reference + response via `AI.embed()`, cosine similarity vs `opts.threshold` (default `0.85`). Embed cost rolls into the case's cost rollup. Requires a provider with `createEmbedding()` (openai/google/mistral/cohere/jina). |
1152
+ | `tokenCost(threshold)` | Passes when `response.usage.totalTokens <= threshold`. Detects prompt-size regressions before they show up as a billing surprise. |
1153
+
1154
+ `compose(...metrics)` runs them in order, short-circuits on the first failure, surfaces its reason. Useful for "must be valid JSON AND under budget" assertions:
1155
+
1156
+ ```ts
1157
+ { input: '…',
1158
+ assert: compose(jsonShape(SummarySchema), tokenCost(800)) }
1159
+ ```
1160
+
1161
+ User-defined metrics implement `(response, ctx) => MetricResult` — no inheritance, no decorators. The catalog is just a starting set.
1162
+
1163
+ **Failure semantics:** the runner never throws upward. Agent errors AND assertion throws become `failed` rows with the message in `reason`. Per-case `timeout` (ms) caps long runs. Per-case `agent` factory overrides the suite default — useful for stress-testing one case against a different model.
1164
+
1165
+ **Record + replay:**
1166
+
1167
+ ```bash
1168
+ pnpm rudder ai:eval --record support # run live, save fixtures
1169
+ pnpm rudder ai:eval --replay support # zero API calls, deterministic
1170
+ ```
1171
+
1172
+ `--record` runs each matching case against the real provider and writes assistant turns (text + tool calls) to `evals/__fixtures__/<suite>/<case>.json` (commit these alongside the suite for diffable regression history). `--replay` swaps the runtime with `AiFake` and feeds each case its recorded fixture — same agent code path, scripted responses. Cases without a fixture fall through to a normal run with a stderr warning. The two modes are mutually exclusive.
1173
+
1174
+ **Telescope hook:** `aiObservers` emits an `agent.eval.completed` event after every case (passing, failing, skipped). Telescope's AI collector aggregates pass-rate per `(suite, case)` over time.
1175
+
1176
+ **HTML report:**
1177
+
1178
+ ```bash
1179
+ pnpm rudder ai:eval --html report.html # write a self-contained HTML report
1180
+ ```
1181
+
1182
+ Self-contained HTML (inline CSS + vanilla JS, no external assets), pasteable into PR comments / Slack threads, openable offline. Coexists with `--json` (JSON to stdout, HTML to disk). Click any case row to expand the prompt + response.
1183
+
1184
+ Annotate suites with optional metadata:
1185
+
1186
+ ```ts
1187
+ export default evalSuite('SupportAgent', {
1188
+ agent: () => new SupportAgent(),
1189
+ cases: [/* … */],
1190
+ metadata: {
1191
+ owner: '@billing-team',
1192
+ lastReviewed: '2026-05-01',
1193
+ ticket: 'AI-42',
1194
+ },
1195
+ })
1196
+ ```
1197
+
1198
+ ### MCP integration
1199
+
1200
+ `@rudderjs/ai/mcp` bridges agents and Model Context Protocol servers in both directions. Optional peer: `@modelcontextprotocol/sdk`.
1201
+
1202
+ ```ts
1203
+ import { mcpClientTools, mcpServerFromAgent } from '@rudderjs/ai/mcp'
1204
+ ```
1205
+
1206
+ #### Consume MCP tools in an Agent — `mcpClientTools(transport, opts?)`
1207
+
1208
+ Connect to a remote MCP server and surface its tools to an agent.
1209
+
1210
+ ```ts
1211
+ // HTTP transport
1212
+ const tools = await mcpClientTools('https://api.example.com/mcp')
1213
+
1214
+ // Local subprocess (stdio)
1215
+ const tools = await mcpClientTools({ command: 'npx', args: ['some-mcp-server'] })
1216
+
1217
+ // Already-connected SDK Client (caller owns lifecycle)
1218
+ const tools = await mcpClientTools(myClient)
1219
+
1220
+ class ResearchAgent extends Agent {
1221
+ instructions() { return 'You have access to remote tools via MCP.' }
1222
+ tools() { return tools }
1223
+ }
1224
+ ```
1225
+
1226
+ The remote server's JSON Schema flows directly to providers via the `jsonSchema` passthrough field on `ToolDefinitionOptions` — no zod round-trip. When this connector owns the underlying client (URL or stdio transport), the returned array exposes a non-enumerable `close()` for shutdown:
1227
+
1228
+ ```ts
1229
+ const tools = await mcpClientTools('https://api.example.com/mcp')
1230
+ // ... use tools in agent ...
1231
+ await tools.close?.()
1232
+ ```
1233
+
1234
+ Options: `filter` (drop tools by name), `namePrefix` (avoid collisions across multiple servers), `streaming` (forward MCP `notifications/progress` as `tool-update` chunks; default `true`).
1235
+
1236
+ #### Expose an Agent as an MCP server — `mcpServerFromAgent(AgentClass, opts?)`
1237
+
1238
+ Wrap an `Agent` so external MCP clients (Claude Desktop, Cursor, etc.) can call it. Returns a `McpServer` from `@modelcontextprotocol/sdk` — connect with any SDK transport.
1239
+
1240
+ ```ts
1241
+ import { mcpServerFromAgent } from '@rudderjs/ai/mcp'
1242
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
1243
+
1244
+ const server = await mcpServerFromAgent(ResearchAgent)
1245
+ await server.connect(new StdioServerTransport())
1246
+ ```
1247
+
1248
+ Three exposure modes via `opts.expose`:
1249
+ - `'tools'` *(default)* — one MCP tool per `agent.tools()` entry; the wrapping agent isn't called, individual tools execute directly
1250
+ - `'agent'` — one MCP tool that runs the whole agent (`prompt(text) → response.text`); the differentiator move — ship an agent, callable from any MCP-aware client
1251
+ - `'both'` — individual tools and the agent prompt-tool side by side
1252
+
1253
+ Other options: `name`, `version`, `instructions` (defaults to `agent.instructions()`), `agentToolName` (renames the prompt-tool when `expose: 'agent' | 'both'`).
1254
+
1255
+ Approval gates (`needsApproval: true`) are dropped on the MCP side — there's no MCP-protocol way to forward "this tool needs human approval" to a remote client. The gate fires only inside the wrapping agent, not for external MCP callers.
1256
+
781
1257
  ## Providers
782
1258
 
783
1259
  | Provider | SDK | Model String | Text | Embeddings | Images | TTS/STT | Reranking | Files |
@@ -787,6 +1263,8 @@ Under strict mode, only `respondWithSequence` entries count as valid responses;
787
1263
  | Google | `@google/genai` | `google/gemini-2.5-pro` | ✓ | ✓ | ✓ | | | ✓ |
788
1264
  | Cohere | `cohere-ai` | `cohere/rerank-v3.5` | | ✓ | | | ✓ | |
789
1265
  | Jina | *(none)* | `jina/jina-reranker-v2-base-multilingual` | | ✓ | | | ✓ | |
1266
+ | VoyageAI | *(none)* | `voyage/voyage-3-large` | | ✓ | | | ✓ | |
1267
+ | ElevenLabs | *(none)* | `elevenlabs/eleven_multilingual_v2` | | | | ✓ | | |
790
1268
  | Ollama | *(none)* | `ollama/llama3` | ✓ | | | | | |
791
1269
  | Groq | *(none)* | `groq/llama-3.3-70b` | ✓ | | | | | |
792
1270
  | DeepSeek | *(none)* | `deepseek/deepseek-chat` | ✓ | | | | | |
@@ -162,6 +162,65 @@ for await (const chunk of stream) {
162
162
  const final = await response // full AgentResponse after stream ends
163
163
  ```
164
164
 
165
+ ### MCP integration (`@rudderjs/ai/mcp`)
166
+
167
+ Bridge agents and Model Context Protocol servers in both directions. Optional peer: `@modelcontextprotocol/sdk`.
168
+
169
+ **Consume MCP tools in an agent:**
170
+
171
+ ```ts
172
+ import { mcpClientTools } from '@rudderjs/ai/mcp'
173
+
174
+ const tools = await mcpClientTools('https://api.example.com/mcp')
175
+ // or: await mcpClientTools({ command: 'npx', args: ['some-mcp-server'] })
176
+
177
+ class ResearchAgent extends Agent {
178
+ instructions() { return 'You can call remote MCP tools.' }
179
+ tools() { return tools }
180
+ }
181
+ ```
182
+
183
+ **Expose an agent as an MCP server** (callable from Claude Desktop, Cursor, etc.):
184
+
185
+ ```ts
186
+ import { mcpServerFromAgent } from '@rudderjs/ai/mcp'
187
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
188
+
189
+ // Default: each agent.tools() entry becomes an MCP tool
190
+ const server = await mcpServerFromAgent(MyAgent)
191
+
192
+ // Or expose the whole agent as one prompt-tool
193
+ const promptServer = await mcpServerFromAgent(MyAgent, { expose: 'agent' })
194
+
195
+ await server.connect(new StdioServerTransport())
196
+ ```
197
+
198
+ When mcpClientTools owns the underlying client (URL or stdio transport), the returned array exposes `close()` for shutdown — call it when the agent is done. With a caller-provided client, lifecycle stays with the caller.
199
+
200
+ ### Queued prompts + live broadcast (`agent.queue().broadcast()`)
201
+
202
+ `agent.queue(input)` ships the run to the background queue (`@rudderjs/queue`). Add `.broadcast(channel)` to stream chunks to a `@rudderjs/broadcast` channel as the job runs — background AI work + live UI without polling.
203
+
204
+ ```ts
205
+ import { agent } from '@rudderjs/ai'
206
+
207
+ // Plain queued — no live updates
208
+ await agent('You help with refunds.')
209
+ .queue('Process refund for order #1234')
210
+ .onQueue('ai')
211
+ .send()
212
+
213
+ // Stream chunks to the user's channel as they arrive
214
+ await new SupportAgent()
215
+ .queue('Help with refund request')
216
+ .broadcast(`user.${userId}.support`)
217
+ .send()
218
+ ```
219
+
220
+ Subscribers on the channel receive `chunk` events (one per `StreamChunk`), then a `done` event with the final `AgentResponse`, or an `error` event on failure. Optional `eventPrefix` namespaces events: `.broadcast('chan', { eventPrefix: 'agent.' })` emits `agent.chunk` / `agent.done` / `agent.error`.
221
+
222
+ `@rudderjs/broadcast`'s in-process WS state is process-local — same-process web + `queue:work` works out of the box; a separate worker process needs a future pub/sub bridge.
223
+
165
224
  ### Structured Output
166
225
 
167
226
  Use `Output` to constrain responses to typed schemas:
@@ -195,6 +254,7 @@ import { Image, Document } from '@rudderjs/ai' // attachments
195
254
  import { MemoryConversationStore, setConversationStore } from '@rudderjs/ai'
196
255
  import { Output } from '@rudderjs/ai' // structured output
197
256
  import { AiRegistry } from '@rudderjs/ai' // provider registry
257
+ import { mcpClientTools, mcpServerFromAgent } from '@rudderjs/ai/mcp' // MCP bridge (Node)
198
258
  import { stepCountIs, hasToolCall } from '@rudderjs/ai' // stop conditions
199
259
  import type { AgentResponse, AiConfig, AiMiddleware, AnyTool, HasTools, HasMiddleware } from '@rudderjs/ai'
200
260
  ```
@@ -1,6 +1,13 @@
1
1
  ---
2
2
  name: ai-agents
3
3
  description: Building AI agents with tools, streaming, conversation memory, approval flows, and middleware in RudderJS
4
+ license: MIT
5
+ appliesTo:
6
+ - '@rudderjs/ai'
7
+ trigger: building an `Agent` class, calling `Agent.prompt()`/`.stream()`, defining `tools()` or `middleware()`, or wiring conversations / failover
8
+ skip: writing a tool definition by itself — load `ai-tools` instead
9
+ metadata:
10
+ author: rudderjs
4
11
  ---
5
12
 
6
13
  # AI Agents
@@ -1,6 +1,13 @@
1
1
  ---
2
2
  name: ai-tools
3
3
  description: Defining server and client tools with Zod schemas, approval gates, streaming yields, and modelOutput for RudderJS AI agents
4
+ license: MIT
5
+ appliesTo:
6
+ - '@rudderjs/ai'
7
+ trigger: writing a `toolDefinition()`, defining server or client tools, adding streaming yields, or wiring approval gates
8
+ skip: configuring an `Agent` class itself — load `ai-agents` instead
9
+ metadata:
10
+ author: rudderjs
4
11
  ---
5
12
 
6
13
  # AI Tools