@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303

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 (407) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +284 -0
  3. package/dist/acp/agent.d.ts +48 -0
  4. package/dist/acp/agent.js +414 -0
  5. package/dist/acp/errors.d.ts +3 -0
  6. package/dist/acp/errors.js +11 -0
  7. package/dist/acp/event-mapper.d.ts +28 -0
  8. package/dist/acp/event-mapper.js +274 -0
  9. package/dist/acp/index.d.ts +9 -0
  10. package/dist/acp/index.js +21 -0
  11. package/dist/acp/runtime.d.ts +5 -0
  12. package/dist/acp/runtime.js +91 -0
  13. package/dist/acp/server.d.ts +4 -0
  14. package/dist/acp/server.js +35 -0
  15. package/dist/acp/skills.d.ts +6 -0
  16. package/dist/acp/skills.js +30 -0
  17. package/dist/acp.d.ts +2 -0
  18. package/dist/acp.js +1 -0
  19. package/dist/agent-connections/messaging-processor.d.ts +17 -0
  20. package/dist/agent-connections/messaging-processor.js +131 -0
  21. package/dist/agent-connections/ownership.d.ts +24 -0
  22. package/dist/agent-connections/ownership.js +96 -0
  23. package/dist/agent-connections/registry.d.ts +20 -0
  24. package/dist/agent-connections/registry.js +167 -0
  25. package/dist/agent-connections/session-advertisement.d.ts +27 -0
  26. package/dist/agent-connections/session-advertisement.js +86 -0
  27. package/dist/agent-connections/signal-provider.d.ts +141 -0
  28. package/dist/agent-connections/signal-provider.js +35 -0
  29. package/dist/agent-connections/state-processor.d.ts +23 -0
  30. package/dist/agent-connections/state-processor.js +270 -0
  31. package/dist/agent-connections/thread-state.d.ts +41 -0
  32. package/dist/agent-connections/thread-state.js +157 -0
  33. package/dist/agent-connections/tools.d.ts +133 -0
  34. package/dist/agent-connections/tools.js +616 -0
  35. package/dist/agent-connections/types.d.ts +99 -0
  36. package/dist/agent-connections/types.js +4 -0
  37. package/dist/agent-connections/untrusted-text.d.ts +5 -0
  38. package/dist/agent-connections/untrusted-text.js +19 -0
  39. package/dist/agents/background-completion-events.d.ts +16 -0
  40. package/dist/agents/background-completion-events.js +16 -0
  41. package/dist/agents/background-completion.d.ts +22 -0
  42. package/dist/agents/background-completion.js +73 -0
  43. package/dist/agents/context-audit.d.ts +84 -0
  44. package/dist/agents/context-audit.js +115 -0
  45. package/dist/agents/credential-resolver.d.ts +74 -0
  46. package/dist/agents/credential-resolver.js +142 -0
  47. package/dist/agents/custom-provider-source.d.ts +35 -0
  48. package/dist/agents/custom-provider-source.js +22 -0
  49. package/dist/agents/fastembed-subprocess.d.ts +52 -0
  50. package/dist/agents/fastembed-subprocess.js +282 -0
  51. package/dist/agents/instructions.d.ts +42 -0
  52. package/dist/agents/instructions.js +69 -0
  53. package/dist/agents/mastracode-gateway.d.ts +85 -0
  54. package/dist/agents/mastracode-gateway.js +500 -0
  55. package/dist/agents/memory.d.ts +36 -0
  56. package/dist/agents/memory.js +248 -0
  57. package/dist/agents/model.d.ts +158 -0
  58. package/dist/agents/model.js +382 -0
  59. package/dist/agents/modes/build.d.ts +12 -0
  60. package/dist/agents/modes/build.js +33 -0
  61. package/dist/agents/modes/explore.d.ts +10 -0
  62. package/dist/agents/modes/explore.js +25 -0
  63. package/dist/agents/modes/plan.d.ts +8 -0
  64. package/dist/agents/modes/plan.js +43 -0
  65. package/dist/agents/prompts/agent-instructions.d.ts +122 -0
  66. package/dist/agents/prompts/agent-instructions.js +617 -0
  67. package/dist/agents/prompts/build.d.ts +12 -0
  68. package/dist/agents/prompts/build.js +73 -0
  69. package/dist/agents/prompts/fast.d.ts +5 -0
  70. package/dist/agents/prompts/fast.js +23 -0
  71. package/dist/agents/prompts/index.d.ts +61 -0
  72. package/dist/agents/prompts/index.js +141 -0
  73. package/dist/agents/prompts/model.d.ts +5 -0
  74. package/dist/agents/prompts/model.js +20 -0
  75. package/dist/agents/prompts/plan.d.ts +11 -0
  76. package/dist/agents/prompts/plan.js +132 -0
  77. package/dist/agents/prompts/tool-guidance.d.ts +18 -0
  78. package/dist/agents/prompts/tool-guidance.js +158 -0
  79. package/dist/agents/sandbox-filesystem.d.ts +232 -0
  80. package/dist/agents/sandbox-filesystem.js +851 -0
  81. package/dist/agents/subagents/execute.d.ts +3 -0
  82. package/dist/agents/subagents/execute.js +24 -0
  83. package/dist/agents/subagents/explore.d.ts +3 -0
  84. package/dist/agents/subagents/explore.js +15 -0
  85. package/dist/agents/subagents/index.d.ts +6 -0
  86. package/dist/agents/subagents/index.js +15 -0
  87. package/dist/agents/subagents/plan.d.ts +3 -0
  88. package/dist/agents/subagents/plan.js +15 -0
  89. package/dist/agents/thread-caveman-state.d.ts +17 -0
  90. package/dist/agents/thread-caveman-state.js +104 -0
  91. package/dist/agents/tool-availability.d.ts +17 -0
  92. package/dist/agents/tool-availability.js +134 -0
  93. package/dist/agents/tools.d.ts +37 -0
  94. package/dist/agents/tools.js +154 -0
  95. package/dist/agents/workflow-builder-agent.d.ts +2 -0
  96. package/dist/agents/workflow-builder-agent.js +79 -0
  97. package/dist/agents/workspace.d.ts +35 -0
  98. package/dist/agents/workspace.js +207 -0
  99. package/dist/analytics.d.ts +18 -0
  100. package/dist/analytics.js +159 -0
  101. package/dist/auth/account-rotation-processor.d.ts +210 -0
  102. package/dist/auth/account-rotation-processor.js +662 -0
  103. package/dist/auth/account-routing-context.d.ts +17 -0
  104. package/dist/auth/account-routing-context.js +38 -0
  105. package/dist/auth/authorization-input.d.ts +16 -0
  106. package/dist/auth/authorization-input.js +39 -0
  107. package/dist/auth/device-code.d.ts +93 -0
  108. package/dist/auth/device-code.js +126 -0
  109. package/dist/auth/index.d.ts +13 -0
  110. package/dist/auth/index.js +9 -0
  111. package/dist/auth/pkce.d.ts +13 -0
  112. package/dist/auth/pkce.js +29 -0
  113. package/dist/auth/provider-auth-error.d.ts +24 -0
  114. package/dist/auth/provider-auth-error.js +44 -0
  115. package/dist/auth/providers/anthropic.d.ts +40 -0
  116. package/dist/auth/providers/anthropic.js +117 -0
  117. package/dist/auth/providers/github-copilot.d.ts +154 -0
  118. package/dist/auth/providers/github-copilot.js +359 -0
  119. package/dist/auth/providers/kimi-coding.d.ts +38 -0
  120. package/dist/auth/providers/kimi-coding.js +225 -0
  121. package/dist/auth/providers/openai-codex.d.ts +141 -0
  122. package/dist/auth/providers/openai-codex.js +531 -0
  123. package/dist/auth/providers/xai.d.ts +64 -0
  124. package/dist/auth/providers/xai.js +223 -0
  125. package/dist/auth/storage.d.ts +222 -0
  126. package/dist/auth/storage.js +805 -0
  127. package/dist/auth/types.d.ts +164 -0
  128. package/dist/auth/types.js +1 -0
  129. package/dist/clipboard/index.d.ts +26 -0
  130. package/dist/clipboard/index.js +224 -0
  131. package/dist/constants.d.ts +29 -0
  132. package/dist/constants.js +34 -0
  133. package/dist/error-classification.d.ts +10 -0
  134. package/dist/error-classification.js +19 -0
  135. package/dist/evals/context-builder.d.ts +41 -0
  136. package/dist/evals/context-builder.js +156 -0
  137. package/dist/evals/index.d.ts +4 -0
  138. package/dist/evals/index.js +5 -0
  139. package/dist/evals/scorers/classify-command.d.ts +30 -0
  140. package/dist/evals/scorers/classify-command.js +61 -0
  141. package/dist/evals/scorers/efficiency.d.ts +44 -0
  142. package/dist/evals/scorers/efficiency.js +256 -0
  143. package/dist/evals/scorers/extract-tools.d.ts +25 -0
  144. package/dist/evals/scorers/extract-tools.js +57 -0
  145. package/dist/evals/scorers/index.d.ts +3 -0
  146. package/dist/evals/scorers/index.js +3 -0
  147. package/dist/evals/scorers/outcome.d.ts +49 -0
  148. package/dist/evals/scorers/outcome.js +360 -0
  149. package/dist/experimental-agent.d.ts +19 -0
  150. package/dist/experimental-agent.js +45 -0
  151. package/dist/factory/client.d.ts +44 -0
  152. package/dist/factory/client.js +110 -0
  153. package/dist/factory/remote-controller.d.ts +34 -0
  154. package/dist/factory/remote-controller.js +40 -0
  155. package/dist/factory/remote-session.d.ts +210 -0
  156. package/dist/factory/remote-session.js +415 -0
  157. package/dist/goal-manager.d.ts +114 -0
  158. package/dist/goal-manager.js +351 -0
  159. package/dist/goal-signal.d.ts +14 -0
  160. package/dist/goal-signal.js +14 -0
  161. package/dist/headless/cli.d.ts +55 -0
  162. package/dist/headless/cli.js +261 -0
  163. package/dist/headless/flags.d.ts +33 -0
  164. package/dist/headless/flags.js +207 -0
  165. package/dist/headless/format.d.ts +41 -0
  166. package/dist/headless/format.js +94 -0
  167. package/dist/headless/index.d.ts +25 -0
  168. package/dist/headless/index.js +6 -0
  169. package/dist/headless/policy.d.ts +17 -0
  170. package/dist/headless/policy.js +39 -0
  171. package/dist/headless/run-mc.d.ts +7 -0
  172. package/dist/headless/run-mc.js +438 -0
  173. package/dist/headless/types.d.ts +175 -0
  174. package/dist/headless/types.js +16 -0
  175. package/dist/hooks/config.d.ts +11 -0
  176. package/dist/hooks/config.js +77 -0
  177. package/dist/hooks/executor.d.ts +13 -0
  178. package/dist/hooks/executor.js +128 -0
  179. package/dist/hooks/index.d.ts +6 -0
  180. package/dist/hooks/index.js +5 -0
  181. package/dist/hooks/manager.d.ts +75 -0
  182. package/dist/hooks/manager.js +289 -0
  183. package/dist/hooks/types.d.ts +180 -0
  184. package/dist/hooks/types.js +5 -0
  185. package/dist/index.d.ts +537 -0
  186. package/dist/index.js +1399 -0
  187. package/dist/ipc/ipc-reporter.d.ts +14 -0
  188. package/dist/ipc/ipc-reporter.js +18 -0
  189. package/dist/knowledge-inspector.d.ts +139 -0
  190. package/dist/knowledge-inspector.js +533 -0
  191. package/dist/knowledge-scope-id.d.ts +7 -0
  192. package/dist/knowledge-scope-id.js +10 -0
  193. package/dist/knowledge-scope.d.ts +41 -0
  194. package/dist/knowledge-scope.js +85 -0
  195. package/dist/lsp/client.d.ts +56 -0
  196. package/dist/lsp/client.js +248 -0
  197. package/dist/lsp/index.d.ts +4 -0
  198. package/dist/lsp/index.js +4 -0
  199. package/dist/lsp/language.d.ts +9 -0
  200. package/dist/lsp/language.js +41 -0
  201. package/dist/lsp/manager.d.ts +34 -0
  202. package/dist/lsp/manager.js +79 -0
  203. package/dist/lsp/server.d.ts +27 -0
  204. package/dist/lsp/server.js +158 -0
  205. package/dist/lsp/workspace.d.ts +9 -0
  206. package/dist/lsp/workspace.js +52 -0
  207. package/dist/mcp/config.d.ts +77 -0
  208. package/dist/mcp/config.js +313 -0
  209. package/dist/mcp/index.d.ts +6 -0
  210. package/dist/mcp/index.js +3 -0
  211. package/dist/mcp/manager.d.ts +104 -0
  212. package/dist/mcp/manager.js +693 -0
  213. package/dist/mcp/state.d.ts +35 -0
  214. package/dist/mcp/state.js +94 -0
  215. package/dist/mcp/types.d.ts +139 -0
  216. package/dist/mcp/types.js +1 -0
  217. package/dist/onboarding/custom-packs.d.ts +7 -0
  218. package/dist/onboarding/custom-packs.js +17 -0
  219. package/dist/onboarding/custom-providers.d.ts +4 -0
  220. package/dist/onboarding/custom-providers.js +27 -0
  221. package/dist/onboarding/index.d.ts +5 -0
  222. package/dist/onboarding/index.js +3 -0
  223. package/dist/onboarding/om-settings.d.ts +47 -0
  224. package/dist/onboarding/om-settings.js +80 -0
  225. package/dist/onboarding/pack-activation.d.ts +43 -0
  226. package/dist/onboarding/pack-activation.js +105 -0
  227. package/dist/onboarding/packs.d.ts +106 -0
  228. package/dist/onboarding/packs.js +283 -0
  229. package/dist/onboarding/settings.d.ts +563 -0
  230. package/dist/onboarding/settings.js +1110 -0
  231. package/dist/permissions.d.ts +55 -0
  232. package/dist/permissions.js +139 -0
  233. package/dist/platform/index.d.ts +74 -0
  234. package/dist/platform/index.js +199 -0
  235. package/dist/plugin.d.ts +156 -0
  236. package/dist/plugin.js +27 -0
  237. package/dist/plugins/dependencies.d.ts +9 -0
  238. package/dist/plugins/dependencies.js +84 -0
  239. package/dist/plugins/install.d.ts +21 -0
  240. package/dist/plugins/install.js +187 -0
  241. package/dist/plugins/loader.d.ts +25 -0
  242. package/dist/plugins/loader.js +264 -0
  243. package/dist/plugins/manager.d.ts +115 -0
  244. package/dist/plugins/manager.js +507 -0
  245. package/dist/plugins/manifest.d.ts +14 -0
  246. package/dist/plugins/manifest.js +47 -0
  247. package/dist/plugins/package-link.d.ts +3 -0
  248. package/dist/plugins/package-link.js +58 -0
  249. package/dist/plugins/paths.d.ts +10 -0
  250. package/dist/plugins/paths.js +22 -0
  251. package/dist/plugins/registry.d.ts +8 -0
  252. package/dist/plugins/registry.js +109 -0
  253. package/dist/plugins/scaffold.d.ts +10 -0
  254. package/dist/plugins/scaffold.js +115 -0
  255. package/dist/plugins/signal-lane.d.ts +59 -0
  256. package/dist/plugins/signal-lane.js +163 -0
  257. package/dist/plugins/types.d.ts +95 -0
  258. package/dist/plugins/types.js +1 -0
  259. package/dist/process-memory-diagnostics.d.ts +136 -0
  260. package/dist/process-memory-diagnostics.js +497 -0
  261. package/dist/processors/plan-rejection-abort.d.ts +16 -0
  262. package/dist/processors/plan-rejection-abort.js +62 -0
  263. package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
  264. package/dist/providers/amazon-bedrock-gateway.js +142 -0
  265. package/dist/providers/amazon-bedrock.d.ts +28 -0
  266. package/dist/providers/amazon-bedrock.js +99 -0
  267. package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
  268. package/dist/providers/anthropic-prompt-cache.js +8 -0
  269. package/dist/providers/anthropic-thinking.d.ts +5 -0
  270. package/dist/providers/anthropic-thinking.js +22 -0
  271. package/dist/providers/claude-max.d.ts +67 -0
  272. package/dist/providers/claude-max.js +232 -0
  273. package/dist/providers/github-copilot-gateway.d.ts +35 -0
  274. package/dist/providers/github-copilot-gateway.js +58 -0
  275. package/dist/providers/github-copilot.d.ts +60 -0
  276. package/dist/providers/github-copilot.js +320 -0
  277. package/dist/providers/google-thinking.d.ts +31 -0
  278. package/dist/providers/google-thinking.js +64 -0
  279. package/dist/providers/google-vertex-gateway.d.ts +23 -0
  280. package/dist/providers/google-vertex-gateway.js +49 -0
  281. package/dist/providers/google-vertex.d.ts +6 -0
  282. package/dist/providers/google-vertex.js +51 -0
  283. package/dist/providers/kimi-coding.d.ts +14 -0
  284. package/dist/providers/kimi-coding.js +80 -0
  285. package/dist/providers/model-ids.d.ts +53 -0
  286. package/dist/providers/model-ids.js +132 -0
  287. package/dist/providers/openai-codex.d.ts +114 -0
  288. package/dist/providers/openai-codex.js +427 -0
  289. package/dist/providers/provider-thinking.d.ts +23 -0
  290. package/dist/providers/provider-thinking.js +61 -0
  291. package/dist/providers/thinking-request.d.ts +14 -0
  292. package/dist/providers/thinking-request.js +87 -0
  293. package/dist/providers/xai.d.ts +33 -0
  294. package/dist/providers/xai.js +72 -0
  295. package/dist/schedules/index.d.ts +10 -0
  296. package/dist/schedules/index.js +6 -0
  297. package/dist/schedules/interval.d.ts +49 -0
  298. package/dist/schedules/interval.js +212 -0
  299. package/dist/schedules/prompt.d.ts +36 -0
  300. package/dist/schedules/prompt.js +36 -0
  301. package/dist/schedules/run-script.d.ts +8 -0
  302. package/dist/schedules/run-script.js +80 -0
  303. package/dist/schedules/scheduler.d.ts +101 -0
  304. package/dist/schedules/scheduler.js +167 -0
  305. package/dist/schedules/tools.d.ts +57 -0
  306. package/dist/schedules/tools.js +217 -0
  307. package/dist/schema.d.ts +499 -0
  308. package/dist/schema.js +131 -0
  309. package/dist/theme-palette.d.ts +17 -0
  310. package/dist/theme-palette.js +18 -0
  311. package/dist/thinking-catalog.d.ts +4 -0
  312. package/dist/thinking-catalog.js +13 -0
  313. package/dist/thinking.d.ts +37 -0
  314. package/dist/thinking.js +134 -0
  315. package/dist/tool-names.d.ts +77 -0
  316. package/dist/tool-names.js +53 -0
  317. package/dist/tools/index.d.ts +6 -0
  318. package/dist/tools/index.js +3 -0
  319. package/dist/tools/request-sandbox-access.d.ts +6 -0
  320. package/dist/tools/request-sandbox-access.js +80 -0
  321. package/dist/tools/utils.d.ts +20 -0
  322. package/dist/tools/utils.js +31 -0
  323. package/dist/tools/web-search.d.ts +116 -0
  324. package/dist/tools/web-search.js +158 -0
  325. package/dist/tools/workflows/create-workflow.d.ts +7 -0
  326. package/dist/tools/workflows/create-workflow.js +82 -0
  327. package/dist/tools/workflows/delete-workflow.d.ts +7 -0
  328. package/dist/tools/workflows/delete-workflow.js +18 -0
  329. package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
  330. package/dist/tools/workflows/ephemeral-memory.js +41 -0
  331. package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
  332. package/dist/tools/workflows/extract-json-schema.js +19 -0
  333. package/dist/tools/workflows/get-workflow.d.ts +11 -0
  334. package/dist/tools/workflows/get-workflow.js +31 -0
  335. package/dist/tools/workflows/list-available-agents.d.ts +8 -0
  336. package/dist/tools/workflows/list-available-agents.js +29 -0
  337. package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
  338. package/dist/tools/workflows/list-available-classifiers.js +53 -0
  339. package/dist/tools/workflows/list-available-tools.d.ts +9 -0
  340. package/dist/tools/workflows/list-available-tools.js +37 -0
  341. package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
  342. package/dist/tools/workflows/list-available-workflows.js +29 -0
  343. package/dist/tools/workflows/list-workflows.d.ts +9 -0
  344. package/dist/tools/workflows/list-workflows.js +30 -0
  345. package/dist/tools/workflows/run-workflow.d.ts +9 -0
  346. package/dist/tools/workflows/run-workflow.js +49 -0
  347. package/dist/tools/workflows/save-workflow.d.ts +1125 -0
  348. package/dist/tools/workflows/save-workflow.js +25 -0
  349. package/dist/tools/workflows/tool-ids.d.ts +16 -0
  350. package/dist/tools/workflows/tool-ids.js +17 -0
  351. package/dist/utils/binaries.d.ts +7 -0
  352. package/dist/utils/binaries.js +97 -0
  353. package/dist/utils/debug-log.d.ts +12 -0
  354. package/dist/utils/debug-log.js +56 -0
  355. package/dist/utils/discarding-scores-storage.d.ts +33 -0
  356. package/dist/utils/discarding-scores-storage.js +51 -0
  357. package/dist/utils/errors.d.ts +36 -0
  358. package/dist/utils/errors.js +215 -0
  359. package/dist/utils/gateway-sync.d.ts +26 -0
  360. package/dist/utils/gateway-sync.js +58 -0
  361. package/dist/utils/local-observability.d.ts +19 -0
  362. package/dist/utils/local-observability.js +54 -0
  363. package/dist/utils/maintenance-lock.d.ts +42 -0
  364. package/dist/utils/maintenance-lock.js +196 -0
  365. package/dist/utils/notification-dispatch.d.ts +74 -0
  366. package/dist/utils/notification-dispatch.js +128 -0
  367. package/dist/utils/open-url.d.ts +10 -0
  368. package/dist/utils/open-url.js +27 -0
  369. package/dist/utils/path-security.d.ts +2 -0
  370. package/dist/utils/path-security.js +7 -0
  371. package/dist/utils/plan-diff.d.ts +25 -0
  372. package/dist/utils/plan-diff.js +59 -0
  373. package/dist/utils/plans.d.ts +61 -0
  374. package/dist/utils/plans.js +120 -0
  375. package/dist/utils/project.d.ts +160 -0
  376. package/dist/utils/project.js +361 -0
  377. package/dist/utils/prune-cli.d.ts +24 -0
  378. package/dist/utils/prune-cli.js +124 -0
  379. package/dist/utils/signals-pubsub.d.ts +103 -0
  380. package/dist/utils/signals-pubsub.js +409 -0
  381. package/dist/utils/slash-command-loader.d.ts +52 -0
  382. package/dist/utils/slash-command-loader.js +139 -0
  383. package/dist/utils/slash-command-processor.d.ts +14 -0
  384. package/dist/utils/slash-command-processor.js +106 -0
  385. package/dist/utils/stdin-pipe.d.ts +33 -0
  386. package/dist/utils/stdin-pipe.js +93 -0
  387. package/dist/utils/storage-factory.d.ts +50 -0
  388. package/dist/utils/storage-factory.js +118 -0
  389. package/dist/utils/storage-maintenance.d.ts +121 -0
  390. package/dist/utils/storage-maintenance.js +352 -0
  391. package/dist/utils/thread-lock.d.ts +26 -0
  392. package/dist/utils/thread-lock.js +109 -0
  393. package/dist/utils/token-estimator.d.ts +3 -0
  394. package/dist/utils/token-estimator.js +19 -0
  395. package/dist/utils/update-check.d.ts +151 -0
  396. package/dist/utils/update-check.js +430 -0
  397. package/dist/utils/wake-session.d.ts +44 -0
  398. package/dist/utils/wake-session.js +83 -0
  399. package/dist/voice/stt-registry.d.ts +67 -0
  400. package/dist/voice/stt-registry.js +144 -0
  401. package/dist/voice/transcribe.d.ts +10 -0
  402. package/dist/voice/transcribe.js +75 -0
  403. package/dist/workflows/register-primitives.d.ts +52 -0
  404. package/dist/workflows/register-primitives.js +40 -0
  405. package/dist/workflows/service.d.ts +64 -0
  406. package/dist/workflows/service.js +50 -0
  407. package/package.json +117 -0
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Metadata for a slash command
3
+ */
4
+ export interface SlashCommandMetadata {
5
+ /** Command name (e.g., "git:commit") */
6
+ name: string;
7
+ /** Human-readable description */
8
+ description: string;
9
+ /** The command template with variables */
10
+ template: string;
11
+ /** Source file path */
12
+ sourcePath: string;
13
+ /** Namespace derived from directory structure */
14
+ namespace?: string;
15
+ /** Whether this command should also be exposed as /goal/<name> */
16
+ goal?: boolean;
17
+ }
18
+ /**
19
+ * Parse a command file and extract metadata and template
20
+ * Supports both frontmatter-based and plain markdown files
21
+ */
22
+ export declare function parseCommandFile(filePath: string, baseDir?: string): Promise<SlashCommandMetadata | null>;
23
+ /**
24
+ * Extract command name from file path
25
+ * Converts path like "git/commit.md" to "git:commit"
26
+ */
27
+ export declare function extractCommandName(filePath: string, baseDir: string): string;
28
+ /**
29
+ * Recursively scan a directory for command files.
30
+ * @param dirPath - Current directory to scan
31
+ * @param rootDir - Original root commands directory (used for namespace derivation).
32
+ * When omitted the first call sets it to dirPath.
33
+ */
34
+ export interface ScanCommandDirectoryOptions {
35
+ allowedRoot?: string;
36
+ visitedDirectories?: Set<string>;
37
+ }
38
+ export declare function scanCommandDirectory(dirPath: string, rootDir?: string, options?: ScanCommandDirectoryOptions): Promise<SlashCommandMetadata[]>;
39
+ /**
40
+ * Load custom slash commands from all configured directories
41
+ * Priority: mastra project > claude project > opencode project > mastra user > claude user > opencode user
42
+ */
43
+ export declare function loadCustomCommands(projectDir?: string, configDirName?: string, extraCommandDirs?: string[]): Promise<SlashCommandMetadata[]>;
44
+ /**
45
+ * Get the commands directory path for a project
46
+ */
47
+ export declare function getProjectCommandsDir(projectDir: string, configDirName?: string): string;
48
+ /**
49
+ * Initialize a commands directory with an example command
50
+ */
51
+ export declare function initCommandsDirectory(projectDir: string, configDirName?: string): Promise<void>;
52
+ //# sourceMappingURL=slash-command-loader.d.ts.map
@@ -0,0 +1,139 @@
1
+ import { DEFAULT_CONFIG_DIR } from "../constants.js";
2
+ import { isPathWithinRoot } from "./path-security.js";
3
+ import * as path$1 from "path";
4
+ import { promises } from "fs";
5
+ import { parse } from "yaml";
6
+ // src/utils/slash-command-loader.ts
7
+ /**
8
+ * Parse a command file and extract metadata and template
9
+ * Supports both frontmatter-based and plain markdown files
10
+ */
11
+ async function parseCommandFile(filePath, baseDir) {
12
+ try {
13
+ const content = await promises.readFile(filePath, "utf-8");
14
+ if (!content.trim().startsWith("---")) return {
15
+ name: baseDir ? extractCommandName(filePath, baseDir) : path$1.basename(filePath, ".md"),
16
+ description: "",
17
+ template: content,
18
+ sourcePath: filePath
19
+ };
20
+ const parts = content.split("---");
21
+ if (parts.length < 3) return null;
22
+ const frontmatter = parts[1].trim();
23
+ const template = parts.slice(2).join("---").trim();
24
+ const metadata = parse(frontmatter);
25
+ let name;
26
+ if (typeof metadata?.name === "string" && metadata.name) name = metadata.name;
27
+ else if (baseDir) name = extractCommandName(filePath, baseDir);
28
+ else name = path$1.basename(filePath, ".md");
29
+ return {
30
+ name,
31
+ description: typeof metadata?.description === "string" ? metadata.description : "",
32
+ template,
33
+ sourcePath: filePath,
34
+ namespace: typeof metadata?.namespace === "string" ? metadata.namespace : void 0,
35
+ goal: metadata?.goal === true
36
+ };
37
+ } catch (error) {
38
+ console.error(`Error parsing command file ${filePath}:`, error);
39
+ return null;
40
+ }
41
+ }
42
+ /**
43
+ * Extract command name from file path
44
+ * Converts path like "git/commit.md" to "git:commit"
45
+ */
46
+ function extractCommandName(filePath, baseDir) {
47
+ const relativePath = path$1.relative(baseDir, filePath);
48
+ const dirName = path$1.dirname(relativePath);
49
+ const baseName = path$1.basename(relativePath, ".md");
50
+ if (dirName === "." || dirName === "") return baseName;
51
+ return `${dirName.replace(/[\\/]/g, ":")}:${baseName}`;
52
+ }
53
+ async function scanCommandDirectory(dirPath, rootDir, options = {}) {
54
+ const baseDir = rootDir ?? dirPath;
55
+ const commands = [];
56
+ const visitedDirectories = options.visitedDirectories ?? /* @__PURE__ */ new Set();
57
+ try {
58
+ const realDirectory = await promises.realpath(dirPath);
59
+ const realAllowedRoot = options.allowedRoot ? await promises.realpath(options.allowedRoot) : void 0;
60
+ if (realAllowedRoot && !isPathWithinRoot(realDirectory, realAllowedRoot)) return commands;
61
+ if (visitedDirectories.has(realDirectory)) return commands;
62
+ visitedDirectories.add(realDirectory);
63
+ const entries = await promises.readdir(dirPath, { withFileTypes: true });
64
+ for (const entry of entries) {
65
+ if (entry.name === "node_modules") continue;
66
+ const fullPath = path$1.join(dirPath, entry.name);
67
+ const stats = entry.isSymbolicLink() ? await promises.stat(fullPath).catch(() => null) : entry;
68
+ if (!stats) continue;
69
+ if (stats.isDirectory()) {
70
+ const subCommands = await scanCommandDirectory(fullPath, baseDir, {
71
+ ...options,
72
+ visitedDirectories
73
+ });
74
+ commands.push(...subCommands);
75
+ } else if (entry.name.endsWith(".md") && stats.isFile()) {
76
+ if (realAllowedRoot) {
77
+ const realFile = await promises.realpath(fullPath).catch(() => null);
78
+ if (!realFile || !isPathWithinRoot(realFile, realAllowedRoot)) continue;
79
+ }
80
+ const command = await parseCommandFile(fullPath, baseDir);
81
+ if (command) commands.push(command);
82
+ }
83
+ }
84
+ } catch {}
85
+ return commands;
86
+ }
87
+ /**
88
+ * Load custom slash commands from all configured directories
89
+ * Priority: mastra project > claude project > opencode project > mastra user > claude user > opencode user
90
+ */
91
+ async function loadCustomCommands(projectDir, configDirName = DEFAULT_CONFIG_DIR, extraCommandDirs = []) {
92
+ const commandMap = /* @__PURE__ */ new Map();
93
+ const addCommands = (newCommands) => {
94
+ for (const cmd of newCommands) commandMap.set(cmd.name, cmd);
95
+ };
96
+ const homeDir = process.env.HOME || process.env.USERPROFILE;
97
+ if (homeDir) addCommands(await scanCommandDirectory(path$1.join(homeDir, ".opencode", "command")));
98
+ if (homeDir) addCommands(await scanCommandDirectory(path$1.join(homeDir, ".claude", "commands")));
99
+ if (homeDir) addCommands(await scanCommandDirectory(path$1.join(homeDir, configDirName, "commands")));
100
+ if (projectDir) addCommands(await scanCommandDirectory(path$1.join(projectDir, ".opencode", "command"), void 0, { allowedRoot: projectDir }));
101
+ if (projectDir) addCommands(await scanCommandDirectory(path$1.join(projectDir, ".claude", "commands"), void 0, { allowedRoot: projectDir }));
102
+ if (projectDir) addCommands(await scanCommandDirectory(path$1.join(projectDir, configDirName, "commands"), void 0, { allowedRoot: projectDir }));
103
+ for (const commandsDir of extraCommandDirs) addCommands(await scanCommandDirectory(commandsDir, void 0, { allowedRoot: commandsDir }));
104
+ return Array.from(commandMap.values());
105
+ }
106
+ /**
107
+ * Get the commands directory path for a project
108
+ */
109
+ function getProjectCommandsDir(projectDir, configDirName = DEFAULT_CONFIG_DIR) {
110
+ return path$1.join(projectDir, configDirName, "commands");
111
+ }
112
+ /**
113
+ * Initialize a commands directory with an example command
114
+ */
115
+ async function initCommandsDirectory(projectDir, configDirName = DEFAULT_CONFIG_DIR) {
116
+ const commandsDir = getProjectCommandsDir(projectDir, configDirName);
117
+ try {
118
+ await promises.mkdir(commandsDir, { recursive: true });
119
+ const examplePath = path$1.join(commandsDir, "example.md");
120
+ const exampleContent = `---
121
+ name: example
122
+ description: An example slash command
123
+ ---
124
+
125
+ This is an example slash command template.
126
+ You can use variables like \$ARGUMENTS or \$1, \$2 for positional args.
127
+ You can also include file content with @filename.
128
+ Shell commands with !command will be executed and output included.
129
+ `;
130
+ try {
131
+ await promises.access(examplePath);
132
+ } catch {
133
+ await promises.writeFile(examplePath, exampleContent, "utf-8");
134
+ }
135
+ } catch (error) {
136
+ console.error("Error initializing commands directory:", error);
137
+ }
138
+ }
139
+ export { extractCommandName, getProjectCommandsDir, initCommandsDirectory, loadCustomCommands, parseCommandFile, scanCommandDirectory };
@@ -0,0 +1,14 @@
1
+ import type { SlashCommandMetadata } from './slash-command-loader.js';
2
+ /**
3
+ * Process a slash command by replacing variables and executing shell commands
4
+ */
5
+ export declare function processSlashCommand(command: SlashCommandMetadata, args: string[], workingDir: string): Promise<string>;
6
+ /**
7
+ * Format a command for display in help/autocomplete
8
+ */
9
+ export declare function formatCommandForDisplay(command: SlashCommandMetadata): string;
10
+ /**
11
+ * Group commands by namespace for display
12
+ */
13
+ export declare function groupCommandsByNamespace(commands: SlashCommandMetadata[]): Map<string, SlashCommandMetadata[]>;
14
+ //# sourceMappingURL=slash-command-processor.d.ts.map
@@ -0,0 +1,106 @@
1
+ import * as path$1 from "path";
2
+ import { promises } from "fs";
3
+ import { execSync } from "child_process";
4
+ // src/utils/slash-command-processor.ts
5
+ /**
6
+ * Process a slash command by replacing variables and executing shell commands
7
+ */
8
+ async function processSlashCommand(command, args, workingDir) {
9
+ const { result: withArgs, shouldAppendRawArgs } = replaceArguments(command.template, args);
10
+ let result = withArgs;
11
+ result = await replaceShellOutput(result, workingDir);
12
+ result = await replaceFileReferences(result, workingDir);
13
+ if (shouldAppendRawArgs) result = result.trimEnd() + `\n\nARGUMENTS: ${args.join(" ")}`;
14
+ return result;
15
+ }
16
+ /**
17
+ * Replace argument variables in template
18
+ * $ARGUMENTS - all arguments joined
19
+ * $1, $2, etc. - positional arguments
20
+ */
21
+ function replaceArguments(template, args) {
22
+ let result = template;
23
+ const hasArgumentsVar = /\$ARGUMENTS/.test(template);
24
+ const hasPositionalVar = /\$[1-9]\d*/.test(template);
25
+ result = result.replace(/\$ARGUMENTS/g, args.join(" "));
26
+ args.forEach((_, index) => {
27
+ const argNumber = index + 1;
28
+ const pattern = new RegExp(`\\\$${argNumber}\\+`, "g");
29
+ result = result.replace(pattern, args.slice(index).join(" "));
30
+ });
31
+ args.forEach((arg, index) => {
32
+ const pattern = new RegExp(`\\\$${index + 1}`, "g");
33
+ result = result.replace(pattern, arg);
34
+ });
35
+ result = result.replace(/\$[1-9]\d*\+?/g, "");
36
+ return {
37
+ result,
38
+ shouldAppendRawArgs: !hasArgumentsVar && !hasPositionalVar && args.length > 0
39
+ };
40
+ }
41
+ /**
42
+ * Replace shell command references with their output
43
+ * Format: !`command`
44
+ */
45
+ async function replaceShellOutput(template, workingDir) {
46
+ const matches = [...template.matchAll(/!`([^`]+)`/g)];
47
+ let result = template;
48
+ for (const match of matches) {
49
+ const [fullMatch, command] = match;
50
+ try {
51
+ const output = execSync(command, {
52
+ cwd: workingDir,
53
+ encoding: "utf-8",
54
+ timeout: 3e4,
55
+ maxBuffer: 1048576
56
+ });
57
+ result = result.replace(fullMatch, output.trim());
58
+ } catch (error) {
59
+ console.error(`Error executing shell command "${command}":`, error);
60
+ result = result.replace(fullMatch, `[Error: Failed to execute "${command}"]`);
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ /**
66
+ * Replace file references with file content
67
+ * Formats: @filename, @path/to/file, @path\to\file, @C:\path\to\file, or @C:/path/to/file
68
+ * Spaces, quoted paths, and glob patterns are not supported.
69
+ */
70
+ async function replaceFileReferences(template, workingDir) {
71
+ const matches = [...template.matchAll(/@((?:[A-Za-z]:[\\/])?[\w./\\-]+)/g)];
72
+ let result = template;
73
+ for (const match of matches) {
74
+ const [fullMatch, filePath] = match;
75
+ try {
76
+ const fullPath = resolveFileReferencePath(workingDir, filePath);
77
+ const content = await promises.readFile(fullPath, "utf-8");
78
+ result = result.replace(fullMatch, content);
79
+ } catch {}
80
+ }
81
+ return result;
82
+ }
83
+ function resolveFileReferencePath(workingDir, filePath) {
84
+ return ([workingDir, filePath].some((value) => /^[A-Za-z]:[\\/]/.test(value) || value.includes("\\")) ? path$1.win32 : path$1).resolve(workingDir, filePath);
85
+ }
86
+ /**
87
+ * Format a command for display in help/autocomplete
88
+ */
89
+ function formatCommandForDisplay(command) {
90
+ const parts = [command.name];
91
+ if (command.description) parts.push(`- ${command.description}`);
92
+ return parts.join(" ");
93
+ }
94
+ /**
95
+ * Group commands by namespace for display
96
+ */
97
+ function groupCommandsByNamespace(commands) {
98
+ const groups = /* @__PURE__ */ new Map();
99
+ for (const command of commands) {
100
+ const namespace = command.namespace || command.name.split(":")[0] || "general";
101
+ if (!groups.has(namespace)) groups.set(namespace, []);
102
+ groups.get(namespace).push(command);
103
+ }
104
+ return groups;
105
+ }
106
+ export { formatCommandForDisplay, groupCommandsByNamespace, processSlashCommand };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Clean up raw piped output so the agent sees readable text, not terminal
3
+ * control noise.
4
+ *
5
+ * 1. Strip all ANSI escape sequences (colors, cursor movement, line clears).
6
+ * 2. Simulate carriage-return overwrites: for each line, split on `\r` and
7
+ * keep only the last segment — this is what the terminal would display
8
+ * after a spinner/progress bar finishes.
9
+ * 3. Collapse runs of blank lines.
10
+ */
11
+ export declare function sanitizePipedOutput(raw: string): string;
12
+ /**
13
+ * If stdin is a pipe (not a TTY), read **all** data until EOF and return it as
14
+ * a string. The returned promise only resolves once the write end of the pipe
15
+ * is closed — i.e. the sending process has fully exited — so callers are
16
+ * guaranteed to receive the complete output, not a partial snapshot from a
17
+ * program that writes progressively.
18
+ *
19
+ * Returns `null` when:
20
+ * - stdin is a TTY (interactive terminal)
21
+ * - the pipe was empty or contained only whitespace
22
+ */
23
+ export declare function drainPipedStdin(): Promise<string | null>;
24
+ /**
25
+ * Reopen `/dev/tty` (or `CON` on Windows) as `process.stdin` so that the
26
+ * interactive TUI can read keyboard input after the original piped stdin has
27
+ * been consumed.
28
+ *
29
+ * @returns `true` if the swap succeeded, `false` if a TTY could not be opened
30
+ * (e.g. running in a headless CI container with no controlling terminal).
31
+ */
32
+ export declare function reopenStdinFromTTY(): boolean;
33
+ //# sourceMappingURL=stdin-pipe.d.ts.map
@@ -0,0 +1,93 @@
1
+ import * as fs$1 from "fs";
2
+ import * as tty from "tty";
3
+ // src/utils/stdin-pipe.ts
4
+ /** Maximum piped input size (1 MB). Content beyond this is truncated. */
5
+ const MAX_PIPE_BYTES = 1048576;
6
+ /**
7
+ * Matches all ANSI escape sequences — SGR (colors), cursor movement, line
8
+ * clears, scrolling, window titles, etc.
9
+ */
10
+ const ANSI_RE = /\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|\([A-Z])/g;
11
+ /**
12
+ * Clean up raw piped output so the agent sees readable text, not terminal
13
+ * control noise.
14
+ *
15
+ * 1. Strip all ANSI escape sequences (colors, cursor movement, line clears).
16
+ * 2. Simulate carriage-return overwrites: for each line, split on `\r` and
17
+ * keep only the last segment — this is what the terminal would display
18
+ * after a spinner/progress bar finishes.
19
+ * 3. Collapse runs of blank lines.
20
+ */
21
+ function sanitizePipedOutput(raw) {
22
+ let text = raw.replace(ANSI_RE, "");
23
+ text = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
24
+ text = text.split("\n").map((line) => {
25
+ if (!line.includes("\r")) return line;
26
+ const segments = line.split("\r");
27
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i].length > 0) return segments[i];
28
+ return "";
29
+ }).join("\n");
30
+ text = text.replace(/\n{3,}/g, "\n\n");
31
+ return text.trim();
32
+ }
33
+ /**
34
+ * If stdin is a pipe (not a TTY), read **all** data until EOF and return it as
35
+ * a string. The returned promise only resolves once the write end of the pipe
36
+ * is closed — i.e. the sending process has fully exited — so callers are
37
+ * guaranteed to receive the complete output, not a partial snapshot from a
38
+ * program that writes progressively.
39
+ *
40
+ * Returns `null` when:
41
+ * - stdin is a TTY (interactive terminal)
42
+ * - the pipe was empty or contained only whitespace
43
+ */
44
+ async function drainPipedStdin() {
45
+ if (process.stdin.isTTY) return null;
46
+ const chunks = [];
47
+ let totalBytes = 0;
48
+ let truncated = false;
49
+ for await (const chunk of process.stdin) {
50
+ const buf = chunk;
51
+ if (totalBytes + buf.length > MAX_PIPE_BYTES) {
52
+ const remaining = MAX_PIPE_BYTES - totalBytes;
53
+ if (remaining > 0) chunks.push(Buffer.from(buf.subarray(0, remaining)));
54
+ buf.fill(0);
55
+ totalBytes = MAX_PIPE_BYTES;
56
+ truncated = true;
57
+ continue;
58
+ }
59
+ chunks.push(buf);
60
+ totalBytes += buf.length;
61
+ }
62
+ if (truncated) process.stderr.write(`Warning: Piped input exceeded ${MAX_PIPE_BYTES / 1024 / 1024}MB and was truncated.\n`);
63
+ const raw = Buffer.concat(chunks).toString("utf-8");
64
+ for (const buf of chunks) buf.fill(0);
65
+ chunks.length = 0;
66
+ const content = sanitizePipedOutput(raw);
67
+ return content.length > 0 ? content : null;
68
+ }
69
+ /**
70
+ * Reopen `/dev/tty` (or `CON` on Windows) as `process.stdin` so that the
71
+ * interactive TUI can read keyboard input after the original piped stdin has
72
+ * been consumed.
73
+ *
74
+ * @returns `true` if the swap succeeded, `false` if a TTY could not be opened
75
+ * (e.g. running in a headless CI container with no controlling terminal).
76
+ */
77
+ function reopenStdinFromTTY() {
78
+ const ttyPath = process.platform === "win32" ? "CON" : "/dev/tty";
79
+ let fd;
80
+ try {
81
+ fd = fs$1.openSync(ttyPath, "r");
82
+ } catch {
83
+ return false;
84
+ }
85
+ const ttyStream = new tty.ReadStream(fd);
86
+ Object.defineProperty(process, "stdin", {
87
+ value: ttyStream,
88
+ writable: true,
89
+ configurable: true
90
+ });
91
+ return true;
92
+ }
93
+ export { drainPipedStdin, reopenStdinFromTTY, sanitizePipedOutput };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Storage factory — creates the appropriate storage backend based on resolved config.
3
+ *
4
+ * If PG is selected but fails to connect, falls back to LibSQL so the TUI
5
+ * can start and the user can fix the connection via /settings.
6
+ */
7
+ import type { MastraCompositeStore, RetentionConfig } from '@mastra/core/storage';
8
+ import type { MastraVector } from '@mastra/core/vector';
9
+ import type { StorageConfig } from './project.js';
10
+ export declare const MASTRA_CODE_LOCAL_PRAGMAS: {
11
+ cacheSize: number;
12
+ mmapSize: number;
13
+ };
14
+ /**
15
+ * Construct a LibSQL store for an arbitrary url/authToken, applying the same
16
+ * local pragmas the default factory uses.
17
+ */
18
+ export declare function buildLibSQLStore(opts: {
19
+ id?: string;
20
+ url: string;
21
+ authToken?: string;
22
+ retention?: RetentionConfig;
23
+ }): MastraCompositeStore;
24
+ /** Construct a LibSQL vector store for an arbitrary url/authToken. */
25
+ export declare function buildLibSQLVector(opts: {
26
+ id?: string;
27
+ url: string;
28
+ authToken?: string;
29
+ }): MastraVector;
30
+ export interface StorageResult {
31
+ storage: MastraCompositeStore;
32
+ /** The effective backend after any fallback logic has run. */
33
+ backend: 'libsql' | 'pg';
34
+ /** Non-null when PG was requested but failed — contains a user-facing warning. */
35
+ warning?: string;
36
+ }
37
+ /**
38
+ * Create a storage instance from the resolved config.
39
+ *
40
+ * - `libsql` backend → LibSQLStore (always available)
41
+ * - `pg` backend → PostgresStore, falls back to LibSQL on connection failure
42
+ */
43
+ export declare function createStorage(config: StorageConfig): Promise<StorageResult>;
44
+ /**
45
+ * Create a vector store for recall search.
46
+ * Uses a separate LibSQL file to avoid bloating the main storage DB with embedding data.
47
+ * For PG backends, reuses the same connection (PG handles the extra tables fine).
48
+ */
49
+ export declare function createVectorStore(config: StorageConfig, effectiveBackend?: 'libsql' | 'pg'): Promise<MastraVector | undefined>;
50
+ //# sourceMappingURL=storage-factory.d.ts.map
@@ -0,0 +1,118 @@
1
+ import { getDatabasePath, getVectorDatabasePath } from "./project.js";
2
+ import { DEFAULT_RETENTION } from "./storage-maintenance.js";
3
+ import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
4
+ // src/utils/storage-factory.ts
5
+ const MASTRA_CODE_LOCAL_PRAGMAS = {
6
+ cacheSize: -128e3,
7
+ mmapSize: 536870912
8
+ };
9
+ /**
10
+ * Construct a LibSQL store for an arbitrary url/authToken, applying the same
11
+ * local pragmas the default factory uses.
12
+ */
13
+ function buildLibSQLStore(opts) {
14
+ return new LibSQLStore({
15
+ id: opts.id ?? "mastra-code-storage",
16
+ url: opts.url,
17
+ ...opts.authToken ? { authToken: opts.authToken } : {},
18
+ ...opts.retention ? { retention: opts.retention } : {},
19
+ localPragmas: MASTRA_CODE_LOCAL_PRAGMAS
20
+ });
21
+ }
22
+ /** Construct a LibSQL vector store for an arbitrary url/authToken. */
23
+ function buildLibSQLVector(opts) {
24
+ return new LibSQLVector({
25
+ id: opts.id ?? "mastra-code-vectors",
26
+ url: opts.url,
27
+ ...opts.authToken ? { authToken: opts.authToken } : {}
28
+ });
29
+ }
30
+ function createFallbackLibSQL() {
31
+ return buildLibSQLStore({
32
+ url: `file:${getDatabasePath()}`,
33
+ retention: DEFAULT_RETENTION
34
+ });
35
+ }
36
+ /**
37
+ * Create a storage instance from the resolved config.
38
+ *
39
+ * - `libsql` backend → LibSQLStore (always available)
40
+ * - `pg` backend → PostgresStore, falls back to LibSQL on connection failure
41
+ */
42
+ async function createStorage(config) {
43
+ if (config.backend === "pg") return createPgStorage(config);
44
+ return {
45
+ storage: buildLibSQLStore({
46
+ url: config.url,
47
+ authToken: config.authToken,
48
+ retention: DEFAULT_RETENTION
49
+ }),
50
+ backend: "libsql"
51
+ };
52
+ }
53
+ async function createPgStorage(config) {
54
+ if (!config.connectionString && !config.host) return {
55
+ storage: createFallbackLibSQL(),
56
+ backend: "libsql",
57
+ warning: "PostgreSQL backend selected but no connection info configured. Using LibSQL fallback. Set a connection string via /settings."
58
+ };
59
+ const { PostgresStore } = await import("@mastra/pg");
60
+ const base = {
61
+ id: "mastra-code-storage",
62
+ retention: DEFAULT_RETENTION,
63
+ ...config.schemaName ? { schemaName: config.schemaName } : {},
64
+ ...config.disableInit ? { disableInit: config.disableInit } : {},
65
+ ...config.skipDefaultIndexes ? { skipDefaultIndexes: config.skipDefaultIndexes } : {}
66
+ };
67
+ const store = config.connectionString ? new PostgresStore({
68
+ ...base,
69
+ connectionString: config.connectionString
70
+ }) : new PostgresStore({
71
+ ...base,
72
+ host: config.host,
73
+ port: config.port,
74
+ database: config.database,
75
+ user: config.user,
76
+ password: config.password
77
+ });
78
+ try {
79
+ await store.init();
80
+ } catch (err) {
81
+ const msg = err?.message ?? String(err);
82
+ const target = config.connectionString ?? `${config.host}:${config.port ?? 5432}`;
83
+ try {
84
+ await store.close();
85
+ } catch {}
86
+ return {
87
+ storage: createFallbackLibSQL(),
88
+ backend: "libsql",
89
+ warning: `Failed to connect to PostgreSQL at ${target}: ${msg}\nUsing LibSQL fallback. Fix the connection via /settings.`
90
+ };
91
+ }
92
+ return {
93
+ storage: store,
94
+ backend: "pg"
95
+ };
96
+ }
97
+ /**
98
+ * Create a vector store for recall search.
99
+ * Uses a separate LibSQL file to avoid bloating the main storage DB with embedding data.
100
+ * For PG backends, reuses the same connection (PG handles the extra tables fine).
101
+ */
102
+ async function createVectorStore(config, effectiveBackend = config.backend) {
103
+ if (effectiveBackend === "pg") {
104
+ const pgConfig = config;
105
+ if (!pgConfig.connectionString && !pgConfig.host) return void 0;
106
+ const { PgVector } = await import("@mastra/pg");
107
+ return new PgVector({
108
+ id: "mastra-code-vectors",
109
+ connectionString: pgConfig.connectionString ?? `postgresql://${pgConfig.user}:${pgConfig.password}@${pgConfig.host}:${pgConfig.port ?? 5432}/${pgConfig.database}`
110
+ });
111
+ }
112
+ const libsqlConfig = config;
113
+ return buildLibSQLVector({
114
+ url: libsqlConfig.vectorUrl ?? `file:${getVectorDatabasePath()}`,
115
+ authToken: libsqlConfig.vectorAuthToken
116
+ });
117
+ }
118
+ export { MASTRA_CODE_LOCAL_PRAGMAS, buildLibSQLStore, buildLibSQLVector, createStorage, createVectorStore };