@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,427 @@
1
+ import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
2
+ import { AuthStorage } from "../auth/storage.js";
3
+ import { runCatalogThinkingLevel } from "../thinking-catalog.js";
4
+ import { supportsMaxReasoningEffort } from "../thinking.js";
5
+ import { createOpenAI } from "@ai-sdk/openai";
6
+ import { wrapLanguageModel } from "ai";
7
+ // src/providers/openai-codex.ts
8
+ /**
9
+ * OpenAI Codex OAuth Provider
10
+ *
11
+ * Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.
12
+ * This allows access to OpenAI models through the ChatGPT OAuth flow.
13
+ *
14
+ * Inspired by opencode's Codex plugin implementation:
15
+ * https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts
16
+ */
17
+ const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
18
+ const CODEX_ORIGINATOR = "mastracode";
19
+ const CODEX_USER_AGENT = "mastracode";
20
+ const CODEX_PROVIDER_NAME = "OpenAI Codex";
21
+ let authStorageInstance = null;
22
+ /**
23
+ * Get or create the shared AuthStorage instance
24
+ */
25
+ function getAuthStorage() {
26
+ if (!authStorageInstance) authStorageInstance = new AuthStorage();
27
+ return authStorageInstance;
28
+ }
29
+ /**
30
+ * Set a custom AuthStorage instance (useful for TUI integration)
31
+ */
32
+ function setAuthStorage(storage) {
33
+ authStorageInstance = storage ?? null;
34
+ }
35
+ const CODEX_INSTRUCTIONS = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
36
+
37
+ IMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;
38
+ const GPT5_MODEL_RE = /^gpt-5(?:\.|-|$)/;
39
+ function getEffectiveThinkingLevel(modelId, level) {
40
+ const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === "off" ? "low" : level;
41
+ return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);
42
+ }
43
+ const THINKING_LEVEL_TO_REASONING_EFFORT = {
44
+ off: void 0,
45
+ low: "low",
46
+ medium: "medium",
47
+ high: "high",
48
+ xhigh: "xhigh",
49
+ max: "max"
50
+ };
51
+ /**
52
+ * Create Codex middleware with the given reasoning effort level.
53
+ */
54
+ function createCodexMiddleware(reasoningEffort, oauthOptions) {
55
+ return {
56
+ specificationVersion: "v4",
57
+ transformParams: async ({ params }) => {
58
+ if (params.temperature !== void 0 && params.temperature !== null) delete params.topP;
59
+ const fast = oauthOptions && (oauthOptions.serviceTier === "fast" || params.providerOptions?.mastracode?.codexServiceTier === "fast");
60
+ params.providerOptions = {
61
+ ...params.providerOptions,
62
+ openai: {
63
+ ...params.providerOptions?.openai ?? {},
64
+ instructions: CODEX_INSTRUCTIONS,
65
+ store: false,
66
+ ...reasoningEffort ? { reasoningEffort } : {},
67
+ ...fast ? { serviceTier: "priority" } : {}
68
+ }
69
+ };
70
+ return params;
71
+ }
72
+ };
73
+ }
74
+ /**
75
+ * The thread a model request belongs to, from the `x-thread-id` header that
76
+ * model resolution adds for requests made inside a thread.
77
+ */
78
+ function getRequestThreadId(headers) {
79
+ if (!headers) return void 0;
80
+ for (const name in headers) if (name.toLowerCase() === "x-thread-id") return headers[name] || void 0;
81
+ }
82
+ /**
83
+ * Create middleware that sends `prompt_cache_key` on OpenAI Responses requests.
84
+ *
85
+ * OpenAI routes a cached prompt by a hash of its start plus this key. Every
86
+ * Mastra Code prompt starts with the same system prompt, so without a key all
87
+ * threads compete for the same cache slot and consecutive steps of one run often
88
+ * land on a machine that doesn't hold their prefix. Keying by thread keeps each
89
+ * thread's requests together. A key the caller already set wins.
90
+ */
91
+ function createPromptCacheKeyMiddleware(promptCacheKey) {
92
+ if (!promptCacheKey) return void 0;
93
+ return {
94
+ specificationVersion: "v4",
95
+ transformParams: async ({ params }) => {
96
+ params.providerOptions = {
97
+ ...params.providerOptions,
98
+ openai: {
99
+ promptCacheKey,
100
+ ...params.providerOptions?.openai ?? {}
101
+ }
102
+ };
103
+ return params;
104
+ }
105
+ };
106
+ }
107
+ /**
108
+ * Create middleware that forwards a resolved reasoning effort to an
109
+ * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.
110
+ *
111
+ * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing
112
+ * (e.g. thinking level `off`), leaving the wire request without a
113
+ * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not
114
+ * inject Codex-only options (instructions/store); it only sets reasoning
115
+ * effort, keyed by the caller-supplied provider id.
116
+ */
117
+ function createReasoningEffortMiddleware(providerKey, reasoningEffort) {
118
+ if (!reasoningEffort) return void 0;
119
+ return {
120
+ specificationVersion: "v4",
121
+ transformParams: async ({ params }) => {
122
+ params.providerOptions = {
123
+ ...params.providerOptions,
124
+ [providerKey]: {
125
+ ...params.providerOptions?.[providerKey] ?? {},
126
+ reasoningEffort
127
+ }
128
+ };
129
+ return params;
130
+ }
131
+ };
132
+ }
133
+ /**
134
+ * Get a live OAuth bearer token for the Codex OAuth credential.
135
+ *
136
+ * Refreshes the token if it's expired, and returns the credential's
137
+ * accountId alongside the access token. Throws if the user isn't logged in
138
+ * or if the refresh fails.
139
+ *
140
+ * This is the only piece of Codex auth that is genuinely shared between
141
+ * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand
142
+ * fetch (`buildCodexStagehandFetch`).
143
+ */
144
+ async function getCodexBearer(authStorage) {
145
+ const storage = authStorage ?? getAuthStorage();
146
+ storage.reload();
147
+ let cred = storage.get("openai-codex");
148
+ if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
149
+ if (storage.getOAuthCredential) {
150
+ cred = await storage.getOAuthCredential("openai-codex");
151
+ if (!cred) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
152
+ } else if (Date.now() >= cred.expires) {
153
+ const refreshedToken = await storage.getApiKey("openai-codex");
154
+ if (!refreshedToken) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
155
+ storage.reload();
156
+ const reloaded = storage.get("openai-codex");
157
+ if (!reloaded || reloaded.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
158
+ cred = {
159
+ ...reloaded,
160
+ access: refreshedToken
161
+ };
162
+ }
163
+ return {
164
+ accessToken: cred.access,
165
+ accountId: cred.accountId
166
+ };
167
+ }
168
+ /**
169
+ * Make a Responses request body safe for Codex's stateless (`store: false`) mode.
170
+ *
171
+ * AI SDK replays earlier output items with their server ids (`rs_…`, `msg_…`,
172
+ * `fc_…`) even when `store` is false. Codex looks those ids up and answers
173
+ * 404 `Item with id 'rs_…' not found` once its short-lived item cache has
174
+ * expired, so every later request in the thread fails the same way. Like the
175
+ * Codex CLI, send items without ids (the encrypted reasoning content carries the
176
+ * reasoning chain) and drop `item_reference`s, which can never resolve.
177
+ */
178
+ function stripCodexInputItemIds(body) {
179
+ let parsed;
180
+ try {
181
+ parsed = JSON.parse(body);
182
+ } catch {
183
+ return body;
184
+ }
185
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.input)) return body;
186
+ const request = parsed;
187
+ if (request.store !== false) return body;
188
+ request.input = request.input.flatMap((item) => {
189
+ if (!item || typeof item !== "object") return [item];
190
+ const { id: _id, ...rest } = item;
191
+ if (rest.type === "item_reference") return [];
192
+ return [rest];
193
+ });
194
+ return JSON.stringify(request);
195
+ }
196
+ /**
197
+ * Build a fetch function that handles OpenAI Codex OAuth.
198
+ * Preserves non-authorization headers from init.
199
+ * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions
200
+ * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the
201
+ * SDK already targets the correct URL.
202
+ */
203
+ function buildOpenAICodexOAuthFetch(opts = {}) {
204
+ return (async (url, init) => {
205
+ const { accessToken, accountId } = await getCodexBearer(opts.authStorage);
206
+ const { headers: initHeaders, ...requestInit } = init ?? {};
207
+ const request = new Request(url, requestInit);
208
+ const headers = new Headers(url instanceof Request ? url.headers : void 0);
209
+ if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));
210
+ headers.delete("authorization");
211
+ headers.delete("x-api-key");
212
+ headers.set("Authorization", `Bearer ${accessToken}`);
213
+ if (!headers.has("originator")) headers.set("originator", CODEX_ORIGINATOR);
214
+ if (!headers.has("User-Agent")) headers.set("User-Agent", CODEX_USER_AGENT);
215
+ if (accountId) headers.set("ChatGPT-Account-ID", accountId);
216
+ const threadId = headers.get("x-thread-id");
217
+ if (threadId) {
218
+ if (!headers.has("session-id")) headers.set("session-id", threadId);
219
+ if (!headers.has("thread-id")) headers.set("thread-id", threadId);
220
+ }
221
+ const parsed = new URL(request.url);
222
+ const finalUrl = opts.rewriteUrl !== false && (parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions")) ? new URL(CODEX_API_ENDPOINT) : parsed;
223
+ const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
224
+ const isJson = headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() === "application/json";
225
+ let body;
226
+ if (hasBody && isJson) {
227
+ body = stripCodexInputItemIds(await request.text());
228
+ headers.delete("content-length");
229
+ } else if (hasBody) body = request.body;
230
+ const finalRequest = new Request(finalUrl, {
231
+ method: request.method,
232
+ headers,
233
+ body,
234
+ signal: request.signal,
235
+ redirect: request.redirect,
236
+ integrity: request.integrity,
237
+ ...body instanceof ReadableStream ? { duplex: "half" } : {}
238
+ });
239
+ try {
240
+ return await rejectUnauthorizedResponse(await fetch(finalRequest), {
241
+ providerName: CODEX_PROVIDER_NAME,
242
+ requestUrl: finalUrl.toString()
243
+ });
244
+ } catch (error) {
245
+ if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
246
+ throw error;
247
+ }
248
+ });
249
+ }
250
+ /**
251
+ * Build a fetch function for Stagehand-on-Codex.
252
+ *
253
+ * The Codex backend has two requirements that AI SDK's non-streaming
254
+ * `generateText` path doesn't naturally satisfy:
255
+ *
256
+ * 1. `stream: true` must be set on every request body.
257
+ * 2. The response is delivered as Server-Sent Events; AI SDK's
258
+ * non-streaming code path expects a single JSON body.
259
+ *
260
+ * This fetch forces streaming on the outgoing request, collects the SSE
261
+ * events, and synthesizes the non-streaming JSON shape that
262
+ * `@ai-sdk/openai`'s Responses API parser expects.
263
+ *
264
+ * Headers, OAuth refresh, and URL targeting are handled by the caller via
265
+ * `baseURL` / `headers` on the AI SDK provider; this fetch only injects the
266
+ * live OAuth bearer per call.
267
+ */
268
+ function buildCodexStagehandFetch(authStorage) {
269
+ return (async (url, init) => {
270
+ const { accessToken } = await getCodexBearer(authStorage);
271
+ const { headers: initHeaders, ...requestInit } = init ?? {};
272
+ const request = new Request(url, requestInit);
273
+ const headers = new Headers(url instanceof Request ? url.headers : void 0);
274
+ if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));
275
+ headers.delete("authorization");
276
+ headers.delete("x-api-key");
277
+ headers.set("Authorization", `Bearer ${accessToken}`);
278
+ headers.set("Accept", "text/event-stream");
279
+ let body = await request.clone().text();
280
+ try {
281
+ const parsed = JSON.parse(body);
282
+ parsed.stream = true;
283
+ body = JSON.stringify(parsed);
284
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
285
+ } catch {}
286
+ const upstream = await fetch(new Request(request, {
287
+ headers,
288
+ ...request.method === "GET" || request.method === "HEAD" ? {} : { body }
289
+ }));
290
+ if (!upstream.ok) return upstream;
291
+ const aggregated = await aggregateCodexStream(upstream);
292
+ return new Response(aggregated, {
293
+ status: 200,
294
+ headers: { "content-type": "application/json" }
295
+ });
296
+ });
297
+ }
298
+ /**
299
+ * Read an SSE Response and reduce it to a single JSON string matching the
300
+ * non-streaming OpenAI Responses-API shape.
301
+ *
302
+ * Event vocabulary we care about (per OpenAI Responses API streaming):
303
+ * - response.created → carries `response` object (id, model, usage stub)
304
+ * - response.output_item.added/done → output items (message, reasoning, etc.)
305
+ * - response.output_text.delta → text chunks
306
+ * - response.completed → final `response` snapshot incl. usage
307
+ * - response.error / error → bubble up as a thrown body
308
+ *
309
+ * Reasoning events (`response.reasoning_summary.*`) are intentionally ignored
310
+ * for the non-streaming text response.
311
+ */
312
+ async function aggregateCodexStream(response) {
313
+ if (!response.body) throw new Error("Codex streaming response had no body");
314
+ const reader = response.body.getReader();
315
+ const decoder = new TextDecoder("utf-8");
316
+ let buffer = "";
317
+ let finalResponse = null;
318
+ let createdResponse = null;
319
+ const items = /* @__PURE__ */ new Map();
320
+ const textBuffers = /* @__PURE__ */ new Map();
321
+ const handleEvent = (event) => {
322
+ if (!event.data || event.data === "[DONE]") return;
323
+ let payload;
324
+ try {
325
+ payload = JSON.parse(event.data);
326
+ } catch {
327
+ return;
328
+ }
329
+ switch (payload.type ?? event.event ?? "") {
330
+ case "response.created":
331
+ createdResponse = payload.response ?? createdResponse;
332
+ break;
333
+ case "response.output_item.added":
334
+ if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
335
+ break;
336
+ case "response.output_item.done":
337
+ if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
338
+ break;
339
+ case "response.output_text.delta": {
340
+ const key = `${payload.output_index}:${payload.content_index ?? 0}`;
341
+ textBuffers.set(key, (textBuffers.get(key) ?? "") + (payload.delta ?? ""));
342
+ break;
343
+ }
344
+ case "response.completed":
345
+ finalResponse = payload.response ?? finalResponse;
346
+ break;
347
+ case "response.error":
348
+ case "error": throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);
349
+ }
350
+ };
351
+ const processChunk = (chunk) => {
352
+ buffer += chunk.replace(/\r\n/g, "\n");
353
+ let sepIdx;
354
+ while ((sepIdx = buffer.indexOf("\n\n")) !== -1) {
355
+ const raw = buffer.slice(0, sepIdx);
356
+ buffer = buffer.slice(sepIdx + 2);
357
+ const event = {};
358
+ const dataLines = [];
359
+ for (const line of raw.split("\n")) if (line.startsWith("event:")) event.event = line.slice(6).trim();
360
+ else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
361
+ if (dataLines.length > 0) event.data = dataLines.join("\n");
362
+ handleEvent(event);
363
+ }
364
+ };
365
+ try {
366
+ while (true) {
367
+ const { value, done } = await reader.read();
368
+ if (done) break;
369
+ processChunk(decoder.decode(value, { stream: true }));
370
+ }
371
+ processChunk(decoder.decode());
372
+ } finally {
373
+ reader.releaseLock();
374
+ }
375
+ const base = finalResponse ?? createdResponse ?? { output: [] };
376
+ const finalItems = Array.from(items.entries()).sort(([a], [b]) => a - b).map(([index, item]) => {
377
+ if (item?.type === "message" && Array.isArray(item.content)) item.content = item.content.map((c, ci) => {
378
+ const key = `${index}:${ci}`;
379
+ if (textBuffers.has(key)) return {
380
+ ...c,
381
+ text: textBuffers.get(key)
382
+ };
383
+ return c;
384
+ });
385
+ return item;
386
+ });
387
+ base.output = finalItems.length > 0 ? finalItems : base.output ?? [];
388
+ return JSON.stringify(base);
389
+ }
390
+ /**
391
+ * Creates an OpenAI model using ChatGPT OAuth authentication
392
+ * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)
393
+ *
394
+ * IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.
395
+ * URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.
396
+ */
397
+ function openaiCodexProvider(modelId = "codex-mini-latest", options) {
398
+ const effectiveLevel = getEffectiveThinkingLevel(modelId, options?.thinkingLevel ?? "medium");
399
+ const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
400
+ const headers = options?.headers;
401
+ const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));
402
+ const useTestApiKey = process.env.NODE_ENV === "test" || Boolean(process.env.VITEST);
403
+ const middleware = [createCodexMiddleware(reasoningEffort, { serviceTier: options?.serviceTier }), ...promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : []];
404
+ const baseURL = process.env.OPENAI_BASE_URL;
405
+ if (useTestApiKey) {
406
+ const openai = createOpenAI({
407
+ apiKey: "test-api-key",
408
+ baseURL,
409
+ headers
410
+ });
411
+ return wrapLanguageModel({
412
+ model: openai.responses(modelId),
413
+ middleware
414
+ });
415
+ }
416
+ const openai = createOpenAI({
417
+ apiKey: "oauth-dummy-key",
418
+ baseURL,
419
+ headers,
420
+ fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage })
421
+ });
422
+ return wrapLanguageModel({
423
+ model: openai.responses(modelId),
424
+ middleware
425
+ });
426
+ }
427
+ export { THINKING_LEVEL_TO_REASONING_EFFORT, buildCodexStagehandFetch, buildOpenAICodexOAuthFetch, createCodexMiddleware, createPromptCacheKeyMiddleware, createReasoningEffortMiddleware, getAuthStorage, getEffectiveThinkingLevel, getRequestThreadId, openaiCodexProvider, setAuthStorage, stripCodexInputItemIds, supportsMaxReasoningEffort };
@@ -0,0 +1,23 @@
1
+ import { ModelRouterLanguageModel } from '@mastra/core/llm';
2
+ import { wrapLanguageModel } from 'ai';
3
+ import type { JSONValue } from 'ai';
4
+ import type { ThinkingLevelSetting } from '../thinking.js';
5
+ export interface ProviderThinkingOptions {
6
+ optionsKey: string;
7
+ options: Record<string, JSONValue>;
8
+ controlKeys: ReadonlySet<string>;
9
+ }
10
+ export declare function providerThinkingOptions(routedModelId: string, level: ThinkingLevelSetting | undefined): ProviderThinkingOptions | undefined;
11
+ type AiSdkLanguageModel = Parameters<typeof wrapLanguageModel>[0]['model'];
12
+ export declare function withThinkingOptionsModel<Model extends AiSdkLanguageModel>(model: Model, thinking: ProviderThinkingOptions | undefined): Model | ReturnType<typeof wrapLanguageModel>;
13
+ type RouterConfig = ConstructorParameters<typeof ModelRouterLanguageModel>[0];
14
+ type RouterCallOptions = Parameters<ModelRouterLanguageModel['doStream']>[0];
15
+ type RouterCallResult = ReturnType<ModelRouterLanguageModel['doStream']>;
16
+ export declare class ModelRouterLanguageModelWithThinking extends ModelRouterLanguageModel {
17
+ #private;
18
+ constructor(config: RouterConfig, thinking: ProviderThinkingOptions | undefined);
19
+ doGenerate(options: RouterCallOptions): RouterCallResult;
20
+ doStream(options: RouterCallOptions): RouterCallResult;
21
+ }
22
+ export {};
23
+ //# sourceMappingURL=provider-thinking.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { requestableReasoningOptions, runThinkingLevel } from "../thinking.js";
2
+ import { thinkingRequestFormatFor } from "./thinking-request.js";
3
+ import { ModelRouterLanguageModel, getModelReasoningOptions } from "@mastra/core/llm";
4
+ import { wrapLanguageModel } from "ai";
5
+ // src/providers/provider-thinking.ts
6
+ function providerThinkingOptions(routedModelId, level) {
7
+ const format = thinkingRequestFormatFor(routedModelId);
8
+ if (!format || !level) return void 0;
9
+ const catalogOptions = getModelReasoningOptions(routedModelId);
10
+ const requestable = requestableReasoningOptions(routedModelId, catalogOptions);
11
+ const runLevel = runThinkingLevel(routedModelId, level, catalogOptions);
12
+ if (!requestable?.length || runLevel === "off") return void 0;
13
+ const effortOptions = format.sendEffort?.(runLevel);
14
+ const options = requestable.some((option) => option.type === "effort") ? effortOptions : format.enableThinking;
15
+ if (!options) return void 0;
16
+ const controlKeys = /* @__PURE__ */ new Set([...Object.keys(effortOptions ?? {}), ...Object.keys(format.enableThinking ?? {})]);
17
+ return {
18
+ optionsKey: format.optionsKey,
19
+ options,
20
+ controlKeys
21
+ };
22
+ }
23
+ function withThinkingOptions(callOptions, thinking) {
24
+ if (!thinking) return callOptions;
25
+ const callerOptions = callOptions.providerOptions?.[thinking.optionsKey] ?? {};
26
+ if (Object.keys(callerOptions).some((key) => thinking.controlKeys.has(key))) return callOptions;
27
+ return {
28
+ ...callOptions,
29
+ providerOptions: {
30
+ ...callOptions.providerOptions,
31
+ [thinking.optionsKey]: {
32
+ ...callerOptions,
33
+ ...thinking.options
34
+ }
35
+ }
36
+ };
37
+ }
38
+ function withThinkingOptionsModel(model, thinking) {
39
+ if (!thinking) return model;
40
+ return wrapLanguageModel({
41
+ model,
42
+ middleware: {
43
+ specificationVersion: "v4",
44
+ transformParams: async ({ params }) => withThinkingOptions(params, thinking)
45
+ }
46
+ });
47
+ }
48
+ var ModelRouterLanguageModelWithThinking = class extends ModelRouterLanguageModel {
49
+ #thinking;
50
+ constructor(config, thinking) {
51
+ super(config);
52
+ this.#thinking = thinking;
53
+ }
54
+ doGenerate(options) {
55
+ return super.doGenerate(withThinkingOptions(options, this.#thinking));
56
+ }
57
+ doStream(options) {
58
+ return super.doStream(withThinkingOptions(options, this.#thinking));
59
+ }
60
+ };
61
+ export { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel };
@@ -0,0 +1,14 @@
1
+ import type { JSONValue } from 'ai';
2
+ import type { ActiveThinkingLevel } from '../thinking.js';
3
+ type ThinkingProviderOptions = Record<string, JSONValue>;
4
+ export interface ThinkingRequestFormat {
5
+ optionsKey: string;
6
+ sendEffort?: (effort: ActiveThinkingLevel) => ThinkingProviderOptions;
7
+ acceptedEfforts?: readonly ActiveThinkingLevel[];
8
+ enableThinking?: ThinkingProviderOptions;
9
+ }
10
+ export declare function isThinkingAdapterProvider(provider: string): boolean;
11
+ export declare function isRoutedWithoutThinking(modelId: string): boolean;
12
+ export declare function thinkingRequestFormatFor(modelId: string): ThinkingRequestFormat | undefined;
13
+ export {};
14
+ //# sourceMappingURL=thinking-request.d.ts.map
@@ -0,0 +1,87 @@
1
+ import { MASTRA_GATEWAY_PREFIX, stripMastraGatewayPrefix } from "./model-ids.js";
2
+ // src/providers/thinking-request.ts
3
+ const LOW_TO_HIGH = [
4
+ "low",
5
+ "medium",
6
+ "high"
7
+ ];
8
+ const sendReasoningEffort = (reasoningEffort) => ({ reasoningEffort });
9
+ const ENABLE_REASONING = { reasoning: { enabled: true } };
10
+ const OPENROUTER_FORMAT = {
11
+ optionsKey: "openrouter",
12
+ sendEffort: (effort) => ({ reasoning: { effort } }),
13
+ enableThinking: ENABLE_REASONING
14
+ };
15
+ const REQUEST_FORMATS_BY_PROVIDER = {
16
+ deepseek: {
17
+ optionsKey: "deepseek",
18
+ sendEffort: sendReasoningEffort,
19
+ enableThinking: { thinking: { type: "enabled" } }
20
+ },
21
+ openrouter: OPENROUTER_FORMAT,
22
+ alibaba: {
23
+ optionsKey: "alibaba",
24
+ enableThinking: { enableThinking: true }
25
+ },
26
+ groq: {
27
+ optionsKey: "groq",
28
+ sendEffort: sendReasoningEffort,
29
+ acceptedEfforts: LOW_TO_HIGH
30
+ },
31
+ mistral: {
32
+ optionsKey: "mistral",
33
+ sendEffort: sendReasoningEffort,
34
+ acceptedEfforts: ["high"]
35
+ },
36
+ xai: {
37
+ optionsKey: "xai",
38
+ sendEffort: sendReasoningEffort,
39
+ acceptedEfforts: [...LOW_TO_HIGH, "xhigh"]
40
+ },
41
+ togetherai: {
42
+ optionsKey: "togetherai",
43
+ sendEffort: sendReasoningEffort,
44
+ acceptedEfforts: LOW_TO_HIGH,
45
+ enableThinking: ENABLE_REASONING
46
+ },
47
+ deepinfra: {
48
+ optionsKey: "deepinfra",
49
+ sendEffort: sendReasoningEffort,
50
+ acceptedEfforts: LOW_TO_HIGH,
51
+ enableThinking: ENABLE_REASONING
52
+ },
53
+ cerebras: {
54
+ optionsKey: "cerebras",
55
+ sendEffort: sendReasoningEffort
56
+ },
57
+ perplexity: {
58
+ optionsKey: "perplexity",
59
+ sendEffort: (effort) => ({ reasoning_effort: effort })
60
+ }
61
+ };
62
+ const THINKING_ADAPTER_PROVIDERS = /* @__PURE__ */ new Set([
63
+ "anthropic",
64
+ "openai",
65
+ "google"
66
+ ]);
67
+ function isThinkingAdapterProvider(provider) {
68
+ return THINKING_ADAPTER_PROVIDERS.has(provider);
69
+ }
70
+ const PROVIDERS_ROUTED_WITHOUT_THINKING = /* @__PURE__ */ new Set([
71
+ "github-copilot",
72
+ "kimi-for-coding",
73
+ "moonshotai",
74
+ "amazon-bedrock"
75
+ ]);
76
+ function isRoutedWithoutThinking(modelId) {
77
+ const [provider = ""] = stripMastraGatewayPrefix(modelId).split("/");
78
+ return PROVIDERS_ROUTED_WITHOUT_THINKING.has(provider);
79
+ }
80
+ function thinkingRequestFormatFor(modelId) {
81
+ const routedThroughMastraGateway = modelId.startsWith(MASTRA_GATEWAY_PREFIX);
82
+ const [provider = ""] = stripMastraGatewayPrefix(modelId).split("/");
83
+ if (isThinkingAdapterProvider(provider)) return void 0;
84
+ if (routedThroughMastraGateway) return OPENROUTER_FORMAT;
85
+ return REQUEST_FORMATS_BY_PROVIDER[provider.includes("alibaba") ? "alibaba" : provider];
86
+ }
87
+ export { isRoutedWithoutThinking, isThinkingAdapterProvider, thinkingRequestFormatFor };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * xAI (Grok) OAuth Provider
3
+ *
4
+ * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.
5
+ * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access
6
+ * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`
7
+ * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)
8
+ * access token.
9
+ */
10
+ import type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
11
+ import { AuthStorage } from '../auth/storage.js';
12
+ import type { CredentialStore } from '../auth/types.js';
13
+ /** Get or create the shared AuthStorage instance. */
14
+ export declare function getAuthStorage(): AuthStorage;
15
+ /** Set a custom AuthStorage instance (useful for tests / TUI integration). */
16
+ export declare function setAuthStorage(storage: AuthStorage | undefined): void;
17
+ /**
18
+ * Build a fetch wrapper that authenticates with xAI OAuth.
19
+ * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,
20
+ * preserving non-auth headers from the caller.
21
+ */
22
+ export declare function buildXAIOAuthFetch(opts?: {
23
+ authStorage?: CredentialStore;
24
+ }): typeof fetch;
25
+ /**
26
+ * Creates an xAI model using OAuth authentication.
27
+ * Uses OAuth tokens from AuthStorage (auto-refreshes when needed).
28
+ */
29
+ export declare function xaiProvider(modelId: string, options?: {
30
+ headers?: Record<string, string>;
31
+ authStorage?: CredentialStore;
32
+ }): ReturnType<OpenAICompatibleProvider['chatModel']>;
33
+ //# sourceMappingURL=xai.d.ts.map