@mastra/core 1.3.0 → 1.4.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 (274) hide show
  1. package/CHANGELOG.md +462 -0
  2. package/datasets.d.ts +1 -0
  3. package/dist/agent/agent.d.ts +1 -1
  4. package/dist/agent/index.cjs +13 -13
  5. package/dist/agent/index.js +2 -2
  6. package/dist/agent/message-list/adapters/AIV4Adapter.d.ts.map +1 -1
  7. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts.map +1 -1
  8. package/dist/agent/message-list/conversion/output-converter.d.ts +2 -1
  9. package/dist/agent/message-list/conversion/output-converter.d.ts.map +1 -1
  10. package/dist/agent/message-list/index.cjs +18 -18
  11. package/dist/agent/message-list/index.js +1 -1
  12. package/dist/agent/workflows/prepare-stream/index.d.ts +1 -1
  13. package/dist/chunk-3JVFFAJX.cjs +1207 -0
  14. package/dist/chunk-3JVFFAJX.cjs.map +1 -0
  15. package/dist/{chunk-WL3AW3YA.js → chunk-3X3CZUXI.js} +4070 -3983
  16. package/dist/chunk-3X3CZUXI.js.map +1 -0
  17. package/dist/{chunk-2GWTJFVM.js → chunk-4EHGOATH.js} +46 -14
  18. package/dist/chunk-4EHGOATH.js.map +1 -0
  19. package/dist/{chunk-YNXIGRQE.cjs → chunk-4IJ4UDZX.cjs} +319 -83
  20. package/dist/chunk-4IJ4UDZX.cjs.map +1 -0
  21. package/dist/{chunk-CGPH7CMG.cjs → chunk-4KFEMXTV.cjs} +46 -14
  22. package/dist/chunk-4KFEMXTV.cjs.map +1 -0
  23. package/dist/{chunk-PHYJYZ32.js → chunk-4TQ4EBYX.js} +16 -8
  24. package/dist/chunk-4TQ4EBYX.js.map +1 -0
  25. package/dist/{chunk-SIZEIYNH.js → chunk-4XSAZPPS.js} +254 -18
  26. package/dist/chunk-4XSAZPPS.js.map +1 -0
  27. package/dist/{chunk-KUTU2YZF.js → chunk-5Q5Y34SS.js} +5 -5
  28. package/dist/{chunk-KUTU2YZF.js.map → chunk-5Q5Y34SS.js.map} +1 -1
  29. package/dist/{chunk-EH6SAGEO.cjs → chunk-64WGYTQK.cjs} +72 -53
  30. package/dist/{chunk-EH6SAGEO.cjs.map → chunk-64WGYTQK.cjs.map} +1 -1
  31. package/dist/{chunk-OOCEAC6U.cjs → chunk-65PHUUMF.cjs} +3 -3
  32. package/dist/{chunk-OOCEAC6U.cjs.map → chunk-65PHUUMF.cjs.map} +1 -1
  33. package/dist/{chunk-JNE2ABVB.js → chunk-7NKUSQEV.js} +1094 -10
  34. package/dist/chunk-7NKUSQEV.js.map +1 -0
  35. package/dist/{chunk-ZHFM7HCQ.js → chunk-AXHBJ4GX.js} +3 -3
  36. package/dist/{chunk-ZHFM7HCQ.js.map → chunk-AXHBJ4GX.js.map} +1 -1
  37. package/dist/{chunk-ILQXPZCD.js → chunk-AY6DBRS3.js} +37 -21
  38. package/dist/chunk-AY6DBRS3.js.map +1 -0
  39. package/dist/{chunk-TERSHTY5.cjs → chunk-BP7VYTOP.cjs} +1116 -21
  40. package/dist/chunk-BP7VYTOP.cjs.map +1 -0
  41. package/dist/{chunk-UE2G2LRP.cjs → chunk-CZ4NQANZ.cjs} +37 -21
  42. package/dist/chunk-CZ4NQANZ.cjs.map +1 -0
  43. package/dist/{chunk-NCC45KOB.cjs → chunk-DBSVT6AR.cjs} +7 -7
  44. package/dist/{chunk-NCC45KOB.cjs.map → chunk-DBSVT6AR.cjs.map} +1 -1
  45. package/dist/{chunk-BXLLXTT4.js → chunk-FLPEGTEK.js} +4 -4
  46. package/dist/{chunk-BXLLXTT4.js.map → chunk-FLPEGTEK.js.map} +1 -1
  47. package/dist/{chunk-ON2KVIUJ.cjs → chunk-HYRYTTMT.cjs} +7 -7
  48. package/dist/{chunk-ON2KVIUJ.cjs.map → chunk-HYRYTTMT.cjs.map} +1 -1
  49. package/dist/chunk-NJ7TL3LQ.js +1196 -0
  50. package/dist/chunk-NJ7TL3LQ.js.map +1 -0
  51. package/dist/{chunk-EUG4AON3.cjs → chunk-NKYWDNCI.cjs} +8 -7
  52. package/dist/{chunk-EUG4AON3.cjs.map → chunk-NKYWDNCI.cjs.map} +1 -1
  53. package/dist/{chunk-UHVG25VW.cjs → chunk-NZG2JAKS.cjs} +23 -15
  54. package/dist/chunk-NZG2JAKS.cjs.map +1 -0
  55. package/dist/{chunk-44SUGDBR.js → chunk-PS5ONCXY.js} +109 -5
  56. package/dist/chunk-PS5ONCXY.js.map +1 -0
  57. package/dist/{chunk-57QAF2ZQ.js → chunk-QTTWRCB5.js} +4 -4
  58. package/dist/{chunk-57QAF2ZQ.js.map → chunk-QTTWRCB5.js.map} +1 -1
  59. package/dist/{chunk-VM25PDSW.js → chunk-RZ4CIIZR.js} +4 -4
  60. package/dist/{chunk-VM25PDSW.js.map → chunk-RZ4CIIZR.js.map} +1 -1
  61. package/dist/{chunk-C3XU7ZDC.cjs → chunk-SU5APAM6.cjs} +123 -4
  62. package/dist/chunk-SU5APAM6.cjs.map +1 -0
  63. package/dist/{chunk-3MJCJLZS.js → chunk-U2HKJZCI.js} +24 -5
  64. package/dist/{chunk-3MJCJLZS.js.map → chunk-U2HKJZCI.js.map} +1 -1
  65. package/dist/{chunk-GCTAD6B7.cjs → chunk-VD5YA6RH.cjs} +12 -12
  66. package/dist/{chunk-GCTAD6B7.cjs.map → chunk-VD5YA6RH.cjs.map} +1 -1
  67. package/dist/{chunk-KAJNBNWP.cjs → chunk-YNNJLLFN.cjs} +4071 -3984
  68. package/dist/chunk-YNNJLLFN.cjs.map +1 -0
  69. package/dist/datasets/dataset.d.ts +153 -0
  70. package/dist/datasets/dataset.d.ts.map +1 -0
  71. package/dist/datasets/experiment/analytics/aggregate.d.ts +46 -0
  72. package/dist/datasets/experiment/analytics/aggregate.d.ts.map +1 -0
  73. package/dist/datasets/experiment/analytics/compare.d.ts +33 -0
  74. package/dist/datasets/experiment/analytics/compare.d.ts.map +1 -0
  75. package/dist/datasets/experiment/analytics/index.d.ts +9 -0
  76. package/dist/datasets/experiment/analytics/index.d.ts.map +1 -0
  77. package/dist/datasets/experiment/analytics/types.d.ts +103 -0
  78. package/dist/datasets/experiment/analytics/types.d.ts.map +1 -0
  79. package/dist/datasets/experiment/executor.d.ts +40 -0
  80. package/dist/datasets/experiment/executor.d.ts.map +1 -0
  81. package/dist/datasets/experiment/index.d.ts +31 -0
  82. package/dist/datasets/experiment/index.d.ts.map +1 -0
  83. package/dist/datasets/experiment/scorer.d.ts +21 -0
  84. package/dist/datasets/experiment/scorer.d.ts.map +1 -0
  85. package/dist/datasets/experiment/types.d.ts +140 -0
  86. package/dist/datasets/experiment/types.d.ts.map +1 -0
  87. package/dist/datasets/index.cjs +69 -0
  88. package/dist/datasets/index.cjs.map +1 -0
  89. package/dist/datasets/index.d.ts +6 -0
  90. package/dist/datasets/index.d.ts.map +1 -0
  91. package/dist/datasets/index.js +4 -0
  92. package/dist/datasets/index.js.map +1 -0
  93. package/dist/datasets/manager.d.ts +73 -0
  94. package/dist/datasets/manager.d.ts.map +1 -0
  95. package/dist/datasets/validation/errors.d.ts +44 -0
  96. package/dist/datasets/validation/errors.d.ts.map +1 -0
  97. package/dist/datasets/validation/index.d.ts +3 -0
  98. package/dist/datasets/validation/index.d.ts.map +1 -0
  99. package/dist/datasets/validation/validator.d.ts +24 -0
  100. package/dist/datasets/validation/validator.d.ts.map +1 -0
  101. package/dist/docs/SKILL.md +1 -3
  102. package/dist/docs/assets/SOURCE_MAP.json +436 -346
  103. package/dist/docs/references/docs-memory-observational-memory.md +86 -11
  104. package/dist/docs/references/docs-streaming-events.md +23 -0
  105. package/dist/docs/references/docs-workspace-filesystem.md +72 -1
  106. package/dist/docs/references/docs-workspace-overview.md +95 -12
  107. package/dist/docs/references/docs-workspace-sandbox.md +2 -0
  108. package/dist/docs/references/guides-agent-frameworks-ai-sdk.md +6 -2
  109. package/dist/docs/references/reference-ai-sdk-with-mastra.md +1 -1
  110. package/dist/docs/references/reference-memory-observational-memory.md +318 -9
  111. package/dist/docs/references/reference-streaming-workflows-stream.md +1 -0
  112. package/dist/docs/references/reference-workflows-workflow-methods-foreach.md +30 -0
  113. package/dist/docs/references/reference.md +3 -0
  114. package/dist/editor/index.d.ts +1 -1
  115. package/dist/editor/index.d.ts.map +1 -1
  116. package/dist/editor/types.d.ts +21 -3
  117. package/dist/editor/types.d.ts.map +1 -1
  118. package/dist/evals/index.cjs +20 -20
  119. package/dist/evals/index.js +3 -3
  120. package/dist/evals/scoreTraces/index.cjs +5 -5
  121. package/dist/evals/scoreTraces/index.js +2 -2
  122. package/dist/features/index.cjs +1 -1
  123. package/dist/features/index.cjs.map +1 -1
  124. package/dist/features/index.d.ts.map +1 -1
  125. package/dist/features/index.js +1 -1
  126. package/dist/features/index.js.map +1 -1
  127. package/dist/index.cjs +2 -7
  128. package/dist/index.d.ts +0 -9
  129. package/dist/index.d.ts.map +1 -1
  130. package/dist/index.js +1 -2
  131. package/dist/llm/index.cjs +10 -10
  132. package/dist/llm/index.js +2 -2
  133. package/dist/llm/model/provider-types.generated.d.ts +1694 -1659
  134. package/dist/loop/index.cjs +12 -12
  135. package/dist/loop/index.js +1 -1
  136. package/dist/loop/network/index.d.ts +1 -1
  137. package/dist/loop/workflows/agentic-execution/index.d.ts +1 -1
  138. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  139. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  140. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  141. package/dist/loop/workflows/agentic-loop/index.d.ts +1 -1
  142. package/dist/loop/workflows/errors.d.ts +4 -0
  143. package/dist/loop/workflows/errors.d.ts.map +1 -0
  144. package/dist/mastra/index.cjs +2 -2
  145. package/dist/mastra/index.d.ts +2 -0
  146. package/dist/mastra/index.d.ts.map +1 -1
  147. package/dist/mastra/index.js +1 -1
  148. package/dist/memory/index.cjs +14 -14
  149. package/dist/memory/index.js +1 -1
  150. package/dist/memory/memory.d.ts +5 -0
  151. package/dist/memory/memory.d.ts.map +1 -1
  152. package/dist/memory/types.d.ts +56 -0
  153. package/dist/memory/types.d.ts.map +1 -1
  154. package/dist/processors/index.cjs +41 -41
  155. package/dist/processors/index.js +1 -1
  156. package/dist/processors/processors/skills.d.ts +1 -1
  157. package/dist/processors/processors/skills.d.ts.map +1 -1
  158. package/dist/processors/runner.d.ts.map +1 -1
  159. package/dist/processors/trailing-assistant-guard.d.ts +34 -0
  160. package/dist/processors/trailing-assistant-guard.d.ts.map +1 -0
  161. package/dist/provider-registry-6LZAGQET.cjs +40 -0
  162. package/dist/{provider-registry-C6XCYX44.cjs.map → provider-registry-6LZAGQET.cjs.map} +1 -1
  163. package/dist/provider-registry-QUNT7S55.js +3 -0
  164. package/dist/{provider-registry-NWU4YFQW.js.map → provider-registry-QUNT7S55.js.map} +1 -1
  165. package/dist/provider-registry.json +4068 -3981
  166. package/dist/relevance/index.cjs +3 -3
  167. package/dist/relevance/index.js +1 -1
  168. package/dist/storage/base.d.ts +4 -1
  169. package/dist/storage/base.d.ts.map +1 -1
  170. package/dist/storage/constants.cjs +87 -27
  171. package/dist/storage/constants.d.ts +21 -2
  172. package/dist/storage/constants.d.ts.map +1 -1
  173. package/dist/storage/constants.js +1 -1
  174. package/dist/storage/domains/agents/inmemory.d.ts.map +1 -1
  175. package/dist/storage/domains/datasets/base.d.ts +83 -0
  176. package/dist/storage/domains/datasets/base.d.ts.map +1 -0
  177. package/dist/storage/domains/datasets/index.d.ts +3 -0
  178. package/dist/storage/domains/datasets/index.d.ts.map +1 -0
  179. package/dist/storage/domains/datasets/inmemory.d.ts +40 -0
  180. package/dist/storage/domains/datasets/inmemory.d.ts.map +1 -0
  181. package/dist/storage/domains/experiments/base.d.ts +28 -0
  182. package/dist/storage/domains/experiments/base.d.ts.map +1 -0
  183. package/dist/storage/domains/experiments/index.d.ts +3 -0
  184. package/dist/storage/domains/experiments/index.d.ts.map +1 -0
  185. package/dist/storage/domains/experiments/inmemory.d.ts +28 -0
  186. package/dist/storage/domains/experiments/inmemory.d.ts.map +1 -0
  187. package/dist/storage/domains/index.d.ts +3 -0
  188. package/dist/storage/domains/index.d.ts.map +1 -1
  189. package/dist/storage/domains/inmemory-db.d.ts +9 -1
  190. package/dist/storage/domains/inmemory-db.d.ts.map +1 -1
  191. package/dist/storage/domains/mcp-clients/base.d.ts +47 -0
  192. package/dist/storage/domains/mcp-clients/base.d.ts.map +1 -0
  193. package/dist/storage/domains/mcp-clients/index.d.ts +3 -0
  194. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -0
  195. package/dist/storage/domains/mcp-clients/inmemory.d.ts +31 -0
  196. package/dist/storage/domains/mcp-clients/inmemory.d.ts.map +1 -0
  197. package/dist/storage/domains/operations/inmemory.d.ts.map +1 -1
  198. package/dist/storage/index.cjs +201 -117
  199. package/dist/storage/index.js +2 -2
  200. package/dist/storage/mock.d.ts.map +1 -1
  201. package/dist/storage/types.d.ts +338 -3
  202. package/dist/storage/types.d.ts.map +1 -1
  203. package/dist/stream/base/output.d.ts.map +1 -1
  204. package/dist/stream/index.cjs +11 -11
  205. package/dist/stream/index.js +2 -2
  206. package/dist/stream/types.d.ts +15 -0
  207. package/dist/stream/types.d.ts.map +1 -1
  208. package/dist/test-utils/llm-mock.cjs +4 -4
  209. package/dist/test-utils/llm-mock.js +1 -1
  210. package/dist/tool-loop-agent/index.cjs +4 -4
  211. package/dist/tool-loop-agent/index.js +1 -1
  212. package/dist/tool-provider/index.cjs +4 -0
  213. package/dist/tool-provider/index.cjs.map +1 -0
  214. package/dist/tool-provider/index.d.ts +2 -0
  215. package/dist/tool-provider/index.d.ts.map +1 -0
  216. package/dist/tool-provider/index.js +3 -0
  217. package/dist/tool-provider/index.js.map +1 -0
  218. package/dist/tool-provider/types.d.ts +113 -0
  219. package/dist/tool-provider/types.d.ts.map +1 -0
  220. package/dist/utils.cjs +23 -23
  221. package/dist/utils.d.ts +1 -1
  222. package/dist/utils.d.ts.map +1 -1
  223. package/dist/utils.js +1 -1
  224. package/dist/vector/index.cjs +7 -7
  225. package/dist/vector/index.js +1 -1
  226. package/dist/workflows/evented/index.cjs +10 -10
  227. package/dist/workflows/evented/index.js +1 -1
  228. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  229. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  230. package/dist/workflows/index.cjs +25 -25
  231. package/dist/workflows/index.js +1 -1
  232. package/dist/workflows/workflow.d.ts +2 -2
  233. package/dist/workflows/workflow.d.ts.map +1 -1
  234. package/dist/workspace/filesystem/filesystem.d.ts +5 -15
  235. package/dist/workspace/filesystem/filesystem.d.ts.map +1 -1
  236. package/dist/workspace/filesystem/local-filesystem.d.ts +18 -2
  237. package/dist/workspace/filesystem/local-filesystem.d.ts.map +1 -1
  238. package/dist/workspace/filesystem/mastra-filesystem.d.ts +21 -1
  239. package/dist/workspace/filesystem/mastra-filesystem.d.ts.map +1 -1
  240. package/dist/workspace/index.cjs +41 -41
  241. package/dist/workspace/index.d.ts +1 -1
  242. package/dist/workspace/index.d.ts.map +1 -1
  243. package/dist/workspace/index.js +1 -1
  244. package/dist/workspace/lifecycle.d.ts +49 -53
  245. package/dist/workspace/lifecycle.d.ts.map +1 -1
  246. package/dist/workspace/sandbox/local-sandbox.d.ts +1 -1
  247. package/dist/workspace/sandbox/local-sandbox.d.ts.map +1 -1
  248. package/dist/workspace/sandbox/mastra-sandbox.d.ts +3 -2
  249. package/dist/workspace/sandbox/mastra-sandbox.d.ts.map +1 -1
  250. package/dist/workspace/sandbox/sandbox.d.ts +3 -4
  251. package/dist/workspace/sandbox/sandbox.d.ts.map +1 -1
  252. package/dist/workspace/workspace.d.ts +2 -15
  253. package/dist/workspace/workspace.d.ts.map +1 -1
  254. package/package.json +7 -7
  255. package/src/llm/model/provider-types.generated.d.ts +1694 -1659
  256. package/tool-provider.d.ts +1 -0
  257. package/dist/chunk-2GWTJFVM.js.map +0 -1
  258. package/dist/chunk-44SUGDBR.js.map +0 -1
  259. package/dist/chunk-C3XU7ZDC.cjs.map +0 -1
  260. package/dist/chunk-CGPH7CMG.cjs.map +0 -1
  261. package/dist/chunk-ILQXPZCD.js.map +0 -1
  262. package/dist/chunk-JNE2ABVB.js.map +0 -1
  263. package/dist/chunk-KAJNBNWP.cjs.map +0 -1
  264. package/dist/chunk-PHYJYZ32.js.map +0 -1
  265. package/dist/chunk-SIZEIYNH.js.map +0 -1
  266. package/dist/chunk-TERSHTY5.cjs.map +0 -1
  267. package/dist/chunk-UE2G2LRP.cjs.map +0 -1
  268. package/dist/chunk-UHVG25VW.cjs.map +0 -1
  269. package/dist/chunk-WL3AW3YA.js.map +0 -1
  270. package/dist/chunk-YNXIGRQE.cjs.map +0 -1
  271. package/dist/docs/references/reference-cli-mastra.md +0 -336
  272. package/dist/docs/references/reference-deployer-cloudflare.md +0 -56
  273. package/dist/provider-registry-C6XCYX44.cjs +0 -40
  274. package/dist/provider-registry-NWU4YFQW.js +0 -3
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/storage/domains/shared.ts","../src/evals/types.ts","../src/storage/domains/observability/types.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","TraceStatus"],"mappings":";;;;AAMO,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,EAAK,CAAE,SAAS,+BAA+B;AAExE,IAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,EAAK,CAAE,SAAS,kCAAkC;AAE3E,IAAM,YAAA,GAAe;AAAA,EAC1B,SAAA,EAAW,cAAA;AAAA,EACX,SAAA,EAAW,eAAe,QAAA;AAC5B;AAMO,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,MAAM,CAAA,CAAE,MAAA,CAAO,MAAA,EAAO,CAAE,KAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,UAAS,CAAE,OAAA,CAAQ,CAAC,CAAA,CAAE,SAAS,0BAA0B,CAAA;AAAA,EAC9F,SAAS,CAAA,CAAE,MAAA,CAAO,QAAO,CAAE,G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AC9C,QAAA,EAAU,EAAE,IAAA,EAAM,OAAA,EAAS,UAAU,IAAA,EAAK;AAAA,IAC1C,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA,EAAM;AAAA,IAChD,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA;AAAM,GAClD;AAAA,EACA,CAAC,YAAY,GAAG,aAAA;AAAA,EAChB,CAAC,oBAAoB,GAAG,qBAAA;AAAA,EACxB,CAAC,mBAAmB,GAAG,oBAAA;AAAA,EACvB,CAAC,2BAA2B,GAAG,4BAAA;AAAA,EAC/B,CAAC,wBAAwB,GAAG,yBAAA;AAAA,EAC5B,CAAC,gCAAgC,GAAG;AACtC;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-44SUGDBR.js","sourcesContent":["import { z } from 'zod';\nimport { EntityType } from '../../observability';\n\n/**\n * Common DB fields\n */\nexport const createdAtField = z.date().describe('Database record creation time');\n\nexport const updatedAtField = z.date().describe('Database record last update time');\n\nexport const dbTimestamps = {\n createdAt: createdAtField,\n updatedAt: updatedAtField.nullable(),\n} as const satisfies z.ZodRawShape;\n\n/**\n * Pagination arguments for list queries (page and perPage only)\n * Uses z.coerce to handle string → number conversion from query params\n */\nexport const paginationArgsSchema = z\n .object({\n page: z.coerce.number().int().min(0).optional().default(0).describe('Zero-indexed page number'),\n perPage: z.coerce.number().int().min(1).max(100).optional().default(10).describe('Number of items per page'),\n })\n .describe('Pagination options for list queries');\n\nexport type PaginationArgs = z.input<typeof paginationArgsSchema>;\n\n/**\n * Pagination response info\n * Used across all paginated endpoints\n */\nexport const paginationInfoSchema = z.object({\n total: z.number().describe('Total number of items available'),\n page: z.number().describe('Current page'),\n perPage: z\n .union([z.number(), z.literal(false)])\n .describe('Number of items per page, or false if pagination is disabled'),\n hasMore: z.boolean().describe('True if more pages are available'),\n});\n\n/**\n * Date range for filtering by time\n * Uses z.coerce to handle ISO string → Date conversion from query params\n */\nexport const dateRangeSchema = z\n .object({\n start: z.coerce.date().optional().describe('Start of date range (inclusive by default)'),\n end: z.coerce.date().optional().describe('End of date range (inclusive by default)'),\n startExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the start date from results (uses > instead of >=)'),\n endExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the end date from results (uses < instead of <=)'),\n })\n .describe('Date range filter for timestamps');\n\nexport type DateRange = z.infer<typeof dateRangeSchema>;\n\nexport const sortDirectionSchema = z.enum(['ASC', 'DESC']).describe(\"Sort direction: 'ASC' | 'DESC'\");\n\nexport const entityTypeField = z\n .nativeEnum(EntityType)\n .describe(`Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')`);\n\nexport const entityIdField = z.string().describe('ID of the entity (e.g., \"weatherAgent\", \"orderWorkflow\")');\n\nexport const entityNameField = z.string().describe('Name of the entity');\n\nexport const userIdField = z.string().describe('Human end-user who triggered execution');\n\nexport const organizationIdField = z.string().describe('Multi-tenant organization/account');\n\nexport const resourceIdField = z.string().describe('Broader resource context (Mastra memory compatibility)');\n\nexport const runIdField = z.string().describe('Unique execution run identifier');\n\nexport const sessionIdField = z.string().describe('Session identifier for grouping traces');\n\nexport const threadIdField = z.string().describe('Conversation thread identifier');\n\nexport const requestIdField = z.string().describe('HTTP request ID for log correlation');\n\nexport const environmentField = z.string().describe(`Environment (e.g., \"production\" | \"staging\" | \"development\")`);\n\nexport const sourceField = z.string().describe(`Source of execution (e.g., \"local\" | \"cloud\" | \"ci\")`);\n\nexport const serviceNameField = z.string().describe('Name of the service');\n","import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { TracingContext } from '../observability';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum(['AGENT', 'WORKFLOW', ...Object.values(SpanType)] as [\n string,\n string,\n ...string[],\n]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n description: z.string(),\n prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n runId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n // Note: tracingContext is not serializable, so we don't include it in the schema\n // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n runId: z.string().optional(),\n scorer: recordSchema,\n input: z.unknown(),\n output: z.unknown(),\n metadata: optionalRecordSchema,\n additionalContext: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema,\n requestContext: optionalRecordSchema,\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Note: tracingContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n result: optionalRecordSchema,\n score: scoringValueSchema,\n prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n runId: z.string(), // Required in this context\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultSchema>,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n id: z.string(),\n scorerId: z.string(),\n entityId: z.string(),\n\n // From ScoringInputWithExtractStepResultAndScoreAndReason\n runId: z.string(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n\n // From ScoringHookInput\n scorer: recordSchema,\n metadata: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema.optional(),\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n\n // Additional ScoreRowData fields\n preprocessStepResult: optionalRecordSchema,\n preprocessPrompt: z.string().optional(),\n generateScorePrompt: z.string().optional(),\n generateReasonPrompt: z.string().optional(),\n\n // Timestamps\n ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n name: string;\n description: string;\n extract?: ExtractionStepFn;\n analyze: AnalyzeStepFn;\n reason?: ReasonStepFn;\n metadata?: Record<string, any>;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n","import { z } from 'zod';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n dateRangeSchema,\n dbTimestamps,\n entityIdField,\n entityNameField,\n entityTypeField,\n environmentField,\n organizationIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n requestIdField,\n resourceIdField,\n runIdField,\n serviceNameField,\n sessionIdField,\n sortDirectionSchema,\n sourceField,\n threadIdField,\n userIdField,\n} from '../shared';\n\n/** Strategy for how tracing data is persisted to storage */\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\n/** Zod schema for trace ID field */\nexport const traceIdField = z.string().describe('Unique trace identifier');\n\n/** Zod schema for span ID field */\nexport const spanIdField = z.string().describe('Unique span identifier within a trace');\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z.record(z.unknown()).describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst metadataField = z.record(z.unknown()).describe('User-defined metadata for custom filtering');\nconst tagsField = z.array(z.string()).describe('Labels for filtering traces (only on the root span)');\nconst scopeField = z\n .record(z.unknown())\n .describe('Arbitrary package/app version info (e.g., {\"core\": \"1.0.0\", \"memory\": \"1.0.0\", \"gitSha\": \"abcd1234\"})');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Status of a trace derived from the root span's state */\nexport enum TraceStatus {\n SUCCESS = 'success',\n ERROR = 'error',\n RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n .preprocess(v => {\n // Handle string \"true\"/\"false\" from query params correctly\n // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n if (v === 'true') return true;\n if (v === 'false') return false;\n return v;\n }, z.boolean())\n .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n // Entity identification - first-class fields for filtering (e.g., agent, workflow, tool)\n entityType: entityTypeField.nullish(),\n entityId: entityIdField.nullish(),\n entityName: entityNameField.nullish(),\n\n // Identity & tenancy - for multi-tenant applications\n userId: userIdField.nullish(),\n organizationId: organizationIdField.nullish(),\n resourceId: resourceIdField.nullish(),\n\n // Correlation IDs - for linking related operations\n runId: runIdField.nullish(),\n sessionId: sessionIdField.nullish(),\n threadId: threadIdField.nullish(),\n requestId: requestIdField.nullish(),\n\n // Deployment context - these fields only exist on the root span\n environment: environmentField.nullish(),\n source: sourceField.nullish(),\n serviceName: serviceNameField.nullish(),\n scope: scopeField.nullish(),\n\n // Filterable data - user-defined metadata and tags (tags only on root span)\n metadata: metadataField.nullish(),\n tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n traceId: traceIdField,\n spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Shared fields\n parentSpanId: parentSpanIdField.nullish(),\n ...sharedFields,\n\n // Additional span-specific nullish fields\n attributes: attributesField.nullish(),\n links: linksField.nullish(),\n input: inputField.nullish(),\n output: outputField.nullish(),\n error: errorField.nullish(),\n endedAt: endedAtField.nullish(),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer<typeof spanRecordSchema>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: SpanRecord): TraceStatus {\n if (span.error != null) return TraceStatus.ERROR;\n if (span.endedAt == null) return TraceStatus.RUNNING;\n return TraceStatus.SUCCESS;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n .extend({\n status: traceStatusField,\n })\n .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n return {\n ...span,\n status: computeTraceStatus(span),\n };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n .object({\n span: createSpanRecordSchema,\n })\n .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n .object({\n records: z.array(createSpanRecordSchema),\n })\n .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n })\n .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\nexport type TraceRecord = GetTraceResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n .object({\n // Date range filters\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Span type filter\n spanType: spanTypeField.optional(),\n\n // Shared fields\n ...sharedFields,\n\n // Filter-specific derived status fields\n status: traceStatusField.optional(),\n hasChildError: hasChildErrorField.optional(),\n })\n .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n .object({\n field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n .object({\n filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({}).describe('Pagination settings'),\n orderBy: tracesOrderBySchema.default({}).describe('Ordering configuration (defaults to startedAt desc)'),\n })\n .describe('Arguments for listing traces');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n pagination: paginationInfoSchema,\n spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n .object({\n spanId: spanIdField,\n traceId: traceIdField,\n updates: updateSpanRecordSchema.partial(),\n })\n .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n .object({\n records: z.array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField,\n updates: updateSpanRecordSchema.partial(),\n }),\n ),\n })\n .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z.array(traceIdField),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n scorerName: z.string().min(1),\n targets: z\n .array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField.optional(),\n }),\n )\n .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n status: z.string(),\n message: z.string(),\n traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport { getZodInnerType, getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n page: number;\n perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n type: StorageColumnType;\n primaryKey?: boolean;\n nullable?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\nexport interface WorkflowRuns {\n runs: WorkflowRun[];\n total: number;\n}\n\nexport interface StorageWorkflowRun {\n workflow_name: string;\n run_id: string;\n resourceId?: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}\nexport interface WorkflowRun {\n workflowName: string;\n runId: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n resourceId?: string;\n}\n\nexport type PaginationInfo = {\n total: number;\n page: number;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When `false`, all matching records are returned in a single response.\n */\n perPage: number | false;\n hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n include?: {\n id: string;\n threadId?: string;\n withPreviousMessages?: number;\n withNextMessages?: number;\n }[];\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 40 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n filter?: {\n dateRange?: {\n start?: Date;\n end?: Date;\n /**\n * When true, excludes the start date from results (uses > instead of >=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n startExclusive?: boolean;\n /**\n * When true, excludes the end date from results (uses < instead of <=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n endExclusive?: boolean;\n };\n };\n orderBy?: StorageOrderBy<'createdAt'>;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n /**\n * Thread ID(s) to query messages from.\n */\n threadId: string | string[];\n /**\n * Optional resource ID to further filter messages within the thread(s).\n */\n resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n /**\n * Resource ID to query ALL messages for the resource across all threads.\n */\n resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When undefined, returns all workflow runs without pagination.\n * When both perPage and page are provided, pagination is applied.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * When both perPage and page are provided, pagination is applied.\n * When either is undefined, all results are returned.\n */\n page?: number;\n resourceId?: string;\n status?: WorkflowRunStatus;\n};\n\nexport type StorageListThreadsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter options for querying threads.\n */\n filter?: {\n /**\n * Filter threads by resource ID.\n */\n resourceId?: string;\n /**\n * Filter threads by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n /** ID of the thread this was cloned from */\n sourceThreadId: string;\n /** Timestamp when the clone was created */\n clonedAt: Date;\n /** ID of the last message included in the clone (if messages were copied) */\n lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n /** ID of the thread to clone */\n sourceThreadId: string;\n /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n newThreadId?: string;\n /** Resource ID for the new thread (defaults to source thread's resourceId) */\n resourceId?: string;\n /** Title for the new cloned thread */\n title?: string;\n /** Additional metadata to merge with clone metadata */\n metadata?: Record<string, unknown>;\n /** Options for filtering which messages to include */\n options?: {\n /** Maximum number of messages to copy (from most recent) */\n messageLimit?: number;\n /** Filter messages by date range or specific IDs */\n messageFilter?: {\n /** Only include messages created on or after this date */\n startDate?: Date;\n /** Only include messages created on or before this date */\n endDate?: Date;\n /** Only include messages with these specific IDs */\n messageIds?: string[];\n };\n };\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n /** The newly created cloned thread */\n thread: StorageThreadType;\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n id: string;\n thread_id: string;\n content: string;\n role: string;\n type: string;\n createdAt: Date;\n resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n orderBy?: ThreadOrderBy;\n sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Per-tool configuration stored in agent snapshots.\n * Allows overriding the tool description for this specific agent.\n */\nexport interface StorageToolConfig {\n /** Custom description override for this tool in this agent context */\n description?: string;\n}\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n /** Sampling configuration for this scorer */\n sampling?: ScoringSamplingConfig;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider: string;\n /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n name: string;\n /** Temperature for generation */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Frequency penalty */\n frequencyPenalty?: number;\n /** Presence penalty */\n presencePenalty?: number;\n /** Maximum completion tokens */\n maxCompletionTokens?: number;\n /** Additional provider-specific options */\n [key: string]: unknown;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n AgentExecutionOptionsBase<any>,\n // Callback functions\n | 'onStepFinish'\n | 'onFinish'\n | 'onChunk'\n | 'onError'\n | 'onAbort'\n | 'prepareStep'\n // Runtime objects\n | 'abortSignal'\n | 'requestContext'\n | 'tracingContext'\n // Functions and processor instances\n | 'inputProcessors'\n | 'outputProcessors'\n | 'clientTools'\n | 'scorers'\n | 'toolsets'\n // Complex types\n | 'context' // ModelMessage includes complex content types (images, files)\n | 'memory' // AgentMemoryOption might contain runtime memory instances\n | 'instructions' // SystemMessage can be arrays or complex message objects\n | 'system' // SystemMessage can be arrays or complex message objects\n | 'stopWhen' // StopCondition is a complex union type from AI SDK\n | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n>;\n\n/**\n * A conditional variant: a value paired with an optional RuleGroup.\n * When rules are present, the value is only used if rules evaluate to true against the request context.\n * When rules are absent, the variant acts as the default/fallback.\n */\nexport interface StorageConditionalVariant<T> {\n value: T;\n rules?: RuleGroup;\n}\n\n/**\n * A field that can be either a static value or an array of conditional variants.\n * When an array of variants, all matching variants accumulate:\n * arrays are concatenated and objects are shallow-merged.\n * A variant with no rules always matches (acts as the default/base).\n */\nexport type StorageConditionalField<T> = T | StorageConditionalVariant<T>[];\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n /** Display name of the agent */\n name: string;\n /** Purpose description */\n description?: string;\n /** System instructions/prompt — plain string for backward compatibility, or array of instruction blocks */\n instructions: string | AgentInstructionBlock[];\n /** Model configuration (provider, name, etc.) — static or conditional on request context */\n model: StorageConditionalField<StorageModelConfig>;\n /** Tool keys with optional per-tool config — static or conditional on request context */\n tools?: StorageConditionalField<Record<string, StorageToolConfig>>;\n /** Default options for generate/stream calls — static or conditional on request context */\n defaultOptions?: StorageConditionalField<StorageDefaultOptions>;\n /** Array of workflow keys to resolve from Mastra's workflow registry — static or conditional on request context */\n workflows?: StorageConditionalField<string[]>;\n /** Array of agent keys to resolve from Mastra's agent registry — static or conditional on request context */\n agents?: StorageConditionalField<string[]>;\n /**\n * Array of specific integration tool IDs selected for this agent.\n * Format: \"provider_toolkitSlug_toolSlug\" (e.g., \"composio_hackernews_HACKERNEWS_GET_FRONTPAGE\")\n */\n integrationTools?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry — static or conditional on request context */\n inputProcessors?: StorageConditionalField<string[]>;\n /** Array of processor keys to resolve from Mastra's processor registry — static or conditional on request context */\n outputProcessors?: StorageConditionalField<string[]>;\n /** Memory configuration object — static or conditional on request context */\n memory?: StorageConditionalField<SerializedMemoryConfig>;\n /** Scorer keys with optional sampling config — static or conditional on request context */\n scorers?: StorageConditionalField<Record<string, StorageScorerConfig>>;\n /** JSON Schema for validating request context values. Stored as JSON Schema since Zod is not serializable. */\n requestContextSchema?: Record<string, unknown>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\nexport interface StorageAgentType {\n /** Unique, immutable identifier */\n id: string;\n /** Agent status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType & StorageAgentSnapshotType;\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n /** Unique identifier for the agent */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n *\n * Memory can be set to `null` to explicitly disable/remove memory from the agent.\n */\nexport type StorageUpdateAgentInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Agent status: 'draft' or 'published' */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<Omit<StorageAgentSnapshotType, 'memory'>> & {\n /** Memory configuration object (static or conditional), or null to disable memory */\n memory?: StorageConditionalField<SerializedMemoryConfig> | null;\n };\n\nexport type StorageListAgentsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter agents by author identifier (indexed for fast lookups).\n * Only agents with matching authorId will be returned.\n */\n authorId?: string;\n /**\n * Filter agents by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n agents: StorageResolvedAgentType[];\n};\n\n// ============================================\n// Prompt Block Storage Types\n// ============================================\n\n/** Instruction block discriminated union, stored in agent snapshots */\nexport type AgentInstructionBlock =\n | { type: 'text'; content: string }\n | { type: 'prompt_block_ref'; id: string }\n | { type: 'prompt_block'; content: string; rules?: RuleGroup };\n\n/** Condition operators for rule evaluation */\nexport type ConditionOperator =\n | 'equals'\n | 'not_equals'\n | 'contains'\n | 'not_contains'\n | 'greater_than'\n | 'less_than'\n | 'greater_than_or_equal'\n | 'less_than_or_equal'\n | 'in'\n | 'not_in'\n | 'exists'\n | 'not_exists';\n\n/** Leaf rule: evaluates a single condition against a context field */\nexport interface Rule {\n field: string;\n operator: ConditionOperator;\n value?: unknown;\n}\n\n/**\n * Rule group with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost groups (depth 2) may only contain leaf Rules.\n * Mid-level groups (depth 1) may contain Rules or depth-2 groups.\n * Top-level groups (depth 0, exported as `RuleGroup`) may contain Rules or depth-1 groups.\n */\nexport interface RuleGroupDepth2 {\n operator: 'AND' | 'OR';\n conditions: Rule[];\n}\n\nexport interface RuleGroupDepth1 {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth2)[];\n}\n\nexport interface RuleGroup {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth1)[];\n}\n\n/**\n * Thin prompt block record (metadata only).\n * All configuration lives in version snapshots (StoragePromptBlockSnapshotType).\n */\nexport interface StoragePromptBlockType {\n /** Unique identifier */\n id: string;\n /** Block status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Prompt block version snapshot containing the content fields.\n * These fields live exclusively in version snapshot rows.\n */\nexport interface StoragePromptBlockSnapshotType {\n /** Display name of the prompt block */\n name: string;\n /** Purpose description */\n description?: string;\n /** Template content with {{variable}} interpolation */\n content: string;\n /** Rules for conditional inclusion */\n rules?: RuleGroup;\n}\n\n/** Resolved prompt block: thin record merged with active version snapshot */\nexport type StorageResolvedPromptBlockType = StoragePromptBlockType & StoragePromptBlockSnapshotType;\n\n/** Input for creating a new prompt block */\nexport type StorageCreatePromptBlockInput = {\n /** Unique identifier for the prompt block */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n} & StoragePromptBlockSnapshotType;\n\n/** Input for updating a prompt block */\nexport type StorageUpdatePromptBlockInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Block status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StoragePromptBlockSnapshotType>;\n\nexport type StorageListPromptBlocksInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter prompt blocks by author identifier.\n */\n authorId?: string;\n /**\n * Filter prompt blocks by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin prompt block records */\nexport type StorageListPromptBlocksOutput = PaginationInfo & {\n promptBlocks: StoragePromptBlockType[];\n};\n\n/** Paginated list output for resolved prompt blocks */\nexport type StorageListPromptBlocksResolvedOutput = PaginationInfo & {\n promptBlocks: StorageResolvedPromptBlockType[];\n};\n\n// ============================================\n// Stored Scorer Types\n// ============================================\n\n/**\n * Scorer type discriminator.\n * - 'llm-judge': Custom LLM-as-judge scorer with user-provided instructions\n * - Preset types: Built-in scorers from @mastra/evals (e.g., 'bias', 'toxicity', 'faithfulness')\n */\nexport type StoredScorerType =\n | 'llm-judge'\n | 'answer-relevancy'\n | 'answer-similarity'\n | 'bias'\n | 'context-precision'\n | 'context-relevance'\n | 'faithfulness'\n | 'hallucination'\n | 'noise-sensitivity'\n | 'prompt-alignment'\n | 'tool-call-accuracy'\n | 'toxicity';\n\n/**\n * Stored scorer version snapshot containing ALL scorer configuration fields.\n * These fields live exclusively in version snapshot rows, not on the scorer record.\n */\nexport interface StorageScorerDefinitionSnapshotType {\n /** Display name of the scorer */\n name: string;\n /** Purpose description */\n description?: string;\n /** Scorer type — determines how the scorer is instantiated at runtime */\n type: StoredScorerType;\n /** Model configuration — used for LLM judge; for presets, overrides the default model */\n model?: StorageModelConfig;\n /** System instructions for the judge LLM (used when type === 'llm-judge') */\n instructions?: string;\n /** Score range configuration (used when type === 'llm-judge') */\n scoreRange?: {\n /** Minimum score value (default: 0) */\n min?: number;\n /** Maximum score value (default: 1) */\n max?: number;\n };\n /** Serializable config options for preset scorers (e.g., { scale: 10, context: [...] }) */\n presetConfig?: Record<string, unknown>;\n /** Default sampling configuration */\n defaultSampling?: ScoringSamplingConfig;\n}\n\n/**\n * Thin stored scorer record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageScorerDefinitionSnapshotType).\n */\nexport interface StorageScorerDefinitionType {\n /** Unique, immutable identifier */\n id: string;\n /** Scorer status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved stored scorer type that combines the thin record with version snapshot config.\n * Returned by getScorerDefinitionByIdResolved and listScorerDefinitionsResolved.\n */\nexport type StorageResolvedScorerDefinitionType = StorageScorerDefinitionType & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for creating a new stored scorer. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateScorerDefinitionInput = {\n /** Unique identifier for the scorer */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n} & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for updating a stored scorer. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateScorerDefinitionInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Scorer status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageScorerDefinitionSnapshotType>;\n\nexport type StorageListScorerDefinitionsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter scorers by author identifier.\n */\n authorId?: string;\n /**\n * Filter scorers by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin stored scorer records */\nexport type StorageListScorerDefinitionsOutput = PaginationInfo & {\n scorerDefinitions: StorageScorerDefinitionType[];\n};\n\n/** Paginated list output for resolved stored scorers */\nexport type StorageListScorerDefinitionsResolvedOutput = PaginationInfo & {\n scorerDefinitions: StorageResolvedScorerDefinitionType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n name: string;\n table: string;\n columns: string[];\n unique?: boolean;\n concurrent?: boolean;\n /**\n * SQL WHERE clause for creating partial indexes.\n * @internal Reserved for internal use only. Callers must pre-validate this value.\n * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n * is concatenated directly into the SQL. Any user-facing usage must validate input.\n */\n where?: string;\n method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n opclass?: string; // Operator class for GIN/GIST indexes\n storage?: Record<string, any>; // Storage parameters\n tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n name: string;\n table: string;\n columns: string[];\n unique: boolean;\n size: string;\n definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n scans: number; // Number of index scans\n tuples_read: number; // Number of tuples read\n tuples_fetched: number; // Number of tuples fetched\n last_used?: Date; // Last time index was used\n method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * A chunk of buffered observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\nexport interface BufferedObservationChunk {\n /** Unique identifier for this chunk */\n id: string;\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were last observed */\n lastObservedAt: Date;\n /** When this chunk was created */\n createdAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n}\n\n/**\n * Input for creating a new buffered observation chunk.\n */\nexport interface BufferedObservationChunkInput {\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were observed */\n lastObservedAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n}\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\nexport interface ObservationalMemoryRecord {\n // Identity\n /** Unique record ID */\n id: string;\n /** Memory scope - thread or resource */\n scope: ObservationalMemoryScope;\n /** Thread ID (null for resource scope) */\n threadId: string | null;\n /** Resource ID (always present) */\n resourceId: string;\n\n // Timestamps (top-level for easy querying)\n /** When this record was created */\n createdAt: Date;\n /** When this record was last updated */\n updatedAt: Date;\n /**\n * Single cursor for message loading - when we last observed ANY thread for this resource.\n * Undefined means no observations have been made yet (all messages are \"unobserved\").\n */\n lastObservedAt?: Date;\n\n // Generation tracking\n /** How this record was created */\n originType: ObservationalMemoryOriginType;\n /** Generation counter - incremented each time a reflection creates a new record */\n generationCount: number;\n\n // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n * For thread scope: Plain observation text.\n */\n activeObservations: string;\n /**\n * Array of buffered observation chunks waiting to be activated.\n * Each chunk represents observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\n bufferedObservationChunks?: BufferedObservationChunk[];\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Observations waiting to be activated (async buffering)\n */\n bufferedObservations?: string;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Token count of buffered observations\n */\n bufferedObservationTokens?: number;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Message IDs being processed in async buffering\n */\n bufferedMessageIds?: string[];\n /** Reflection waiting to be swapped in (async buffering) */\n bufferedReflection?: string;\n /** Token count of buffered reflection (post-compression output) */\n bufferedReflectionTokens?: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n bufferedReflectionInputTokens?: number;\n /**\n * The number of lines in activeObservations that were reflected on\n * when the buffered reflection was created. Used at activation time\n * to separate reflected vs unreflected observations.\n */\n reflectedObservationLineCount?: number;\n\n /**\n * Message IDs observed in the current generation.\n * Used as a safeguard against re-observation if timestamp filtering fails.\n * Reset on reflection (new generation starts fresh).\n */\n observedMessageIds?: string[];\n\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Stored for debugging and auditing observation dates.\n * Example: \"America/Los_Angeles\", \"Europe/London\"\n */\n observedTimezone?: string;\n\n // Token tracking\n /** Running total of all tokens observed */\n totalTokensObserved: number;\n /** Current size of active observations */\n observationTokenCount: number;\n /** Accumulated tokens from pending (unobserved) messages across sessions */\n pendingMessageTokens: number;\n\n // State flags\n /** Is a reflection currently in progress? */\n isReflecting: boolean;\n /** Is observation currently in progress? */\n isObserving: boolean;\n /** Is async observation buffering currently in progress? */\n isBufferingObservation: boolean;\n /** Is async reflection buffering currently in progress? */\n isBufferingReflection: boolean;\n /**\n * The pending message token count at which the last async observation buffer was triggered.\n * Used to determine when the next bufferTokens interval is crossed.\n * Persisted so new instances (created per request) can pick up where the last left off.\n */\n lastBufferedAtTokens: number;\n /**\n * Timestamp cursor for buffered messages.\n * Set to the max message timestamp (+1ms) of the last successfully buffered chunk.\n * Used to filter out already-buffered messages when starting the next buffer.\n * Reset on activation.\n */\n lastBufferedAtTime: Date | null;\n\n // Configuration\n /** Current configuration (stored as JSON) */\n config: Record<string, unknown>;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n threadId: string | null;\n resourceId: string;\n scope: ObservationalMemoryScope;\n config: Record<string, unknown>;\n /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n id: string;\n observations: string;\n tokenCount: number;\n /** Timestamp when these observations were created (for cursor-based message loading) */\n lastObservedAt: Date;\n /**\n * IDs of messages that were observed in this cycle.\n * Stored in record metadata as a safeguard against re-observation on process restart.\n * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n */\n observedMessageIds?: string[];\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating buffered observations.\n * Used when async buffering is enabled via `bufferTokens` config.\n * Adds a new chunk to the bufferedObservationChunks array.\n */\nexport interface UpdateBufferedObservationsInput {\n id: string;\n /** The observation chunk to add to the buffer */\n chunk: BufferedObservationChunkInput;\n /** Timestamp cursor for the last buffered message boundary. Set to max message timestamp + 1ms. */\n lastBufferedAtTime?: Date;\n}\n\n/**\n * Input for swapping buffered observations to active.\n * Supports partial activation via `activationRatio`.\n */\nexport interface SwapBufferedToActiveInput {\n id: string;\n /**\n * Ratio controlling how much context to retain after activation (0-1 float).\n * `1 - activationRatio` is the fraction of the threshold to keep as raw messages.\n * Target tokens to remove = `currentPendingTokens - messageTokensThreshold * (1 - activationRatio)`.\n * Chunks are selected by boundary, biased under the target.\n */\n activationRatio: number;\n /**\n * The message token threshold (e.g., observation.messageTokens config value).\n * Used with `activationRatio` to compute the retention floor.\n */\n messageTokensThreshold: number;\n /**\n * Current total pending message tokens in the context window.\n * Used to compute how many tokens need to be removed to reach the retention floor.\n */\n currentPendingTokens: number;\n /**\n * Optional timestamp to use as lastObservedAt after swap.\n * If not provided, the adapter will use the lastObservedAt from the latest activated chunk.\n */\n lastObservedAt?: Date;\n}\n\n/**\n * Result from swapping buffered observations to active.\n * Contains info about what was activated for UI feedback.\n */\nexport interface SwapBufferedToActiveResult {\n /** Number of chunks that were activated */\n chunksActivated: number;\n /** Total message tokens from activated chunks (context cleared) */\n messageTokensActivated: number;\n /** Total observation tokens from activated chunks */\n observationTokensActivated: number;\n /** Total messages from activated chunks */\n messagesActivated: number;\n /** CycleIds of the activated chunks (for linking UI markers) */\n activatedCycleIds: string[];\n /** All message IDs from activated chunks (for removing from context) */\n activatedMessageIds: string[];\n /** Concatenated observations from activated chunks (for UI display) */\n observations?: string;\n /** Per-chunk breakdown for individual UI markers */\n perChunk?: Array<{\n cycleId: string;\n messageTokens: number;\n observationTokens: number;\n messageCount: number;\n observations: string;\n }>;\n}\n\n/**\n * Input for updating buffered reflection.\n * Used when async reflection buffering is enabled via `bufferTokens` config.\n */\nexport interface UpdateBufferedReflectionInput {\n id: string;\n reflection: string;\n /** Token count of the buffered reflection (post-compression output) */\n tokenCount: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n inputTokenCount: number;\n /**\n * The number of lines in activeObservations at the time of reflection.\n * Used at activation time to know which observations were already reflected on.\n */\n reflectedObservationLineCount: number;\n}\n\n/**\n * Input for swapping buffered reflection to active (creates new generation).\n * Uses the stored `reflectedObservationLineCount` to determine which observations\n * were already reflected on, replaces those with the buffered reflection,\n * and appends any unreflected observations that were added after the reflection started.\n */\nexport interface SwapBufferedReflectionToActiveInput {\n currentRecord: ObservationalMemoryRecord;\n /**\n * Token count for the combined new activeObservations (bufferedReflection + unreflected).\n * Computed by the processor using its token counter before calling the adapter.\n */\n tokenCount: number;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\n}\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult<any, any, any, any>;\n error?: SerializedError;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n while (true) {\n const typeName = getZodTypeName(current);\n if (!typeName) break;\n\n if (typeName === 'ZodNullable' || typeName === 'ZodOptional') {\n nullable = true;\n }\n\n const inner = getZodInnerType(current, typeName);\n if (!inner) break;\n current = inner;\n }\n\n return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks, Zod 4 uses _zod.def.checks.\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n const schemaAny = schema as any;\n // Zod 4 structure\n if (schemaAny._zod?.def?.checks) {\n return schemaAny._zod.def.checks;\n }\n // Zod 3 structure\n if (schemaAny._def?.checks) {\n return schemaAny._def.checks;\n }\n return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n const typeName = getZodTypeName(schema);\n\n if (typeName === 'ZodString') {\n // Check for UUID validation\n const checks = getZodChecks(schema);\n if (checks.some(c => c.kind === 'uuid')) {\n return 'uuid';\n }\n return 'text';\n }\n if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n return 'text';\n }\n if (typeName === 'ZodNumber') {\n // Check for integer validation\n const checks = getZodChecks(schema);\n return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n }\n if (typeName === 'ZodBigInt') {\n return 'bigint';\n }\n if (typeName === 'ZodDate') {\n return 'timestamp';\n }\n if (typeName === 'ZodBoolean') {\n return 'boolean';\n }\n // fall back for objects/records/unknown\n return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n const shape = zObject.shape;\n const result: Record<string, StorageColumn> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n result[key] = {\n type: zodToStorageType(base),\n nullable,\n };\n }\n\n return result as Record<keyof Shape & string, StorageColumn>;\n}\n","import { spanRecordSchema } from './domains/observability/types';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\nexport const TABLE_PROMPT_BLOCKS = 'mastra_prompt_blocks';\nexport const TABLE_PROMPT_BLOCK_VERSIONS = 'mastra_prompt_block_versions';\nexport const TABLE_SCORER_DEFINITIONS = 'mastra_scorer_definitions';\nexport const TABLE_SCORER_DEFINITION_VERSIONS = 'mastra_scorer_definition_versions';\n\nexport type TABLE_NAMES =\n | typeof TABLE_WORKFLOW_SNAPSHOT\n | typeof TABLE_MESSAGES\n | typeof TABLE_THREADS\n | typeof TABLE_TRACES\n | typeof TABLE_RESOURCES\n | typeof TABLE_SCORERS\n | typeof TABLE_SPANS\n | typeof TABLE_AGENTS\n | typeof TABLE_AGENT_VERSIONS\n | typeof TABLE_PROMPT_BLOCKS\n | typeof TABLE_PROMPT_BLOCK_VERSIONS\n | typeof TABLE_SCORER_DEFINITIONS\n | typeof TABLE_SCORER_DEFINITION_VERSIONS;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerId: { type: 'text' },\n traceId: { type: 'text', nullable: true },\n spanId: { type: 'text', nullable: true },\n runId: { type: 'text' },\n scorer: { type: 'jsonb' },\n preprocessStepResult: { type: 'jsonb', nullable: true },\n extractStepResult: { type: 'jsonb', nullable: true },\n analyzeStepResult: { type: 'jsonb', nullable: true },\n score: { type: 'float' },\n reason: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n preprocessPrompt: { type: 'text', nullable: true },\n extractPrompt: { type: 'text', nullable: true },\n generateScorePrompt: { type: 'text', nullable: true },\n generateReasonPrompt: { type: 'text', nullable: true },\n analyzePrompt: { type: 'text', nullable: true },\n\n // Deprecated\n reasonPrompt: { type: 'text', nullable: true },\n input: { type: 'jsonb' },\n output: { type: 'jsonb' }, // MESSAGE OUTPUT\n additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n /**\n * Things you can evaluate\n */\n entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entityId: { type: 'text', nullable: true },\n source: { type: 'text' },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp' },\n updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n // Composite primary key of traceId and spanId\n traceId: { type: 'text', nullable: false },\n spanId: { type: 'text', nullable: false },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n attributes: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n input: { type: 'jsonb', nullable: true },\n output: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false }, // When the span started\n endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft' or 'published'\n activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n agentId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n // Agent config fields\n name: { type: 'text', nullable: false }, // Agent display name\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: false },\n model: { type: 'jsonb', nullable: false },\n tools: { type: 'jsonb', nullable: true },\n defaultOptions: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n integrationTools: { type: 'jsonb', nullable: true },\n inputProcessors: { type: 'jsonb', nullable: true },\n outputProcessors: { type: 'jsonb', nullable: true },\n memory: { type: 'jsonb', nullable: true },\n scorers: { type: 'jsonb', nullable: true },\n // Version metadata\n changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCKS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to prompt_block_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCK_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n blockId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n content: { type: 'text', nullable: false },\n rules: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to scorer_definition_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITION_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerDefinitionId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n type: { type: 'text', nullable: false }, // 'llm-judge', 'bias', 'toxicity', etc.\n model: { type: 'jsonb', nullable: true },\n instructions: { type: 'text', nullable: true },\n scoreRange: { type: 'jsonb', nullable: true },\n presetConfig: { type: 'jsonb', nullable: true },\n defaultSampling: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n config: { type: 'text', nullable: false }, // JSON object\n generationCount: { type: 'integer', nullable: false },\n lastObservedAt: { type: 'timestamp', nullable: true },\n lastReflectionAt: { type: 'timestamp', nullable: true },\n pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n isObserving: { type: 'boolean', nullable: false },\n isReflecting: { type: 'boolean', nullable: false },\n observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n // Async buffering columns\n bufferedObservations: { type: 'text', nullable: true }, // JSON string of buffered observation content\n bufferedObservationTokens: { type: 'integer', nullable: true }, // Token count of buffered observations\n bufferedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs in the buffer\n bufferedReflection: { type: 'text', nullable: true }, // JSON string of buffered reflection content\n bufferedReflectionTokens: { type: 'integer', nullable: true }, // Token count of buffered reflection (post-compression)\n bufferedReflectionInputTokens: { type: 'integer', nullable: true }, // Token count of observations fed to reflector (pre-compression)\n reflectedObservationLineCount: { type: 'integer', nullable: true }, // Number of observation lines that were reflected on during async buffering\n bufferedObservationChunks: { type: 'jsonb', nullable: true }, // JSON array of BufferedObservationChunk objects\n isBufferingObservation: { type: 'boolean', nullable: false },\n isBufferingReflection: { type: 'boolean', nullable: false },\n lastBufferedAtTokens: { type: 'integer', nullable: false },\n lastBufferedAtTime: { type: 'timestamp', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n [TABLE_WORKFLOW_SNAPSHOT]: {\n workflow_name: {\n type: 'text',\n },\n run_id: {\n type: 'text',\n },\n resourceId: { type: 'text', nullable: true },\n snapshot: {\n type: 'jsonb',\n },\n createdAt: {\n type: 'timestamp',\n },\n updatedAt: {\n type: 'timestamp',\n },\n },\n [TABLE_SCORERS]: SCORERS_SCHEMA,\n [TABLE_THREADS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n resourceId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_MESSAGES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n thread_id: { type: 'text', nullable: false },\n content: { type: 'text', nullable: false },\n role: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n resourceId: { type: 'text', nullable: true },\n },\n [TABLE_SPANS]: SPAN_SCHEMA,\n [TABLE_TRACES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n traceId: { type: 'text', nullable: false },\n scope: { type: 'text', nullable: false },\n kind: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n status: { type: 'jsonb', nullable: true },\n events: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n other: { type: 'text', nullable: true },\n startTime: { type: 'bigint', nullable: false },\n endTime: { type: 'bigint', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_RESOURCES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n workingMemory: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_AGENTS]: AGENTS_SCHEMA,\n [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n [TABLE_PROMPT_BLOCKS]: PROMPT_BLOCKS_SCHEMA,\n [TABLE_PROMPT_BLOCK_VERSIONS]: PROMPT_BLOCK_VERSIONS_SCHEMA,\n [TABLE_SCORER_DEFINITIONS]: SCORER_DEFINITIONS_SCHEMA,\n [TABLE_SCORER_DEFINITION_VERSIONS]: SCORER_DEFINITION_VERSIONS_SCHEMA,\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/storage/domains/shared.ts","../src/evals/types.ts","../src/storage/domains/observability/types.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","EntityType","SpanType","TraceStatus","getZodTypeName","getZodInnerType"],"mappings":";;;;;;AAMO,IAAM,cAAA,GAAiBA,KAAA,CAAE,IAAA,EAAK,CAAE,SAAS,+BAA+B;AAExE,IAAM,cAAA,GAAiBA,KAAA,CAAE,IAAA,EAAK,CAAE,SAAS,kCAAkC;AAE3E,IAAM,YAAA,GAAe;AAAA,EAC1B,SAAA,EAAW,cAAA;AAAA,EACX,SAAA,EAAW,eAAe,QAAA;AAC5B;AAMO,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,MAAMA,KAAA,CAAE,MAAA,CAAO,MAAA,EAAO,CAAE,KAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,UAAS,CAAE,OAAA,CAAQ,CAAC,CAAA,CAAE,SAAS,0BAA0B,CAAA;AAAA,EAC9F,SAASA,KAAA,CAAE,MAAA,CAAO,QAAO,CAAE,GAAA,GAAM,GAAA,CAAI,CAAC,EAAE,GAAA,CAAI,GAAG,EAAE,QAAA,EAAS,CAAE,QAAQ,EAAE,CAAA,CAAE,SAAS,0BAA0B;AAC7G,CAAC,CAAA,CACA,SAAS,qCAAqC;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,EAAa,UAAU,KAAA,EAAM;AAAA,IAChD,SAAA,EAAW,EAAE,IAAA,EAAM,WAAA,EAAa,UAAU,KAAA;AAAM,GAClD;AAAA,EACA,CAAC,YAAY,GAAG,aAAA;AAAA,EAChB,CAAC,oBAAoB,GAAG,qBAAA;AAAA,EACxB,CAAC,mBAAmB,GAAG,oBAAA;AAAA,EACvB,CAAC,2BAA2B,GAAG,4BAAA;AAAA,EAC/B,CAAC,wBAAwB,GAAG,yBAAA;AAAA,EAC5B,CAAC,gCAAgC,GAAG;AACtC;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-C3XU7ZDC.cjs","sourcesContent":["import { z } from 'zod';\nimport { EntityType } from '../../observability';\n\n/**\n * Common DB fields\n */\nexport const createdAtField = z.date().describe('Database record creation time');\n\nexport const updatedAtField = z.date().describe('Database record last update time');\n\nexport const dbTimestamps = {\n createdAt: createdAtField,\n updatedAt: updatedAtField.nullable(),\n} as const satisfies z.ZodRawShape;\n\n/**\n * Pagination arguments for list queries (page and perPage only)\n * Uses z.coerce to handle string → number conversion from query params\n */\nexport const paginationArgsSchema = z\n .object({\n page: z.coerce.number().int().min(0).optional().default(0).describe('Zero-indexed page number'),\n perPage: z.coerce.number().int().min(1).max(100).optional().default(10).describe('Number of items per page'),\n })\n .describe('Pagination options for list queries');\n\nexport type PaginationArgs = z.input<typeof paginationArgsSchema>;\n\n/**\n * Pagination response info\n * Used across all paginated endpoints\n */\nexport const paginationInfoSchema = z.object({\n total: z.number().describe('Total number of items available'),\n page: z.number().describe('Current page'),\n perPage: z\n .union([z.number(), z.literal(false)])\n .describe('Number of items per page, or false if pagination is disabled'),\n hasMore: z.boolean().describe('True if more pages are available'),\n});\n\n/**\n * Date range for filtering by time\n * Uses z.coerce to handle ISO string → Date conversion from query params\n */\nexport const dateRangeSchema = z\n .object({\n start: z.coerce.date().optional().describe('Start of date range (inclusive by default)'),\n end: z.coerce.date().optional().describe('End of date range (inclusive by default)'),\n startExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the start date from results (uses > instead of >=)'),\n endExclusive: z\n .boolean()\n .optional()\n .describe('When true, excludes the end date from results (uses < instead of <=)'),\n })\n .describe('Date range filter for timestamps');\n\nexport type DateRange = z.infer<typeof dateRangeSchema>;\n\nexport const sortDirectionSchema = z.enum(['ASC', 'DESC']).describe(\"Sort direction: 'ASC' | 'DESC'\");\n\nexport const entityTypeField = z\n .nativeEnum(EntityType)\n .describe(`Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')`);\n\nexport const entityIdField = z.string().describe('ID of the entity (e.g., \"weatherAgent\", \"orderWorkflow\")');\n\nexport const entityNameField = z.string().describe('Name of the entity');\n\nexport const userIdField = z.string().describe('Human end-user who triggered execution');\n\nexport const organizationIdField = z.string().describe('Multi-tenant organization/account');\n\nexport const resourceIdField = z.string().describe('Broader resource context (Mastra memory compatibility)');\n\nexport const runIdField = z.string().describe('Unique execution run identifier');\n\nexport const sessionIdField = z.string().describe('Session identifier for grouping traces');\n\nexport const threadIdField = z.string().describe('Conversation thread identifier');\n\nexport const requestIdField = z.string().describe('HTTP request ID for log correlation');\n\nexport const environmentField = z.string().describe(`Environment (e.g., \"production\" | \"staging\" | \"development\")`);\n\nexport const sourceField = z.string().describe(`Source of execution (e.g., \"local\" | \"cloud\" | \"ci\")`);\n\nexport const serviceNameField = z.string().describe('Name of the service');\n","import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { TracingContext } from '../observability';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum(['AGENT', 'WORKFLOW', ...Object.values(SpanType)] as [\n string,\n string,\n ...string[],\n]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n description: z.string(),\n prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n runId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n // Note: tracingContext is not serializable, so we don't include it in the schema\n // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n runId: z.string().optional(),\n scorer: recordSchema,\n input: z.unknown(),\n output: z.unknown(),\n metadata: optionalRecordSchema,\n additionalContext: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema,\n requestContext: optionalRecordSchema,\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n // Note: tracingContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n result: optionalRecordSchema,\n score: scoringValueSchema,\n prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n runId: z.string(), // Required in this context\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultSchema>,\n 'extractStepResult'\n> & {\n extractStepResult?: TExtract;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n scoringInputWithExtractStepResultSchema.extend({\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n 'extractStepResult' | 'analyzeStepResult'\n> & {\n extractStepResult?: TExtract;\n analyzeStepResult?: TScore;\n tracingContext?: TracingContext;\n};\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> & {\n tracingContext?: TracingContext;\n};\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n id: z.string(),\n scorerId: z.string(),\n entityId: z.string(),\n\n // From ScoringInputWithExtractStepResultAndScoreAndReason\n runId: z.string(),\n input: z.unknown().optional(),\n output: z.unknown(),\n additionalContext: optionalRecordSchema,\n requestContext: optionalRecordSchema,\n extractStepResult: optionalRecordSchema,\n extractPrompt: z.string().optional(),\n score: z.number(),\n analyzeStepResult: optionalRecordSchema,\n analyzePrompt: z.string().optional(),\n reason: z.string().optional(),\n reasonPrompt: z.string().optional(),\n\n // From ScoringHookInput\n scorer: recordSchema,\n metadata: optionalRecordSchema,\n source: scoringSourceSchema,\n entity: recordSchema,\n entityType: scoringEntityTypeSchema.optional(),\n structuredOutput: z.boolean().optional(),\n traceId: z.string().optional(),\n spanId: z.string().optional(),\n resourceId: z.string().optional(),\n threadId: z.string().optional(),\n\n // Additional ScoreRowData fields\n preprocessStepResult: optionalRecordSchema,\n preprocessPrompt: z.string().optional(),\n generateScorePrompt: z.string().optional(),\n generateReasonPrompt: z.string().optional(),\n\n // Timestamps\n ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n id: true,\n createdAt: true,\n updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n name: string;\n description: string;\n extract?: ExtractionStepFn;\n analyze: AnalyzeStepFn;\n reason?: ReasonStepFn;\n metadata?: Record<string, any>;\n isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n inputMessages: MastraDBMessage[];\n rememberedMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n","import { z } from 'zod';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n dateRangeSchema,\n dbTimestamps,\n entityIdField,\n entityNameField,\n entityTypeField,\n environmentField,\n organizationIdField,\n paginationArgsSchema,\n paginationInfoSchema,\n requestIdField,\n resourceIdField,\n runIdField,\n serviceNameField,\n sessionIdField,\n sortDirectionSchema,\n sourceField,\n threadIdField,\n userIdField,\n} from '../shared';\n\n/** Strategy for how tracing data is persisted to storage */\nexport type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only';\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\n/** Zod schema for trace ID field */\nexport const traceIdField = z.string().describe('Unique trace identifier');\n\n/** Zod schema for span ID field */\nexport const spanIdField = z.string().describe('Unique span identifier within a trace');\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z.record(z.unknown()).describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst metadataField = z.record(z.unknown()).describe('User-defined metadata for custom filtering');\nconst tagsField = z.array(z.string()).describe('Labels for filtering traces (only on the root span)');\nconst scopeField = z\n .record(z.unknown())\n .describe('Arbitrary package/app version info (e.g., {\"core\": \"1.0.0\", \"memory\": \"1.0.0\", \"gitSha\": \"abcd1234\"})');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Status of a trace derived from the root span's state */\nexport enum TraceStatus {\n SUCCESS = 'success',\n ERROR = 'error',\n RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n .preprocess(v => {\n // Handle string \"true\"/\"false\" from query params correctly\n // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n if (v === 'true') return true;\n if (v === 'false') return false;\n return v;\n }, z.boolean())\n .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n // Entity identification - first-class fields for filtering (e.g., agent, workflow, tool)\n entityType: entityTypeField.nullish(),\n entityId: entityIdField.nullish(),\n entityName: entityNameField.nullish(),\n\n // Identity & tenancy - for multi-tenant applications\n userId: userIdField.nullish(),\n organizationId: organizationIdField.nullish(),\n resourceId: resourceIdField.nullish(),\n\n // Correlation IDs - for linking related operations\n runId: runIdField.nullish(),\n sessionId: sessionIdField.nullish(),\n threadId: threadIdField.nullish(),\n requestId: requestIdField.nullish(),\n\n // Deployment context - these fields only exist on the root span\n environment: environmentField.nullish(),\n source: sourceField.nullish(),\n serviceName: serviceNameField.nullish(),\n scope: scopeField.nullish(),\n\n // Filterable data - user-defined metadata and tags (tags only on root span)\n metadata: metadataField.nullish(),\n tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n traceId: traceIdField,\n spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n .object({\n // Required identifiers\n ...spanIds,\n name: spanNameField,\n spanType: spanTypeField,\n isEvent: isEventField,\n startedAt: startedAtField,\n\n // Shared fields\n parentSpanId: parentSpanIdField.nullish(),\n ...sharedFields,\n\n // Additional span-specific nullish fields\n attributes: attributesField.nullish(),\n links: linksField.nullish(),\n input: inputField.nullish(),\n output: outputField.nullish(),\n error: errorField.nullish(),\n endedAt: endedAtField.nullish(),\n\n // Database timestamps\n ...dbTimestamps,\n })\n .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer<typeof spanRecordSchema>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: SpanRecord): TraceStatus {\n if (span.error != null) return TraceStatus.ERROR;\n if (span.endedAt == null) return TraceStatus.RUNNING;\n return TraceStatus.SUCCESS;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n .extend({\n status: traceStatusField,\n })\n .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n return {\n ...span,\n status: computeTraceStatus(span),\n };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n .object({\n span: createSpanRecordSchema,\n })\n .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n .object({\n records: z.array(createSpanRecordSchema),\n })\n .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n spanId: spanIdField.min(1),\n })\n .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n .object({\n traceId: traceIdField.min(1),\n })\n .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n traceId: traceIdField,\n spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\nexport type TraceRecord = GetTraceResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n .object({\n // Date range filters\n startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n // Span type filter\n spanType: spanTypeField.optional(),\n\n // Shared fields\n ...sharedFields,\n\n // Filter-specific derived status fields\n status: traceStatusField.optional(),\n hasChildError: hasChildErrorField.optional(),\n })\n .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n .enum(['startedAt', 'endedAt'])\n .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n .object({\n field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n })\n .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n .object({\n filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n pagination: paginationArgsSchema.default({}).describe('Pagination settings'),\n orderBy: tracesOrderBySchema.default({}).describe('Ordering configuration (defaults to startedAt desc)'),\n })\n .describe('Arguments for listing traces');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n pagination: paginationInfoSchema,\n spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n .object({\n spanId: spanIdField,\n traceId: traceIdField,\n updates: updateSpanRecordSchema.partial(),\n })\n .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n .object({\n records: z.array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField,\n updates: updateSpanRecordSchema.partial(),\n }),\n ),\n })\n .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n .object({\n traceIds: z.array(traceIdField),\n })\n .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n pagination: paginationInfoSchema,\n scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n scorerName: z.string().min(1),\n targets: z\n .array(\n z.object({\n traceId: traceIdField,\n spanId: spanIdField.optional(),\n }),\n )\n .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n status: z.string(),\n message: z.string(),\n traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport { getZodInnerType, getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n page: number;\n perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n type: StorageColumnType;\n primaryKey?: boolean;\n nullable?: boolean;\n references?: {\n table: string;\n column: string;\n };\n}\nexport interface WorkflowRuns {\n runs: WorkflowRun[];\n total: number;\n}\n\nexport interface StorageWorkflowRun {\n workflow_name: string;\n run_id: string;\n resourceId?: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n}\nexport interface WorkflowRun {\n workflowName: string;\n runId: string;\n snapshot: WorkflowRunState | string;\n createdAt: Date;\n updatedAt: Date;\n resourceId?: string;\n}\n\nexport type PaginationInfo = {\n total: number;\n page: number;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When `false`, all matching records are returned in a single response.\n */\n perPage: number | false;\n hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n include?: {\n id: string;\n threadId?: string;\n withPreviousMessages?: number;\n withNextMessages?: number;\n }[];\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 40 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n filter?: {\n dateRange?: {\n start?: Date;\n end?: Date;\n /**\n * When true, excludes the start date from results (uses > instead of >=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n startExclusive?: boolean;\n /**\n * When true, excludes the end date from results (uses < instead of <=).\n * Useful for cursor-based pagination to avoid duplicates.\n * @default false\n */\n endExclusive?: boolean;\n };\n };\n orderBy?: StorageOrderBy<'createdAt'>;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n /**\n * Thread ID(s) to query messages from.\n */\n threadId: string | string[];\n /**\n * Optional resource ID to further filter messages within the thread(s).\n */\n resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n /**\n * Resource ID to query ALL messages for the resource across all threads.\n */\n resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n workflowName?: string;\n fromDate?: Date;\n toDate?: Date;\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * When undefined, returns all workflow runs without pagination.\n * When both perPage and page are provided, pagination is applied.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * When both perPage and page are provided, pagination is applied.\n * When either is undefined, all results are returned.\n */\n page?: number;\n resourceId?: string;\n status?: WorkflowRunStatus;\n};\n\nexport type StorageListThreadsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter options for querying threads.\n */\n filter?: {\n /**\n * Filter threads by resource ID.\n */\n resourceId?: string;\n /**\n * Filter threads by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n /** ID of the thread this was cloned from */\n sourceThreadId: string;\n /** Timestamp when the clone was created */\n clonedAt: Date;\n /** ID of the last message included in the clone (if messages were copied) */\n lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n /** ID of the thread to clone */\n sourceThreadId: string;\n /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n newThreadId?: string;\n /** Resource ID for the new thread (defaults to source thread's resourceId) */\n resourceId?: string;\n /** Title for the new cloned thread */\n title?: string;\n /** Additional metadata to merge with clone metadata */\n metadata?: Record<string, unknown>;\n /** Options for filtering which messages to include */\n options?: {\n /** Maximum number of messages to copy (from most recent) */\n messageLimit?: number;\n /** Filter messages by date range or specific IDs */\n messageFilter?: {\n /** Only include messages created on or after this date */\n startDate?: Date;\n /** Only include messages created on or before this date */\n endDate?: Date;\n /** Only include messages with these specific IDs */\n messageIds?: string[];\n };\n };\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n /** The newly created cloned thread */\n thread: StorageThreadType;\n /** The messages that were copied to the new thread */\n clonedMessages: MastraDBMessage[];\n};\n\nexport type StorageResourceType = {\n id: string;\n workingMemory?: string;\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n id: string;\n thread_id: string;\n content: string;\n role: string;\n type: string;\n createdAt: Date;\n resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n field?: TField;\n direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n orderBy?: ThreadOrderBy;\n sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Per-tool configuration stored in agent snapshots.\n * Allows overriding the tool description for this specific agent.\n */\nexport interface StorageToolConfig {\n /** Custom description override for this tool in this agent context */\n description?: string;\n}\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n /** Sampling configuration for this scorer */\n sampling?: ScoringSamplingConfig;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n /** Model provider (e.g., 'openai', 'anthropic') */\n provider: string;\n /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n name: string;\n /** Temperature for generation */\n temperature?: number;\n /** Top-p sampling parameter */\n topP?: number;\n /** Frequency penalty */\n frequencyPenalty?: number;\n /** Presence penalty */\n presencePenalty?: number;\n /** Maximum completion tokens */\n maxCompletionTokens?: number;\n /** Additional provider-specific options */\n [key: string]: unknown;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n AgentExecutionOptionsBase<any>,\n // Callback functions\n | 'onStepFinish'\n | 'onFinish'\n | 'onChunk'\n | 'onError'\n | 'onAbort'\n | 'prepareStep'\n // Runtime objects\n | 'abortSignal'\n | 'requestContext'\n | 'tracingContext'\n // Functions and processor instances\n | 'inputProcessors'\n | 'outputProcessors'\n | 'clientTools'\n | 'scorers'\n | 'toolsets'\n // Complex types\n | 'context' // ModelMessage includes complex content types (images, files)\n | 'memory' // AgentMemoryOption might contain runtime memory instances\n | 'instructions' // SystemMessage can be arrays or complex message objects\n | 'system' // SystemMessage can be arrays or complex message objects\n | 'stopWhen' // StopCondition is a complex union type from AI SDK\n | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n>;\n\n/**\n * A conditional variant: a value paired with an optional RuleGroup.\n * When rules are present, the value is only used if rules evaluate to true against the request context.\n * When rules are absent, the variant acts as the default/fallback.\n */\nexport interface StorageConditionalVariant<T> {\n value: T;\n rules?: RuleGroup;\n}\n\n/**\n * A field that can be either a static value or an array of conditional variants.\n * When an array of variants, all matching variants accumulate:\n * arrays are concatenated and objects are shallow-merged.\n * A variant with no rules always matches (acts as the default/base).\n */\nexport type StorageConditionalField<T> = T | StorageConditionalVariant<T>[];\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n /** Display name of the agent */\n name: string;\n /** Purpose description */\n description?: string;\n /** System instructions/prompt — plain string for backward compatibility, or array of instruction blocks */\n instructions: string | AgentInstructionBlock[];\n /** Model configuration (provider, name, etc.) — static or conditional on request context */\n model: StorageConditionalField<StorageModelConfig>;\n /** Tool keys with optional per-tool config — static or conditional on request context */\n tools?: StorageConditionalField<Record<string, StorageToolConfig>>;\n /** Default options for generate/stream calls — static or conditional on request context */\n defaultOptions?: StorageConditionalField<StorageDefaultOptions>;\n /** Array of workflow keys to resolve from Mastra's workflow registry — static or conditional on request context */\n workflows?: StorageConditionalField<string[]>;\n /** Array of agent keys to resolve from Mastra's agent registry — static or conditional on request context */\n agents?: StorageConditionalField<string[]>;\n /**\n * Array of specific integration tool IDs selected for this agent.\n * Format: \"provider_toolkitSlug_toolSlug\" (e.g., \"composio_hackernews_HACKERNEWS_GET_FRONTPAGE\")\n */\n integrationTools?: string[];\n /** Array of processor keys to resolve from Mastra's processor registry — static or conditional on request context */\n inputProcessors?: StorageConditionalField<string[]>;\n /** Array of processor keys to resolve from Mastra's processor registry — static or conditional on request context */\n outputProcessors?: StorageConditionalField<string[]>;\n /** Memory configuration object — static or conditional on request context */\n memory?: StorageConditionalField<SerializedMemoryConfig>;\n /** Scorer keys with optional sampling config — static or conditional on request context */\n scorers?: StorageConditionalField<Record<string, StorageScorerConfig>>;\n /** JSON Schema for validating request context values. Stored as JSON Schema since Zod is not serializable. */\n requestContextSchema?: Record<string, unknown>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\nexport interface StorageAgentType {\n /** Unique, immutable identifier */\n id: string;\n /** Agent status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType & StorageAgentSnapshotType;\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n /** Unique identifier for the agent */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n *\n * Memory can be set to `null` to explicitly disable/remove memory from the agent.\n */\nexport type StorageUpdateAgentInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the agent */\n metadata?: Record<string, unknown>;\n /** FK to agent_versions.id - the currently active version */\n activeVersionId?: string;\n /** Agent status: 'draft' or 'published' */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<Omit<StorageAgentSnapshotType, 'memory'>> & {\n /** Memory configuration object (static or conditional), or null to disable memory */\n memory?: StorageConditionalField<SerializedMemoryConfig> | null;\n };\n\nexport type StorageListAgentsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter agents by author identifier (indexed for fast lookups).\n * Only agents with matching authorId will be returned.\n */\n authorId?: string;\n /**\n * Filter agents by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n agents: StorageResolvedAgentType[];\n};\n\n// ============================================\n// Prompt Block Storage Types\n// ============================================\n\n/** Instruction block discriminated union, stored in agent snapshots */\nexport type AgentInstructionBlock =\n | { type: 'text'; content: string }\n | { type: 'prompt_block_ref'; id: string }\n | { type: 'prompt_block'; content: string; rules?: RuleGroup };\n\n/** Condition operators for rule evaluation */\nexport type ConditionOperator =\n | 'equals'\n | 'not_equals'\n | 'contains'\n | 'not_contains'\n | 'greater_than'\n | 'less_than'\n | 'greater_than_or_equal'\n | 'less_than_or_equal'\n | 'in'\n | 'not_in'\n | 'exists'\n | 'not_exists';\n\n/** Leaf rule: evaluates a single condition against a context field */\nexport interface Rule {\n field: string;\n operator: ConditionOperator;\n value?: unknown;\n}\n\n/**\n * Rule group with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost groups (depth 2) may only contain leaf Rules.\n * Mid-level groups (depth 1) may contain Rules or depth-2 groups.\n * Top-level groups (depth 0, exported as `RuleGroup`) may contain Rules or depth-1 groups.\n */\nexport interface RuleGroupDepth2 {\n operator: 'AND' | 'OR';\n conditions: Rule[];\n}\n\nexport interface RuleGroupDepth1 {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth2)[];\n}\n\nexport interface RuleGroup {\n operator: 'AND' | 'OR';\n conditions: (Rule | RuleGroupDepth1)[];\n}\n\n/**\n * Thin prompt block record (metadata only).\n * All configuration lives in version snapshots (StoragePromptBlockSnapshotType).\n */\nexport interface StoragePromptBlockType {\n /** Unique identifier */\n id: string;\n /** Block status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Prompt block version snapshot containing the content fields.\n * These fields live exclusively in version snapshot rows.\n */\nexport interface StoragePromptBlockSnapshotType {\n /** Display name of the prompt block */\n name: string;\n /** Purpose description */\n description?: string;\n /** Template content with {{variable}} interpolation */\n content: string;\n /** Rules for conditional inclusion */\n rules?: RuleGroup;\n}\n\n/** Resolved prompt block: thin record merged with active version snapshot */\nexport type StorageResolvedPromptBlockType = StoragePromptBlockType & StoragePromptBlockSnapshotType;\n\n/** Input for creating a new prompt block */\nexport type StorageCreatePromptBlockInput = {\n /** Unique identifier for the prompt block */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n} & StoragePromptBlockSnapshotType;\n\n/** Input for updating a prompt block */\nexport type StorageUpdatePromptBlockInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** FK to prompt_block_versions.id — the currently active version */\n activeVersionId?: string;\n /** Block status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StoragePromptBlockSnapshotType>;\n\nexport type StorageListPromptBlocksInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter prompt blocks by author identifier.\n */\n authorId?: string;\n /**\n * Filter prompt blocks by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin prompt block records */\nexport type StorageListPromptBlocksOutput = PaginationInfo & {\n promptBlocks: StoragePromptBlockType[];\n};\n\n/** Paginated list output for resolved prompt blocks */\nexport type StorageListPromptBlocksResolvedOutput = PaginationInfo & {\n promptBlocks: StorageResolvedPromptBlockType[];\n};\n\n// ============================================\n// Stored Scorer Types\n// ============================================\n\n/**\n * Scorer type discriminator.\n * - 'llm-judge': Custom LLM-as-judge scorer with user-provided instructions\n * - Preset types: Built-in scorers from @mastra/evals (e.g., 'bias', 'toxicity', 'faithfulness')\n */\nexport type StoredScorerType =\n | 'llm-judge'\n | 'answer-relevancy'\n | 'answer-similarity'\n | 'bias'\n | 'context-precision'\n | 'context-relevance'\n | 'faithfulness'\n | 'hallucination'\n | 'noise-sensitivity'\n | 'prompt-alignment'\n | 'tool-call-accuracy'\n | 'toxicity';\n\n/**\n * Stored scorer version snapshot containing ALL scorer configuration fields.\n * These fields live exclusively in version snapshot rows, not on the scorer record.\n */\nexport interface StorageScorerDefinitionSnapshotType {\n /** Display name of the scorer */\n name: string;\n /** Purpose description */\n description?: string;\n /** Scorer type — determines how the scorer is instantiated at runtime */\n type: StoredScorerType;\n /** Model configuration — used for LLM judge; for presets, overrides the default model */\n model?: StorageModelConfig;\n /** System instructions for the judge LLM (used when type === 'llm-judge') */\n instructions?: string;\n /** Score range configuration (used when type === 'llm-judge') */\n scoreRange?: {\n /** Minimum score value (default: 0) */\n min?: number;\n /** Maximum score value (default: 1) */\n max?: number;\n };\n /** Serializable config options for preset scorers (e.g., { scale: 10, context: [...] }) */\n presetConfig?: Record<string, unknown>;\n /** Default sampling configuration */\n defaultSampling?: ScoringSamplingConfig;\n}\n\n/**\n * Thin stored scorer record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageScorerDefinitionSnapshotType).\n */\nexport interface StorageScorerDefinitionType {\n /** Unique, immutable identifier */\n id: string;\n /** Scorer status: 'draft' on creation, 'published' when a version is activated */\n status: 'draft' | 'published' | 'archived';\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Resolved stored scorer type that combines the thin record with version snapshot config.\n * Returned by getScorerDefinitionByIdResolved and listScorerDefinitionsResolved.\n */\nexport type StorageResolvedScorerDefinitionType = StorageScorerDefinitionType & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for creating a new stored scorer. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateScorerDefinitionInput = {\n /** Unique identifier for the scorer */\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n} & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for updating a stored scorer. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateScorerDefinitionInput = {\n id: string;\n /** Author identifier for multi-tenant filtering */\n authorId?: string;\n /** Additional metadata for the scorer */\n metadata?: Record<string, unknown>;\n /** FK to scorer_definition_versions.id - the currently active version */\n activeVersionId?: string;\n /** Scorer status */\n status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageScorerDefinitionSnapshotType>;\n\nexport type StorageListScorerDefinitionsInput = {\n /**\n * Number of items per page, or `false` to fetch all records without pagination limit.\n * Defaults to 100 if not specified.\n */\n perPage?: number | false;\n /**\n * Zero-indexed page number for pagination.\n * Defaults to 0 if not specified.\n */\n page?: number;\n orderBy?: StorageOrderBy;\n /**\n * Filter scorers by author identifier.\n */\n authorId?: string;\n /**\n * Filter scorers by metadata key-value pairs.\n * All specified key-value pairs must match (AND logic).\n */\n metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin stored scorer records */\nexport type StorageListScorerDefinitionsOutput = PaginationInfo & {\n scorerDefinitions: StorageScorerDefinitionType[];\n};\n\n/** Paginated list output for resolved stored scorers */\nexport type StorageListScorerDefinitionsResolvedOutput = PaginationInfo & {\n scorerDefinitions: StorageResolvedScorerDefinitionType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n name: string;\n table: string;\n columns: string[];\n unique?: boolean;\n concurrent?: boolean;\n /**\n * SQL WHERE clause for creating partial indexes.\n * @internal Reserved for internal use only. Callers must pre-validate this value.\n * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n * is concatenated directly into the SQL. Any user-facing usage must validate input.\n */\n where?: string;\n method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n opclass?: string; // Operator class for GIN/GIST indexes\n storage?: Record<string, any>; // Storage parameters\n tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n name: string;\n table: string;\n columns: string[];\n unique: boolean;\n size: string;\n definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n scans: number; // Number of index scans\n tuples_read: number; // Number of tuples read\n tuples_fetched: number; // Number of tuples fetched\n last_used?: Date; // Last time index was used\n method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * A chunk of buffered observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\nexport interface BufferedObservationChunk {\n /** Unique identifier for this chunk */\n id: string;\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were last observed */\n lastObservedAt: Date;\n /** When this chunk was created */\n createdAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n}\n\n/**\n * Input for creating a new buffered observation chunk.\n */\nexport interface BufferedObservationChunkInput {\n /** Cycle ID for linking to UI buffering markers */\n cycleId: string;\n /** The observation text content */\n observations: string;\n /** Token count of this chunk's observations */\n tokenCount: number;\n /** Message IDs that were observed in this chunk */\n messageIds: string[];\n /** Token count of the messages that were observed (for activation calculation) */\n messageTokens: number;\n /** When the messages were observed */\n lastObservedAt: Date;\n /** Optional suggested continuation from the observer */\n suggestedContinuation?: string;\n /** Optional current task context */\n currentTask?: string;\n}\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\nexport interface ObservationalMemoryRecord {\n // Identity\n /** Unique record ID */\n id: string;\n /** Memory scope - thread or resource */\n scope: ObservationalMemoryScope;\n /** Thread ID (null for resource scope) */\n threadId: string | null;\n /** Resource ID (always present) */\n resourceId: string;\n\n // Timestamps (top-level for easy querying)\n /** When this record was created */\n createdAt: Date;\n /** When this record was last updated */\n updatedAt: Date;\n /**\n * Single cursor for message loading - when we last observed ANY thread for this resource.\n * Undefined means no observations have been made yet (all messages are \"unobserved\").\n */\n lastObservedAt?: Date;\n\n // Generation tracking\n /** How this record was created */\n originType: ObservationalMemoryOriginType;\n /** Generation counter - incremented each time a reflection creates a new record */\n generationCount: number;\n\n // Observation content\n /**\n * Currently active observations.\n * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n * For thread scope: Plain observation text.\n */\n activeObservations: string;\n /**\n * Array of buffered observation chunks waiting to be activated.\n * Each chunk represents observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\n bufferedObservationChunks?: BufferedObservationChunk[];\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Observations waiting to be activated (async buffering)\n */\n bufferedObservations?: string;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Token count of buffered observations\n */\n bufferedObservationTokens?: number;\n /**\n * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n * Message IDs being processed in async buffering\n */\n bufferedMessageIds?: string[];\n /** Reflection waiting to be swapped in (async buffering) */\n bufferedReflection?: string;\n /** Token count of buffered reflection (post-compression output) */\n bufferedReflectionTokens?: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n bufferedReflectionInputTokens?: number;\n /**\n * The number of lines in activeObservations that were reflected on\n * when the buffered reflection was created. Used at activation time\n * to separate reflected vs unreflected observations.\n */\n reflectedObservationLineCount?: number;\n\n /**\n * Message IDs observed in the current generation.\n * Used as a safeguard against re-observation if timestamp filtering fails.\n * Reset on reflection (new generation starts fresh).\n */\n observedMessageIds?: string[];\n\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Stored for debugging and auditing observation dates.\n * Example: \"America/Los_Angeles\", \"Europe/London\"\n */\n observedTimezone?: string;\n\n // Token tracking\n /** Running total of all tokens observed */\n totalTokensObserved: number;\n /** Current size of active observations */\n observationTokenCount: number;\n /** Accumulated tokens from pending (unobserved) messages across sessions */\n pendingMessageTokens: number;\n\n // State flags\n /** Is a reflection currently in progress? */\n isReflecting: boolean;\n /** Is observation currently in progress? */\n isObserving: boolean;\n /** Is async observation buffering currently in progress? */\n isBufferingObservation: boolean;\n /** Is async reflection buffering currently in progress? */\n isBufferingReflection: boolean;\n /**\n * The pending message token count at which the last async observation buffer was triggered.\n * Used to determine when the next bufferTokens interval is crossed.\n * Persisted so new instances (created per request) can pick up where the last left off.\n */\n lastBufferedAtTokens: number;\n /**\n * Timestamp cursor for buffered messages.\n * Set to the max message timestamp (+1ms) of the last successfully buffered chunk.\n * Used to filter out already-buffered messages when starting the next buffer.\n * Reset on activation.\n */\n lastBufferedAtTime: Date | null;\n\n // Configuration\n /** Current configuration (stored as JSON) */\n config: Record<string, unknown>;\n\n // Extensible metadata (app-specific, optional)\n /** Optional metadata for app-specific extensions */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n threadId: string | null;\n resourceId: string;\n scope: ObservationalMemoryScope;\n config: Record<string, unknown>;\n /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n id: string;\n observations: string;\n tokenCount: number;\n /** Timestamp when these observations were created (for cursor-based message loading) */\n lastObservedAt: Date;\n /**\n * IDs of messages that were observed in this cycle.\n * Stored in record metadata as a safeguard against re-observation on process restart.\n * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n */\n observedMessageIds?: string[];\n /**\n * The timezone used when formatting dates for the Observer agent.\n * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n */\n observedTimezone?: string;\n}\n\n/**\n * Input for updating buffered observations.\n * Used when async buffering is enabled via `bufferTokens` config.\n * Adds a new chunk to the bufferedObservationChunks array.\n */\nexport interface UpdateBufferedObservationsInput {\n id: string;\n /** The observation chunk to add to the buffer */\n chunk: BufferedObservationChunkInput;\n /** Timestamp cursor for the last buffered message boundary. Set to max message timestamp + 1ms. */\n lastBufferedAtTime?: Date;\n}\n\n/**\n * Input for swapping buffered observations to active.\n * Supports partial activation via `activationRatio`.\n */\nexport interface SwapBufferedToActiveInput {\n id: string;\n /**\n * Ratio controlling how much context to retain after activation (0-1 float).\n * `1 - activationRatio` is the fraction of the threshold to keep as raw messages.\n * Target tokens to remove = `currentPendingTokens - messageTokensThreshold * (1 - activationRatio)`.\n * Chunks are selected by boundary, biased under the target.\n */\n activationRatio: number;\n /**\n * The message token threshold (e.g., observation.messageTokens config value).\n * Used with `activationRatio` to compute the retention floor.\n */\n messageTokensThreshold: number;\n /**\n * Current total pending message tokens in the context window.\n * Used to compute how many tokens need to be removed to reach the retention floor.\n */\n currentPendingTokens: number;\n /**\n * Optional timestamp to use as lastObservedAt after swap.\n * If not provided, the adapter will use the lastObservedAt from the latest activated chunk.\n */\n lastObservedAt?: Date;\n}\n\n/**\n * Result from swapping buffered observations to active.\n * Contains info about what was activated for UI feedback.\n */\nexport interface SwapBufferedToActiveResult {\n /** Number of chunks that were activated */\n chunksActivated: number;\n /** Total message tokens from activated chunks (context cleared) */\n messageTokensActivated: number;\n /** Total observation tokens from activated chunks */\n observationTokensActivated: number;\n /** Total messages from activated chunks */\n messagesActivated: number;\n /** CycleIds of the activated chunks (for linking UI markers) */\n activatedCycleIds: string[];\n /** All message IDs from activated chunks (for removing from context) */\n activatedMessageIds: string[];\n /** Concatenated observations from activated chunks (for UI display) */\n observations?: string;\n /** Per-chunk breakdown for individual UI markers */\n perChunk?: Array<{\n cycleId: string;\n messageTokens: number;\n observationTokens: number;\n messageCount: number;\n observations: string;\n }>;\n}\n\n/**\n * Input for updating buffered reflection.\n * Used when async reflection buffering is enabled via `bufferTokens` config.\n */\nexport interface UpdateBufferedReflectionInput {\n id: string;\n reflection: string;\n /** Token count of the buffered reflection (post-compression output) */\n tokenCount: number;\n /** Observation tokens that were fed into the reflector (pre-compression input) */\n inputTokenCount: number;\n /**\n * The number of lines in activeObservations at the time of reflection.\n * Used at activation time to know which observations were already reflected on.\n */\n reflectedObservationLineCount: number;\n}\n\n/**\n * Input for swapping buffered reflection to active (creates new generation).\n * Uses the stored `reflectedObservationLineCount` to determine which observations\n * were already reflected on, replaces those with the buffered reflection,\n * and appends any unreflected observations that were added after the reflection started.\n */\nexport interface SwapBufferedReflectionToActiveInput {\n currentRecord: ObservationalMemoryRecord;\n /**\n * Token count for the combined new activeObservations (bufferedReflection + unreflected).\n * Computed by the processor using its token counter before calling the adapter.\n */\n tokenCount: number;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n currentRecord: ObservationalMemoryRecord;\n reflection: string;\n tokenCount: number;\n}\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n status: WorkflowRunStatus;\n result?: StepResult<any, any, any, any>;\n error?: SerializedError;\n suspendedPaths?: Record<string, number[]>;\n waitingPaths?: Record<string, number[]>;\n resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n while (true) {\n const typeName = getZodTypeName(current);\n if (!typeName) break;\n\n if (typeName === 'ZodNullable' || typeName === 'ZodOptional') {\n nullable = true;\n }\n\n const inner = getZodInnerType(current, typeName);\n if (!inner) break;\n current = inner;\n }\n\n return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks, Zod 4 uses _zod.def.checks.\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n const schemaAny = schema as any;\n // Zod 4 structure\n if (schemaAny._zod?.def?.checks) {\n return schemaAny._zod.def.checks;\n }\n // Zod 3 structure\n if (schemaAny._def?.checks) {\n return schemaAny._def.checks;\n }\n return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n const typeName = getZodTypeName(schema);\n\n if (typeName === 'ZodString') {\n // Check for UUID validation\n const checks = getZodChecks(schema);\n if (checks.some(c => c.kind === 'uuid')) {\n return 'uuid';\n }\n return 'text';\n }\n if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n return 'text';\n }\n if (typeName === 'ZodNumber') {\n // Check for integer validation\n const checks = getZodChecks(schema);\n return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n }\n if (typeName === 'ZodBigInt') {\n return 'bigint';\n }\n if (typeName === 'ZodDate') {\n return 'timestamp';\n }\n if (typeName === 'ZodBoolean') {\n return 'boolean';\n }\n // fall back for objects/records/unknown\n return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n const shape = zObject.shape;\n const result: Record<string, StorageColumn> = {};\n\n for (const [key, field] of Object.entries(shape)) {\n const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n result[key] = {\n type: zodToStorageType(base),\n nullable,\n };\n }\n\n return result as Record<keyof Shape & string, StorageColumn>;\n}\n","import { spanRecordSchema } from './domains/observability/types';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\nexport const TABLE_PROMPT_BLOCKS = 'mastra_prompt_blocks';\nexport const TABLE_PROMPT_BLOCK_VERSIONS = 'mastra_prompt_block_versions';\nexport const TABLE_SCORER_DEFINITIONS = 'mastra_scorer_definitions';\nexport const TABLE_SCORER_DEFINITION_VERSIONS = 'mastra_scorer_definition_versions';\n\nexport type TABLE_NAMES =\n | typeof TABLE_WORKFLOW_SNAPSHOT\n | typeof TABLE_MESSAGES\n | typeof TABLE_THREADS\n | typeof TABLE_TRACES\n | typeof TABLE_RESOURCES\n | typeof TABLE_SCORERS\n | typeof TABLE_SPANS\n | typeof TABLE_AGENTS\n | typeof TABLE_AGENT_VERSIONS\n | typeof TABLE_PROMPT_BLOCKS\n | typeof TABLE_PROMPT_BLOCK_VERSIONS\n | typeof TABLE_SCORER_DEFINITIONS\n | typeof TABLE_SCORER_DEFINITION_VERSIONS;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerId: { type: 'text' },\n traceId: { type: 'text', nullable: true },\n spanId: { type: 'text', nullable: true },\n runId: { type: 'text' },\n scorer: { type: 'jsonb' },\n preprocessStepResult: { type: 'jsonb', nullable: true },\n extractStepResult: { type: 'jsonb', nullable: true },\n analyzeStepResult: { type: 'jsonb', nullable: true },\n score: { type: 'float' },\n reason: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n preprocessPrompt: { type: 'text', nullable: true },\n extractPrompt: { type: 'text', nullable: true },\n generateScorePrompt: { type: 'text', nullable: true },\n generateReasonPrompt: { type: 'text', nullable: true },\n analyzePrompt: { type: 'text', nullable: true },\n\n // Deprecated\n reasonPrompt: { type: 'text', nullable: true },\n input: { type: 'jsonb' },\n output: { type: 'jsonb' }, // MESSAGE OUTPUT\n additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n /**\n * Things you can evaluate\n */\n entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n entityId: { type: 'text', nullable: true },\n source: { type: 'text' },\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp' },\n updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n // Composite primary key of traceId and spanId\n traceId: { type: 'text', nullable: false },\n spanId: { type: 'text', nullable: false },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n attributes: { type: 'jsonb', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n input: { type: 'jsonb', nullable: true },\n output: { type: 'jsonb', nullable: true },\n error: { type: 'jsonb', nullable: true },\n startedAt: { type: 'timestamp', nullable: false }, // When the span started\n endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft' or 'published'\n activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n agentId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n // Agent config fields\n name: { type: 'text', nullable: false }, // Agent display name\n description: { type: 'text', nullable: true },\n instructions: { type: 'text', nullable: false },\n model: { type: 'jsonb', nullable: false },\n tools: { type: 'jsonb', nullable: true },\n defaultOptions: { type: 'jsonb', nullable: true },\n workflows: { type: 'jsonb', nullable: true },\n agents: { type: 'jsonb', nullable: true },\n integrationTools: { type: 'jsonb', nullable: true },\n inputProcessors: { type: 'jsonb', nullable: true },\n outputProcessors: { type: 'jsonb', nullable: true },\n memory: { type: 'jsonb', nullable: true },\n scorers: { type: 'jsonb', nullable: true },\n // Version metadata\n changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCKS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to prompt_block_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCK_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n blockId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n content: { type: 'text', nullable: false },\n rules: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n activeVersionId: { type: 'text', nullable: true }, // FK to scorer_definition_versions.id\n authorId: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITION_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n scorerDefinitionId: { type: 'text', nullable: false },\n versionNumber: { type: 'integer', nullable: false },\n name: { type: 'text', nullable: false },\n description: { type: 'text', nullable: true },\n type: { type: 'text', nullable: false }, // 'llm-judge', 'bias', 'toxicity', etc.\n model: { type: 'jsonb', nullable: true },\n instructions: { type: 'text', nullable: true },\n scoreRange: { type: 'jsonb', nullable: true },\n presetConfig: { type: 'jsonb', nullable: true },\n defaultSampling: { type: 'jsonb', nullable: true },\n changedFields: { type: 'jsonb', nullable: true },\n changeMessage: { type: 'text', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n id: { type: 'text', nullable: false, primaryKey: true },\n lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n resourceId: { type: 'text', nullable: true },\n threadId: { type: 'text', nullable: true },\n activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n config: { type: 'text', nullable: false }, // JSON object\n generationCount: { type: 'integer', nullable: false },\n lastObservedAt: { type: 'timestamp', nullable: true },\n lastReflectionAt: { type: 'timestamp', nullable: true },\n pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n isObserving: { type: 'boolean', nullable: false },\n isReflecting: { type: 'boolean', nullable: false },\n observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n // Async buffering columns\n bufferedObservations: { type: 'text', nullable: true }, // JSON string of buffered observation content\n bufferedObservationTokens: { type: 'integer', nullable: true }, // Token count of buffered observations\n bufferedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs in the buffer\n bufferedReflection: { type: 'text', nullable: true }, // JSON string of buffered reflection content\n bufferedReflectionTokens: { type: 'integer', nullable: true }, // Token count of buffered reflection (post-compression)\n bufferedReflectionInputTokens: { type: 'integer', nullable: true }, // Token count of observations fed to reflector (pre-compression)\n reflectedObservationLineCount: { type: 'integer', nullable: true }, // Number of observation lines that were reflected on during async buffering\n bufferedObservationChunks: { type: 'jsonb', nullable: true }, // JSON array of BufferedObservationChunk objects\n isBufferingObservation: { type: 'boolean', nullable: false },\n isBufferingReflection: { type: 'boolean', nullable: false },\n lastBufferedAtTokens: { type: 'integer', nullable: false },\n lastBufferedAtTime: { type: 'timestamp', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n [TABLE_WORKFLOW_SNAPSHOT]: {\n workflow_name: {\n type: 'text',\n },\n run_id: {\n type: 'text',\n },\n resourceId: { type: 'text', nullable: true },\n snapshot: {\n type: 'jsonb',\n },\n createdAt: {\n type: 'timestamp',\n },\n updatedAt: {\n type: 'timestamp',\n },\n },\n [TABLE_SCORERS]: SCORERS_SCHEMA,\n [TABLE_THREADS]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n resourceId: { type: 'text', nullable: false },\n title: { type: 'text', nullable: false },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_MESSAGES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n thread_id: { type: 'text', nullable: false },\n content: { type: 'text', nullable: false },\n role: { type: 'text', nullable: false },\n type: { type: 'text', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n resourceId: { type: 'text', nullable: true },\n },\n [TABLE_SPANS]: SPAN_SCHEMA,\n [TABLE_TRACES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n parentSpanId: { type: 'text', nullable: true },\n name: { type: 'text', nullable: false },\n traceId: { type: 'text', nullable: false },\n scope: { type: 'text', nullable: false },\n kind: { type: 'integer', nullable: false },\n attributes: { type: 'jsonb', nullable: true },\n status: { type: 'jsonb', nullable: true },\n events: { type: 'jsonb', nullable: true },\n links: { type: 'jsonb', nullable: true },\n other: { type: 'text', nullable: true },\n startTime: { type: 'bigint', nullable: false },\n endTime: { type: 'bigint', nullable: false },\n createdAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_RESOURCES]: {\n id: { type: 'text', nullable: false, primaryKey: true },\n workingMemory: { type: 'text', nullable: true },\n metadata: { type: 'jsonb', nullable: true },\n createdAt: { type: 'timestamp', nullable: false },\n updatedAt: { type: 'timestamp', nullable: false },\n },\n [TABLE_AGENTS]: AGENTS_SCHEMA,\n [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n [TABLE_PROMPT_BLOCKS]: PROMPT_BLOCKS_SCHEMA,\n [TABLE_PROMPT_BLOCK_VERSIONS]: PROMPT_BLOCK_VERSIONS_SCHEMA,\n [TABLE_SCORER_DEFINITIONS]: SCORER_DEFINITIONS_SCHEMA,\n [TABLE_SCORER_DEFINITION_VERSIONS]: SCORER_DEFINITION_VERSIONS_SCHEMA,\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n"]}