@rudderjs/ai 1.17.2 → 1.18.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 (377) hide show
  1. package/README.md +19 -1274
  2. package/dist/budget-orm/index.d.ts +1 -95
  3. package/dist/budget-orm/index.d.ts.map +1 -1
  4. package/dist/budget-orm/index.js +4 -176
  5. package/dist/budget-orm/index.js.map +1 -1
  6. package/dist/chat-mentions.d.ts +1 -58
  7. package/dist/chat-mentions.d.ts.map +1 -1
  8. package/dist/chat-mentions.js +4 -80
  9. package/dist/chat-mentions.js.map +1 -1
  10. package/dist/commands/ai-eval.d.ts +1 -92
  11. package/dist/commands/ai-eval.d.ts.map +1 -1
  12. package/dist/commands/ai-eval.js +4 -377
  13. package/dist/commands/ai-eval.js.map +1 -1
  14. package/dist/commands/make-agent.d.ts +1 -2
  15. package/dist/commands/make-agent.d.ts.map +1 -1
  16. package/dist/commands/make-agent.js +4 -22
  17. package/dist/commands/make-agent.js.map +1 -1
  18. package/dist/computer-use/index.d.ts +1 -52
  19. package/dist/computer-use/index.d.ts.map +1 -1
  20. package/dist/computer-use/index.js +4 -50
  21. package/dist/computer-use/index.js.map +1 -1
  22. package/dist/conversation-orm/index.d.ts +1 -108
  23. package/dist/conversation-orm/index.d.ts.map +1 -1
  24. package/dist/conversation-orm/index.js +4 -214
  25. package/dist/conversation-orm/index.js.map +1 -1
  26. package/dist/doctor.d.ts +1 -1
  27. package/dist/doctor.d.ts.map +1 -1
  28. package/dist/doctor.js +4 -65
  29. package/dist/doctor.js.map +1 -1
  30. package/dist/eval/index.d.ts +1 -270
  31. package/dist/eval/index.d.ts.map +1 -1
  32. package/dist/eval/index.js +4 -509
  33. package/dist/eval/index.js.map +1 -1
  34. package/dist/gateway/index.d.ts +1 -10
  35. package/dist/gateway/index.d.ts.map +1 -1
  36. package/dist/gateway/index.js +4 -10
  37. package/dist/gateway/index.js.map +1 -1
  38. package/dist/index.d.ts +1 -66
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +4 -78
  41. package/dist/index.js.map +1 -1
  42. package/dist/mcp/index.d.ts +1 -15
  43. package/dist/mcp/index.d.ts.map +1 -1
  44. package/dist/mcp/index.js +4 -14
  45. package/dist/mcp/index.js.map +1 -1
  46. package/dist/memory-embedding/index.d.ts +1 -120
  47. package/dist/memory-embedding/index.d.ts.map +1 -1
  48. package/dist/memory-embedding/index.js +4 -228
  49. package/dist/memory-embedding/index.js.map +1 -1
  50. package/dist/memory-orm/index.d.ts +1 -117
  51. package/dist/memory-orm/index.d.ts.map +1 -1
  52. package/dist/memory-orm/index.js +4 -186
  53. package/dist/memory-orm/index.js.map +1 -1
  54. package/dist/node/index.d.ts +1 -2
  55. package/dist/node/index.d.ts.map +1 -1
  56. package/dist/node/index.js +4 -2
  57. package/dist/node/index.js.map +1 -1
  58. package/dist/observers.d.ts +1 -129
  59. package/dist/observers.d.ts.map +1 -1
  60. package/dist/observers.js +4 -39
  61. package/dist/observers.js.map +1 -1
  62. package/dist/react/index.d.ts +1 -15
  63. package/dist/react/index.d.ts.map +1 -1
  64. package/dist/react/index.js +4 -15
  65. package/dist/react/index.js.map +1 -1
  66. package/dist/server/index.d.ts +1 -1
  67. package/dist/server/index.d.ts.map +1 -1
  68. package/dist/server/index.js +4 -1
  69. package/dist/server/index.js.map +1 -1
  70. package/package.json +9 -13
  71. package/boost/guidelines.md +0 -260
  72. package/boost/skills/ai-agents/SKILL.md +0 -240
  73. package/boost/skills/ai-tools/SKILL.md +0 -260
  74. package/dist/agent-run-store.d.ts +0 -161
  75. package/dist/agent-run-store.d.ts.map +0 -1
  76. package/dist/agent-run-store.js +0 -98
  77. package/dist/agent-run-store.js.map +0 -1
  78. package/dist/agent-sse.d.ts +0 -153
  79. package/dist/agent-sse.d.ts.map +0 -1
  80. package/dist/agent-sse.js +0 -282
  81. package/dist/agent-sse.js.map +0 -1
  82. package/dist/agent.d.ts +0 -508
  83. package/dist/agent.d.ts.map +0 -1
  84. package/dist/agent.js +0 -1538
  85. package/dist/agent.js.map +0 -1
  86. package/dist/attachment.d.ts +0 -31
  87. package/dist/attachment.d.ts.map +0 -1
  88. package/dist/attachment.js +0 -89
  89. package/dist/attachment.js.map +0 -1
  90. package/dist/audio.d.ts +0 -45
  91. package/dist/audio.d.ts.map +0 -1
  92. package/dist/audio.js +0 -93
  93. package/dist/audio.js.map +0 -1
  94. package/dist/base64.d.ts +0 -7
  95. package/dist/base64.d.ts.map +0 -1
  96. package/dist/base64.js +0 -39
  97. package/dist/base64.js.map +0 -1
  98. package/dist/budget/pricing.d.ts +0 -124
  99. package/dist/budget/pricing.d.ts.map +0 -1
  100. package/dist/budget/pricing.js +0 -175
  101. package/dist/budget/pricing.js.map +0 -1
  102. package/dist/budget/storage.d.ts +0 -104
  103. package/dist/budget/storage.d.ts.map +0 -1
  104. package/dist/budget/storage.js +0 -0
  105. package/dist/budget/storage.js.map +0 -1
  106. package/dist/budget/with-budget.d.ts +0 -119
  107. package/dist/budget/with-budget.d.ts.map +0 -1
  108. package/dist/budget/with-budget.js +0 -175
  109. package/dist/budget/with-budget.js.map +0 -1
  110. package/dist/cached-embedding.d.ts +0 -14
  111. package/dist/cached-embedding.d.ts.map +0 -1
  112. package/dist/cached-embedding.js +0 -44
  113. package/dist/cached-embedding.js.map +0 -1
  114. package/dist/computer-use/actions.d.ts +0 -214
  115. package/dist/computer-use/actions.d.ts.map +0 -1
  116. package/dist/computer-use/actions.js +0 -48
  117. package/dist/computer-use/actions.js.map +0 -1
  118. package/dist/computer-use/errors.d.ts +0 -57
  119. package/dist/computer-use/errors.d.ts.map +0 -1
  120. package/dist/computer-use/errors.js +0 -76
  121. package/dist/computer-use/errors.js.map +0 -1
  122. package/dist/computer-use/playwright.d.ts +0 -76
  123. package/dist/computer-use/playwright.d.ts.map +0 -1
  124. package/dist/computer-use/playwright.js +0 -270
  125. package/dist/computer-use/playwright.js.map +0 -1
  126. package/dist/computer-use/tool.d.ts +0 -154
  127. package/dist/computer-use/tool.d.ts.map +0 -1
  128. package/dist/computer-use/tool.js +0 -210
  129. package/dist/computer-use/tool.js.map +0 -1
  130. package/dist/continuation-validation.d.ts +0 -85
  131. package/dist/continuation-validation.d.ts.map +0 -1
  132. package/dist/continuation-validation.js +0 -166
  133. package/dist/continuation-validation.js.map +0 -1
  134. package/dist/conversation-persistence.d.ts +0 -46
  135. package/dist/conversation-persistence.d.ts.map +0 -1
  136. package/dist/conversation-persistence.js +0 -176
  137. package/dist/conversation-persistence.js.map +0 -1
  138. package/dist/conversation.d.ts +0 -11
  139. package/dist/conversation.d.ts.map +0 -1
  140. package/dist/conversation.js +0 -55
  141. package/dist/conversation.js.map +0 -1
  142. package/dist/eval/fixtures.d.ts +0 -65
  143. package/dist/eval/fixtures.d.ts.map +0 -1
  144. package/dist/eval/fixtures.js +0 -110
  145. package/dist/eval/fixtures.js.map +0 -1
  146. package/dist/eval/html-reporter.d.ts +0 -25
  147. package/dist/eval/html-reporter.d.ts.map +0 -1
  148. package/dist/eval/html-reporter.js +0 -209
  149. package/dist/eval/html-reporter.js.map +0 -1
  150. package/dist/eval/json-reporter.d.ts +0 -43
  151. package/dist/eval/json-reporter.d.ts.map +0 -1
  152. package/dist/eval/json-reporter.js +0 -40
  153. package/dist/eval/json-reporter.js.map +0 -1
  154. package/dist/facade.d.ts +0 -96
  155. package/dist/facade.d.ts.map +0 -1
  156. package/dist/facade.js +0 -146
  157. package/dist/facade.js.map +0 -1
  158. package/dist/fake.d.ts +0 -201
  159. package/dist/fake.d.ts.map +0 -1
  160. package/dist/fake.js +0 -428
  161. package/dist/fake.js.map +0 -1
  162. package/dist/file-search.d.ts +0 -168
  163. package/dist/file-search.d.ts.map +0 -1
  164. package/dist/file-search.js +0 -158
  165. package/dist/file-search.js.map +0 -1
  166. package/dist/files.d.ts +0 -27
  167. package/dist/files.d.ts.map +0 -1
  168. package/dist/files.js +0 -44
  169. package/dist/files.js.map +0 -1
  170. package/dist/gateway/http-gateway-adapter.d.ts +0 -94
  171. package/dist/gateway/http-gateway-adapter.d.ts.map +0 -1
  172. package/dist/gateway/http-gateway-adapter.js +0 -106
  173. package/dist/gateway/http-gateway-adapter.js.map +0 -1
  174. package/dist/gateway/sse.d.ts +0 -28
  175. package/dist/gateway/sse.d.ts.map +0 -1
  176. package/dist/gateway/sse.js +0 -78
  177. package/dist/gateway/sse.js.map +0 -1
  178. package/dist/handoff.d.ts +0 -95
  179. package/dist/handoff.d.ts.map +0 -1
  180. package/dist/handoff.js +0 -78
  181. package/dist/handoff.js.map +0 -1
  182. package/dist/handoffs-driver.d.ts +0 -58
  183. package/dist/handoffs-driver.d.ts.map +0 -1
  184. package/dist/handoffs-driver.js +0 -103
  185. package/dist/handoffs-driver.js.map +0 -1
  186. package/dist/image.d.ts +0 -40
  187. package/dist/image.d.ts.map +0 -1
  188. package/dist/image.js +0 -109
  189. package/dist/image.js.map +0 -1
  190. package/dist/mcp/client-tools.d.ts +0 -39
  191. package/dist/mcp/client-tools.d.ts.map +0 -1
  192. package/dist/mcp/client-tools.js +0 -147
  193. package/dist/mcp/client-tools.js.map +0 -1
  194. package/dist/mcp/server-from-agent.d.ts +0 -24
  195. package/dist/mcp/server-from-agent.d.ts.map +0 -1
  196. package/dist/mcp/server-from-agent.js +0 -113
  197. package/dist/mcp/server-from-agent.js.map +0 -1
  198. package/dist/mcp/types.d.ts +0 -64
  199. package/dist/mcp/types.d.ts.map +0 -1
  200. package/dist/mcp/types.js +0 -6
  201. package/dist/mcp/types.js.map +0 -1
  202. package/dist/memory-extract.d.ts +0 -60
  203. package/dist/memory-extract.d.ts.map +0 -1
  204. package/dist/memory-extract.js +0 -163
  205. package/dist/memory-extract.js.map +0 -1
  206. package/dist/memory-inject.d.ts +0 -39
  207. package/dist/memory-inject.d.ts.map +0 -1
  208. package/dist/memory-inject.js +0 -135
  209. package/dist/memory-inject.js.map +0 -1
  210. package/dist/memory.d.ts +0 -55
  211. package/dist/memory.d.ts.map +0 -1
  212. package/dist/memory.js +0 -132
  213. package/dist/memory.js.map +0 -1
  214. package/dist/middleware.d.ts +0 -18
  215. package/dist/middleware.d.ts.map +0 -1
  216. package/dist/middleware.js +0 -72
  217. package/dist/middleware.js.map +0 -1
  218. package/dist/node/attachment.d.ts +0 -6
  219. package/dist/node/attachment.d.ts.map +0 -1
  220. package/dist/node/attachment.js +0 -35
  221. package/dist/node/attachment.js.map +0 -1
  222. package/dist/node/transcription.d.ts +0 -4
  223. package/dist/node/transcription.d.ts.map +0 -1
  224. package/dist/node/transcription.js +0 -8
  225. package/dist/node/transcription.js.map +0 -1
  226. package/dist/output.d.ts +0 -22
  227. package/dist/output.d.ts.map +0 -1
  228. package/dist/output.js +0 -60
  229. package/dist/output.js.map +0 -1
  230. package/dist/provider-tools.d.ts +0 -87
  231. package/dist/provider-tools.d.ts.map +0 -1
  232. package/dist/provider-tools.js +0 -189
  233. package/dist/provider-tools.js.map +0 -1
  234. package/dist/providers/anthropic.d.ts +0 -24
  235. package/dist/providers/anthropic.d.ts.map +0 -1
  236. package/dist/providers/anthropic.js +0 -405
  237. package/dist/providers/anthropic.js.map +0 -1
  238. package/dist/providers/azure.d.ts +0 -13
  239. package/dist/providers/azure.d.ts.map +0 -1
  240. package/dist/providers/azure.js +0 -15
  241. package/dist/providers/azure.js.map +0 -1
  242. package/dist/providers/bedrock.d.ts +0 -75
  243. package/dist/providers/bedrock.d.ts.map +0 -1
  244. package/dist/providers/bedrock.js +0 -181
  245. package/dist/providers/bedrock.js.map +0 -1
  246. package/dist/providers/cohere.d.ts +0 -13
  247. package/dist/providers/cohere.d.ts.map +0 -1
  248. package/dist/providers/cohere.js +0 -87
  249. package/dist/providers/cohere.js.map +0 -1
  250. package/dist/providers/deepseek.d.ts +0 -12
  251. package/dist/providers/deepseek.d.ts.map +0 -1
  252. package/dist/providers/deepseek.js +0 -15
  253. package/dist/providers/deepseek.js.map +0 -1
  254. package/dist/providers/elevenlabs.d.ts +0 -98
  255. package/dist/providers/elevenlabs.d.ts.map +0 -1
  256. package/dist/providers/elevenlabs.js +0 -229
  257. package/dist/providers/elevenlabs.js.map +0 -1
  258. package/dist/providers/google-cache-registry.d.ts +0 -132
  259. package/dist/providers/google-cache-registry.d.ts.map +0 -1
  260. package/dist/providers/google-cache-registry.js +0 -209
  261. package/dist/providers/google-cache-registry.js.map +0 -1
  262. package/dist/providers/google.d.ts +0 -38
  263. package/dist/providers/google.d.ts.map +0 -1
  264. package/dist/providers/google.js +0 -903
  265. package/dist/providers/google.js.map +0 -1
  266. package/dist/providers/groq.d.ts +0 -12
  267. package/dist/providers/groq.d.ts.map +0 -1
  268. package/dist/providers/groq.js +0 -15
  269. package/dist/providers/groq.js.map +0 -1
  270. package/dist/providers/jina.d.ts +0 -13
  271. package/dist/providers/jina.d.ts.map +0 -1
  272. package/dist/providers/jina.js +0 -90
  273. package/dist/providers/jina.js.map +0 -1
  274. package/dist/providers/mistral.d.ts +0 -13
  275. package/dist/providers/mistral.d.ts.map +0 -1
  276. package/dist/providers/mistral.js +0 -46
  277. package/dist/providers/mistral.js.map +0 -1
  278. package/dist/providers/ollama.d.ts +0 -11
  279. package/dist/providers/ollama.d.ts.map +0 -1
  280. package/dist/providers/ollama.js +0 -15
  281. package/dist/providers/ollama.js.map +0 -1
  282. package/dist/providers/openai.d.ts +0 -79
  283. package/dist/providers/openai.d.ts.map +0 -1
  284. package/dist/providers/openai.js +0 -792
  285. package/dist/providers/openai.js.map +0 -1
  286. package/dist/providers/openrouter.d.ts +0 -43
  287. package/dist/providers/openrouter.d.ts.map +0 -1
  288. package/dist/providers/openrouter.js +0 -21
  289. package/dist/providers/openrouter.js.map +0 -1
  290. package/dist/providers/voyage.d.ts +0 -91
  291. package/dist/providers/voyage.d.ts.map +0 -1
  292. package/dist/providers/voyage.js +0 -166
  293. package/dist/providers/voyage.js.map +0 -1
  294. package/dist/providers/xai.d.ts +0 -12
  295. package/dist/providers/xai.d.ts.map +0 -1
  296. package/dist/providers/xai.js +0 -15
  297. package/dist/providers/xai.js.map +0 -1
  298. package/dist/queue-job.d.ts +0 -100
  299. package/dist/queue-job.d.ts.map +0 -1
  300. package/dist/queue-job.js +0 -185
  301. package/dist/queue-job.js.map +0 -1
  302. package/dist/react/agent-run.d.ts +0 -111
  303. package/dist/react/agent-run.d.ts.map +0 -1
  304. package/dist/react/agent-run.js +0 -107
  305. package/dist/react/agent-run.js.map +0 -1
  306. package/dist/react/useAgentRun.d.ts +0 -68
  307. package/dist/react/useAgentRun.d.ts.map +0 -1
  308. package/dist/react/useAgentRun.js +0 -125
  309. package/dist/react/useAgentRun.js.map +0 -1
  310. package/dist/registry.d.ts +0 -45
  311. package/dist/registry.d.ts.map +0 -1
  312. package/dist/registry.js +0 -131
  313. package/dist/registry.js.map +0 -1
  314. package/dist/rerank.d.ts +0 -20
  315. package/dist/rerank.d.ts.map +0 -1
  316. package/dist/rerank.js +0 -40
  317. package/dist/rerank.js.map +0 -1
  318. package/dist/resume-approval.d.ts +0 -30
  319. package/dist/resume-approval.d.ts.map +0 -1
  320. package/dist/resume-approval.js +0 -147
  321. package/dist/resume-approval.js.map +0 -1
  322. package/dist/sanitize-conversation.d.ts +0 -43
  323. package/dist/sanitize-conversation.d.ts.map +0 -1
  324. package/dist/sanitize-conversation.js +0 -85
  325. package/dist/sanitize-conversation.js.map +0 -1
  326. package/dist/scoped-tool.d.ts +0 -98
  327. package/dist/scoped-tool.d.ts.map +0 -1
  328. package/dist/scoped-tool.js +0 -174
  329. package/dist/scoped-tool.js.map +0 -1
  330. package/dist/server/provider.d.ts +0 -22
  331. package/dist/server/provider.d.ts.map +0 -1
  332. package/dist/server/provider.js +0 -194
  333. package/dist/server/provider.js.map +0 -1
  334. package/dist/similarity-search.d.ts +0 -163
  335. package/dist/similarity-search.d.ts.map +0 -1
  336. package/dist/similarity-search.js +0 -147
  337. package/dist/similarity-search.js.map +0 -1
  338. package/dist/sub-agent-run-store.d.ts +0 -157
  339. package/dist/sub-agent-run-store.d.ts.map +0 -1
  340. package/dist/sub-agent-run-store.js +0 -87
  341. package/dist/sub-agent-run-store.js.map +0 -1
  342. package/dist/tool-execution.d.ts +0 -16
  343. package/dist/tool-execution.d.ts.map +0 -1
  344. package/dist/tool-execution.js +0 -498
  345. package/dist/tool-execution.js.map +0 -1
  346. package/dist/tool-helpers.d.ts +0 -77
  347. package/dist/tool-helpers.d.ts.map +0 -1
  348. package/dist/tool-helpers.js +0 -117
  349. package/dist/tool-helpers.js.map +0 -1
  350. package/dist/tool.d.ts +0 -216
  351. package/dist/tool.d.ts.map +0 -1
  352. package/dist/tool.js +0 -175
  353. package/dist/tool.js.map +0 -1
  354. package/dist/transcription.d.ts +0 -42
  355. package/dist/transcription.d.ts.map +0 -1
  356. package/dist/transcription.js +0 -77
  357. package/dist/transcription.js.map +0 -1
  358. package/dist/types.d.ts +0 -1020
  359. package/dist/types.d.ts.map +0 -1
  360. package/dist/types.js +0 -2
  361. package/dist/types.js.map +0 -1
  362. package/dist/util/hash.d.ts +0 -11
  363. package/dist/util/hash.d.ts.map +0 -1
  364. package/dist/util/hash.js +0 -23
  365. package/dist/util/hash.js.map +0 -1
  366. package/dist/vector-stores/index.d.ts +0 -96
  367. package/dist/vector-stores/index.d.ts.map +0 -1
  368. package/dist/vector-stores/index.js +0 -153
  369. package/dist/vector-stores/index.js.map +0 -1
  370. package/dist/vercel-protocol.d.ts +0 -18
  371. package/dist/vercel-protocol.d.ts.map +0 -1
  372. package/dist/vercel-protocol.js +0 -75
  373. package/dist/vercel-protocol.js.map +0 -1
  374. package/dist/zod-to-json-schema.d.ts +0 -16
  375. package/dist/zod-to-json-schema.d.ts.map +0 -1
  376. package/dist/zod-to-json-schema.js +0 -17
  377. package/dist/zod-to-json-schema.js.map +0 -1
package/dist/types.d.ts DELETED
@@ -1,1020 +0,0 @@
1
- import type { z } from 'zod';
2
- /** A single content part (text, image, or document) */
3
- export type ContentPart = {
4
- type: 'text';
5
- text: string;
6
- } | {
7
- type: 'image';
8
- data: string;
9
- mimeType: string;
10
- } | {
11
- type: 'document';
12
- data: string;
13
- mimeType: string;
14
- name?: string;
15
- };
16
- /** A message in the conversation */
17
- export interface AiMessage {
18
- role: 'system' | 'user' | 'assistant' | 'tool';
19
- content: string | ContentPart[];
20
- /** Present when role === 'tool' */
21
- toolCallId?: string;
22
- /** Present when role === 'assistant' and model wants to call tools */
23
- toolCalls?: ToolCall[];
24
- }
25
- /** A tool call from the model */
26
- export interface ToolCall {
27
- id: string;
28
- name: string;
29
- arguments: Record<string, unknown>;
30
- }
31
- /** A tool result to feed back to the model */
32
- export interface ToolResult {
33
- toolCallId: string;
34
- result: unknown;
35
- /**
36
- * Wall-clock milliseconds spent inside the tool's `execute` for this
37
- * call. Captured by the agent loop with `performance.now()` around the
38
- * execute generator. Absent (or 0) for paths where no `execute` ran —
39
- * unknown-tool, rejected, middleware-skipped, validation-failure,
40
- * client-tool-placeholder.
41
- */
42
- duration?: number;
43
- }
44
- /** Token usage stats */
45
- export interface TokenUsage {
46
- promptTokens: number;
47
- completionTokens: number;
48
- totalTokens: number;
49
- }
50
- /** Non-streaming response from a provider */
51
- export interface ProviderResponse {
52
- message: AiMessage;
53
- usage: TokenUsage;
54
- finishReason: FinishReason;
55
- }
56
- export type FinishReason = 'stop' | 'tool_calls' | 'length' | 'content_filter'
57
- /** Loop stopped because client-side tool calls are pending execution. */
58
- | 'client_tool_calls'
59
- /** Loop stopped because a tool call requires user approval. */
60
- | 'tool_approval_required';
61
- /** A single streamed chunk */
62
- export interface StreamChunk {
63
- type: 'text-delta' | 'tool-call-delta' | 'tool-call' | 'tool-result' | 'tool-update' | 'usage' | 'finish' | 'pending-client-tools' | 'pending-approval' | 'handoff';
64
- /** Text content delta (when type === 'text-delta') */
65
- text?: string;
66
- /** Tool call info (when type === 'tool-call', 'tool-call-delta', 'tool-result', 'tool-update', or 'pending-approval') */
67
- toolCall?: Partial<ToolCall>;
68
- /**
69
- * Position of the streamed tool call in the parallel-call array (when
70
- * `type === 'tool-call-delta'`). Set by adapters that interleave parallel
71
- * tool calls by index — OpenAI ships every `delta.tool_calls[i]` with its
72
- * `index`; the agent loop routes arg-delta chunks to the matching partial
73
- * by this field rather than guessing from insertion order. Adapters whose
74
- * tool calls arrive whole per block (Anthropic, Google) don't set this.
75
- */
76
- toolCallIndex?: number;
77
- /** Tool execution result (when type === 'tool-result') */
78
- result?: unknown;
79
- /**
80
- * Preliminary tool progress payload (when type === 'tool-update').
81
- * Emitted by async-generator tool executes for each `yield`.
82
- * Ephemeral: not persisted, not seen by the model on the next step.
83
- */
84
- update?: unknown;
85
- /** Pending client tool calls (when type === 'pending-client-tools') */
86
- toolCalls?: ToolCall[];
87
- /** Approval-pending metadata (when type === 'pending-approval') */
88
- isClientTool?: boolean;
89
- /** Usage stats (when type === 'finish' or 'usage') */
90
- usage?: TokenUsage | undefined;
91
- /** Finish reason (when type === 'finish') */
92
- finishReason?: FinishReason;
93
- /**
94
- * Handoff metadata (when type === 'handoff'). Emitted right before the
95
- * parent agent's loop ends and control transfers to a new agent. UIs
96
- * typically render a "transferred to X" indicator before the next
97
- * agent's chunks start streaming.
98
- */
99
- handoff?: {
100
- /** Class name of the agent that just yielded control. */
101
- from: string;
102
- /** Class name of the agent now in control. */
103
- to: string;
104
- /** Transition message the parent's model wrote — if any. */
105
- message?: string;
106
- };
107
- }
108
- /** Options passed to the provider for each request */
109
- export interface ProviderRequestOptions {
110
- model: string;
111
- messages: AiMessage[];
112
- tools?: ToolDefinitionSchema[] | undefined;
113
- toolChoice?: ToolChoice | undefined;
114
- temperature?: number | undefined;
115
- maxTokens?: number | undefined;
116
- topP?: number | undefined;
117
- stop?: string[] | undefined;
118
- /**
119
- * Optional AbortSignal forwarded by the agent loop. Provider adapters
120
- * SHOULD pass this through to their underlying SDK / fetch call so a
121
- * caller-side `.abort()` cancels the in-flight network request.
122
- */
123
- signal?: AbortSignal | undefined;
124
- /** Provider-specific options */
125
- providerOptions?: Record<string, unknown> | undefined;
126
- /**
127
- * Resolved prompt-caching markers — populated by the agent loop from
128
- * `Agent.cacheable()` (and the per-call `cache` override). Provider
129
- * adapters translate these to native cache primitives:
130
- *
131
- * - **Anthropic** — adds `cache_control: { type: 'ephemeral' }` to the
132
- * last content block of each marked region (system, tools, messages[N]).
133
- * - **OpenAI** — caching is automatic above 1024 tokens; the adapter sets
134
- * `prompt_cache_key` from a stable hash of the cached regions for routing
135
- * affinity (so repeat requests hit the same backend's cached prefix).
136
- * - **Google (Gemini)** — translates to `cachedContent` resources via a
137
- * pluggable registry that uses `@rudderjs/cache` when installed. TTL is
138
- * configurable via {@link CacheableConfig.ttl} (default `'1h'`).
139
- *
140
- * Adapters that don't support caching ignore this field — the request
141
- * still runs uncached.
142
- */
143
- cache?: CacheableMarkers | undefined;
144
- }
145
- /**
146
- * Declarative cache configuration on the {@link Agent} class. Each marked
147
- * region is a hint that the *content there is stable across requests* and
148
- * worth caching. The agent loop resolves this into {@link CacheableMarkers}
149
- * for the provider.
150
- *
151
- * Example:
152
- * ```ts
153
- * class SupportAgent extends Agent {
154
- * cacheable() {
155
- * return { instructions: true, tools: true, messages: 2 }
156
- * // ^ cache the first 2 messages
157
- * }
158
- * }
159
- * ```
160
- */
161
- export interface CacheableConfig {
162
- /** Cache the system instructions. */
163
- instructions?: boolean;
164
- /** Cache the tool definitions. */
165
- tools?: boolean;
166
- /**
167
- * Cache the first N messages (oldest). The cache breakpoint goes
168
- * immediately after the Nth message. Useful for multi-turn conversations
169
- * where the early context (history, examples) doesn't change.
170
- */
171
- messages?: number;
172
- /**
173
- * How long the cache entry should live. Duration string accepted by
174
- * `@rudderjs/support`'s parser — `'30m'`, `'2h'`, `'1d'`, etc. Default
175
- * `'1h'` when omitted.
176
- *
177
- * **Google-only for now.** Anthropic's ephemeral cache and OpenAI's
178
- * automatic prefix cache have no per-call TTL knob; their adapters ignore
179
- * this field. Google's `cachedContent` is a stateful resource with a
180
- * configurable TTL (max ~24h, model-dependent), and this controls it.
181
- */
182
- ttl?: string;
183
- }
184
- /**
185
- * Resolved cache markers — the post-merge shape the agent loop hands to
186
- * provider adapters. `messages` is normalized to a positive integer (the
187
- * count of leading messages to cache); `0` or absent means "don't cache".
188
- */
189
- export interface CacheableMarkers {
190
- instructions?: boolean;
191
- tools?: boolean;
192
- messages?: number;
193
- /** See {@link CacheableConfig.ttl}. */
194
- ttl?: string;
195
- }
196
- export type ToolChoice = 'auto' | 'required' | 'none' | {
197
- name: string;
198
- };
199
- /**
200
- * Side-channel hint a tool can carry to ask provider adapters for
201
- * non-default behavior — e.g. emit a native provider tool block instead
202
- * of a generic function-call schema.
203
- *
204
- * `type` is the namespace + variant (`'computer-use'`); other fields are
205
- * hint-specific. Adapters that don't recognize the `type` SHOULD ignore
206
- * the hint and fall back to the standard function-call serialization.
207
- *
208
- * Currently used by `@rudderjs/ai/computer-use` to map to Anthropic's
209
- * native `computer_20250124` tool block.
210
- */
211
- export interface ProviderHint {
212
- type: string;
213
- [k: string]: unknown;
214
- }
215
- /** Tool definition as sent to the provider (JSON Schema) */
216
- export interface ToolDefinitionSchema {
217
- name: string;
218
- description: string;
219
- parameters: Record<string, unknown>;
220
- /**
221
- * Optional provider-specific hint. Adapters that recognize the
222
- * `providerHint.type` substitute their native serialization; others
223
- * ignore the hint and emit the standard function-call shape.
224
- */
225
- providerHint?: ProviderHint;
226
- }
227
- /** Provider adapter — thin wrapper around a provider SDK */
228
- export interface ProviderAdapter {
229
- /** Generate a complete response */
230
- generate(options: ProviderRequestOptions): Promise<ProviderResponse>;
231
- /** Stream a response */
232
- stream(options: ProviderRequestOptions): AsyncIterable<StreamChunk>;
233
- }
234
- /** Embedding response */
235
- export interface EmbeddingResult {
236
- embeddings: number[][];
237
- usage: {
238
- promptTokens: number;
239
- totalTokens: number;
240
- };
241
- }
242
- /** Provider adapter that supports embeddings */
243
- export interface EmbeddingAdapter {
244
- embed(input: string | string[], model: string): Promise<EmbeddingResult>;
245
- }
246
- export interface ImageGenerationOptions {
247
- prompt: string;
248
- model?: string | undefined;
249
- size?: 'square' | 'landscape' | 'portrait' | string | undefined;
250
- quality?: 'standard' | 'hd' | undefined;
251
- style?: 'natural' | 'vivid' | undefined;
252
- n?: number | undefined;
253
- }
254
- export interface ImageGenerationResult {
255
- images: Array<{
256
- url?: string | undefined;
257
- base64?: string | undefined;
258
- revisedPrompt?: string | undefined;
259
- }>;
260
- model: string;
261
- }
262
- export interface ImageGenerationAdapter {
263
- generate(options: ImageGenerationOptions): Promise<ImageGenerationResult>;
264
- }
265
- /** Provider factory — creates a ProviderAdapter from a model string */
266
- export interface ProviderFactory {
267
- readonly name: string;
268
- create(model: string): ProviderAdapter;
269
- /** Create an embedding adapter (optional — not all providers support embeddings) */
270
- createEmbedding?(model: string): EmbeddingAdapter;
271
- /** Create an image generation adapter (optional — not all providers support image generation) */
272
- createImage?(model: string): ImageGenerationAdapter;
273
- /** Create a text-to-speech adapter (optional) */
274
- createTts?(model: string): TextToSpeechAdapter;
275
- /** Create a speech-to-text adapter (optional) */
276
- createStt?(model: string): SpeechToTextAdapter;
277
- /** Create a reranking adapter (optional) */
278
- createReranking?(model: string): RerankingAdapter;
279
- /** Create a file management adapter (optional) */
280
- createFiles?(): FileAdapter;
281
- /** Create a vector-store adapter (optional — #B8) */
282
- createVectorStores?(): VectorStoreAdapter;
283
- }
284
- export interface FileUploadOptions {
285
- filePath: string;
286
- purpose?: string | undefined;
287
- }
288
- export interface FileUploadResult {
289
- id: string;
290
- filename: string;
291
- bytes: number;
292
- purpose?: string | undefined;
293
- }
294
- export interface FileListResult {
295
- files: FileUploadResult[];
296
- }
297
- export interface FileContent {
298
- data: Buffer;
299
- mimeType: string;
300
- }
301
- export interface FileAdapter {
302
- upload(options: FileUploadOptions): Promise<FileUploadResult>;
303
- list(): Promise<FileListResult>;
304
- delete(fileId: string): Promise<void>;
305
- retrieve?(fileId: string): Promise<FileContent>;
306
- }
307
- export interface VectorStoreCreateOptions {
308
- name: string;
309
- /** Free-form key/value metadata. OpenAI caps values at 512 chars. */
310
- metadata?: Record<string, string>;
311
- /**
312
- * Auto-expire policy. OpenAI charges for storage so most apps want
313
- * an idle-expiry on transient stores.
314
- */
315
- expiresAfter?: {
316
- anchor: 'last_active_at';
317
- days: number;
318
- };
319
- /** Provider override (defaults to the registered AI default). */
320
- provider?: string;
321
- }
322
- export interface VectorStoreInfo {
323
- id: string;
324
- name: string;
325
- createdAt: number;
326
- /** Number of files attached. Provider-reported, may include in-progress. */
327
- fileCount: number;
328
- bytesUsed?: number;
329
- metadata?: Record<string, string>;
330
- }
331
- export interface VectorStoreFileInfo {
332
- id: string;
333
- vectorStoreId: string;
334
- status: 'in_progress' | 'completed' | 'failed' | 'cancelled';
335
- createdAt: number;
336
- bytes?: number;
337
- /**
338
- * Per-file searchable metadata exposed by OpenAI's `attributes` field.
339
- * `fileSearch({ where: ... })` (B8 Phase 2) filters on these.
340
- */
341
- attributes?: Record<string, string | number | boolean>;
342
- /** When status === 'failed', the provider's error message. */
343
- lastError?: string;
344
- }
345
- export interface VectorStoreAddOptions {
346
- /** Either an existing provider file id or a local path/Buffer to upload. */
347
- fileId?: string;
348
- filePath?: string;
349
- fileBuffer?: {
350
- data: Uint8Array;
351
- filename: string;
352
- };
353
- /** Searchable metadata stored alongside the file in the vector store. */
354
- attributes?: Record<string, string | number | boolean>;
355
- /**
356
- * Pass through to the provider's chunking config. Opaque on our side
357
- * — apps that want to tune chunk size / overlap pass the provider's
358
- * native shape. OpenAI: `{ type: 'static', static: { max_chunk_size_tokens, chunk_overlap_tokens } }`.
359
- */
360
- chunkingStrategy?: unknown;
361
- /**
362
- * Wait for the file to finish ingesting + embedding before resolving.
363
- * Default `true`. Set `false` for fire-and-forget — useful when
364
- * batching many files.
365
- */
366
- wait?: boolean;
367
- /** Polling interval in ms. Default 1000. */
368
- pollInterval?: number;
369
- /** Total polling timeout in ms. Default 120_000 (2 min). */
370
- pollTimeout?: number;
371
- }
372
- export interface VectorStoreListOptions {
373
- limit?: number;
374
- after?: string;
375
- before?: string;
376
- }
377
- export interface VectorStoreList {
378
- stores: VectorStoreInfo[];
379
- }
380
- export interface VectorStoreFileList {
381
- files: VectorStoreFileInfo[];
382
- }
383
- export interface VectorStoreAdapter {
384
- create(opts: VectorStoreCreateOptions): Promise<VectorStoreInfo>;
385
- list(opts?: VectorStoreListOptions): Promise<VectorStoreList>;
386
- get(id: string): Promise<VectorStoreInfo>;
387
- delete(id: string): Promise<void>;
388
- /**
389
- * Attach a file to the store. The file is either an already-uploaded
390
- * provider file (`fileId`) or a local source the adapter will upload
391
- * first (`filePath` / `fileBuffer`). Defaults to waiting until the
392
- * file is fully indexed.
393
- */
394
- addFile(storeId: string, opts: VectorStoreAddOptions): Promise<VectorStoreFileInfo>;
395
- removeFile(storeId: string, fileId: string): Promise<void>;
396
- listFiles(storeId: string, opts?: VectorStoreListOptions): Promise<VectorStoreFileList>;
397
- }
398
- export interface RerankingOptions {
399
- query: string;
400
- documents: string[];
401
- model?: string | undefined;
402
- topK?: number | undefined;
403
- }
404
- export interface RerankingResult {
405
- results: Array<{
406
- index: number;
407
- relevanceScore: number;
408
- document: string;
409
- }>;
410
- usage?: {
411
- tokens?: number | undefined;
412
- } | undefined;
413
- }
414
- export interface RerankingAdapter {
415
- rerank(options: RerankingOptions): Promise<RerankingResult>;
416
- }
417
- export interface TextToSpeechOptions {
418
- text: string;
419
- model?: string | undefined;
420
- voice?: string | undefined;
421
- speed?: number | undefined;
422
- format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | undefined;
423
- }
424
- export interface TextToSpeechResult {
425
- audio: Buffer;
426
- format: string;
427
- model: string;
428
- }
429
- export interface SpeechToTextOptions {
430
- audio: Uint8Array;
431
- model?: string | undefined;
432
- language?: string | undefined;
433
- prompt?: string | undefined;
434
- }
435
- export interface SpeechToTextResult {
436
- text: string;
437
- language?: string | undefined;
438
- duration?: number | undefined;
439
- model: string;
440
- }
441
- export interface TextToSpeechAdapter {
442
- generate(options: TextToSpeechOptions): Promise<TextToSpeechResult>;
443
- }
444
- export interface SpeechToTextAdapter {
445
- transcribe(options: SpeechToTextOptions): Promise<SpeechToTextResult>;
446
- }
447
- /**
448
- * Per-call context passed to a tool's `execute` as an optional second
449
- * argument. Carries loop-level identity that the tool would otherwise have
450
- * no way to observe.
451
- *
452
- * Today it contains only `toolCallId` — the id the model assigned to this
453
- * particular invocation. Tools that need to correlate their side-effects
454
- * with the surrounding loop (e.g. a sub-agent runner that pauses on a
455
- * client tool and needs to record which parent tool-call id its suspension
456
- * belongs to) read this id.
457
- *
458
- * Additional fields may be added over time; tools should destructure only
459
- * what they need. The whole parameter is optional on the call signature so
460
- * existing single-arg executes keep working.
461
- */
462
- export interface ToolCallContext {
463
- /** The id the model assigned to this particular tool call. */
464
- readonly toolCallId: string;
465
- }
466
- /**
467
- * Tool execute function.
468
- *
469
- * Returns either a value (sync), a promise (async), or an async generator.
470
- * Generator-style executes can `yield` preliminary progress payloads —
471
- * each yield is emitted as a `tool-update` stream chunk while the tool runs.
472
- * The generator's `return` value is the final tool result (the value the
473
- * model and the persisted store both see).
474
- *
475
- * The optional second `ctx` parameter carries loop-level metadata such as
476
- * `toolCallId`. Tools that don't care can omit it and keep a one-arg
477
- * signature — TypeScript's contravariant function parameter rules mean
478
- * `(input) => ...` still satisfies `(input, ctx?) => ...`.
479
- *
480
- * `TUpdate` defaults to `never` so non-generator call sites infer cleanly
481
- * without a third type parameter on every existing tool definition.
482
- */
483
- export type ToolExecuteFn<TInput = unknown, TOutput = unknown, TUpdate = never> = (input: TInput, ctx?: ToolCallContext) => TOutput | Promise<TOutput> | AsyncGenerator<TUpdate, TOutput, void>;
484
- export type ToolNeedsApproval<TInput = unknown> = boolean | ((input: TInput) => boolean | Promise<boolean>);
485
- export interface ToolDefinitionOptions<TInput extends z.ZodType = z.ZodType, TOutput extends z.ZodType = z.ZodType> {
486
- name: string;
487
- description: string;
488
- inputSchema: TInput;
489
- outputSchema?: TOutput | undefined;
490
- needsApproval?: ToolNeedsApproval<z.infer<TInput>> | undefined;
491
- lazy?: boolean | undefined;
492
- /** Arbitrary metadata — used by provider-native tools to signal special handling */
493
- meta?: Record<string, unknown> | undefined;
494
- /**
495
- * Pre-built JSON Schema for the tool's parameters. When set, takes precedence
496
- * over `inputSchema` — the agent loop ships this directly to providers without
497
- * a zod round-trip. Use for tools whose schema is constructed dynamically and
498
- * already lives as JSON Schema (MCP imports via `mcpClientTools()`, OpenAPI
499
- * generators). `inputSchema` should still be supplied as `z.unknown()` (or a
500
- * placeholder) for runtime parsing in the agent loop.
501
- */
502
- jsonSchema?: Record<string, unknown> | undefined;
503
- /**
504
- * Provider-specific hint. Adapters that recognize the `providerHint.type`
505
- * substitute their native tool serialization (e.g. Anthropic's
506
- * `computer_20250124` block for `'computer-use'`, OpenAI's `file_search`
507
- * block for `'file-search'`); others ignore it and emit the standard
508
- * function-call shape. Propagated onto {@link ToolDefinitionSchema} by
509
- * `toolToSchema`.
510
- */
511
- providerHint?: ProviderHint | undefined;
512
- }
513
- /**
514
- * A tool the model can call.
515
- *
516
- * `execute` is optional — its presence/absence is the only discriminator
517
- * between server tools (have an executor) and client tools (run in the
518
- * browser via the `clientTools` registry on the panels side).
519
- *
520
- * This shape mirrors Vercel AI SDK v4+ and TanStack AI.
521
- */
522
- export interface Tool<TInput = unknown, TOutput = unknown> {
523
- readonly definition: ToolDefinitionOptions;
524
- readonly execute?: ToolExecuteFn<TInput, TOutput, unknown> | undefined;
525
- /**
526
- * Optional transform from the tool's structured `result` to the string the
527
- * **model** sees on its next step. The UI (`tool-result` chunk and
528
- * `step.toolResults`) still receives the original `result`.
529
- *
530
- * Use this to summarize, redact, or shrink large/binary tool outputs so
531
- * the parent model doesn't get the full payload stuffed into its context
532
- * (e.g. subagent transcripts, base64 blobs). Default — when this is
533
- * absent — is the same `JSON.stringify`-or-pass-through behavior as before.
534
- */
535
- readonly toModelOutput?: ((result: TOutput) => string | Promise<string>) | undefined;
536
- }
537
- export type AnyTool = Tool<any, any>;
538
- /**
539
- * @deprecated Use {@link Tool}. A "server tool" is just a `Tool` whose
540
- * `execute` is defined.
541
- */
542
- export interface ServerTool<TInput = unknown, TOutput = unknown> extends Tool<TInput, TOutput> {
543
- readonly execute: ToolExecuteFn<TInput, TOutput, unknown>;
544
- }
545
- /**
546
- * @deprecated Use {@link Tool}. A "client tool" is just a `Tool` whose
547
- * `execute` is omitted; the browser handles execution via the
548
- * `clientTools` registry in `@rudderjs/panels`.
549
- */
550
- export type ClientTool<TInput = unknown, TOutput = unknown> = Tool<TInput, TOutput>;
551
- export interface MiddlewareContext {
552
- requestId: string;
553
- iteration: number;
554
- chunkIndex: number;
555
- messages: AiMessage[];
556
- model: string;
557
- provider: string;
558
- toolNames: string[];
559
- context?: unknown;
560
- abort(reason?: string): void;
561
- }
562
- export interface MiddlewareConfigResult {
563
- messages?: AiMessage[];
564
- systemPrompts?: string[];
565
- tools?: AnyTool[];
566
- temperature?: number;
567
- maxTokens?: number;
568
- providerOptions?: Record<string, unknown>;
569
- }
570
- export type BeforeToolCallResult = void | {
571
- type: 'transformArgs';
572
- args: Record<string, unknown>;
573
- } | {
574
- type: 'skip';
575
- result: unknown;
576
- } | {
577
- type: 'abort';
578
- reason: string;
579
- };
580
- export interface AiMiddleware {
581
- name: string;
582
- onConfig?(ctx: MiddlewareContext, config: MiddlewareConfigResult, phase: 'init' | 'beforeModel'): MiddlewareConfigResult | void;
583
- onStart?(ctx: MiddlewareContext): void | Promise<void>;
584
- onIteration?(ctx: MiddlewareContext): void | Promise<void>;
585
- onChunk?(ctx: MiddlewareContext, chunk: StreamChunk): StreamChunk | null;
586
- onBeforeToolCall?(ctx: MiddlewareContext, toolName: string, args: Record<string, unknown>): BeforeToolCallResult | Promise<BeforeToolCallResult>;
587
- onAfterToolCall?(ctx: MiddlewareContext, toolName: string, args: Record<string, unknown>, result: unknown): void | Promise<void>;
588
- onToolPhaseComplete?(ctx: MiddlewareContext): void | Promise<void>;
589
- onUsage?(ctx: MiddlewareContext, usage: TokenUsage): void | Promise<void>;
590
- onFinish?(ctx: MiddlewareContext): void | Promise<void>;
591
- onAbort?(ctx: MiddlewareContext, reason: string): void | Promise<void>;
592
- onError?(ctx: MiddlewareContext, error: unknown): void | Promise<void>;
593
- }
594
- export interface HasTools {
595
- tools(): AnyTool[];
596
- }
597
- export interface HasMemory {
598
- conversationId?: string;
599
- messages(): AiMessage[] | Promise<AiMessage[]>;
600
- }
601
- export interface HasStructuredOutput {
602
- outputSchema(): z.ZodType;
603
- }
604
- export interface HasMiddleware {
605
- middleware(): AiMiddleware[];
606
- }
607
- export type StopCondition = (ctx: {
608
- steps: AgentStep[];
609
- iteration: number;
610
- lastMessage: AiMessage;
611
- }) => boolean;
612
- export interface AgentStep {
613
- message: AiMessage;
614
- toolCalls: ToolCall[];
615
- toolResults: ToolResult[];
616
- usage: TokenUsage;
617
- finishReason: FinishReason;
618
- }
619
- export interface PrepareStepResult {
620
- model?: string;
621
- tools?: AnyTool[];
622
- toolChoice?: ToolChoice;
623
- messages?: AiMessage[];
624
- system?: string;
625
- providerOptions?: Record<string, unknown>;
626
- }
627
- export interface AgentResponse {
628
- text: string;
629
- steps: AgentStep[];
630
- usage: TokenUsage;
631
- conversationId?: string;
632
- /** When the loop stopped early, why. */
633
- finishReason?: FinishReason;
634
- /** Client tool calls awaiting browser-side execution. */
635
- pendingClientToolCalls?: ToolCall[];
636
- /** A tool call awaiting user approval. */
637
- pendingApprovalToolCall?: {
638
- toolCall: ToolCall;
639
- isClientTool: boolean;
640
- };
641
- /**
642
- * Tool result messages that were injected at the start of a continuation
643
- * to fulfill an `assistant{toolCalls}` carried over from the previous turn
644
- * (e.g. an approval round-trip). The panels dispatcher persists these so
645
- * the conversation store never holds an unfulfilled `tool_use` block.
646
- */
647
- resumedToolMessages?: AiMessage[];
648
- /**
649
- * Chain of agent class names traversed when one or more handoffs occurred
650
- * during the run, in the order each took control. The first entry is the
651
- * agent originally invoked; the last is the agent that produced `text`.
652
- * Absent when no handoff happened.
653
- *
654
- * @example ['TriageAgent', 'SalesAgent']
655
- */
656
- handoffPath?: string[];
657
- }
658
- export interface AgentStreamResponse {
659
- stream: AsyncIterable<StreamChunk>;
660
- response: Promise<AgentResponse>;
661
- }
662
- export interface AiProviderConfig {
663
- driver: string;
664
- apiKey?: string;
665
- baseUrl?: string;
666
- [key: string]: unknown;
667
- }
668
- export interface AiModelConfig {
669
- id: string;
670
- label: string;
671
- }
672
- export interface AiConfig {
673
- default: string;
674
- providers: Record<string, AiProviderConfig>;
675
- failover?: string[];
676
- models?: AiModelConfig[];
677
- /** Conversation store for persisting agent conversations */
678
- conversations?: ConversationStore;
679
- /** User memory store for persisting per-user facts beyond conversation history (#A4) */
680
- memory?: UserMemory;
681
- /** Eval framework knobs (#A5). Optional; the CLI applies sensible defaults. */
682
- eval?: {
683
- /**
684
- * Glob-like pattern for `pnpm rudder ai:eval` discovery. Default
685
- * `'evals/**\/*.eval.ts'`. Supports `<dir>/**\/*<suffix>` and
686
- * `*<suffix>` shapes; richer patterns belong in a userland script.
687
- */
688
- pattern?: string;
689
- };
690
- }
691
- export interface AgentPromptOptions {
692
- /** Prior conversation messages to prepend (after system prompt, before current user message) */
693
- history?: AiMessage[];
694
- /**
695
- * Full message list to send instead of `[system, ...history, user(input)]`.
696
- * When set, the loop runs with `[system, ...messages]` directly — `input`
697
- * is ignored. Used for continuations after a client-tool round-trip or
698
- * approval round-trip, where the conversation ends with a tool result
699
- * message and there is no fresh user input.
700
- */
701
- messages?: AiMessage[];
702
- /** File/image attachments to include with the prompt */
703
- attachments?: Attachment[];
704
- /**
705
- * How to handle tool calls for tools without a server-side handler.
706
- *
707
- * - `'placeholder'` (default): write a placeholder tool result and continue the loop.
708
- * Preserves the historical behavior.
709
- * - `'stop-on-client-tool'`: stop the loop, expose pending tool calls on the
710
- * `AgentResponse`, and let the caller (typically the panels chat handler)
711
- * re-submit with tool results once the browser has executed them.
712
- */
713
- toolCallStreamingMode?: 'placeholder' | 'stop-on-client-tool';
714
- /** Tool call ids the user has approved. */
715
- approvedToolCallIds?: string[];
716
- /** Tool call ids the user has rejected. */
717
- rejectedToolCallIds?: string[];
718
- /**
719
- * Optional AbortSignal that cancels the in-flight agent run. Honored at
720
- * iteration boundaries (between provider calls and between failover
721
- * attempts) and forwarded to provider adapters so the underlying network
722
- * request is also cancelled. When the signal aborts, `prompt()` rejects
723
- * (and the streaming variant's `response` promise rejects) with the
724
- * signal's reason — typically `DOMException: This operation was aborted`,
725
- * or `TimeoutError` for `AbortSignal.timeout()`.
726
- */
727
- signal?: AbortSignal;
728
- /**
729
- * When the model emits multiple tool calls in a single step, run their
730
- * `execute()` functions concurrently (`true`, default) instead of one
731
- * after another (`false`). Parallelism applies only to `execute()`; the
732
- * streamed chunk order is preserved as `tool-call A → updates A →
733
- * tool-result A → tool-call B → ...` so consumers see deterministic
734
- * sequences regardless of which tool finishes first.
735
- *
736
- * Approval gates, client-tool pauses, and `onBeforeToolCall` middleware
737
- * decisions still resolve serially in tool-call order *before* any
738
- * `execute()` runs — if a tool needs approval, the loop breaks at that
739
- * point exactly as in serial mode and no later tools are dispatched.
740
- *
741
- * Set to `false` for tools with non-idempotent shared state (counters,
742
- * file writes against the same path, sequential DB transactions).
743
- * Per-call value wins over the agent-wide `Agent.parallelTools()`
744
- * override.
745
- */
746
- parallelTools?: boolean;
747
- /**
748
- * Per-call override for the agent's `cacheable()` declaration.
749
- *
750
- * - `false` — disable caching for this call (overrides any agent default).
751
- * - {@link CacheableConfig} — replace the agent's declaration for this call.
752
- * - omitted — use the agent's declaration unchanged.
753
- */
754
- cache?: false | CacheableConfig;
755
- /**
756
- * Per-call override for the agent's `conversational()` declaration.
757
- *
758
- * - `false` — disable auto-persist for this call (overrides any agent default).
759
- * - {@link ConversationalSpec} — replace the agent's declaration for this call.
760
- * - omitted — use the agent's declaration unchanged.
761
- *
762
- * Explicit `agent.forUser(id)` / `agent.continue(id)` chains shadow this
763
- * override (and the class declaration) — see the docs for the precedence
764
- * chain.
765
- */
766
- conversation?: ConversationalOverride;
767
- /**
768
- * Per-call override for the agent's `remembers()` declaration.
769
- *
770
- * - `false` — disable user-memory for this call (overrides any agent default).
771
- * - {@link RemembersSpec} — replace the agent's declaration for this call.
772
- * - omitted — use the agent's declaration unchanged.
773
- *
774
- * Auto-inject and auto-extract behaviors land in later phases (#A4 Phase 2/3);
775
- * Phase 1 only wires the declaration + per-call precedence chain so manual
776
- * `app().make<UserMemory>('ai.memory')` callers and downstream phases can
777
- * read a consistent spec.
778
- */
779
- memory?: RemembersOverride;
780
- /**
781
- * Continuation-validation hook for the auto-persist / continuation path.
782
- *
783
- * When set and the call runs through conversation persistence
784
- * (`Agent.conversational()`, `forUser()`, or `continue()`), the hook is
785
- * invoked with the server-persisted history and the caller's incoming
786
- * messages just before the agent loop runs. Throw to reject the request
787
- * (forged tool result, rewritten history, cross-user continuation); the
788
- * rejection propagates out of `prompt()` / the stream. Stateless calls
789
- * (no persistence) never invoke it.
790
- *
791
- * Use {@link ContinuationValidator} directly, or
792
- * `defaultContinuationValidator()` from `@rudderjs/ai` for the built-in
793
- * prefix + tool-result-forgery + approval-forgery gate.
794
- */
795
- validate?: ContinuationValidator;
796
- }
797
- /** Options forwarded to a {@link ContinuationValidator}. */
798
- export interface ValidateContinuationOptions {
799
- /** Tool-call ids the caller claims the user approved this turn. */
800
- approvedToolCallIds?: readonly string[];
801
- /** Tool-call ids the caller claims the user rejected this turn. */
802
- rejectedToolCallIds?: readonly string[];
803
- }
804
- /**
805
- * Hook shape consumed by {@link AgentPromptOptions.validate}. Called by
806
- * `runWithPersistence` (and the streaming variant) with the server-persisted
807
- * history and the caller's incoming messages. Throw to reject the
808
- * continuation. See `@rudderjs/ai`'s `validateContinuation` /
809
- * `defaultContinuationValidator` for the reference implementation.
810
- */
811
- export type ContinuationValidator = (persisted: readonly AiMessage[], incoming: readonly AiMessage[], opts: ValidateContinuationOptions) => void | Promise<void>;
812
- /** An attachment (file or image) to include with a prompt */
813
- export interface Attachment {
814
- type: 'image' | 'document';
815
- data: string;
816
- mimeType: string;
817
- name?: string;
818
- }
819
- export interface ConversationStoreMeta {
820
- userId?: string;
821
- resourceSlug?: string;
822
- recordId?: string;
823
- /**
824
- * Optional thread-segregation key — set by the auto-persist machinery so
825
- * one user can talk to multiple agent classes without their threads
826
- * cross-contaminating. Defaults to the agent class's name; overridable
827
- * via the `agent` field returned by `Agent.conversational()`.
828
- */
829
- agent?: string;
830
- }
831
- export interface ConversationStoreListEntry {
832
- id: string;
833
- title: string;
834
- createdAt: Date;
835
- updatedAt?: Date;
836
- /** Mirrors {@link ConversationStoreMeta.agent} on the source row. */
837
- agent?: string;
838
- }
839
- export interface ConversationStore {
840
- create(title?: string, meta?: ConversationStoreMeta): Promise<string>;
841
- load(conversationId: string): Promise<AiMessage[]>;
842
- append(conversationId: string, messages: AiMessage[]): Promise<void>;
843
- setTitle(conversationId: string, title: string): Promise<void>;
844
- list(userId?: string): Promise<ConversationStoreListEntry[]>;
845
- delete?(conversationId: string): Promise<void>;
846
- }
847
- /**
848
- * Return shape of {@link Agent.conversational} when an agent opts into the
849
- * auto-persist behavior. Inspired by Laravel's `RemembersConversations` —
850
- * declare once on the class, then `agent.prompt(input)` auto-loads the user's
851
- * thread, runs, and appends without each caller threading a userId through.
852
- */
853
- export interface ConversationalSpec {
854
- /** Identity of the user owning the conversation thread. */
855
- user: string;
856
- /**
857
- * Specific thread id to resume. When omitted, the auto-persist machinery
858
- * resumes the user's most-recent thread for this `agent` key, or creates
859
- * a new one if none exists.
860
- */
861
- id?: string;
862
- /**
863
- * Override the thread-segregation key. Defaults to the agent class's
864
- * name. Set this when you rename the class but want existing threads to
865
- * keep flowing into the same agent (`agent: 'chat-v2'`), or when two
866
- * different classes should share threads (rare).
867
- */
868
- agent?: string;
869
- /**
870
- * Cap loaded history to the last N messages. Default unbounded. Use this
871
- * for chat agents whose threads can grow long; for token-aware trimming,
872
- * write a middleware instead.
873
- */
874
- historyLimit?: number;
875
- }
876
- /**
877
- * Per-call override for `AgentPromptOptions.conversation`. `false` disables
878
- * auto-persist for this call; a partial spec replaces the agent's
879
- * declaration; omitted falls through to `Agent.conversational()`.
880
- */
881
- export type ConversationalOverride = false | ConversationalSpec;
882
- /**
883
- * A single user-memory entry — a fact about a user, persisted across
884
- * conversations. Backends may add their own internal columns but the
885
- * framework only consumes this shape.
886
- */
887
- export interface MemoryEntry {
888
- id: string;
889
- userId: string;
890
- fact: string;
891
- tags?: string[];
892
- /**
893
- * Optional confidence score in `[0, 1]`. Auto-extract sets this from
894
- * the small model's self-rating; manual `remember()` calls may omit
895
- * it. `recall()` ranking is implementation-defined when scores are
896
- * absent.
897
- */
898
- score?: number;
899
- createdAt: Date;
900
- updatedAt?: Date;
901
- }
902
- /**
903
- * Per-user fact storage. Drop-in alongside `ConversationStore`. Backends
904
- * range from in-process (`MemoryUserMemory`) to ORM-backed (Phase 4) to
905
- * embedding-backed (Phase 5). The interface is intentionally narrow so
906
- * substring-match, full-text, and vector backends all satisfy it.
907
- */
908
- export interface UserMemory {
909
- remember(userId: string, fact: string, opts?: {
910
- tags?: string[];
911
- score?: number;
912
- }): Promise<MemoryEntry>;
913
- recall(userId: string, query: string, opts?: {
914
- limit?: number;
915
- tags?: string[];
916
- }): Promise<MemoryEntry[]>;
917
- forget(userId: string, factId: string): Promise<void>;
918
- list(userId: string, opts?: {
919
- tags?: string[];
920
- limit?: number;
921
- }): Promise<MemoryEntry[]>;
922
- /**
923
- * Optional bulk-erase for GDPR right-to-be-forgotten. Backends that
924
- * don't implement it leave the cascade to the app.
925
- */
926
- forgetAll?(userId: string): Promise<void>;
927
- }
928
- /**
929
- * Return shape of {@link Agent.remembers} when an agent opts into user
930
- * memory. Phase 1 wires the declaration + per-call precedence chain;
931
- * the `inject` and `extract` knobs come live in Phase 2/3.
932
- */
933
- export interface RemembersSpec {
934
- /** Identity of the user whose memory this agent reads/writes. */
935
- user: string;
936
- /**
937
- * Auto-injection policy:
938
- * - `'auto'` (Phase 2) — `recall()` runs before each turn and matches
939
- * are prepended to the system message.
940
- * - `'manual'` — agent code calls `recall()` itself.
941
- * - `false` (default) — no injection.
942
- */
943
- inject?: 'auto' | 'manual' | false;
944
- /**
945
- * Auto-extraction policy:
946
- * - `'auto'` (Phase 3) — a small model distills facts from each turn
947
- * and writes them via `remember()`.
948
- * - `'manual'` — agent code calls `remember()` itself.
949
- * - `false` (default) — no extraction.
950
- */
951
- extract?: 'auto' | 'manual' | false;
952
- /**
953
- * Small-model id for `extract: 'auto'`. Required when extraction is
954
- * enabled. Format: `'<provider>/<model>'`, e.g.
955
- * `'anthropic/claude-haiku-4-5'`.
956
- */
957
- extractWith?: string;
958
- /** Tag scope for both inject and extract. */
959
- tags?: string[];
960
- /** Cap injected facts per turn. Default unbounded (Phase 2). */
961
- injectLimit?: number;
962
- /** Hard token cap on the rendered injected block (Phase 2). */
963
- injectTokenBudget?: number;
964
- }
965
- /**
966
- * Per-call override for `AgentPromptOptions.memory`. `false` disables
967
- * memory for this call; a spec replaces the agent's declaration;
968
- * omitted falls through to `Agent.remembers()`.
969
- */
970
- export type RemembersOverride = false | RemembersSpec;
971
- /**
972
- * Higher-level progress event surfaced by a streaming
973
- * {@link Agent.asTool} wrapper to the parent agent's stream. Emitted as
974
- * `tool-update` chunks with this payload as the chunk's `update` field —
975
- * the parent's UI can switch on `kind` to render sub-agent progress
976
- * (agent name, tool calls in progress, step boundaries, completion,
977
- * suspend pauses).
978
- *
979
- * The default projection emits `agent_start` once at the beginning,
980
- * `tool_call` per inner `tool-call` chunk, `agent_done` once at the end,
981
- * and `subagent_paused` when the inner loop pauses on a client tool.
982
- * For approval-gated tools, the inner loop's `pending-approval` chunk
983
- * surfaces as `agent_pending_approval` (informational, during streaming)
984
- * and the suspend boundary emits `subagent_paused_approval` (carrying
985
- * the `subRunId` the host needs to drive resume). The split mirrors the
986
- * `tool_call` / `subagent_paused` cadence for client tools.
987
- *
988
- * Hosts wanting a different shape pass `streaming: chunk => …` to
989
- * {@link Agent.asTool} and own the discriminator.
990
- */
991
- export type SubAgentUpdate = {
992
- kind: 'agent_start';
993
- agentName: string;
994
- } | {
995
- kind: 'tool_call';
996
- tool: string;
997
- args?: Record<string, unknown>;
998
- } | {
999
- kind: 'agent_step';
1000
- step: number;
1001
- tokens: number;
1002
- } | {
1003
- kind: 'agent_done';
1004
- steps: number;
1005
- tokens: number;
1006
- } | {
1007
- kind: 'subagent_paused';
1008
- subRunId: string;
1009
- pendingToolCallIds: string[];
1010
- } | {
1011
- kind: 'agent_pending_approval';
1012
- toolCall: ToolCall;
1013
- isClientTool: boolean;
1014
- } | {
1015
- kind: 'subagent_paused_approval';
1016
- subRunId: string;
1017
- toolCall: ToolCall;
1018
- isClientTool: boolean;
1019
- };
1020
- //# sourceMappingURL=types.d.ts.map