@od-oneapp/ai-platform 0.1.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 (872) hide show
  1. package/README.md +235 -0
  2. package/dist/agents-base.d.mts +12 -0
  3. package/dist/agents-base.d.mts.map +1 -0
  4. package/dist/agents-base.mjs +20 -0
  5. package/dist/agents-base.mjs.map +1 -0
  6. package/dist/agents-control-flow.d.mts +115 -0
  7. package/dist/agents-control-flow.d.mts.map +1 -0
  8. package/dist/agents-control-flow.mjs +514 -0
  9. package/dist/agents-control-flow.mjs.map +1 -0
  10. package/dist/agents-coordinator.d.mts +11 -0
  11. package/dist/agents-coordinator.d.mts.map +1 -0
  12. package/dist/agents-coordinator.mjs +12 -0
  13. package/dist/agents-coordinator.mjs.map +1 -0
  14. package/dist/agents-experimental.d.mts +153 -0
  15. package/dist/agents-experimental.d.mts.map +1 -0
  16. package/dist/agents-experimental.mjs +580 -0
  17. package/dist/agents-experimental.mjs.map +1 -0
  18. package/dist/agents-fallback.d.mts +10 -0
  19. package/dist/agents-fallback.d.mts.map +1 -0
  20. package/dist/agents-fallback.mjs +15 -0
  21. package/dist/agents-fallback.mjs.map +1 -0
  22. package/dist/agents-multi-swarm.d.mts +9 -0
  23. package/dist/agents-multi-swarm.d.mts.map +1 -0
  24. package/dist/agents-multi-swarm.mjs +44 -0
  25. package/dist/agents-multi-swarm.mjs.map +1 -0
  26. package/dist/agents-multi.d.mts +10 -0
  27. package/dist/agents-multi.d.mts.map +1 -0
  28. package/dist/agents-multi.mjs +44 -0
  29. package/dist/agents-multi.mjs.map +1 -0
  30. package/dist/agents-observability.d.mts +161 -0
  31. package/dist/agents-observability.d.mts.map +1 -0
  32. package/dist/agents-observability.mjs +550 -0
  33. package/dist/agents-observability.mjs.map +1 -0
  34. package/dist/agents-patterns.d.mts +9 -0
  35. package/dist/agents-patterns.d.mts.map +1 -0
  36. package/dist/agents-patterns.mjs +18 -0
  37. package/dist/agents-patterns.mjs.map +1 -0
  38. package/dist/agents-persistence.d.mts +234 -0
  39. package/dist/agents-persistence.d.mts.map +1 -0
  40. package/dist/agents-persistence.mjs +447 -0
  41. package/dist/agents-persistence.mjs.map +1 -0
  42. package/dist/agents-triage.d.mts +11 -0
  43. package/dist/agents-triage.d.mts.map +1 -0
  44. package/dist/agents-triage.mjs +13 -0
  45. package/dist/agents-triage.mjs.map +1 -0
  46. package/dist/agents-workflows.d.mts +9 -0
  47. package/dist/agents-workflows.d.mts.map +1 -0
  48. package/dist/agents-workflows.mjs +9 -0
  49. package/dist/agents-workflows.mjs.map +1 -0
  50. package/dist/agents.d.mts +30 -0
  51. package/dist/agents.d.mts.map +1 -0
  52. package/dist/agents.mjs +50 -0
  53. package/dist/agents.mjs.map +1 -0
  54. package/dist/aggregation-8KJF1uzp.d.mts +276 -0
  55. package/dist/aggregation-8KJF1uzp.d.mts.map +1 -0
  56. package/dist/aggregation-BDop87kL.mjs +1180 -0
  57. package/dist/aggregation-BDop87kL.mjs.map +1 -0
  58. package/dist/ai-runtime-CDzQztTt.mjs +85 -0
  59. package/dist/ai-runtime-CDzQztTt.mjs.map +1 -0
  60. package/dist/ai-runtime-DIwOEc6g.d.mts +56 -0
  61. package/dist/ai-runtime-DIwOEc6g.d.mts.map +1 -0
  62. package/dist/ai-sdk-error-integration-D0GDqrM0.d.mts +553 -0
  63. package/dist/ai-sdk-error-integration-D0GDqrM0.d.mts.map +1 -0
  64. package/dist/approval-queue-BcDDQ4oQ.mjs +104 -0
  65. package/dist/approval-queue-BcDDQ4oQ.mjs.map +1 -0
  66. package/dist/approval-queue-CiKiFT9z.d.mts +21 -0
  67. package/dist/approval-queue-CiKiFT9z.d.mts.map +1 -0
  68. package/dist/audio-BzvN7r10.d.mts +79 -0
  69. package/dist/audio-BzvN7r10.d.mts.map +1 -0
  70. package/dist/audio-vBG_62ME.mjs +226 -0
  71. package/dist/audio-vBG_62ME.mjs.map +1 -0
  72. package/dist/audit-logger-Bb2JIcIk.d.mts +12 -0
  73. package/dist/audit-logger-Bb2JIcIk.d.mts.map +1 -0
  74. package/dist/audit-logger-CHIP8bRO.mjs +596 -0
  75. package/dist/audit-logger-CHIP8bRO.mjs.map +1 -0
  76. package/dist/auto-resume-BpUNbPtp.d.mts +160 -0
  77. package/dist/auto-resume-BpUNbPtp.d.mts.map +1 -0
  78. package/dist/auto-resume-BuFRNvAX.mjs +638 -0
  79. package/dist/auto-resume-BuFRNvAX.mjs.map +1 -0
  80. package/dist/budget-guard-C83KCH9V.d.mts +52 -0
  81. package/dist/budget-guard-C83KCH9V.d.mts.map +1 -0
  82. package/dist/budget-guard-d_b5rq4u.mjs +158 -0
  83. package/dist/budget-guard-d_b5rq4u.mjs.map +1 -0
  84. package/dist/budget-guard-gyhJS00s.mjs +234 -0
  85. package/dist/budget-guard-gyhJS00s.mjs.map +1 -0
  86. package/dist/buffer-BC8mvXHE.d.mts +98 -0
  87. package/dist/buffer-BC8mvXHE.d.mts.map +1 -0
  88. package/dist/buffer-CefJGbRy.mjs +289 -0
  89. package/dist/buffer-CefJGbRy.mjs.map +1 -0
  90. package/dist/caching-adapters.d.mts +5 -0
  91. package/dist/caching-adapters.mjs +3 -0
  92. package/dist/caching-strategies.d.mts +52 -0
  93. package/dist/caching-strategies.d.mts.map +1 -0
  94. package/dist/caching-strategies.mjs +703 -0
  95. package/dist/caching-strategies.mjs.map +1 -0
  96. package/dist/caching.d.mts +14 -0
  97. package/dist/caching.d.mts.map +1 -0
  98. package/dist/caching.mjs +15 -0
  99. package/dist/caching.mjs.map +1 -0
  100. package/dist/catalog.d.mts +19 -0
  101. package/dist/catalog.d.mts.map +1 -0
  102. package/dist/catalog.mjs +1114 -0
  103. package/dist/catalog.mjs.map +1 -0
  104. package/dist/chunk-CkzbjWQW.mjs +20 -0
  105. package/dist/circuit-breaker-DoKWPORd.mjs +262 -0
  106. package/dist/circuit-breaker-DoKWPORd.mjs.map +1 -0
  107. package/dist/circuit-breaker-Mey3E7tW.d.mts +64 -0
  108. package/dist/circuit-breaker-Mey3E7tW.d.mts.map +1 -0
  109. package/dist/citation-generator-C-9RpbHq.mjs +103 -0
  110. package/dist/citation-generator-C-9RpbHq.mjs.map +1 -0
  111. package/dist/citation-generator-CDSymDs_.d.mts +18 -0
  112. package/dist/citation-generator-CDSymDs_.d.mts.map +1 -0
  113. package/dist/client-CpacYDIE.mjs +882 -0
  114. package/dist/client-CpacYDIE.mjs.map +1 -0
  115. package/dist/client.d.mts +103 -0
  116. package/dist/client.d.mts.map +1 -0
  117. package/dist/client.mjs +470 -0
  118. package/dist/client.mjs.map +1 -0
  119. package/dist/compliance-approval-queue-DQGLojAm.mjs +172 -0
  120. package/dist/compliance-approval-queue-DQGLojAm.mjs.map +1 -0
  121. package/dist/compliance-approval-queue-IrMxFfSJ.d.mts +99 -0
  122. package/dist/compliance-approval-queue-IrMxFfSJ.d.mts.map +1 -0
  123. package/dist/compliance-wrapper-CrOMHhHN.mjs +528 -0
  124. package/dist/compliance-wrapper-CrOMHhHN.mjs.map +1 -0
  125. package/dist/conditions-DmQ6Y1Wt.mjs +179 -0
  126. package/dist/conditions-DmQ6Y1Wt.mjs.map +1 -0
  127. package/dist/conditions-zDrKfrc3.d.mts +42 -0
  128. package/dist/conditions-zDrKfrc3.d.mts.map +1 -0
  129. package/dist/console-BGMxxPZN.mjs +181 -0
  130. package/dist/console-BGMxxPZN.mjs.map +1 -0
  131. package/dist/console-DqEqZd4A.d.mts +76 -0
  132. package/dist/console-DqEqZd4A.d.mts.map +1 -0
  133. package/dist/controller-BOy3-xbC.mjs +501 -0
  134. package/dist/controller-BOy3-xbC.mjs.map +1 -0
  135. package/dist/controller-Y0NGosbJ.d.mts +104 -0
  136. package/dist/controller-Y0NGosbJ.d.mts.map +1 -0
  137. package/dist/coordinator-agent-BglqZLwo.d.mts +54 -0
  138. package/dist/coordinator-agent-BglqZLwo.d.mts.map +1 -0
  139. package/dist/coordinator-agent-WFWBRL-G.mjs +236 -0
  140. package/dist/coordinator-agent-WFWBRL-G.mjs.map +1 -0
  141. package/dist/crypto-8ABhc3TD.mjs +40 -0
  142. package/dist/crypto-8ABhc3TD.mjs.map +1 -0
  143. package/dist/environment-CSoJb0SW.mjs +255 -0
  144. package/dist/environment-CSoJb0SW.mjs.map +1 -0
  145. package/dist/error-handling-DNVkm6RY.mjs +1334 -0
  146. package/dist/error-handling-DNVkm6RY.mjs.map +1 -0
  147. package/dist/errors-CQ8tF4dP.mjs +985 -0
  148. package/dist/errors-CQ8tF4dP.mjs.map +1 -0
  149. package/dist/errors-CfYdVeum.d.mts +212 -0
  150. package/dist/errors-CfYdVeum.d.mts.map +1 -0
  151. package/dist/errors-Dtn-UeRi.mjs +61 -0
  152. package/dist/errors-Dtn-UeRi.mjs.map +1 -0
  153. package/dist/evaluator-Cs84qkr8.mjs +91 -0
  154. package/dist/evaluator-Cs84qkr8.mjs.map +1 -0
  155. package/dist/evaluator-optimizer-De67_mJC.mjs +1086 -0
  156. package/dist/evaluator-optimizer-De67_mJC.mjs.map +1 -0
  157. package/dist/evaluator-optimizer-pattern-B5939s2Z.mjs +367 -0
  158. package/dist/evaluator-optimizer-pattern-B5939s2Z.mjs.map +1 -0
  159. package/dist/evaluator-optimizer-pattern-D1AJrzBD.d.mts +72 -0
  160. package/dist/evaluator-optimizer-pattern-D1AJrzBD.d.mts.map +1 -0
  161. package/dist/factory-DP6VSl8C.mjs +307 -0
  162. package/dist/factory-DP6VSl8C.mjs.map +1 -0
  163. package/dist/generative-ui-catalog.d.mts +8 -0
  164. package/dist/generative-ui-catalog.d.mts.map +1 -0
  165. package/dist/generative-ui-catalog.mjs +679 -0
  166. package/dist/generative-ui-catalog.mjs.map +1 -0
  167. package/dist/generative-ui-registry.d.mts +195 -0
  168. package/dist/generative-ui-registry.d.mts.map +1 -0
  169. package/dist/generative-ui-registry.mjs +250 -0
  170. package/dist/generative-ui-registry.mjs.map +1 -0
  171. package/dist/generative-ui-stream.d.mts +23 -0
  172. package/dist/generative-ui-stream.d.mts.map +1 -0
  173. package/dist/generative-ui-stream.mjs +219 -0
  174. package/dist/generative-ui-stream.mjs.map +1 -0
  175. package/dist/generative-ui-types.d.mts +123 -0
  176. package/dist/generative-ui-types.d.mts.map +1 -0
  177. package/dist/generative-ui-types.mjs +1 -0
  178. package/dist/generative-ui.d.mts +13 -0
  179. package/dist/generative-ui.d.mts.map +1 -0
  180. package/dist/generative-ui.mjs +21 -0
  181. package/dist/generative-ui.mjs.map +1 -0
  182. package/dist/governance-audit.d.mts +3 -0
  183. package/dist/governance-audit.mjs +3 -0
  184. package/dist/governance-compliance.d.mts +5 -0
  185. package/dist/governance-compliance.mjs +4 -0
  186. package/dist/governance-policies.d.mts +4 -0
  187. package/dist/governance-policies.mjs +4 -0
  188. package/dist/governance-tenancy.d.mts +3 -0
  189. package/dist/governance-tenancy.mjs +3 -0
  190. package/dist/governance.d.mts +88 -0
  191. package/dist/governance.d.mts.map +1 -0
  192. package/dist/governance.mjs +432 -0
  193. package/dist/governance.mjs.map +1 -0
  194. package/dist/grounding-attribution.d.mts +63 -0
  195. package/dist/grounding-attribution.d.mts.map +1 -0
  196. package/dist/grounding-attribution.mjs +259 -0
  197. package/dist/grounding-attribution.mjs.map +1 -0
  198. package/dist/grounding-citation.d.mts +2 -0
  199. package/dist/grounding-citation.mjs +3 -0
  200. package/dist/grounding-context.d.mts +9 -0
  201. package/dist/grounding-context.d.mts.map +1 -0
  202. package/dist/grounding-context.mjs +19 -0
  203. package/dist/grounding-context.mjs.map +1 -0
  204. package/dist/grounding-embed.d.mts +102 -0
  205. package/dist/grounding-embed.d.mts.map +1 -0
  206. package/dist/grounding-embed.mjs +417 -0
  207. package/dist/grounding-embed.mjs.map +1 -0
  208. package/dist/grounding-hallucination.d.mts +44 -0
  209. package/dist/grounding-hallucination.d.mts.map +1 -0
  210. package/dist/grounding-hallucination.mjs +115 -0
  211. package/dist/grounding-hallucination.mjs.map +1 -0
  212. package/dist/grounding-proof-map.d.mts +9 -0
  213. package/dist/grounding-proof-map.d.mts.map +1 -0
  214. package/dist/grounding-proof-map.mjs +26 -0
  215. package/dist/grounding-proof-map.mjs.map +1 -0
  216. package/dist/grounding-rag.d.mts +10 -0
  217. package/dist/grounding-rag.d.mts.map +1 -0
  218. package/dist/grounding-rag.mjs +27 -0
  219. package/dist/grounding-rag.mjs.map +1 -0
  220. package/dist/grounding-verification.d.mts +48 -0
  221. package/dist/grounding-verification.d.mts.map +1 -0
  222. package/dist/grounding-verification.mjs +224 -0
  223. package/dist/grounding-verification.mjs.map +1 -0
  224. package/dist/grounding.d.mts +24 -0
  225. package/dist/grounding.d.mts.map +1 -0
  226. package/dist/grounding.mjs +77 -0
  227. package/dist/grounding.mjs.map +1 -0
  228. package/dist/hitl-active-learning.d.mts +41 -0
  229. package/dist/hitl-active-learning.d.mts.map +1 -0
  230. package/dist/hitl-active-learning.mjs +178 -0
  231. package/dist/hitl-active-learning.mjs.map +1 -0
  232. package/dist/hitl-annotation.d.mts +74 -0
  233. package/dist/hitl-annotation.d.mts.map +1 -0
  234. package/dist/hitl-annotation.mjs +170 -0
  235. package/dist/hitl-annotation.mjs.map +1 -0
  236. package/dist/hitl-approval.d.mts +2 -0
  237. package/dist/hitl-approval.mjs +3 -0
  238. package/dist/hitl-feedback.d.mts +59 -0
  239. package/dist/hitl-feedback.d.mts.map +1 -0
  240. package/dist/hitl-feedback.mjs +137 -0
  241. package/dist/hitl-feedback.mjs.map +1 -0
  242. package/dist/hitl-review.d.mts +2 -0
  243. package/dist/hitl-review.mjs +3 -0
  244. package/dist/hitl.d.mts +14 -0
  245. package/dist/hitl.d.mts.map +1 -0
  246. package/dist/hitl.mjs +22 -0
  247. package/dist/hitl.mjs.map +1 -0
  248. package/dist/index-B17HT-VL.d.mts +285 -0
  249. package/dist/index-B17HT-VL.d.mts.map +1 -0
  250. package/dist/index-BDwgsK9B.d.mts +101 -0
  251. package/dist/index-BDwgsK9B.d.mts.map +1 -0
  252. package/dist/index-BGgMn_Ev.d.mts +2615 -0
  253. package/dist/index-BGgMn_Ev.d.mts.map +1 -0
  254. package/dist/index-DOqe5r9G.d.mts +318 -0
  255. package/dist/index-DOqe5r9G.d.mts.map +1 -0
  256. package/dist/index-DotINT7o.d.mts +1004 -0
  257. package/dist/index-DotINT7o.d.mts.map +1 -0
  258. package/dist/index-URlW7aD1.d.mts +67 -0
  259. package/dist/index-URlW7aD1.d.mts.map +1 -0
  260. package/dist/index.d.mts +64 -0
  261. package/dist/index.d.mts.map +1 -0
  262. package/dist/index.mjs +46 -0
  263. package/dist/index.mjs.map +1 -0
  264. package/dist/integrations-blob-storage.d.mts +25 -0
  265. package/dist/integrations-blob-storage.d.mts.map +1 -0
  266. package/dist/integrations-blob-storage.mjs +3 -0
  267. package/dist/integrations-notifications.d.mts +2 -0
  268. package/dist/integrations-notifications.mjs +3 -0
  269. package/dist/integrations-rate-limit.d.mts +27 -0
  270. package/dist/integrations-rate-limit.d.mts.map +1 -0
  271. package/dist/integrations-rate-limit.mjs +30 -0
  272. package/dist/integrations-rate-limit.mjs.map +1 -0
  273. package/dist/integrations-redis.d.mts +3 -0
  274. package/dist/integrations-redis.mjs +3 -0
  275. package/dist/integrations-stream.d.mts +14 -0
  276. package/dist/integrations-stream.d.mts.map +1 -0
  277. package/dist/integrations-stream.mjs +3 -0
  278. package/dist/integrations.d.mts +7 -0
  279. package/dist/integrations.mjs +7 -0
  280. package/dist/log-adapter-BLegSZtz.d.mts +16 -0
  281. package/dist/log-adapter-BLegSZtz.d.mts.map +1 -0
  282. package/dist/log-adapter-PPe_2Pwv.mjs +28 -0
  283. package/dist/log-adapter-PPe_2Pwv.mjs.map +1 -0
  284. package/dist/loop-BOYEtr2g.mjs +520 -0
  285. package/dist/loop-BOYEtr2g.mjs.map +1 -0
  286. package/dist/loop-C-tBBOqi.d.mts +219 -0
  287. package/dist/loop-C-tBBOqi.d.mts.map +1 -0
  288. package/dist/middleware-5wQ9bANW.mjs +306 -0
  289. package/dist/middleware-5wQ9bANW.mjs.map +1 -0
  290. package/dist/middleware-C1apSrj0.mjs +613 -0
  291. package/dist/middleware-C1apSrj0.mjs.map +1 -0
  292. package/dist/middleware-C7k0uItW.d.mts +9 -0
  293. package/dist/middleware-C7k0uItW.d.mts.map +1 -0
  294. package/dist/middleware-CZQCTHfl.mjs +366 -0
  295. package/dist/middleware-CZQCTHfl.mjs.map +1 -0
  296. package/dist/models.d.mts +11 -0
  297. package/dist/models.d.mts.map +1 -0
  298. package/dist/models.mjs +32 -0
  299. package/dist/models.mjs.map +1 -0
  300. package/dist/observability-analytics.d.mts +107 -0
  301. package/dist/observability-analytics.d.mts.map +1 -0
  302. package/dist/observability-analytics.mjs +409 -0
  303. package/dist/observability-analytics.mjs.map +1 -0
  304. package/dist/observability-cost.d.mts +10 -0
  305. package/dist/observability-cost.d.mts.map +1 -0
  306. package/dist/observability-cost.mjs +15 -0
  307. package/dist/observability-cost.mjs.map +1 -0
  308. package/dist/observability-telemetry.d.mts +111 -0
  309. package/dist/observability-telemetry.d.mts.map +1 -0
  310. package/dist/observability-telemetry.mjs +343 -0
  311. package/dist/observability-telemetry.mjs.map +1 -0
  312. package/dist/observability-tracing.d.mts +10 -0
  313. package/dist/observability-tracing.d.mts.map +1 -0
  314. package/dist/observability-tracing.mjs +17 -0
  315. package/dist/observability-tracing.mjs.map +1 -0
  316. package/dist/observability.d.mts +15 -0
  317. package/dist/observability.d.mts.map +1 -0
  318. package/dist/observability.mjs +17 -0
  319. package/dist/observability.mjs.map +1 -0
  320. package/dist/optimizer-DhXXpci6.mjs +97 -0
  321. package/dist/optimizer-DhXXpci6.mjs.map +1 -0
  322. package/dist/output-multimodal.d.mts +9 -0
  323. package/dist/output-multimodal.d.mts.map +1 -0
  324. package/dist/output-multimodal.mjs +18 -0
  325. package/dist/output-multimodal.mjs.map +1 -0
  326. package/dist/output.d.mts +11 -0
  327. package/dist/output.d.mts.map +1 -0
  328. package/dist/output.mjs +40 -0
  329. package/dist/output.mjs.map +1 -0
  330. package/dist/pii-filter-3AxmYSiu.d.mts +23 -0
  331. package/dist/pii-filter-3AxmYSiu.d.mts.map +1 -0
  332. package/dist/pipelines.d.mts +448 -0
  333. package/dist/pipelines.d.mts.map +1 -0
  334. package/dist/pipelines.mjs +1534 -0
  335. package/dist/pipelines.mjs.map +1 -0
  336. package/dist/prompt-injection-DQXchzsV.d.mts +8 -0
  337. package/dist/prompt-injection-DQXchzsV.d.mts.map +1 -0
  338. package/dist/prompt-injection-RpoLPwSa.mjs +52 -0
  339. package/dist/prompt-injection-RpoLPwSa.mjs.map +1 -0
  340. package/dist/prompts.d.mts +192 -0
  341. package/dist/prompts.d.mts.map +1 -0
  342. package/dist/prompts.mjs +732 -0
  343. package/dist/prompts.mjs.map +1 -0
  344. package/dist/protocol-DfBiEsnl.d.mts +112 -0
  345. package/dist/protocol-DfBiEsnl.d.mts.map +1 -0
  346. package/dist/quota-manager-0iPMkQWN.d.mts +62 -0
  347. package/dist/quota-manager-0iPMkQWN.d.mts.map +1 -0
  348. package/dist/quota-manager-D_N7FuQ2.mjs +180 -0
  349. package/dist/quota-manager-D_N7FuQ2.mjs.map +1 -0
  350. package/dist/redaction-utils-DcQwsiNh.mjs +438 -0
  351. package/dist/redaction-utils-DcQwsiNh.mjs.map +1 -0
  352. package/dist/redis-CpsSrF8K.mjs +102 -0
  353. package/dist/redis-CpsSrF8K.mjs.map +1 -0
  354. package/dist/redis-CwguYFGh.d.mts +33 -0
  355. package/dist/redis-CwguYFGh.d.mts.map +1 -0
  356. package/dist/registry-CsD3iTIx.mjs +190 -0
  357. package/dist/registry-CsD3iTIx.mjs.map +1 -0
  358. package/dist/registry-DVPWzkXR.d.mts +36 -0
  359. package/dist/registry-DVPWzkXR.d.mts.map +1 -0
  360. package/dist/reranking-BpWYhYzl.d.mts +72 -0
  361. package/dist/reranking-BpWYhYzl.d.mts.map +1 -0
  362. package/dist/reranking-Ck8aKZW7.mjs +331 -0
  363. package/dist/reranking-Ck8aKZW7.mjs.map +1 -0
  364. package/dist/resumable-adapter-CO1HtsgJ.mjs +21 -0
  365. package/dist/resumable-adapter-CO1HtsgJ.mjs.map +1 -0
  366. package/dist/review-trigger-DmAsiQlM.d.mts +24 -0
  367. package/dist/review-trigger-DmAsiQlM.d.mts.map +1 -0
  368. package/dist/review-trigger-DwXfpww9.mjs +112 -0
  369. package/dist/review-trigger-DwXfpww9.mjs.map +1 -0
  370. package/dist/safe-context-BynhkTKR.d.mts +54 -0
  371. package/dist/safe-context-BynhkTKR.d.mts.map +1 -0
  372. package/dist/safe-context-C5A3Wv3b.mjs +143 -0
  373. package/dist/safe-context-C5A3Wv3b.mjs.map +1 -0
  374. package/dist/schema-Bu2noOZ4.mjs +27 -0
  375. package/dist/schema-Bu2noOZ4.mjs.map +1 -0
  376. package/dist/schema-CwFvuCnA.mjs +97 -0
  377. package/dist/schema-CwFvuCnA.mjs.map +1 -0
  378. package/dist/schema-Wz-1-ro9.d.mts +37 -0
  379. package/dist/schema-Wz-1-ro9.d.mts.map +1 -0
  380. package/dist/schemas-CxQtxIga.mjs +62 -0
  381. package/dist/schemas-CxQtxIga.mjs.map +1 -0
  382. package/dist/schemas-DBOhxgW7.d.mts +32 -0
  383. package/dist/schemas-DBOhxgW7.d.mts.map +1 -0
  384. package/dist/schemas-Dp_OCqBt.d.mts +63 -0
  385. package/dist/schemas-Dp_OCqBt.d.mts.map +1 -0
  386. package/dist/schemas-SwCsnT0z.mjs +83 -0
  387. package/dist/schemas-SwCsnT0z.mjs.map +1 -0
  388. package/dist/sdk-errors.d.mts +2 -0
  389. package/dist/sdk-errors.mjs +3 -0
  390. package/dist/sdk-experimental.d.mts +59 -0
  391. package/dist/sdk-experimental.d.mts.map +1 -0
  392. package/dist/sdk-experimental.mjs +193 -0
  393. package/dist/sdk-experimental.mjs.map +1 -0
  394. package/dist/sdk-stop-conditions.d.mts +3 -0
  395. package/dist/sdk-stop-conditions.mjs +3 -0
  396. package/dist/sdk.d.mts +15 -0
  397. package/dist/sdk.d.mts.map +1 -0
  398. package/dist/sdk.mjs +50 -0
  399. package/dist/sdk.mjs.map +1 -0
  400. package/dist/security-guardrails.d.mts +3 -0
  401. package/dist/security-guardrails.mjs +3 -0
  402. package/dist/security-injection.d.mts +2 -0
  403. package/dist/security-injection.mjs +3 -0
  404. package/dist/security.d.mts +12 -0
  405. package/dist/security.d.mts.map +1 -0
  406. package/dist/security.mjs +18 -0
  407. package/dist/security.mjs.map +1 -0
  408. package/dist/server.d.mts +420 -0
  409. package/dist/server.d.mts.map +1 -0
  410. package/dist/server.mjs +2225 -0
  411. package/dist/server.mjs.map +1 -0
  412. package/dist/shared.d.mts +2 -0
  413. package/dist/shared.mjs +3 -0
  414. package/dist/streaming-control.d.mts +2 -0
  415. package/dist/streaming-control.mjs +4 -0
  416. package/dist/streaming-core.d.mts +4 -0
  417. package/dist/streaming-core.mjs +3 -0
  418. package/dist/streaming-infra-resilience.d.mts +120 -0
  419. package/dist/streaming-infra-resilience.d.mts.map +1 -0
  420. package/dist/streaming-infra-resilience.mjs +358 -0
  421. package/dist/streaming-infra-resilience.mjs.map +1 -0
  422. package/dist/streaming-infra-transport.d.mts +57 -0
  423. package/dist/streaming-infra-transport.d.mts.map +1 -0
  424. package/dist/streaming-infra-transport.mjs +488 -0
  425. package/dist/streaming-infra-transport.mjs.map +1 -0
  426. package/dist/streaming-infra.d.mts +5 -0
  427. package/dist/streaming-infra.mjs +5 -0
  428. package/dist/streaming.d.mts +17 -0
  429. package/dist/streaming.d.mts.map +1 -0
  430. package/dist/streaming.mjs +71 -0
  431. package/dist/streaming.mjs.map +1 -0
  432. package/dist/telemetry-2eKMojIb.mjs +1046 -0
  433. package/dist/telemetry-2eKMojIb.mjs.map +1 -0
  434. package/dist/telemetry-C2t03dwD.d.mts +59 -0
  435. package/dist/telemetry-C2t03dwD.d.mts.map +1 -0
  436. package/dist/tool-Btbththq.d.mts +253 -0
  437. package/dist/tool-Btbththq.d.mts.map +1 -0
  438. package/dist/tool-JSf8JXZ8.mjs +1150 -0
  439. package/dist/tool-JSf8JXZ8.mjs.map +1 -0
  440. package/dist/tool-safety-CZO8a4D4.d.mts +60 -0
  441. package/dist/tool-safety-CZO8a4D4.d.mts.map +1 -0
  442. package/dist/tool-safety-DXtYDXod.mjs +319 -0
  443. package/dist/tool-safety-DXtYDXod.mjs.map +1 -0
  444. package/dist/tools-BuS2Uv0q.mjs +1708 -0
  445. package/dist/tools-BuS2Uv0q.mjs.map +1 -0
  446. package/dist/tools-approval.d.mts +99 -0
  447. package/dist/tools-approval.d.mts.map +1 -0
  448. package/dist/tools-approval.mjs +395 -0
  449. package/dist/tools-approval.mjs.map +1 -0
  450. package/dist/tools-compliance.d.mts +67 -0
  451. package/dist/tools-compliance.d.mts.map +1 -0
  452. package/dist/tools-compliance.mjs +330 -0
  453. package/dist/tools-compliance.mjs.map +1 -0
  454. package/dist/tools-computer.d.mts +25 -0
  455. package/dist/tools-computer.d.mts.map +1 -0
  456. package/dist/tools-computer.mjs +64 -0
  457. package/dist/tools-computer.mjs.map +1 -0
  458. package/dist/tools-core.d.mts +3 -0
  459. package/dist/tools-core.mjs +3 -0
  460. package/dist/tools-mcp.d.mts +3 -0
  461. package/dist/tools-mcp.mjs +5 -0
  462. package/dist/tools-superpowers.d.mts +2 -0
  463. package/dist/tools-superpowers.mjs +3 -0
  464. package/dist/tools.d.mts +401 -0
  465. package/dist/tools.d.mts.map +1 -0
  466. package/dist/tools.mjs +1921 -0
  467. package/dist/tools.mjs.map +1 -0
  468. package/dist/transport-selector-D-Ib05X1.mjs +1936 -0
  469. package/dist/transport-selector-D-Ib05X1.mjs.map +1 -0
  470. package/dist/triage-agent-BEsXg5sw.d.mts +63 -0
  471. package/dist/triage-agent-BEsXg5sw.d.mts.map +1 -0
  472. package/dist/triage-agent-CBsfX-HW.mjs +167 -0
  473. package/dist/triage-agent-CBsfX-HW.mjs.map +1 -0
  474. package/dist/types-BPnq3GQo.d.mts +23 -0
  475. package/dist/types-BPnq3GQo.d.mts.map +1 -0
  476. package/dist/types-BjWgimpY.d.mts +16 -0
  477. package/dist/types-BjWgimpY.d.mts.map +1 -0
  478. package/dist/types-BxD-5btB.d.mts +41 -0
  479. package/dist/types-BxD-5btB.d.mts.map +1 -0
  480. package/dist/types-By-r93bE.d.mts +36 -0
  481. package/dist/types-By-r93bE.d.mts.map +1 -0
  482. package/dist/types-CLBWFRZN.d.mts +69 -0
  483. package/dist/types-CLBWFRZN.d.mts.map +1 -0
  484. package/dist/types-CQ0HFd0u.d.mts +62 -0
  485. package/dist/types-CQ0HFd0u.d.mts.map +1 -0
  486. package/dist/types-D3zJb59_.d.mts +47 -0
  487. package/dist/types-D3zJb59_.d.mts.map +1 -0
  488. package/dist/types-DJnugQX0.d.mts +80 -0
  489. package/dist/types-DJnugQX0.d.mts.map +1 -0
  490. package/dist/types-DbUfMCnT.d.mts +70 -0
  491. package/dist/types-DbUfMCnT.d.mts.map +1 -0
  492. package/dist/upstash-adapter-D96Caq2O.mjs +22 -0
  493. package/dist/upstash-adapter-D96Caq2O.mjs.map +1 -0
  494. package/dist/upstash-adapter-DD4433dx.d.mts +8 -0
  495. package/dist/upstash-adapter-DD4433dx.d.mts.map +1 -0
  496. package/dist/utils-BlYhcD6M.mjs +319 -0
  497. package/dist/utils-BlYhcD6M.mjs.map +1 -0
  498. package/dist/utils-DpJGOb3y.d.mts +120 -0
  499. package/dist/utils-DpJGOb3y.d.mts.map +1 -0
  500. package/dist/vercel-blob-adapter-CkOXLT2D.mjs +25 -0
  501. package/dist/vercel-blob-adapter-CkOXLT2D.mjs.map +1 -0
  502. package/dist/xai-CbV_dCnP.mjs +1600 -0
  503. package/dist/xai-CbV_dCnP.mjs.map +1 -0
  504. package/package.json +479 -0
  505. package/src/agents/base/factory.ts +382 -0
  506. package/src/agents/base/index.ts +8 -0
  507. package/src/agents/base/schemas.ts +117 -0
  508. package/src/agents/base/types.ts +192 -0
  509. package/src/agents/control-flow/index.ts +683 -0
  510. package/src/agents/coordinator/coordinator-agent.ts +381 -0
  511. package/src/agents/coordinator/index.ts +6 -0
  512. package/src/agents/default-agent.ts +211 -0
  513. package/src/agents/evaluator-optimizer/README.md +612 -0
  514. package/src/agents/evaluator-optimizer/evaluator-optimizer.example.ts +437 -0
  515. package/src/agents/evaluator-optimizer/evaluator.ts +282 -0
  516. package/src/agents/evaluator-optimizer/index.test.ts +416 -0
  517. package/src/agents/evaluator-optimizer/index.ts +519 -0
  518. package/src/agents/evaluator-optimizer/optimizer.ts +322 -0
  519. package/src/agents/evaluator-optimizer/schema.ts +302 -0
  520. package/src/agents/evaluator-optimizer/utils.ts +42 -0
  521. package/src/agents/experimental/index.ts +1095 -0
  522. package/src/agents/experimental/types.ts +212 -0
  523. package/src/agents/fallback/index.ts +18 -0
  524. package/src/agents/fallback/recovery/circuit-breaker.ts +166 -0
  525. package/src/agents/fallback/strategies/model-fallback.ts +192 -0
  526. package/src/agents/fallback/types.ts +87 -0
  527. package/src/agents/governance-agent.ts +446 -0
  528. package/src/agents/index.ts +79 -0
  529. package/src/agents/multi/coordination/index.ts +6 -0
  530. package/src/agents/multi/coordination/message-bus.ts +144 -0
  531. package/src/agents/multi/index.ts +6 -0
  532. package/src/agents/multi/state/index.ts +162 -0
  533. package/src/agents/multi/supervisor/index.ts +7 -0
  534. package/src/agents/multi/supervisor/supervisor.ts +254 -0
  535. package/src/agents/multi/swarm/aggregation.ts +466 -0
  536. package/src/agents/multi/swarm/communication.ts +388 -0
  537. package/src/agents/multi/swarm/coordination.ts +380 -0
  538. package/src/agents/multi/swarm/index.ts +73 -0
  539. package/src/agents/multi/swarm/swarm-executor.ts +479 -0
  540. package/src/agents/multi/types.ts +181 -0
  541. package/src/agents/observability/index.ts +914 -0
  542. package/src/agents/orchestrator.ts +218 -0
  543. package/src/agents/patterns/README.md +512 -0
  544. package/src/agents/patterns/evaluator-optimizer-pattern.example.ts +455 -0
  545. package/src/agents/patterns/evaluator-optimizer-pattern.ts +653 -0
  546. package/src/agents/patterns/index.ts +26 -0
  547. package/src/agents/persistence/index.ts +726 -0
  548. package/src/agents/tools/index.ts +291 -0
  549. package/src/agents/tools/mcp.ts +188 -0
  550. package/src/agents/triage/index.ts +6 -0
  551. package/src/agents/triage/triage-agent.ts +280 -0
  552. package/src/agents/workflows/index.ts +6 -0
  553. package/src/agents/workflows/interfaces.ts +36 -0
  554. package/src/agents/workflows/schema.ts +20 -0
  555. package/src/caching/adapters/index.ts +7 -0
  556. package/src/caching/adapters/memory.ts +77 -0
  557. package/src/caching/adapters/redis.ts +60 -0
  558. package/src/caching/index.ts +17 -0
  559. package/src/caching/middleware.ts +452 -0
  560. package/src/caching/strategies/index.ts +1008 -0
  561. package/src/caching/types.ts +47 -0
  562. package/src/catalog.ts +921 -0
  563. package/src/client/chat-usage.ts +53 -0
  564. package/src/client/hooks.ts +343 -0
  565. package/src/client/index.ts +36 -0
  566. package/src/client/message-utils.ts +29 -0
  567. package/src/client/use-generative-ui.ts +174 -0
  568. package/src/client/utils.ts +66 -0
  569. package/src/generative-ui/catalog.ts +653 -0
  570. package/src/generative-ui/index.ts +82 -0
  571. package/src/generative-ui/registry.ts +273 -0
  572. package/src/generative-ui/stream.ts +324 -0
  573. package/src/generative-ui/types.ts +376 -0
  574. package/src/governance/audit/audit-logger.ts +239 -0
  575. package/src/governance/audit/audit-schema.ts +82 -0
  576. package/src/governance/audit/index.ts +6 -0
  577. package/src/governance/compliance/abac/policy-engine.ts +175 -0
  578. package/src/governance/compliance/abac/types.ts +40 -0
  579. package/src/governance/compliance/approval/compliance-approval-queue.ts +217 -0
  580. package/src/governance/compliance/index.ts +16 -0
  581. package/src/governance/compliance/schemas.ts +68 -0
  582. package/src/governance/compliance/types.ts +143 -0
  583. package/src/governance/compliance/validators/phi-detector.ts +145 -0
  584. package/src/governance/compliance/validators/redaction-utils.ts +176 -0
  585. package/src/governance/compliance/validators/safe-harbor.ts +135 -0
  586. package/src/governance/entitlements/index.ts +585 -0
  587. package/src/governance/entitlements/middleware.ts +651 -0
  588. package/src/governance/entitlements/rate-limiter.ts +711 -0
  589. package/src/governance/index.ts +32 -0
  590. package/src/governance/policies/guardrails.ts +1121 -0
  591. package/src/governance/policies/index.ts +42 -0
  592. package/src/governance/policies/loop-controls.ts +136 -0
  593. package/src/governance/policies/telemetry.ts +63 -0
  594. package/src/governance/tenancy/index.ts +30 -0
  595. package/src/governance/tenancy/isolation/context.ts +92 -0
  596. package/src/governance/tenancy/isolation/index.ts +13 -0
  597. package/src/governance/tenancy/quotas/index.ts +11 -0
  598. package/src/governance/tenancy/quotas/quota-manager.ts +180 -0
  599. package/src/governance/tenancy/types.ts +66 -0
  600. package/src/governance/types.ts +16 -0
  601. package/src/governance/versioning/index.ts +573 -0
  602. package/src/grounding/attribution/index.ts +424 -0
  603. package/src/grounding/citation/citation-generator.ts +174 -0
  604. package/src/grounding/citation/index.ts +12 -0
  605. package/src/grounding/context/index.ts +32 -0
  606. package/src/grounding/context/safe-context.ts +116 -0
  607. package/src/grounding/context/types.ts +62 -0
  608. package/src/grounding/context-engineering/error-handling.ts +359 -0
  609. package/src/grounding/context-engineering/index.ts +23 -0
  610. package/src/grounding/context-engineering/memory.ts +559 -0
  611. package/src/grounding/context-engineering/tool-masking.ts +338 -0
  612. package/src/grounding/embed/index.ts +704 -0
  613. package/src/grounding/embed/reranking.ts +604 -0
  614. package/src/grounding/hallucination/index.ts +223 -0
  615. package/src/grounding/index.ts +82 -0
  616. package/src/grounding/proof-map/applyPatch.ts +172 -0
  617. package/src/grounding/proof-map/index.ts +41 -0
  618. package/src/grounding/proof-map/loop.ts +275 -0
  619. package/src/grounding/proof-map/schema.ts +217 -0
  620. package/src/grounding/rag/__tests__/pipeline.test.ts +274 -0
  621. package/src/grounding/rag/__tests__/tool.test.ts +202 -0
  622. package/src/grounding/rag/__tests__/trace.test.ts +229 -0
  623. package/src/grounding/rag/circuit-breaker.ts +152 -0
  624. package/src/grounding/rag/index.ts +64 -0
  625. package/src/grounding/rag/pipeline.ts +602 -0
  626. package/src/grounding/rag/tool.ts +281 -0
  627. package/src/grounding/rag/trace.ts +503 -0
  628. package/src/grounding/rag/types.ts +284 -0
  629. package/src/grounding/retrieval/in-memory-store.ts +107 -0
  630. package/src/grounding/sources/index.ts +943 -0
  631. package/src/grounding/tests/applyPatch.test.ts +194 -0
  632. package/src/grounding/tests/loop.test.ts +141 -0
  633. package/src/grounding/tests/schema.test.ts +160 -0
  634. package/src/grounding/types.ts +100 -0
  635. package/src/grounding/verification/index.ts +419 -0
  636. package/src/hitl/active-learning/index.ts +332 -0
  637. package/src/hitl/annotation/index.ts +362 -0
  638. package/src/hitl/approval/approval-queue.ts +132 -0
  639. package/src/hitl/approval/index.ts +5 -0
  640. package/src/hitl/feedback/index.ts +284 -0
  641. package/src/hitl/index.ts +69 -0
  642. package/src/hitl/review/index.ts +6 -0
  643. package/src/hitl/review/review-trigger.ts +162 -0
  644. package/src/hitl/types.ts +126 -0
  645. package/src/index.ts +125 -0
  646. package/src/integrations/blob-storage/index.ts +7 -0
  647. package/src/integrations/blob-storage/types.ts +28 -0
  648. package/src/integrations/blob-storage/vercel-blob-adapter.ts +35 -0
  649. package/src/integrations/index.ts +15 -0
  650. package/src/integrations/notifications/index.ts +7 -0
  651. package/src/integrations/notifications/log-adapter.ts +30 -0
  652. package/src/integrations/notifications/types.ts +27 -0
  653. package/src/integrations/rate-limit/index.ts +7 -0
  654. package/src/integrations/rate-limit/types.ts +26 -0
  655. package/src/integrations/rate-limit/upstash-adapter.ts +45 -0
  656. package/src/integrations/redis/index.ts +7 -0
  657. package/src/integrations/redis/types.ts +67 -0
  658. package/src/integrations/redis/upstash-adapter.ts +18 -0
  659. package/src/integrations/stream/index.ts +7 -0
  660. package/src/integrations/stream/resumable-adapter.ts +20 -0
  661. package/src/integrations/stream/types.ts +21 -0
  662. package/src/internal/__tests__/hallucination.test.ts +162 -0
  663. package/src/internal/__tests__/models.test.ts +104 -0
  664. package/src/internal/__tests__/sdk-errors.test.ts +201 -0
  665. package/src/internal/__tests__/stop-conditions.test.ts +210 -0
  666. package/src/internal/shared/ai-types.ts +942 -0
  667. package/src/internal/testing/evaluators.ts +575 -0
  668. package/src/internal/testing/index.ts +960 -0
  669. package/src/internal/ui/data-parts.ts +511 -0
  670. package/src/internal/ui/type-guards.ts +344 -0
  671. package/src/internal/ui-factories/__tests__/ui-factories.test.ts +548 -0
  672. package/src/internal/ui-factories/artifact-factory.ts +667 -0
  673. package/src/internal/ui-factories/index.ts +82 -0
  674. package/src/internal/ui-factories/shimmer-manager.ts +220 -0
  675. package/src/internal/ui-factories/status-helpers.ts +149 -0
  676. package/src/internal/ui-factories/tool-renderer.ts +167 -0
  677. package/src/internal/ui-factories/types.ts +235 -0
  678. package/src/models/capabilities.ts +88 -0
  679. package/src/models/index.ts +16 -0
  680. package/src/models/provider-factory.ts +229 -0
  681. package/src/models/providers/anthropic.ts +539 -0
  682. package/src/models/providers/google.ts +354 -0
  683. package/src/models/providers/index.ts +21 -0
  684. package/src/models/providers/openai.ts +346 -0
  685. package/src/models/providers/perplexity.ts +276 -0
  686. package/src/models/providers/shared.ts +90 -0
  687. package/src/models/providers/xai.ts +269 -0
  688. package/src/models/registry.ts +208 -0
  689. package/src/models/routing/index.ts +45 -0
  690. package/src/models/routing/intent-router.ts +143 -0
  691. package/src/models/routing/model-router.ts +300 -0
  692. package/src/models/routing/types.ts +106 -0
  693. package/src/models/types.ts +23 -0
  694. package/src/observability/analytics/index.ts +593 -0
  695. package/src/observability/cost/index.ts +16 -0
  696. package/src/observability/cost/tracking/budget-guard.ts +110 -0
  697. package/src/observability/cost/tracking/usage-tracker.ts +120 -0
  698. package/src/observability/cost/types.ts +85 -0
  699. package/src/observability/index.ts +17 -0
  700. package/src/observability/telemetry/index.ts +508 -0
  701. package/src/observability/tracing/index.ts +30 -0
  702. package/src/observability/tracing/otel/ai-instrumentation.ts +193 -0
  703. package/src/observability/tracing/otel/exporters/console.ts +58 -0
  704. package/src/observability/tracing/otel/exporters/index.ts +6 -0
  705. package/src/observability/tracing/provenance.ts +769 -0
  706. package/src/observability/tracing/types.ts +92 -0
  707. package/src/output/__tests__/output.test.ts +737 -0
  708. package/src/output/element-stream.ts +678 -0
  709. package/src/output/errors.ts +108 -0
  710. package/src/output/factories.ts +392 -0
  711. package/src/output/index.ts +98 -0
  712. package/src/output/multimodal/EXPORTS.md +306 -0
  713. package/src/output/multimodal/IMPLEMENTATION_SUMMARY.md +421 -0
  714. package/src/output/multimodal/README.md +349 -0
  715. package/src/output/multimodal/SETUP_GUIDE.md +472 -0
  716. package/src/output/multimodal/audio.ts +650 -0
  717. package/src/output/multimodal/image.ts +22 -0
  718. package/src/output/multimodal/index.ts +32 -0
  719. package/src/output/multimodal/providers.example.ts +375 -0
  720. package/src/output/validator.ts +495 -0
  721. package/src/pipelines/adapters/trace-storage-blob.ts +458 -0
  722. package/src/pipelines/adapters/trace-storage-memory.ts +319 -0
  723. package/src/pipelines/defaults.ts +109 -0
  724. package/src/pipelines/index.ts +24 -0
  725. package/src/pipelines/message-transforms.ts +107 -0
  726. package/src/pipelines/multi-step-wrapper.ts +433 -0
  727. package/src/pipelines/pipeline-presets.ts +339 -0
  728. package/src/pipelines/step-executor.ts +257 -0
  729. package/src/pipelines/storage-factory.ts +85 -0
  730. package/src/pipelines/trace-storage-interface.ts +216 -0
  731. package/src/pipelines/types.ts +255 -0
  732. package/src/pipelines/validation.ts +323 -0
  733. package/src/prompts/index.ts +271 -0
  734. package/src/prompts/model-variants.ts +410 -0
  735. package/src/prompts/templates.ts +327 -0
  736. package/src/sdk/errors/base.ts +296 -0
  737. package/src/sdk/errors/index.ts +31 -0
  738. package/src/sdk/errors/utils.ts +148 -0
  739. package/src/sdk/experimental/index.ts +286 -0
  740. package/src/sdk/index.ts +25 -0
  741. package/src/sdk/middleware/ai-middleware.ts +95 -0
  742. package/src/sdk/middleware/cache.ts +154 -0
  743. package/src/sdk/middleware/circuit-breaker.ts +388 -0
  744. package/src/sdk/middleware/compose.ts +81 -0
  745. package/src/sdk/middleware/deduplication.ts +307 -0
  746. package/src/sdk/middleware/index.ts +660 -0
  747. package/src/sdk/middleware/model-middleware.ts +200 -0
  748. package/src/sdk/stop-conditions/conditions.ts +209 -0
  749. package/src/sdk/stop-conditions/index.ts +35 -0
  750. package/src/sdk/stop-conditions/types.ts +59 -0
  751. package/src/security/guardrails/index.ts +6 -0
  752. package/src/security/guardrails/middleware.ts +465 -0
  753. package/src/security/guardrails/pii-filter.ts +396 -0
  754. package/src/security/index.ts +33 -0
  755. package/src/security/injection/index.ts +5 -0
  756. package/src/security/injection/prompt-injection.ts +64 -0
  757. package/src/security/types.ts +85 -0
  758. package/src/server/cache/crypto.ts +47 -0
  759. package/src/server/cache/performance.ts +79 -0
  760. package/src/server/error-handler.ts +93 -0
  761. package/src/server/errors.ts +73 -0
  762. package/src/server/helpers.ts +944 -0
  763. package/src/server/http.ts +156 -0
  764. package/src/server/index.ts +12 -0
  765. package/src/server/messages/__tests__/messages.test.ts +720 -0
  766. package/src/server/messages/converter.ts +245 -0
  767. package/src/server/messages/data-parts.ts +338 -0
  768. package/src/server/messages/extraction.ts +328 -0
  769. package/src/server/messages/index.ts +126 -0
  770. package/src/server/messages/types.ts +355 -0
  771. package/src/server/messages/window.ts +450 -0
  772. package/src/server/rate-limit/env.ts +8 -0
  773. package/src/server/rate-limit/rate-limit.ts +165 -0
  774. package/src/server/routes/HEALTH_CHECK.md +502 -0
  775. package/src/server/routes/IMPLEMENTATION_SUMMARY.md +432 -0
  776. package/src/server/routes/QUICK_START.md +327 -0
  777. package/src/server/routes/README.md +357 -0
  778. package/src/server/routes/__tests__/routes.test.ts +628 -0
  779. package/src/server/routes/agent-route.ts +224 -0
  780. package/src/server/routes/agent-routes.ts +191 -0
  781. package/src/server/routes/embed-config.ts +181 -0
  782. package/src/server/routes/health-check.example.ts +507 -0
  783. package/src/server/routes/health-check.test.ts +533 -0
  784. package/src/server/routes/health-check.ts +639 -0
  785. package/src/server/routes/health-check.types.ts +217 -0
  786. package/src/server/routes/index.ts +32 -0
  787. package/src/server/routes/types.ts +274 -0
  788. package/src/shared/__tests__/schemas.test.ts +317 -0
  789. package/src/shared/ai-runtime.ts +139 -0
  790. package/src/shared/ai-types.ts +133 -0
  791. package/src/shared/index.ts +30 -0
  792. package/src/shared/sdk-runtime.ts +198 -0
  793. package/src/shared/sdk-types.ts +301 -0
  794. package/src/streaming/control/__tests__/streaming-control.test.ts +708 -0
  795. package/src/streaming/control/budget-guard.ts +264 -0
  796. package/src/streaming/control/controller.ts +255 -0
  797. package/src/streaming/control/index.ts +105 -0
  798. package/src/streaming/control/smoothing.ts +201 -0
  799. package/src/streaming/control/step-limit.ts +215 -0
  800. package/src/streaming/control/types.ts +234 -0
  801. package/src/streaming/core/auto-resume.ts +276 -0
  802. package/src/streaming/core/index.ts +85 -0
  803. package/src/streaming/core/multi-step.ts +471 -0
  804. package/src/streaming/core/protocol.ts +194 -0
  805. package/src/streaming/core/types.ts +182 -0
  806. package/src/streaming/index.ts +97 -0
  807. package/src/streaming/infra/backpressure/buffer.ts +210 -0
  808. package/src/streaming/infra/backpressure/index.ts +6 -0
  809. package/src/streaming/infra/index.ts +75 -0
  810. package/src/streaming/infra/multiplexing/index.ts +311 -0
  811. package/src/streaming/infra/resilience/index.ts +684 -0
  812. package/src/streaming/infra/transform/index.ts +15 -0
  813. package/src/streaming/infra/transform/stream-transforms.ts +166 -0
  814. package/src/streaming/infra/transport/index.ts +774 -0
  815. package/src/streaming/infra/types.ts +118 -0
  816. package/src/streaming/infra-extra/types.ts +118 -0
  817. package/src/tools/advanced/caching.ts +299 -0
  818. package/src/tools/advanced/generator.ts +267 -0
  819. package/src/tools/advanced/hitl.ts +251 -0
  820. package/src/tools/advanced/index.ts +9 -0
  821. package/src/tools/advanced/llm-tool.ts +208 -0
  822. package/src/tools/approval/FILES.md +449 -0
  823. package/src/tools/approval/IMPLEMENTATION_SUMMARY.md +567 -0
  824. package/src/tools/approval/QUICK_START.md +362 -0
  825. package/src/tools/approval/README.md +514 -0
  826. package/src/tools/approval/advanced-approval-queue.ts +7 -0
  827. package/src/tools/approval/approval.example.ts +571 -0
  828. package/src/tools/approval/in-memory-queue.ts +405 -0
  829. package/src/tools/approval/index.ts +737 -0
  830. package/src/tools/approval/middleware.ts +590 -0
  831. package/src/tools/approval/queue-factory.ts +162 -0
  832. package/src/tools/approval/redis-queue.ts +327 -0
  833. package/src/tools/approval/testing.ts +493 -0
  834. package/src/tools/approval/types.ts +221 -0
  835. package/src/tools/approval/with-approval.ts +366 -0
  836. package/src/tools/artifacts/artifact-tools.ts +273 -0
  837. package/src/tools/artifacts/index.ts +6 -0
  838. package/src/tools/compliance/compliance-wrapper.ts +789 -0
  839. package/src/tools/compliance/create-compliant-stream.ts +226 -0
  840. package/src/tools/compliance/index.ts +8 -0
  841. package/src/tools/compliance/phi-redaction.ts +406 -0
  842. package/src/tools/compliance/tool-wrapper.ts +306 -0
  843. package/src/tools/computer/index.ts +99 -0
  844. package/src/tools/computer/types.ts +41 -0
  845. package/src/tools/core/abort.ts +202 -0
  846. package/src/tools/core/factory.ts +197 -0
  847. package/src/tools/core/index.ts +8 -0
  848. package/src/tools/core/tool-safety.ts +112 -0
  849. package/src/tools/generic/index.ts +9 -0
  850. package/src/tools/generic/json-schema-tool.ts +301 -0
  851. package/src/tools/generic/tiptap-context.ts +619 -0
  852. package/src/tools/generic/web-search-tool.ts +82 -0
  853. package/src/tools/generic/web-search.ts +142 -0
  854. package/src/tools/index.ts +36 -0
  855. package/src/tools/mcp/ai-sdk-error-integration.ts +401 -0
  856. package/src/tools/mcp/client.ts +988 -0
  857. package/src/tools/mcp/connection-manager.ts +380 -0
  858. package/src/tools/mcp/connection-pool.ts +408 -0
  859. package/src/tools/mcp/edge-runtime.ts +318 -0
  860. package/src/tools/mcp/environment.ts +310 -0
  861. package/src/tools/mcp/index.ts +20 -0
  862. package/src/tools/mcp/next-pattern.ts +401 -0
  863. package/src/tools/mcp/stream-lifecycle-integration.ts +617 -0
  864. package/src/tools/mcp/tool-cache.ts +359 -0
  865. package/src/tools/mcp/transport-selector.ts +492 -0
  866. package/src/tools/mcp/transports.ts +99 -0
  867. package/src/tools/simple-factory.ts +55 -0
  868. package/src/tools/superpowers/index.ts +122 -0
  869. package/src/tools/superpowers/prompts/index.ts +533 -0
  870. package/src/tools/superpowers/schemas/index.ts +701 -0
  871. package/src/tools/superpowers/tools/index.ts +721 -0
  872. package/src/tools/validation-wrapper.ts +97 -0
@@ -0,0 +1,1150 @@
1
+ import { Ft as tool, et as generateText, h as anthropic, vt as openai } from "./ai-runtime-CDzQztTt.mjs";
2
+ import { z } from "zod";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { logError, logWarn } from "@od-oneapp/shared/logs";
5
+ import { promises } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+
8
+ //#region src/grounding/rag/circuit-breaker.ts
9
+ var CircuitBreaker = class {
10
+ config;
11
+ state;
12
+ constructor(config) {
13
+ this.config = config;
14
+ this.state = {
15
+ state: "closed",
16
+ failures: 0,
17
+ successes: 0,
18
+ halfOpenAttempts: 0
19
+ };
20
+ }
21
+ getMetrics() {
22
+ return {
23
+ name: this.config.name,
24
+ state: this.state.state,
25
+ failures: this.state.failures,
26
+ successes: this.state.successes,
27
+ lastFailureAt: this.state.lastFailureAt,
28
+ lastSuccessAt: this.state.lastSuccessAt,
29
+ openUntil: this.state.openUntil
30
+ };
31
+ }
32
+ reset() {
33
+ this.state = {
34
+ state: "closed",
35
+ failures: 0,
36
+ successes: 0,
37
+ halfOpenAttempts: 0
38
+ };
39
+ }
40
+ async execute(fn) {
41
+ const now = Date.now();
42
+ if (this.state.state === "open") {
43
+ if (now >= (this.state.openUntil ?? 0)) this.transitionTo("half-open");
44
+ else if (this.config.fallbackBehavior !== "allow") throw new Error(`[CircuitBreaker] ${this.config.name} is open`);
45
+ }
46
+ if (this.state.state === "half-open") if (this.state.halfOpenAttempts >= this.config.halfOpenRequests) {
47
+ if (this.config.fallbackBehavior !== "allow") throw new Error(`[CircuitBreaker] ${this.config.name} half-open limit reached`);
48
+ } else this.state.halfOpenAttempts += 1;
49
+ try {
50
+ const result = await fn();
51
+ this.recordSuccess();
52
+ return result;
53
+ } catch (error) {
54
+ this.recordFailure();
55
+ throw error;
56
+ }
57
+ }
58
+ recordSuccess() {
59
+ const now = Date.now();
60
+ this.state.lastSuccessAt = now;
61
+ this.state.failures = 0;
62
+ if (this.state.state === "half-open") {
63
+ this.state.successes += 1;
64
+ if (this.state.successes >= this.config.halfOpenRequests) this.transitionTo("closed");
65
+ } else this.state.successes += 1;
66
+ }
67
+ recordFailure() {
68
+ const now = Date.now();
69
+ this.state.lastFailureAt = now;
70
+ this.state.failures += 1;
71
+ this.state.successes = 0;
72
+ if (this.state.state === "half-open" || this.state.failures >= this.config.failureThreshold) this.transitionTo("open");
73
+ }
74
+ transitionTo(next) {
75
+ if (this.state.state === next) return;
76
+ const prev = this.state.state;
77
+ this.state.state = next;
78
+ if (next === "open") {
79
+ this.state.openUntil = Date.now() + this.config.resetTimeout;
80
+ this.state.halfOpenAttempts = 0;
81
+ }
82
+ if (next === "half-open") {
83
+ this.state.halfOpenAttempts = 0;
84
+ this.state.successes = 0;
85
+ this.state.openUntil = void 0;
86
+ }
87
+ if (next === "closed") {
88
+ this.state.failures = 0;
89
+ this.state.halfOpenAttempts = 0;
90
+ this.state.openUntil = void 0;
91
+ }
92
+ this.config.onStateChange?.(prev, next);
93
+ }
94
+ };
95
+
96
+ //#endregion
97
+ //#region src/grounding/rag/pipeline.ts
98
+ /**
99
+ * @fileoverview Multi-model research pipeline
100
+ *
101
+ * Three-stage research pipeline for high-quality, verified research:
102
+ * 1. Perplexity: Context expansion (grounded notes + citations)
103
+ * 2. Sonnet 4.5: Structured reasoning (claims, assumptions, gaps)
104
+ * 3. GPT-5: Verification (fact-check, tighten citations)
105
+ *
106
+ * Benefits:
107
+ * - Cuts hallucinations via grounded notes
108
+ * - Readable traces (notes → reasoning → verification)
109
+ * - Tunable research depth (fast/balanced/deep)
110
+ * - Circuit breaker protection for fault tolerance
111
+ *
112
+ * @module @od-oneapp/ai-platform/research/pipeline
113
+ */
114
+ /**
115
+ * Circuit breaker instances for each pipeline stage.
116
+ * @internal
117
+ */
118
+ const pipelineCircuits = {
119
+ perplexity: new CircuitBreaker({
120
+ name: "research-perplexity",
121
+ failureThreshold: 3,
122
+ resetTimeout: 6e4,
123
+ halfOpenRequests: 1,
124
+ fallbackBehavior: "error",
125
+ onStateChange: (from, to) => {
126
+ if (to === "open") logError("[Pipeline] Perplexity circuit opened - requests will fail until reset");
127
+ }
128
+ }),
129
+ sonnet: new CircuitBreaker({
130
+ name: "research-sonnet",
131
+ failureThreshold: 3,
132
+ resetTimeout: 45e3,
133
+ halfOpenRequests: 1,
134
+ fallbackBehavior: "error"
135
+ }),
136
+ verification: new CircuitBreaker({
137
+ name: "research-verification",
138
+ failureThreshold: 3,
139
+ resetTimeout: 45e3,
140
+ halfOpenRequests: 1,
141
+ fallbackBehavior: "error"
142
+ })
143
+ };
144
+ /**
145
+ * Tier configurations for research depth.
146
+ * Defines token limits and modes for each tier.
147
+ * @internal
148
+ */
149
+ const TIER_CONFIGS = {
150
+ fast: {
151
+ maxTokens: 400,
152
+ mode: "concise-notes"
153
+ },
154
+ balanced: {
155
+ maxTokens: 800,
156
+ mode: "concise-notes"
157
+ },
158
+ deep: {
159
+ maxTokens: 1600,
160
+ mode: "deep-notes"
161
+ }
162
+ };
163
+ /**
164
+ * Gets verification model from environment variable.
165
+ * Supports: gpt-4-turbo, o1-preview, o1-pro, gpt-5
166
+ * @returns Model identifier (defaults to 'gpt-4-turbo').
167
+ * @internal
168
+ */
169
+ function getVerificationModel() {
170
+ return process.env.NEXT_AI_VERIFICATION_MODEL ?? "gpt-4-turbo";
171
+ }
172
+ /**
173
+ * Step 1: Perplexity - Context expansion.
174
+ * Returns crisp notes + URLs only (no long prose).
175
+ * Bounded context keeps costs predictable.
176
+ * Protected by circuit breaker for fault tolerance.
177
+ *
178
+ * @param query - Research question or query.
179
+ * @param tier - Research depth tier (defaults to 'balanced').
180
+ * @returns Perplexity response with notes, citations, and usage stats.
181
+ * @throws {Error} If Perplexity API fails and GPT-4 Turbo fallback also fails.
182
+ * @throws {CircuitOpenError} If circuit breaker is open after repeated failures.
183
+ * @remarks Falls back to GPT-4 Turbo if Perplexity API is unavailable or times out (30s timeout).
184
+ * Extracts citations from both API response and inline [Source: URL] markers.
185
+ * Limits citations to maximum of 7 URLs.
186
+ * Circuit breaker opens after 3 failures and resets after 60 seconds.
187
+ * @example
188
+ * ```ts
189
+ * const result = await researchWithPerplexity('What is quantum computing?', 'balanced');
190
+ * console.log(result.notes, result.cites);
191
+ * ```
192
+ */
193
+ async function researchWithPerplexity(query, tier = "balanced") {
194
+ return pipelineCircuits.perplexity.execute(async () => {
195
+ return researchWithPerplexityInternal(query, tier);
196
+ });
197
+ }
198
+ /**
199
+ * Internal implementation of Perplexity research.
200
+ * @internal
201
+ */
202
+ async function researchWithPerplexityInternal(query, tier) {
203
+ const config = TIER_CONFIGS[tier];
204
+ if (process.env.PPLX_API_KEY) {
205
+ const controller = new AbortController();
206
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
207
+ try {
208
+ const response = await fetch("https://api.perplexity.ai/chat/completions", {
209
+ method: "POST",
210
+ signal: controller.signal,
211
+ headers: {
212
+ Authorization: `Bearer ${process.env.PPLX_API_KEY}`,
213
+ "Content-Type": "application/json"
214
+ },
215
+ body: JSON.stringify({
216
+ model: "llama-3.1-sonar-large-128k-online",
217
+ messages: [{
218
+ role: "system",
219
+ content: `You are a research assistant. Provide concise, citation-dense notes.
220
+ Format:
221
+ - Use bullet points
222
+ - Include specific facts and figures
223
+ - Cite sources as [Source: URL]
224
+ - Keep to ${config.maxTokens} tokens max
225
+ - ${config.mode === "deep-notes" ? "Provide comprehensive coverage" : "Be concise"}`
226
+ }, {
227
+ role: "user",
228
+ content: query
229
+ }],
230
+ max_tokens: config.maxTokens,
231
+ return_citations: true,
232
+ temperature: .3
233
+ })
234
+ });
235
+ clearTimeout(timeoutId);
236
+ if (!response.ok) {
237
+ const errorBody = await response.text().catch(() => "Unable to read error body");
238
+ throw new Error(`Perplexity API error: ${response.status} ${response.statusText} - ${errorBody}`);
239
+ }
240
+ const data = await response.json();
241
+ const cites = data.citations ?? [];
242
+ const content = data.choices?.[0]?.message?.content ?? "";
243
+ const citationRegex = /\[Source: (https?:\/\/[^\]]+)\]/g;
244
+ let match;
245
+ while ((match = citationRegex.exec(content)) !== null) {
246
+ const url = match[1];
247
+ if (url && !cites.includes(url)) cites.push(url);
248
+ }
249
+ return {
250
+ notes: content,
251
+ cites: cites.slice(0, 7),
252
+ usage: {
253
+ inputTokens: data.usage?.prompt_tokens ?? 0,
254
+ outputTokens: data.usage?.completion_tokens ?? 0
255
+ }
256
+ };
257
+ } catch (error) {
258
+ clearTimeout(timeoutId);
259
+ if (error instanceof Error) if (error.name === "AbortError") logWarn("[Perplexity] Request timed out after 30s, falling back to GPT-4 Turbo");
260
+ else logWarn("[Perplexity] API call failed, falling back to GPT-4 Turbo", { error: error.message });
261
+ else logWarn("[Perplexity] Unknown error, falling back to GPT-4 Turbo", { error: String(error) });
262
+ }
263
+ }
264
+ const result = await generateText({
265
+ model: openai("gpt-4-turbo"),
266
+ prompt: `You are a research assistant. Provide concise, citation-dense notes for: "${query}"
267
+
268
+ Format:
269
+ - Use bullet points
270
+ - Include specific facts and figures
271
+ - Cite sources as [Source: URL]
272
+ - Keep to ${config.maxTokens} tokens max
273
+ - ${config.mode === "deep-notes" ? "Provide comprehensive coverage" : "Be concise"}
274
+
275
+ Return only the notes with citations.`,
276
+ maxRetries: 2
277
+ });
278
+ const citationRegex = /\[Source: (https?:\/\/[^\]]+)\]/g;
279
+ const cites = [];
280
+ let match;
281
+ while ((match = citationRegex.exec(result.text)) !== null) {
282
+ const url = match[1];
283
+ if (url && !cites.includes(url)) cites.push(url);
284
+ }
285
+ return {
286
+ notes: result.text,
287
+ cites: cites.slice(0, 7),
288
+ usage: {
289
+ inputTokens: result.usage.inputTokens ?? 0,
290
+ outputTokens: result.usage.outputTokens ?? 0
291
+ }
292
+ };
293
+ }
294
+ /**
295
+ * Schema for Sonnet reasoning output.
296
+ * @internal
297
+ */
298
+ const reasoningSchema = z.object({
299
+ claims: z.array(z.object({
300
+ statement: z.string(),
301
+ supportedBy: z.array(z.string()).describe("Citation URLs"),
302
+ confidence: z.enum([
303
+ "high",
304
+ "medium",
305
+ "low"
306
+ ])
307
+ })),
308
+ assumptions: z.array(z.string()).describe("Underlying assumptions made"),
309
+ gaps: z.array(z.object({
310
+ description: z.string(),
311
+ sources: z.array(z.string()).describe("Conflicting sources if any")
312
+ })).describe("Knowledge gaps or conflicts"),
313
+ answerDraft: z.string().describe("Draft answer based on notes")
314
+ });
315
+ /**
316
+ * Step 2: Sonnet 4.5 - Structured reasoning.
317
+ * Reasons over ONLY the provided notes.
318
+ * Outputs: claims[], assumptions[], gaps[], answerDraft.
319
+ * Protected by circuit breaker for fault tolerance.
320
+ *
321
+ * @param input - Reasoning input containing question, notes, and citations.
322
+ * @param input.question - Research question.
323
+ * @param input.notes - Research notes from Perplexity.
324
+ * @param input.cites - Citation URLs.
325
+ * @returns Reasoning output with claims, assumptions, gaps, and draft answer.
326
+ * @throws {Error} If JSON extraction or parsing fails, or if model call fails.
327
+ * @throws {CircuitOpenError} If circuit breaker is open after repeated failures.
328
+ * @remarks Uses Claude 3.5 Sonnet with temperature 0.3 for consistent reasoning.
329
+ * Strictly enforces using only provided notes (no external knowledge).
330
+ * Returns structured JSON matching the reasoning schema.
331
+ * Circuit breaker opens after 3 failures and resets after 45 seconds.
332
+ * @example
333
+ * ```ts
334
+ * const reasoning = await reasonWithSonnet({
335
+ * question: 'What is quantum computing?',
336
+ * notes: perplexityResult.notes,
337
+ * cites: perplexityResult.cites
338
+ * });
339
+ * ```
340
+ */
341
+ async function reasonWithSonnet(input) {
342
+ return pipelineCircuits.sonnet.execute(async () => {
343
+ return reasonWithSonnetInternal(input);
344
+ });
345
+ }
346
+ /**
347
+ * Internal implementation of Sonnet reasoning.
348
+ * @internal
349
+ */
350
+ async function reasonWithSonnetInternal(input) {
351
+ const systemPrompt = `You are a rigorous analyst.
352
+
353
+ CRITICAL RULES:
354
+ 1. Use ONLY the provided notes and citations
355
+ 2. Do not add external knowledge
356
+ 3. Explicitly mark any assumptions
357
+ 4. Flag gaps where citations conflict or are insufficient
358
+ 5. Output structured JSON matching the schema
359
+
360
+ Your goal is to produce verifiable, citation-backed reasoning.`;
361
+ const scratchpad = `## QUESTION
362
+ ${input.question}
363
+
364
+ ## NOTES
365
+ ${input.notes}
366
+
367
+ ## CITATIONS
368
+ ${input.cites.map((c, i) => `[${i + 1}] ${c}`).join("\n")}
369
+
370
+ ## TASK
371
+ Analyze the notes and produce structured reasoning. Return JSON only.`;
372
+ const result = await generateText({
373
+ model: anthropic("claude-3-5-sonnet-20241022"),
374
+ system: systemPrompt,
375
+ prompt: scratchpad,
376
+ temperature: .3,
377
+ maxRetries: 2
378
+ });
379
+ const jsonMatch = result.text.match(/\{[\s\S]*\}/);
380
+ if (!jsonMatch) throw new Error("Failed to extract JSON from Sonnet response");
381
+ let parsed;
382
+ try {
383
+ parsed = JSON.parse(jsonMatch[0]);
384
+ } catch (parseError) {
385
+ throw new Error(`Failed to parse JSON from Sonnet: ${parseError instanceof Error ? parseError.message : "Unknown error"}`);
386
+ }
387
+ return {
388
+ ...reasoningSchema.parse(parsed),
389
+ usage: {
390
+ inputTokens: result.usage.inputTokens ?? 0,
391
+ outputTokens: result.usage.outputTokens ?? 0
392
+ }
393
+ };
394
+ }
395
+ /**
396
+ * Schema for GPT-5 verification output.
397
+ * @internal
398
+ */
399
+ const verificationSchema = z.object({
400
+ finalAnswer: z.string().describe("Verified, tightened answer"),
401
+ flags: z.array(z.object({
402
+ claim: z.string(),
403
+ issue: z.enum([
404
+ "unverifiable",
405
+ "weak-citation",
406
+ "conflicting-sources"
407
+ ]),
408
+ details: z.string()
409
+ })).describe("Issues found during verification"),
410
+ trace: z.array(z.object({
411
+ claim: z.string(),
412
+ citationCheck: z.enum([
413
+ "verified",
414
+ "partial",
415
+ "failed"
416
+ ]),
417
+ notes: z.string().optional()
418
+ })).describe("Per-claim verification trace"),
419
+ confidence: z.enum([
420
+ "high",
421
+ "medium",
422
+ "low"
423
+ ]).describe("Overall confidence in answer")
424
+ });
425
+ /**
426
+ * Step 3: GPT-5 - Verification.
427
+ * Fact-checks each claim against citations.
428
+ * Flags unverifiable items.
429
+ * Returns final answer with trace.
430
+ * Protected by circuit breaker for fault tolerance.
431
+ *
432
+ * @param draft - Reasoning output from Sonnet stage.
433
+ * @param cites - Citation URLs to verify against.
434
+ * @returns Verification output with final answer, flags, trace, and confidence.
435
+ * @throws {Error} If JSON extraction or parsing fails, or if model call fails.
436
+ * @throws {CircuitOpenError} If circuit breaker is open after repeated failures.
437
+ * @remarks Uses verification model from NEXT_AI_VERIFICATION_MODEL env var (defaults to 'gpt-4-turbo').
438
+ * Supports: gpt-4-turbo, o1-preview, o1-pro, gpt-5.
439
+ * Uses temperature 0.2 for strict verification.
440
+ * Returns verification trace for each claim with citation check results.
441
+ * Circuit breaker opens after 3 failures and resets after 45 seconds.
442
+ * @example
443
+ * ```ts
444
+ * const verification = await verifyWithGPT5(reasoning, cites);
445
+ * console.log(verification.finalAnswer, verification.confidence);
446
+ * ```
447
+ */
448
+ async function verifyWithGPT5(draft, cites) {
449
+ return pipelineCircuits.verification.execute(async () => {
450
+ return verifyWithGPT5Internal(draft, cites);
451
+ });
452
+ }
453
+ /**
454
+ * Internal implementation of GPT-5 verification.
455
+ * @internal
456
+ */
457
+ async function verifyWithGPT5Internal(draft, cites) {
458
+ const verificationModel = getVerificationModel();
459
+ const systemPrompt = `You are ${verificationModel}, a verification model.
460
+
461
+ TASKS:
462
+ 1. Check each claim against the provided citations
463
+ 2. Flag claims that lack strong citation support
464
+ 3. Identify conflicting sources
465
+ 4. Produce a tightened final answer
466
+ 5. Return structured JSON with verification trace
467
+
468
+ VERIFICATION RULES:
469
+ - "verified": Claim directly supported by citation
470
+ - "partial": Citation provides weak or indirect support
471
+ - "failed": No citation support found
472
+
473
+ Be strict but fair. Better to flag uncertainty than claim certainty.`;
474
+ const verificationInput = {
475
+ draft: {
476
+ claims: draft.claims,
477
+ assumptions: draft.assumptions,
478
+ gaps: draft.gaps,
479
+ answerDraft: draft.answerDraft
480
+ },
481
+ citations: cites.map((c, i) => ({
482
+ id: i + 1,
483
+ url: c
484
+ }))
485
+ };
486
+ const result = await generateText({
487
+ model: openai(verificationModel),
488
+ system: systemPrompt,
489
+ prompt: `Verify this reasoning:\n\n${JSON.stringify(verificationInput, null, 2)}\n\nReturn JSON only.`,
490
+ temperature: .2,
491
+ maxRetries: 2
492
+ });
493
+ const jsonMatch = result.text.match(/\{[\s\S]*\}/);
494
+ if (!jsonMatch) throw new Error("Failed to extract JSON from verification response");
495
+ let parsed;
496
+ try {
497
+ parsed = JSON.parse(jsonMatch[0]);
498
+ } catch (parseError) {
499
+ throw new Error(`Failed to parse JSON from verification: ${parseError instanceof Error ? parseError.message : "Unknown error"}`);
500
+ }
501
+ return {
502
+ ...verificationSchema.parse(parsed),
503
+ usage: {
504
+ inputTokens: result.usage.inputTokens ?? 0,
505
+ outputTokens: result.usage.outputTokens ?? 0
506
+ }
507
+ };
508
+ }
509
+ /**
510
+ * Orchestrator: Full research pipeline.
511
+ * Executes all three steps in sequence (Perplexity → Sonnet → GPT-5).
512
+ * Returns final answer with full trace.
513
+ *
514
+ * @param question - Research question to answer.
515
+ * @param config - Research configuration (defaults to { tier: 'balanced' }).
516
+ * @returns Complete research pipeline result with answer, confidence, flags, and trace.
517
+ * @throws {Error} If any pipeline stage fails (propagates errors from individual stages).
518
+ * @remarks Executes stages sequentially. Each stage's output feeds into the next.
519
+ * Full trace includes token usage and results from all three stages.
520
+ * Confidence level reflects overall verification quality.
521
+ * @example
522
+ * ```ts
523
+ * const result = await executeResearchPipeline(
524
+ * 'What are the latest developments in quantum computing?',
525
+ * { tier: 'deep' }
526
+ * );
527
+ * console.log(result.answer, result.confidence);
528
+ * ```
529
+ */
530
+ async function executeResearchPipeline(question, config = { tier: "balanced" }) {
531
+ const { notes, cites, usage: perplexityUsage } = await researchWithPerplexity(question, config.tier);
532
+ const reasoning = await reasonWithSonnet({
533
+ question,
534
+ notes,
535
+ cites
536
+ });
537
+ const verification = await verifyWithGPT5(reasoning, cites);
538
+ return {
539
+ answer: verification.finalAnswer,
540
+ confidence: verification.confidence,
541
+ flags: verification.flags,
542
+ trace: {
543
+ contextExpansion: {
544
+ notes,
545
+ cites,
546
+ usage: perplexityUsage
547
+ },
548
+ reasoning: {
549
+ claims: reasoning.claims,
550
+ assumptions: reasoning.assumptions,
551
+ gaps: reasoning.gaps,
552
+ usage: reasoning.usage
553
+ },
554
+ verification: {
555
+ trace: verification.trace,
556
+ flags: verification.flags,
557
+ usage: verification.usage
558
+ }
559
+ }
560
+ };
561
+ }
562
+
563
+ //#endregion
564
+ //#region src/grounding/rag/trace.ts
565
+ /**
566
+ * @fileoverview Research trace storage with cost & latency tracking
567
+ *
568
+ * Extends the artifact pattern for multi-model research runs:
569
+ * - Per-step artifact storage (context expansion → reasoning → verification)
570
+ * - Cost tracking per model (configurable via PipelineModelConfig.costRates)
571
+ * - Latency profiling
572
+ * - Fast indexing for dashboard queries
573
+ *
574
+ * Storage pattern:
575
+ * - File-based for prototype (like artifacts.ts)
576
+ * - Production: Neon Postgres + Upstash Redis + R2
577
+ *
578
+ * @module @od-oneapp/ai-platform/research/trace
579
+ */
580
+ /** Directory for storing research traces. */
581
+ const TRACES_DIR = process.env.NEXT_AI_TRACES_PATH ?? "/tmp/next-ai-traces";
582
+ /**
583
+ * Validates run ID to prevent path traversal attacks.
584
+ * Format: {timestamp}-{12-char-hex}
585
+ * Example: 1733875200000-a1b2c3d4e5f6
586
+ *
587
+ * @param runId - Run ID to validate.
588
+ * @returns `true` if run ID is valid, `false` otherwise.
589
+ * @internal
590
+ */
591
+ function validateRunId(runId) {
592
+ return /^[0-9]+-[0-9a-f]{12}$/i.test(runId);
593
+ }
594
+ /**
595
+ * Safely constructs run path with validation.
596
+ * Prevents path traversal attacks by ensuring paths stay within TRACES_DIR.
597
+ *
598
+ * @param runId - Run ID (validated).
599
+ * @param filename - Optional filename to append.
600
+ * @returns Resolved path or `null` if validation fails.
601
+ * @internal
602
+ */
603
+ function getRunPath(runId, filename) {
604
+ if (!validateRunId(runId)) {
605
+ logError("Invalid run ID format", { runId });
606
+ return null;
607
+ }
608
+ const runPath = filename ? resolve(join(TRACES_DIR, runId, filename)) : resolve(join(TRACES_DIR, runId));
609
+ const baseDir = resolve(TRACES_DIR);
610
+ if (!runPath.startsWith(baseDir)) {
611
+ logError("Path traversal attempt detected", { runId });
612
+ return null;
613
+ }
614
+ return runPath;
615
+ }
616
+ /**
617
+ * Default token-based cost rates ($/1k tokens).
618
+ * Override via `PipelineModelConfig.costRates` or the `customRates` param on `estimateCost`.
619
+ */
620
+ const DEFAULT_COST_RATES = {
621
+ "perplexity-latest": { flat: .002 },
622
+ "llama-3.1-sonar-large-128k-online": { flat: .002 },
623
+ "gpt-4-turbo": {
624
+ input: .01,
625
+ output: .03
626
+ },
627
+ "gpt-5": {
628
+ input: .01,
629
+ output: .03
630
+ },
631
+ "claude-3-5-sonnet-20241022": {
632
+ input: .003,
633
+ output: .015
634
+ }
635
+ };
636
+ /**
637
+ * Estimates cost for a model call based on token usage.
638
+ *
639
+ * @param model - Model identifier.
640
+ * @param inputTokens - Input tokens consumed (defaults to 0).
641
+ * @param outputTokens - Output tokens generated (defaults to 0).
642
+ * @returns Estimated cost in USD.
643
+ * @remarks Cost rates ($/1k tokens):
644
+ * - Perplexity: $0.002 flat per call
645
+ * - Claude 3.5 Sonnet: $0.003 input, $0.015 output
646
+ * - GPT-4 Turbo: $0.01 input, $0.03 output
647
+ * Returns 0 if model is not in cost rates table.
648
+ * @example
649
+ * ```ts
650
+ * const cost = estimateCost('claude-3-5-sonnet-20241022', 1000, 500);
651
+ * // Returns: (1000/1000 * 0.003) + (500/1000 * 0.015) = 0.0105
652
+ * ```
653
+ */
654
+ function estimateCost(model, inputTokens = 0, outputTokens = 0, customRates) {
655
+ const rate = (customRates ? {
656
+ ...DEFAULT_COST_RATES,
657
+ ...customRates
658
+ } : DEFAULT_COST_RATES)[model];
659
+ if (!rate) return 0;
660
+ if (rate.flat) return rate.flat;
661
+ return inputTokens / 1e3 * (rate.input ?? 0) + outputTokens / 1e3 * (rate.output ?? 0);
662
+ }
663
+ /**
664
+ * Ensures traces directory exists.
665
+ * Creates directory recursively if it doesn't exist.
666
+ * @internal
667
+ */
668
+ async function ensureTracesDir() {
669
+ try {
670
+ await promises.mkdir(TRACES_DIR, { recursive: true });
671
+ } catch (error) {
672
+ logError("Failed to create traces directory", { error });
673
+ }
674
+ }
675
+ /**
676
+ * Starts a new research run trace.
677
+ * Creates a new TraceRun with generated runId and initial timestamp.
678
+ *
679
+ * @param question - Research question.
680
+ * @param tier - Research tier.
681
+ * @param app - Application/client identifier (defaults to 'research-agent').
682
+ * @returns New TraceRun object.
683
+ * @example
684
+ * ```ts
685
+ * const run = startRun('What is quantum computing?', 'balanced', 'my-app');
686
+ * ```
687
+ */
688
+ function startRun(question, tier, app = "research-agent") {
689
+ const timestamp = Date.now();
690
+ return {
691
+ runId: `${timestamp}-${createHash("sha256").update(`${timestamp}-${question}`).digest("hex").slice(0, 12)}`,
692
+ app,
693
+ question,
694
+ tier,
695
+ startedAt: timestamp,
696
+ steps: []
697
+ };
698
+ }
699
+ /**
700
+ * Starts a new research step trace.
701
+ * Creates a new TraceStep with generated ID and start timestamp.
702
+ *
703
+ * @param kind - Pipeline stage kind ('context-expansion', 'reasoning', or 'verification').
704
+ * @param model - Optional model identifier.
705
+ * @returns New TraceStep object.
706
+ * @example
707
+ * ```ts
708
+ * const step = startStep('context-expansion', 'llama-3.1-sonar-large-128k-online');
709
+ * ```
710
+ */
711
+ function startStep(kind, model) {
712
+ return {
713
+ id: randomUUID(),
714
+ kind,
715
+ startAt: Date.now(),
716
+ endAt: 0,
717
+ latencyMs: 0,
718
+ model,
719
+ artifacts: {},
720
+ artifactKeys: []
721
+ };
722
+ }
723
+ /**
724
+ * Ends a research step with usage metrics.
725
+ * Calculates latency and cost, updates step with token usage.
726
+ *
727
+ * @param step - Step to end.
728
+ * @param usage - Optional usage metrics (inputTokens, outputTokens, costUSD).
729
+ * @returns Updated step with end timestamp, latency, and cost.
730
+ * @example
731
+ * ```ts
732
+ * const completedStep = endStep(step, {
733
+ * inputTokens: 1000,
734
+ * outputTokens: 500
735
+ * });
736
+ * ```
737
+ */
738
+ function endStep(step, usage) {
739
+ step.endAt = Date.now();
740
+ step.latencyMs = step.endAt - step.startAt;
741
+ if (usage?.inputTokens) step.inputTokens = usage.inputTokens;
742
+ if (usage?.outputTokens) step.outputTokens = usage.outputTokens;
743
+ if (usage?.costUSD !== void 0) step.costUSD = usage.costUSD;
744
+ else if (step.model) step.costUSD = estimateCost(step.model, step.inputTokens ?? 0, step.outputTokens ?? 0);
745
+ return step;
746
+ }
747
+ /**
748
+ * Ends a research run and calculates totals.
749
+ * Computes total latency and cost from all steps.
750
+ *
751
+ * @param run - Run to end.
752
+ * @returns Updated run with end timestamp, total latency, and total cost.
753
+ * @example
754
+ * ```ts
755
+ * const completedRun = endRun(run);
756
+ * console.log(`Total cost: $${completedRun.totalCostUSD}`);
757
+ * ```
758
+ */
759
+ function endRun(run) {
760
+ run.endedAt = Date.now();
761
+ run.totalLatencyMs = run.endedAt - run.startedAt;
762
+ run.totalCostUSD = run.steps.reduce((acc, s) => acc + (s.costUSD ?? 0), 0);
763
+ return run;
764
+ }
765
+ /**
766
+ * Persists step artifacts to storage.
767
+ * Writes step artifacts as JSON files in the run directory.
768
+ *
769
+ * @param run - Research run.
770
+ * @param step - Research step.
771
+ * @param payloads - Artifact payloads keyed by name.
772
+ * @throws {Error} If run ID is invalid or file write fails.
773
+ * @remarks Production: Replace with R2 writes.
774
+ * Artifact keys are added to step.artifactKeys array for reference.
775
+ * Files are named as: `{step.kind}-{step.id}.{name}.json`
776
+ * @example
777
+ * ```ts
778
+ * await persistStep(run, step, {
779
+ * p_notes: { notes: '...', cites: [...] },
780
+ * p_index: { sources: [...], fetchedAt: '...' }
781
+ * });
782
+ * ```
783
+ */
784
+ async function persistStep(run, step, payloads) {
785
+ await ensureTracesDir();
786
+ const runDir = getRunPath(run.runId);
787
+ if (!runDir) throw new Error(`Invalid run ID: ${run.runId}`);
788
+ await promises.mkdir(runDir, { recursive: true });
789
+ for (const [name, body] of Object.entries(payloads)) {
790
+ const filename = `${step.kind}-${step.id}.${name}.json`;
791
+ const filepath = join(runDir, filename);
792
+ await promises.writeFile(filepath, JSON.stringify(body, null, 2), "utf-8");
793
+ step.artifactKeys.push(filename);
794
+ }
795
+ }
796
+ /**
797
+ * Persists run index for fast listing.
798
+ * Creates an index file with run metadata for quick queries.
799
+ *
800
+ * @param run - Research run to index.
801
+ * @remarks Production: Write to Upstash Redis ZSET.
802
+ * @example
803
+ * ```ts
804
+ * await persistRunIndex(run);
805
+ * ```
806
+ */
807
+ async function persistRunIndex(run) {
808
+ await ensureTracesDir();
809
+ const indexPath = join(TRACES_DIR, `${run.runId}.index.json`);
810
+ const index = {
811
+ runId: run.runId,
812
+ app: run.app,
813
+ question: run.question,
814
+ tier: run.tier,
815
+ startedAt: run.startedAt,
816
+ endedAt: run.endedAt ?? 0,
817
+ totalLatencyMs: run.totalLatencyMs ?? 0,
818
+ totalCostUSD: run.totalCostUSD ?? 0,
819
+ flags: run.flags ?? []
820
+ };
821
+ await promises.writeFile(indexPath, JSON.stringify(index, null, 2), "utf-8");
822
+ }
823
+ /**
824
+ * Persists full run metadata.
825
+ * Writes complete run object as JSON file.
826
+ *
827
+ * @param run - Research run to persist.
828
+ * @throws {Error} If run ID is invalid or file write fails.
829
+ * @remarks Writes to `{runId}/run.meta.json` in traces directory.
830
+ * Contains complete run state including all steps and metadata.
831
+ * @example
832
+ * ```ts
833
+ * await persistRunMeta(run);
834
+ * ```
835
+ */
836
+ async function persistRunMeta(run) {
837
+ await ensureTracesDir();
838
+ const runDir = getRunPath(run.runId);
839
+ if (!runDir) throw new Error(`Invalid run ID: ${run.runId}`);
840
+ await promises.mkdir(runDir, { recursive: true });
841
+ const metaPath = join(runDir, "run.meta.json");
842
+ await promises.writeFile(metaPath, JSON.stringify(run, null, 2), "utf-8");
843
+ }
844
+ /**
845
+ * Lists recent research runs.
846
+ * Returns runs sorted by start time (most recent first).
847
+ *
848
+ * @param limit - Maximum number of runs to return (defaults to 100).
849
+ * @returns Array of TraceRun objects sorted by startedAt descending.
850
+ * @remarks Production: Query from Redis ZSET.
851
+ * Reads index files from traces directory and parses JSON.
852
+ * Returns empty array on error (logs error to console).
853
+ * @example
854
+ * ```ts
855
+ * const runs = await listRuns(50);
856
+ * ```
857
+ */
858
+ async function listRuns(limit = 100) {
859
+ await ensureTracesDir();
860
+ try {
861
+ const indexFiles = (await promises.readdir(TRACES_DIR)).filter((f) => f.endsWith(".index.json"));
862
+ return (await Promise.all(indexFiles.map(async (file) => {
863
+ const content = await promises.readFile(join(TRACES_DIR, file), "utf-8");
864
+ return JSON.parse(content);
865
+ }))).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit);
866
+ } catch (error) {
867
+ logError("Failed to list runs", { error });
868
+ return [];
869
+ }
870
+ }
871
+ /**
872
+ * Loads full run metadata from storage.
873
+ *
874
+ * @param runId - Run identifier.
875
+ * @returns TraceRun object or `null` if not found or invalid.
876
+ * @remarks Reads from `{runId}/run.meta.json` file.
877
+ * Returns `null` if file doesn't exist, runId is invalid, or parse fails.
878
+ * Logs errors to console.
879
+ * @example
880
+ * ```ts
881
+ * const run = await loadRun('1733875200000-a1b2c3d4e5f6');
882
+ * ```
883
+ */
884
+ async function loadRun(runId) {
885
+ try {
886
+ const metaPath = getRunPath(runId, "run.meta.json");
887
+ if (!metaPath) return null;
888
+ const content = await promises.readFile(metaPath, "utf-8");
889
+ return JSON.parse(content);
890
+ } catch (error) {
891
+ logError("Failed to load run", {
892
+ error,
893
+ runId
894
+ });
895
+ return null;
896
+ }
897
+ }
898
+ /**
899
+ * Loads a step artifact from storage.
900
+ * Validates artifact key to prevent path traversal attacks.
901
+ *
902
+ * @param runId - Run identifier.
903
+ * @param artifactKey - Artifact key (filename).
904
+ * @returns Artifact data or `null` if not found or validation fails.
905
+ * @remarks Rejects artifact keys containing '..' or '/' to prevent path traversal.
906
+ * Returns `null` on any error (file not found, invalid key, parse error).
907
+ * @example
908
+ * ```ts
909
+ * const artifact = await loadStepArtifact(runId, 'perplexity-123.p_notes.json');
910
+ * ```
911
+ */
912
+ async function loadStepArtifact(runId, artifactKey) {
913
+ try {
914
+ if (artifactKey.includes("..") || artifactKey.includes("/")) {
915
+ logError("Invalid artifact key", { artifactKey });
916
+ return null;
917
+ }
918
+ const artifactPath = getRunPath(runId, artifactKey);
919
+ if (!artifactPath) return null;
920
+ const content = await promises.readFile(artifactPath, "utf-8");
921
+ return JSON.parse(content);
922
+ } catch (error) {
923
+ logError("Failed to load artifact", {
924
+ error,
925
+ artifactKey,
926
+ runId
927
+ });
928
+ return null;
929
+ }
930
+ }
931
+
932
+ //#endregion
933
+ //#region src/grounding/rag/tool.ts
934
+ /**
935
+ * @fileoverview Research tool for agent integration
936
+ *
937
+ * Wraps the three-stage research pipeline as an AI SDK tool
938
+ * that can be used by any agent (canvas, chat, etc.)
939
+ *
940
+ * Features:
941
+ * - Configurable models per stage via PipelineModelConfig
942
+ * - Tier-based research (fast/balanced/deep)
943
+ * - Full trace with cost/latency
944
+ * - Compliance signal integration
945
+ * - Artifact storage for research results
946
+ *
947
+ * @module @od-oneapp/ai-platform/research/tool
948
+ */
949
+ /**
950
+ * Schema for research tool input.
951
+ */
952
+ const researchInputSchema = z.object({
953
+ question: z.string().min(1).describe("Research question or query"),
954
+ tier: z.enum([
955
+ "fast",
956
+ "balanced",
957
+ "deep"
958
+ ]).optional().default("balanced").describe("Research depth: fast (400 tokens), balanced (800 tokens), deep (1600 tokens)")
959
+ });
960
+ /**
961
+ * Creates a research tool for AI SDK agents.
962
+ * Wraps the multi-model research pipeline with trace storage and compliance signals.
963
+ *
964
+ * @param options - Optional tool configuration:
965
+ * - `onSignal` - Callback for compliance signal emission
966
+ * - `onTrace` - Callback for trace step completion (receives runId, step kind, latency, cost)
967
+ * @returns AI SDK tool ready for agent integration.
968
+ * @remarks Tool executes full three-stage research pipeline (context expansion → reasoning → verification).
969
+ * Persists step artifacts and run metadata for traceability.
970
+ * Emits compliance signals at start and completion.
971
+ * Returns structured result with answer, confidence, citations, flags, and trace.
972
+ * On error, returns failure result with error message and emits guardrail.blocked signal.
973
+ * @example
974
+ * ```ts
975
+ * const researchTool = createResearchTool({
976
+ * onSignal: (signal) => persistSignal(signal),
977
+ * onTrace: (runId, step) => console.log(`Step ${step.kind} completed`)
978
+ * });
979
+ *
980
+ * const agent = createAgent({
981
+ * tools: { research: researchTool }
982
+ * });
983
+ * ```
984
+ */
985
+ function createResearchTool(options) {
986
+ return tool({
987
+ description: `Perform multi-model research using a three-stage pipeline: context expansion → structured reasoning → verification.
988
+
989
+ This tool provides grounded, verified research with:
990
+ - Context expansion (notes + citations)
991
+ - Structured reasoning (claims, assumptions, gaps)
992
+ - Verification (fact-checking, confidence scoring)
993
+
994
+ Use this tool when you need factual, citation-backed answers to complex questions.
995
+
996
+ Tiers:
997
+ - fast: Quick research (400 tokens, ~2-3 citations)
998
+ - balanced: Standard research (800 tokens, ~5 citations)
999
+ - deep: Comprehensive research (1600 tokens, ~7 citations)`,
1000
+ inputSchema: researchInputSchema,
1001
+ execute: async (input) => {
1002
+ const { question, tier } = input;
1003
+ try {
1004
+ const run = startRun(question, tier, "next-ai");
1005
+ options?.onSignal?.({
1006
+ id: crypto.randomUUID(),
1007
+ type: "tool.executed",
1008
+ message: `Starting multi-model research (tier: ${tier})`,
1009
+ runId: run.runId,
1010
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1011
+ metadata: {
1012
+ question,
1013
+ tier
1014
+ }
1015
+ });
1016
+ const mc = options?.modelConfig;
1017
+ const expansionStep = startStep("context-expansion", mc?.contextExpansion?.model ?? "llama-3.1-sonar-large-128k-online");
1018
+ const { notes, cites, usage: expansionUsage } = await researchWithPerplexity(question, tier);
1019
+ endStep(expansionStep, {
1020
+ inputTokens: expansionUsage.inputTokens,
1021
+ outputTokens: expansionUsage.outputTokens
1022
+ });
1023
+ await persistStep(run, expansionStep, {
1024
+ expansion_notes: {
1025
+ notes,
1026
+ cites
1027
+ },
1028
+ expansion_index: {
1029
+ sources: cites,
1030
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
1031
+ tier
1032
+ }
1033
+ });
1034
+ run.steps.push(expansionStep);
1035
+ options?.onTrace?.(run.runId, {
1036
+ kind: "context-expansion",
1037
+ latencyMs: expansionStep.latencyMs,
1038
+ costUSD: expansionStep.costUSD ?? 0
1039
+ });
1040
+ const reasoningStep = startStep("reasoning", mc?.reasoning?.model ?? "claude-3-5-sonnet-20241022");
1041
+ const reasoning = await reasonWithSonnet({
1042
+ question,
1043
+ notes,
1044
+ cites
1045
+ });
1046
+ endStep(reasoningStep, {
1047
+ inputTokens: reasoning.usage.inputTokens,
1048
+ outputTokens: reasoning.usage.outputTokens
1049
+ });
1050
+ await persistStep(run, reasoningStep, { reasoning_output: {
1051
+ claims: reasoning.claims,
1052
+ assumptions: reasoning.assumptions,
1053
+ gaps: reasoning.gaps,
1054
+ answerDraft: reasoning.answerDraft,
1055
+ meta: {
1056
+ model: reasoningStep.model,
1057
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1058
+ }
1059
+ } });
1060
+ run.steps.push(reasoningStep);
1061
+ options?.onTrace?.(run.runId, {
1062
+ kind: "reasoning",
1063
+ latencyMs: reasoningStep.latencyMs,
1064
+ costUSD: reasoningStep.costUSD ?? 0
1065
+ });
1066
+ const verificationStep = startStep("verification", mc?.verification?.model ?? process.env.NEXT_AI_VERIFICATION_MODEL ?? "gpt-4-turbo");
1067
+ const verification = await verifyWithGPT5(reasoning, cites);
1068
+ endStep(verificationStep, {
1069
+ inputTokens: verification.usage.inputTokens,
1070
+ outputTokens: verification.usage.outputTokens
1071
+ });
1072
+ await persistStep(run, verificationStep, { verification_output: {
1073
+ finalAnswer: verification.finalAnswer,
1074
+ flags: verification.flags,
1075
+ trace: verification.trace,
1076
+ confidence: verification.confidence,
1077
+ meta: {
1078
+ model: verificationStep.model,
1079
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1080
+ }
1081
+ } });
1082
+ run.steps.push(verificationStep);
1083
+ options?.onTrace?.(run.runId, {
1084
+ kind: "verification",
1085
+ latencyMs: verificationStep.latencyMs,
1086
+ costUSD: verificationStep.costUSD ?? 0
1087
+ });
1088
+ run.flags = verification.flags.map((f) => f.issue);
1089
+ endRun(run);
1090
+ await persistRunMeta(run);
1091
+ await persistRunIndex(run);
1092
+ options?.onSignal?.({
1093
+ id: crypto.randomUUID(),
1094
+ type: "tool.executed",
1095
+ message: `Research completed (confidence: ${verification.confidence}, ${verification.flags.length} flags)`,
1096
+ runId: run.runId,
1097
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1098
+ metadata: {
1099
+ runId: run.runId,
1100
+ latencyMs: run.totalLatencyMs,
1101
+ costUSD: run.totalCostUSD,
1102
+ confidence: verification.confidence,
1103
+ flagCount: verification.flags.length
1104
+ }
1105
+ });
1106
+ return {
1107
+ success: true,
1108
+ answer: verification.finalAnswer,
1109
+ confidence: verification.confidence,
1110
+ citations: cites.map((url, i) => `[${i + 1}] ${url}`).join("\n"),
1111
+ flags: verification.flags.length > 0 ? verification.flags.map((f) => `⚠️ ${f.claim}: ${f.issue} (${f.details})`).join("\n") : "No verification issues",
1112
+ reasoning: {
1113
+ claims: reasoning.claims.length,
1114
+ assumptions: reasoning.assumptions.length,
1115
+ gaps: reasoning.gaps.length
1116
+ },
1117
+ trace: {
1118
+ runId: run.runId,
1119
+ latencyMs: run.totalLatencyMs,
1120
+ costUSD: `$${run.totalCostUSD?.toFixed(4)}`,
1121
+ steps: run.steps.map((s) => ({
1122
+ kind: s.kind,
1123
+ latencyMs: s.latencyMs,
1124
+ costUSD: `$${s.costUSD?.toFixed(4)}`
1125
+ }))
1126
+ }
1127
+ };
1128
+ } catch (error) {
1129
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1130
+ options?.onSignal?.({
1131
+ id: crypto.randomUUID(),
1132
+ type: "guardrail.blocked",
1133
+ message: `Research failed: ${errorMessage}`,
1134
+ runId: crypto.randomUUID(),
1135
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1136
+ metadata: { error: errorMessage }
1137
+ });
1138
+ return {
1139
+ success: false,
1140
+ error: errorMessage,
1141
+ answer: "Research pipeline failed. Please try again or rephrase your question."
1142
+ };
1143
+ }
1144
+ }
1145
+ });
1146
+ }
1147
+
1148
+ //#endregion
1149
+ export { verifyWithGPT5 as _, estimateCost as a, loadStepArtifact as c, persistStep as d, startRun as f, researchWithPerplexity as g, reasonWithSonnet as h, endStep as i, persistRunIndex as l, executeResearchPipeline as m, DEFAULT_COST_RATES as n, listRuns as o, startStep as p, endRun as r, loadRun as s, createResearchTool as t, persistRunMeta as u };
1150
+ //# sourceMappingURL=tool-JSf8JXZ8.mjs.map